⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 checksum.java

📁 java ant的源码!非常值得看的源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                ct++;            }            if (ct > 1) {                throw new BuildException(                    "Multiple files cannot be used when Property is specified");            }        }        if (verifyProperty != null) {            isCondition = true;        }        if (verifyProperty != null && forceOverwrite) {            throw new BuildException("VerifyProperty and ForceOverwrite cannot co-exist.");        }        if (isCondition && forceOverwrite) {            throw new BuildException(                "ForceOverwrite cannot be used when conditions are being used.");        }        messageDigest = null;        if (provider != null) {            try {                messageDigest = MessageDigest.getInstance(algorithm, provider);            } catch (NoSuchAlgorithmException noalgo) {                throw new BuildException(noalgo, getLocation());            } catch (NoSuchProviderException noprovider) {                throw new BuildException(noprovider, getLocation());            }        } else {            try {                messageDigest = MessageDigest.getInstance(algorithm);            } catch (NoSuchAlgorithmException noalgo) {                throw new BuildException(noalgo, getLocation());            }        }        if (messageDigest == null) {            throw new BuildException("Unable to create Message Digest", getLocation());        }        if (fileext == null) {            fileext = "." + algorithm;        } else if (fileext.trim().length() == 0) {            throw new BuildException("File extension when specified must not be an empty string");        }        try {            if (resources != null) {                for (Iterator i = resources.iterator(); i.hasNext();) {                    FileResource fr = (FileResource) i.next();                    File src = fr.getFile();                    if (totalproperty != null || todir != null) {                        // Use '/' to calculate digest based on file name.                        // This is required in order to get the same result                        // on different platforms.                        relativeFilePaths.put(src, fr.getName().replace(File.separatorChar, '/'));                    }                    addToIncludeFileMap(src);                }            }            if (file != null) {                if (totalproperty != null || todir != null) {                    relativeFilePaths.put(                        file, file.getName().replace(File.separatorChar, '/'));                }                addToIncludeFileMap(file);            }            return generateChecksums();        } finally {            fileext = savedFileExt;            includeFileMap.clear();        }    }    /**     * Add key-value pair to the hashtable upon which     * to later operate upon.     */    private void addToIncludeFileMap(File file) throws BuildException {        if (file.exists()) {            if (property == null) {                File checksumFile = getChecksumFile(file);                if (forceOverwrite || isCondition                    || (file.lastModified() > checksumFile.lastModified())) {                    includeFileMap.put(file, checksumFile);                } else {                    log(file + " omitted as " + checksumFile + " is up to date.",                        Project.MSG_VERBOSE);                    if (totalproperty != null) {                        // Read the checksum from disk.                        String checksum = readChecksum(checksumFile);                        byte[] digest = decodeHex(checksum.toCharArray());                        allDigests.put(file, digest);                    }                }            } else {                includeFileMap.put(file, property);            }        } else {            String message = "Could not find file "                + file.getAbsolutePath()                + " to generate checksum for.";            log(message);            throw new BuildException(message, getLocation());        }    }    private File getChecksumFile(File file) {        File directory;        if (todir != null) {            // A separate directory was explicitly declared            String path = (String) relativeFilePaths.get(file);            if (path == null) {                //bug 37386. this should not occur, but it has, once.                throw new BuildException(                    "Internal error: "                    + "relativeFilePaths could not match file"                    + file + "\n"                    + "please file a bug report on this");            }            directory = new File(todir, path).getParentFile();            // Create the directory, as it might not exist.            directory.mkdirs();        } else {            // Just use the same directory as the file itself.            // This directory will exist            directory = file.getParentFile();        }        File checksumFile = new File(directory, file.getName() + fileext);        return checksumFile;    }    /**     * Generate checksum(s) using the message digest created earlier.     */    private boolean generateChecksums() throws BuildException {        boolean checksumMatches = true;        FileInputStream fis = null;        FileOutputStream fos = null;        byte[] buf = new byte[readBufferSize];        try {            for (Enumeration e = includeFileMap.keys(); e.hasMoreElements();) {                messageDigest.reset();                File src = (File) e.nextElement();                if (!isCondition) {                    log("Calculating " + algorithm + " checksum for " + src, Project.MSG_VERBOSE);                }                fis = new FileInputStream(src);                DigestInputStream dis = new DigestInputStream(fis,                                                              messageDigest);                while (dis.read(buf, 0, readBufferSize) != -1) {                    // Empty statement                }                dis.close();                fis.close();                fis = null;                byte[] fileDigest = messageDigest.digest ();                if (totalproperty != null) {                    allDigests.put(src, fileDigest);                }                String checksum = createDigestString(fileDigest);                //can either be a property name string or a file                Object destination = includeFileMap.get(src);                if (destination instanceof java.lang.String) {                    String prop = (String) destination;                    if (isCondition) {                        checksumMatches                            = checksumMatches && checksum.equals(property);                    } else {                        getProject().setNewProperty(prop, checksum);                    }                } else if (destination instanceof java.io.File) {                    if (isCondition) {                        File existingFile = (File) destination;                        if (existingFile.exists()) {                            try {                                String suppliedChecksum =                                    readChecksum(existingFile);                                checksumMatches = checksumMatches                                    && checksum.equals(suppliedChecksum);                            } catch (BuildException be) {                                // file is on wrong format, swallow                                checksumMatches = false;                            }                        } else {                            checksumMatches = false;                        }                    } else {                        File dest = (File) destination;                        fos = new FileOutputStream(dest);                        fos.write(format.format(new Object[] {                                                    checksum,                                                    src.getName(),                                                }).getBytes());                        fos.write(StringUtils.LINE_SEP.getBytes());                        fos.close();                        fos = null;                    }                }            }            if (totalproperty != null) {                // Calculate the total checksum                // Convert the keys (source files) into a sorted array.                Set keys = allDigests.keySet();                Object[] keyArray = keys.toArray();                // File is Comparable, so sorting is trivial                Arrays.sort(keyArray);                // Loop over the checksums and generate a total hash.                messageDigest.reset();                for (int i = 0; i < keyArray.length; i++) {                    File src = (File) keyArray[i];                    // Add the digest for the file content                    byte[] digest = (byte[]) allDigests.get(src);                    messageDigest.update(digest);                    // Add the file path                    String fileName = (String) relativeFilePaths.get(src);                    messageDigest.update(fileName.getBytes());                }                String totalChecksum = createDigestString(messageDigest.digest());                getProject().setNewProperty(totalproperty, totalChecksum);            }        } catch (Exception e) {            throw new BuildException(e, getLocation());        } finally {            FileUtils.close(fis);            FileUtils.close(fos);        }        return checksumMatches;    }    private String createDigestString(byte[] fileDigest) {        StringBuffer checksumSb = new StringBuffer();        for (int i = 0; i < fileDigest.length; i++) {            String hexStr = Integer.toHexString(0x00ff & fileDigest[i]);            if (hexStr.length() < 2) {                checksumSb.append("0");            }            checksumSb.append(hexStr);        }        return checksumSb.toString();    }    /**     * Converts an array of characters representing hexadecimal values into an     * array of bytes of those same values. The returned array will be half the     * length of the passed array, as it takes two characters to represent any     * given byte. An exception is thrown if the passed char array has an odd     * number of elements.     *     * NOTE: This code is copied from jakarta-commons codec.     * @param data an array of characters representing hexadecimal values     * @return the converted array of bytes     * @throws BuildException on error     */    public static byte[] decodeHex(char[] data) throws BuildException {        int l = data.length;        if ((l & 0x01) != 0) {            throw new BuildException("odd number of characters.");        }        byte[] out = new byte[l >> 1];        // two characters form the hex value.        for (int i = 0, j = 0; j < l; i++) {            int f = Character.digit(data[j++], 16) << 4;            f = f | Character.digit(data[j++], 16);            out[i] = (byte) (f & 0xFF);        }        return out;    }    /**     * reads the checksum from a file using the specified format.     *     * @since 1.7     */    private String readChecksum(File f) {        BufferedReader diskChecksumReader = null;        try {            diskChecksumReader = new BufferedReader(new FileReader(f));            Object[] result = format.parse(diskChecksumReader.readLine());            if (result == null || result.length == 0 || result[0] == null) {                throw new BuildException("failed to find a checksum");            }            return (String) result[0];        } catch (IOException e) {            throw new BuildException("Couldn't read checksum file " + f, e);        } catch (ParseException e) {            throw new BuildException("Couldn't read checksum file " + f, e);        } finally {            FileUtils.close(diskChecksumReader);        }    }    /**     * Helper class for the format attribute.     *     * @since 1.7     */    public static class FormatElement extends EnumeratedAttribute {        private static HashMap formatMap = new HashMap();        private static final String CHECKSUM = "CHECKSUM";        private static final String MD5SUM = "MD5SUM";        private static final String SVF = "SVF";        static {            formatMap.put(CHECKSUM, new MessageFormat("{0}"));            formatMap.put(MD5SUM, new MessageFormat("{0} *{1}"));            formatMap.put(SVF, new MessageFormat("MD5 ({1}) = {0}"));        }        /** Constructor for FormatElement */        public FormatElement() {            super();        }        /**         * Get the default value - CHECKSUM.         * @return the defaul value.         */        public static FormatElement getDefault() {            FormatElement e = new FormatElement();            e.setValue(CHECKSUM);            return e;        }        /**         * Convert this enumerated type to a <code>MessageFormat</code>.         * @return a <code>MessageFormat</code> object.         */        public MessageFormat getFormat() {            return (MessageFormat) formatMap.get(getValue());        }        /**         * Get the valid values.         * @return an array of values.         */        public String[] getValues() {            return new String[] {CHECKSUM, MD5SUM, SVF};        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -