001package ca.uhn.hl7v2.hoh.encoder;
002
003import static ca.uhn.hl7v2.hoh.util.StringUtils.*;
004
005import java.io.IOException;
006import java.io.InputStream;
007
008import ca.uhn.hl7v2.hoh.api.DecodeException;
009
010public class Hl7OverHttpResponseDecoder extends AbstractHl7OverHttpDecoder {
011
012        private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(Hl7OverHttpResponseDecoder.class);
013        private String myActionLine;
014
015        @Override
016        protected String readActionLineAndDecode(InputStream theInputStream) throws IOException, NoMessageReceivedException, DecodeException {
017                ourLog.trace("Entering readActionLineAndDecode(InputStream)");
018
019                if (myActionLine == null) {
020                        String firstLine = readFirstLine(theInputStream);
021                        if (firstLine == null || isBlank(firstLine)) {
022                                throw new NoMessageReceivedException();
023                        }
024
025                        if (!firstLine.startsWith("HTTP/1.1 ")) {
026                                throw new DecodeException("HTTP response begins with unknown HTTP version. Line is: " + firstLine);
027                        }
028
029                        String statusPart = firstLine.substring(9);
030                        int spaceIdx = statusPart.indexOf(' ');
031                        if (spaceIdx == -1) {
032                                throw new DecodeException("Invalid response line, no space after status code. Line is: " + firstLine);
033                        }
034
035                        String statusCode = statusPart.substring(0, spaceIdx);
036                        try {
037                                setResponseStatus(Integer.parseInt(statusCode));
038                        } catch (NumberFormatException e) {
039                                throw new DecodeException("Invalid response line. Bad status code: " + statusCode);
040                        }
041
042                        setResponseName(statusPart.substring(spaceIdx).trim());
043                        myActionLine = firstLine;
044                        ourLog.trace("Action line is {}", myActionLine);
045
046                } else {
047                        ourLog.trace("Already have an action line");
048                }
049                
050                return myActionLine;
051        }
052
053        @Override
054        protected void authorize() throws AuthorizationFailureException {
055                // responses do not need authorization
056        }
057
058        /**
059         * Returns true if the connection=close header was present in the response
060         */
061        @Override
062        public boolean isConnectionCloseHeaderPresent() {
063                return super.isConnectionCloseHeaderPresent();
064        }
065
066}