001package fr.ifremer.adagio.synchro.socket;
002
003/*
004 * #%L
005 * SIH-Adagio :: Synchronization
006 * $Id:$
007 * $HeadURL:$
008 * %%
009 * Copyright (C) 2012 - 2014 Ifremer
010 * %%
011 * This program is free software: you can redistribute it and/or modify
012 * it under the terms of the GNU Affero General Public License as published by
013 * the Free Software Foundation, either version 3 of the License, or
014 * (at your option) any later version.
015 * 
016 * This program is distributed in the hope that it will be useful,
017 * but WITHOUT ANY WARRANTY; without even the implied warranty of
018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
019 * GNU General Public License for more details.
020 * 
021 * You should have received a copy of the GNU Affero General Public License
022 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
023 * #L%
024 */
025
026import java.io.File;
027import java.io.IOException;
028import java.net.URLDecoder;
029import java.nio.charset.Charset;
030import java.text.ParseException;
031import java.text.SimpleDateFormat;
032import java.util.Date;
033import java.util.Locale;
034import java.util.regex.Pattern;
035
036import org.apache.commons.lang3.time.DateFormatUtils;
037import org.apache.commons.logging.Log;
038import org.apache.commons.logging.LogFactory;
039import org.apache.http.HttpEntity;
040import org.apache.http.HttpEntityEnclosingRequest;
041import org.apache.http.HttpException;
042import org.apache.http.HttpRequest;
043import org.apache.http.HttpResponse;
044import org.apache.http.HttpStatus;
045import org.apache.http.MethodNotSupportedException;
046import org.apache.http.entity.ContentType;
047import org.apache.http.entity.FileEntity;
048import org.apache.http.entity.StringEntity;
049import org.apache.http.protocol.HttpContext;
050import org.apache.http.protocol.HttpRequestHandler;
051import org.apache.http.util.EntityUtils;
052
053public class SynchroHttpHandler implements HttpRequestHandler {
054    /* Logger */
055    private static final Log log = LogFactory.getLog(SynchroHttpHandler.class);
056
057    private final File dataDirectory;
058
059    private SimpleDateFormat dateFormatter;
060
061    private Pattern datePattern;
062
063    public SynchroHttpHandler(final File dataDirectory) {
064        super();
065        this.dataDirectory = dataDirectory;
066        this.dateFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
067        datePattern = Pattern.compile("20[0-9]{6}_[0-9]{6}_[0-9]{3}");
068    }
069
070    public void handle(
071            final HttpRequest request,
072            final HttpResponse response,
073            final HttpContext context) throws HttpException, IOException {
074
075        String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
076        if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
077            throw new MethodNotSupportedException(method + " method not supported");
078        }
079        String target = request.getRequestLine().getUri();
080
081        if (request instanceof HttpEntityEnclosingRequest) {
082            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
083            byte[] entityContent = EntityUtils.toByteArray(entity);
084            log.debug("Incoming entity content (bytes): " + entityContent.length);
085        }
086
087        String path = URLDecoder.decode(target, "UTF-8");
088        if ("/new".equals(path)) {
089            Date sysdate = new Date();
090            String dateStr = dateFormatter.format(sysdate);
091            StringEntity entity = new StringEntity(
092                    dateStr,
093                    ContentType.create("text/html", "UTF-8"));
094            response.setEntity(entity);
095            return;
096        }
097        if (datePattern.matcher(path.substring(1)).matches()) {
098            Date sysdate = null;
099            try {
100                sysdate = dateFormatter.parse(path.substring(1));
101            } catch (ParseException e) {
102                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
103                StringEntity entity = new StringEntity(
104                        "<html><body><h1>File " + path +
105                                " not found</h1></body></html>",
106                        ContentType.create("text/html", "UTF-8"));
107                response.setEntity(entity);
108                log.warn("Path " + path + " not found");
109                return;
110            }
111            int percent = 50;
112            String message = "Table XXX";
113            StringEntity entity = new StringEntity(
114                    String.format("{percent: %s, message: %s}", percent, message),
115                    ContentType.create("text/html", "UTF-8"));
116            response.setEntity(entity);
117            return;
118        }
119        final File file = new File(this.dataDirectory, URLDecoder.decode(target, "UTF-8"));
120        if (!file.exists()) {
121
122            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
123            StringEntity entity = new StringEntity(
124                    "<html><body><h1>File" + file.getPath() +
125                            " not found</h1></body></html>",
126                    ContentType.create("text/html", "UTF-8"));
127            response.setEntity(entity);
128            log.warn("File " + file.getPath() + " not found");
129
130        } else if (!file.canRead() || file.isDirectory()) {
131
132            response.setStatusCode(HttpStatus.SC_FORBIDDEN);
133            StringEntity entity = new StringEntity(
134                    "<html><body><h1>Access denied</h1></body></html>",
135                    ContentType.create("text/html", "UTF-8"));
136            response.setEntity(entity);
137            log.warn("Cannot read file " + file.getPath());
138
139        } else {
140
141            response.setStatusCode(HttpStatus.SC_OK);
142            FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null));
143            response.setEntity(body);
144            log.debug("Serving file " + file.getPath());
145        }
146    }
147
148}