de.elomagic.carafile.client.CaraFileUtils.java Source code

Java tutorial

Introduction

Here is the source code for de.elomagic.carafile.client.CaraFileUtils.java

Source

/*
 * Copyright 2014 Carsten Rambow, elomagic.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.elomagic.carafile.client;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;

import de.elomagic.carafile.share.ChunkData;
import de.elomagic.carafile.share.MetaData;

/**
 *
 * @author rambow
 */
public final class CaraFileUtils {

    private CaraFileUtils() {
    }

    /**
     * DEFAULT_PIECE_SIZE = 1024 * 512.
     */
    public static final int DEFAULT_PIECE_SIZE = 1024 * 512;

    /**
     * Creates a meta file from the given file.
     *
     * @param path Path of the file
     * @param filename Real name of the file because it can differ from path parameter
     * @return
     * @throws IOException
     * @throws GeneralSecurityException
     */
    public static final MetaData createMetaData(final Path path, final String filename)
            throws IOException, GeneralSecurityException {
        if (Files.notExists(path)) {
            throw new FileNotFoundException("File " + path.toString() + " not found!");
        }

        if (Files.isDirectory(path)) {
            throw new IllegalArgumentException("Not a file: " + path.toString());
        }

        MetaData md = new MetaData();
        md.setSize(Files.size(path));
        md.setFilename(filename);
        md.setCreationDate(new Date());
        md.setChunkSize(DEFAULT_PIECE_SIZE);

        try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ);
                BufferedInputStream bin = new BufferedInputStream(in)) {
            MessageDigest mdComplete = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1);

            byte[] buffer = new byte[DEFAULT_PIECE_SIZE];
            int bytesRead;

            while ((bytesRead = bin.read(buffer)) > 0) {
                mdComplete.update(buffer, 0, bytesRead);

                ChunkData chunk = new ChunkData(
                        DigestUtils.sha1Hex(new ByteArrayInputStream(buffer, 0, bytesRead)));
                md.addChunk(chunk);
            }

            String sha1 = Hex.encodeHexString(mdComplete.digest());
            md.setId(sha1);
        }

        return md;
    }

    /**
     * Creates an URI from a base URI and given path elements.
     * <p/>
     * Path elements will be encoded when required.
     *
     * @param base {@link URI} base
     * @param pathElements Valid base URI path elements.
     * @return An URI
     * @throws java.io.UnsupportedEncodingException Thrown when pathElements includes unsupported characters
     */
    public static URI buildURI(final URI base, final String... pathElements) throws UnsupportedEncodingException {
        String s = base.toString();

        for (String value : pathElements) {
            if (!s.endsWith("/")) {
                s += "/";
            }

            s += URLEncoder.encode(value, "utf-8");
            ;
        }

        try {
            return new URI(s);
        } catch (URISyntaxException ex) {
            throw new IllegalArgumentException(
                    "Unable to build URI. base=" + base + ";values=" + Arrays.toString(pathElements));
        }
    }

    /**
     * Validates a given file path.
     *
     * @param file
     * @throws IllegalArgumentException Thrown when file includes invalid characters.
     */
    public static void validateFile(final String file) {
        String f = file.replace("\\", "/");
        if (f.contains("./") || f.contains("..") || f.contains("?")
        //|| f.contains("'")
                || f.contains("//") || f.contains("\"") || f.contains(":") || f.contains("|") || f.contains("<")
                || f.contains(">") || f.contains("%")
                //|| f.contains("&") Must be escaped ???
                || f.contains("*") || f.startsWith(" ") || f.endsWith(" ") || f.endsWith(".")) {
            throw new IllegalArgumentException("The filename \"" + file + "\" contains illegal characters");
        }
    }
}