001//
002/* ***** BEGIN LICENSE BLOCK *****
003 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
004 *
005 * The contents of this file are subject to the Mozilla Public License Version
006 * 1.1 (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 * http://www.mozilla.org/MPL/
009 *
010 * Software distributed under the License is distributed on an "AS IS" basis,
011 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
012 * for the specific language governing rights and limitations under the
013 * License.
014 *
015 * The Original Code is part of dcm4che, an implementation of DICOM(TM) in
016 * Java(TM), hosted at https://github.com/gunterze/dcm4che.
017 *
018 * The Initial Developer of the Original Code is
019 * Agfa Healthcare.
020 * Portions created by the Initial Developer are Copyright (C) 2011
021 * the Initial Developer. All Rights Reserved.
022 *
023 * Contributor(s):
024 * See @authors listed below
025 *
026 * Alternatively, the contents of this file may be used under the terms of
027 * either the GNU General Public License Version 2 or later (the "GPL"), or
028 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
029 * in which case the provisions of the GPL or the LGPL are applicable instead
030 * of those above. If you wish to allow use of your version of this file only
031 * under the terms of either the GPL or the LGPL, and not to allow others to
032 * use your version of this file under the terms of the MPL, indicate your
033 * decision by deleting the provisions above and replace them with the notice
034 * and other provisions required by the GPL or the LGPL. If you do not delete
035 * the provisions above, a recipient may use your version of this file under
036 * the terms of any one of the MPL, the GPL or the LGPL.
037 *
038 * ***** END LICENSE BLOCK ***** */
039
040package org.dcm4che3.tool.dcmqrscp;
041
042import java.io.File;
043import java.io.IOException;
044import java.util.Random;
045
046import org.dcm4che3.data.Attributes;
047import org.dcm4che3.data.Tag;
048import org.dcm4che3.data.VR;
049import org.dcm4che3.io.DicomInputStream;
050import org.dcm4che3.io.DicomInputStream.IncludeBulkData;
051import org.dcm4che3.io.DicomOutputStream;
052import org.dcm4che3.media.DicomDirWriter;
053import org.dcm4che3.media.RecordFactory;
054import org.dcm4che3.media.RecordType;
055import org.dcm4che3.net.Association;
056import org.dcm4che3.net.PDVInputStream;
057import org.dcm4che3.net.Status;
058import org.dcm4che3.net.pdu.PresentationContext;
059import org.dcm4che3.net.service.BasicCStoreSCP;
060import org.dcm4che3.net.service.DicomServiceException;
061import org.dcm4che3.util.AttributesFormat;
062import org.dcm4che3.util.SafeClose;
063import org.dcm4che3.util.TagUtils;
064import org.slf4j.Logger;
065import org.slf4j.LoggerFactory;
066
067public class CStoreSCPImpl extends BasicCStoreSCP {
068    private static final Logger LOG = LoggerFactory.getLogger(CStoreSCPImpl.class);
069
070    private final File storageDir;
071    private final DicomDirWriter dicomDirWriter;
072    private final RecordFactory recordFactory;
073    private final AttributesFormat filePathFormat;
074
075    public CStoreSCPImpl(DicomDirWriter dicomDirWriter, AttributesFormat filePathFormat, RecordFactory recordFactory) {
076        super("*");
077        this.dicomDirWriter = dicomDirWriter;
078        this.storageDir = dicomDirWriter.getFile().getParentFile();
079        this.filePathFormat = filePathFormat;
080        this.recordFactory = recordFactory;
081    }
082
083    @Override
084    protected void store(Association as, PresentationContext pc, Attributes rq,
085            PDVInputStream data, Attributes rsp) throws IOException {
086        String cuid = rq.getString(Tag.AffectedSOPClassUID);
087        String iuid = rq.getString(Tag.AffectedSOPInstanceUID);
088        String tsuid = pc.getTransferSyntax();
089        File file = new File(storageDir, iuid);
090        try {
091            Attributes fmi = as.createFileMetaInformation(iuid, cuid, tsuid);
092            storeTo(as, fmi, data, file);
093            Attributes attrs = parse(file);
094            File dest = getDestinationFile(attrs);
095            renameTo(as, file, dest);
096            file = dest;
097            if (addDicomDirRecords(as, attrs, fmi, file)) {
098                LOG.info("{}: M-UPDATE {}", as, dicomDirWriter.getFile());
099            } else {
100                LOG.info("{}: ignore received object", as);
101                deleteFile(as, file);
102            }
103
104        } catch (Exception e) {
105            deleteFile(as, file);
106            throw new DicomServiceException(Status.ProcessingFailure, e);
107        }
108    }
109
110    private static void storeTo(Association as, Attributes fmi, PDVInputStream data, File file)
111            throws IOException {
112        LOG.info("{}: M-WRITE {}", as, file);
113        file.getParentFile().mkdirs();
114        DicomOutputStream out = new DicomOutputStream(file);
115        try {
116            out.writeFileMetaInformation(fmi);
117            data.copyTo(out);
118        } finally {
119            SafeClose.close(out);
120        }
121    }
122
123    private File getDestinationFile(Attributes attrs) {
124        File file = new File(storageDir, filePathFormat.format(attrs));
125        while (file.exists())
126            file = new File(file.getParentFile(), TagUtils.toHexString(new Random().nextInt()));
127        return file;
128    }
129
130    private static void renameTo(Association as, File from, File dest) throws IOException {
131        LOG.info("{}: M-RENAME {}", new Object[] { as, from, dest });
132        dest.getParentFile().mkdirs();
133        if (!from.renameTo(dest))
134            throw new IOException("Failed to rename " + from + " to " + dest);
135    }
136
137    private static Attributes parse(File file) throws IOException {
138        DicomInputStream in = new DicomInputStream(file);
139        try {
140            in.setIncludeBulkData(IncludeBulkData.NO);
141            return in.readDataset(-1, Tag.PixelData);
142        } finally {
143            SafeClose.close(in);
144        }
145    }
146
147    private static void deleteFile(Association as, File file) {
148        if (file.delete())
149            LOG.info("{}: M-DELETE {}", as, file);
150        else
151            LOG.warn("{}: M-DELETE {} failed!", as, file);
152    }
153
154    protected boolean addDicomDirRecords(Association as, Attributes ds, Attributes fmi, File f)
155            throws IOException {
156        DicomDirWriter ddWriter = dicomDirWriter;
157        RecordFactory recFact = recordFactory;
158        String pid = ds.getString(Tag.PatientID, null);
159        String styuid = ds.getString(Tag.StudyInstanceUID, null);
160        String seruid = ds.getString(Tag.SeriesInstanceUID, null);
161        String iuid = fmi.getString(Tag.MediaStorageSOPInstanceUID, null);
162        if (pid == null)
163            ds.setString(Tag.PatientID, VR.LO, pid = styuid);
164
165        Attributes patRec = ddWriter.findPatientRecord(pid);
166        if (patRec == null) {
167            patRec = recFact.createRecord(RecordType.PATIENT, null, ds, null, null);
168            ddWriter.addRootDirectoryRecord(patRec);
169        }
170        Attributes studyRec = ddWriter.findStudyRecord(patRec, styuid);
171        if (studyRec == null) {
172            studyRec = recFact.createRecord(RecordType.STUDY, null, ds, null, null);
173            ddWriter.addLowerDirectoryRecord(patRec, studyRec);
174        }
175        Attributes seriesRec = ddWriter.findSeriesRecord(studyRec, seruid);
176        if (seriesRec == null) {
177            seriesRec = recFact.createRecord(RecordType.SERIES, null, ds, null, null);
178            ddWriter.addLowerDirectoryRecord(studyRec, seriesRec);
179        }
180        Attributes instRec = ddWriter.findLowerInstanceRecord(seriesRec, false, iuid);
181        if (instRec != null)
182            return false;
183
184        instRec = recFact.createRecord(ds, fmi, ddWriter.toFileIDs(f));
185        ddWriter.addLowerDirectoryRecord(seriesRec, instRec);
186        ddWriter.commit();
187        return true;
188    }
189
190}