001/**
002 * Copyright (C) 2014  Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
003 *
004 * This file is part of Dicoogle/dicoogle.
005 *
006 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * Dicoogle/dicoogle is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with Dicoogle.  If not, see <http://www.gnu.org/licenses/>.
018 */
019package pt.ua.dicoogle.core.query;
020
021import java.io.OutputStream;
022import java.io.PrintWriter;
023import java.util.HashMap;
024import java.util.List;
025import java.util.concurrent.CountDownLatch;
026import java.util.concurrent.ExecutionException;
027
028import org.apache.commons.lang3.StringUtils;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031
032import pt.ua.dicoogle.sdk.datastructs.SearchResult;
033import pt.ua.dicoogle.sdk.task.JointQueryTask;
034import pt.ua.dicoogle.sdk.task.Task;
035
036public class ExportToCSVQueryTask extends JointQueryTask {
037
038        private static final Logger log = LoggerFactory.getLogger(ExportToCSVQueryTask.class);
039        
040        private static String[] searchChars = new String[]{"\n", ";"};
041        private static String[] replaceChars = new String[]{"", ","};
042        
043        private List<String> tagsOrder;
044        // private OutputStream outputStream;
045        private PrintWriter writter;
046        private CountDownLatch latch;
047        
048        private int nLines = 0;
049
050        public ExportToCSVQueryTask(List<String> tagsOrder, OutputStream outputStream) {
051                super();
052                this.tagsOrder = tagsOrder;
053                this.latch = new CountDownLatch(1);
054                writter = new PrintWriter(outputStream);
055
056                printFirstLine();
057        }
058
059        @Override
060        public void onCompletion() {
061                log.debug("ExportToCSV task: completed");
062                writter.flush();
063                writter.close();
064                latch.countDown();
065                
066                log.info("Exported CSV Table: ", tagsOrder.toString(), nLines);
067        }
068
069        @Override
070        public void onReceive(Task<Iterable<SearchResult>> e) {
071                log.debug("ExportToCSV task: Received results");
072                try {
073                        Iterable<SearchResult> it = e.get();
074                        for (SearchResult result : it) {
075                                printLine(result);
076                        }
077                } catch (InterruptedException | ExecutionException e1) {
078                        e1.printStackTrace();
079                }
080
081        }
082
083        /**
084         * Print the first line of the .csv file
085         * 
086         */
087        private void printFirstLine() {
088                StringBuilder builder = new StringBuilder();
089                
090                log.debug("Started, Printing first line: ", tagsOrder);
091                
092                for (String tag : tagsOrder) {
093                        builder.append("\"").append(tag).append("\";");
094                }
095
096                this.writter.println(builder.toString());
097        }
098
099        private void printLine(SearchResult result){
100                StringBuilder builder = new StringBuilder();
101                
102                HashMap<String, Object> extraFields = result.getExtraData();
103                
104                for (String tag : tagsOrder) {
105                        Object temp1 = extraFields.get(tag);
106
107                        final String s = (temp1 != null) ?
108                                temp1.toString().trim() : "";
109
110                        if (s.length() > 0) {
111                                String temp = StringUtils.replaceEach(s, searchChars, replaceChars);
112                                builder.append('\"').append(temp).append("\";");
113                        } else {
114                                builder.append(";");
115                        }
116                }
117                
118                log.trace("Printing Line: ", builder.toString());
119                nLines++;
120                this.writter.println(builder.toString());
121        }
122
123        public void await() {
124                try {
125                        latch.await();
126                } catch (InterruptedException e) {
127                        e.printStackTrace();
128                }
129        }
130        
131}