com.github.kubakaszycki.jkhttpd.api.FileURLHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.github.kubakaszycki.jkhttpd.api.FileURLHandler.java

Source

/*
 * Copyright (C) 2016 Jakub Kaszycki
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.github.kubakaszycki.jkhttpd.api;

import com.github.kubakaszycki.jkhttpd.HttpRequest;
import com.github.kubakaszycki.jkhttpd.HttpResponse;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Jakub Kaszycki
 */
public class FileURLHandler implements URLHandler {

    private final File baseDir;

    public FileURLHandler(File baseDir) {
        this.baseDir = baseDir;
    }

    public File getBaseDir() {
        return baseDir;
    }

    @Override
    public void handle(String res, HttpRequest req, HttpResponse resp)
            throws IOException, IllegalArgumentException {
        File relativeFile = new File(baseDir, res);
        if (!relativeFile.exists()) {
            resp.setCode(404);
            resp.setCodeString();
            return;
        }
        if (relativeFile.isDirectory()) {
            resp.setContents(CharBuffer.wrap(DirectoryListing.doDirectoryListing(relativeFile, res)));
        } else {
            resp.setContents(
                    Charset.defaultCharset().decode(ByteBuffer.wrap(FileUtils.readFileToByteArray(relativeFile))));
        }
        resp.setCode(200);
        resp.setCodeString();
    }
}