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.server.web.rest.elements;
020
021import java.io.BufferedWriter;
022import java.io.File;
023import java.io.FileWriter;
024import java.io.IOException;
025import java.util.AbstractMap.SimpleEntry;
026import java.util.Calendar;
027import java.util.Collection;
028import java.util.HashMap;
029import java.util.List;
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032import org.slf4j.Logger;
033import org.slf4j.LoggerFactory;
034
035/**
036 *
037 * @author samuelcampos
038 */
039public class TExamTime extends Thread {
040
041    private File file;
042    private boolean stop = false;
043
044    public TExamTime(File file) {
045        if (file.isDirectory()) {
046            throw new IllegalArgumentException("Invalid FILE");
047        }
048
049        this.file = file;
050    }
051
052    public synchronized void stopThread() {
053        if(stop)
054            return; // A Thread j?? parou ou est?? a parar
055        
056        stop = true;
057
058        try {
059            while (stop == true) {
060                wait();
061            }
062        } catch (InterruptedException ex) {
063            LoggerFactory.getLogger(TExamTime.class).error(ex.getMessage(), ex);
064        }
065    }
066
067    @Override
068    public void run() {
069        throw new UnsupportedOperationException();/*
070        long beginTime = System.currentTimeMillis();
071        long endTime;
072        ExamTimeCore examTime = ExamTimeCore.getInstance();
073        BufferedWriter out = null;
074        try {
075            out = new BufferedWriter(new FileWriter(file, false));
076
077
078            IndexEngine core = IndexEngine.getInstance();
079
080            Set<String> enumList = core.enumField("AccessionNumber", false);
081            
082            examTime.setTotal(enumList.size());
083
084            List<String> extrafields = new ArrayList<String>();
085            extrafields.add("SeriesInstanceUID");
086            extrafields.add("AcquisitionDateTime");
087            extrafields.add("AcquisitionTime");
088            extrafields.add("AcquisitionDate");
089
090
091            int i = 0, j = 0, k = 0;
092            for (String accessionNumber : enumList) {
093
094                List<SearchResult> results = core.searchSync("AccessionNumber:" + accessionNumber, extrafields);
095
096                HashMap<String, List<String>> DateTimes = new HashMap<String, List<String>>();
097
098                for (SearchResult result : results) {
099                    synchronized (this) {
100                        if (stop) {
101                            stop = false;
102                            out.close();
103                            
104                            notify();
105                            return;
106                        }
107                    }
108
109
110                    Hashtable<String, String> fields = result.getExtrafields();
111
112                    String SeriesInstanceUID = fields.get("SeriesInstanceUID");
113
114                    if (SeriesInstanceUID == null) {
115                        // Its not possible to calculate the Series Time!
116                        throw new NullPointerException("SeriesInstanceUID IS NULL!!!!");
117                    }
118
119                    String time = fields.get("AcquisitionDateTime");
120
121                    if (time != null) {
122                        List<String> lt = DateTimes.get(SeriesInstanceUID);
123
124                        if (lt == null) {
125                            lt = new ArrayList<String>();
126                            DateTimes.put(SeriesInstanceUID, lt);
127                        }
128
129                        lt.add(time);
130
131                    } else {
132                        time = fields.get("AcquisitionTime");
133                        String date = fields.get("AcquisitionDate");
134
135                        if (time != null) {
136                            if (date == null) {
137                                throw new NullPointerException("DATE IS NULL!!!!");
138                            }
139
140                            List<String> lt = DateTimes.get(SeriesInstanceUID);
141
142                            if (lt == null) {
143                                lt = new ArrayList<String>();
144                                DateTimes.put(SeriesInstanceUID, lt);
145                            }
146
147                            lt.add(date + time);
148                        } else {
149                            k++;
150                        }
151                    }
152
153                    j++;
154                }
155
156                if (!DateTimes.isEmpty()) {
157                    HashMap<String, SimpleEntry<Integer, Integer>> times = getSeriesDateTimes(DateTimes);
158
159                    writeFileLine(out, accessionNumber, times.values());
160                }
161                
162                
163                examTime.increment();
164
165//                i++;
166//
167//                if (i == 50) {
168//                    break;
169//                }
170            }
171            
172            examTime.threadFinished();
173            
174        } catch (Exception ex) {
175            LoggerFactory.getLogger(TExamTime.class).error(ex.getMessage(), ex);
176        } finally {
177            try {
178                out.close();
179            } catch (IOException ex) {
180                LoggerFactory.getLogger(TExamTime.class).error(ex.getMessage(), ex);
181            }
182        }
183
184        synchronized (this) {
185            stop = true;
186            notify();
187        }
188        
189        endTime = System.currentTimeMillis();
190        
191        System.out.println("SpentTime (ms): " + (endTime - beginTime));*/
192    }
193
194    private void writeFileLine(BufferedWriter out, String accessionNumber, Collection<SimpleEntry<Integer, Integer>> times) throws IOException {
195        StringBuilder st = new StringBuilder();
196
197        st.append(accessionNumber).append(";");
198
199        for (SimpleEntry<Integer, Integer> time : times) {
200            st.append(time.getKey()).append(";").append(time.getValue()).append(";");
201        }
202        st.deleteCharAt(st.length()-1); 
203        st.append("\n");
204
205
206        out.write(st.toString());
207    }
208
209    /**
210     * Calcula o tempo de dura????o de cada uma das S??ries, dado tempos em "Ano,
211     * M??s, Dia, Hora, Minuto, Segundo"
212     *
213     * @param dateTime
214     * @return
215     */
216    private HashMap<String, SimpleEntry<Integer, Integer>> getSeriesDateTimes(HashMap<String, List<String>> dateTime) {
217        HashMap<String, SimpleEntry<Integer, Integer>> result = new HashMap<String, SimpleEntry<Integer, Integer>>();
218
219        for (String SeriesInstanceUID : dateTime.keySet()) {
220            List<String> times = dateTime.get(SeriesInstanceUID);
221
222            int min = Integer.MAX_VALUE;
223            int max = Integer.MIN_VALUE;
224
225
226            for (String time : times) {
227                Calendar cal = Calendar.getInstance();
228                cal.set(Integer.valueOf(time.substring(0, 4)), Integer.valueOf(time.substring(4, 6)), Integer.valueOf(time.substring(6, 8)), Integer.valueOf(time.substring(8, 10)), Integer.valueOf(time.substring(10, 12)), Integer.valueOf(time.substring(12, 14)));
229
230                int actual = (int) (cal.getTimeInMillis() / 1000);
231
232                if (actual < min) {
233                    min = actual;
234                }
235
236                if (actual > max) {
237                    max = actual;
238                }
239            }
240
241            result.put(SeriesInstanceUID, new SimpleEntry<Integer, Integer>((max - min), times.size()));
242        }
243
244        return result;
245    }
246}