View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.chukwa.validationframework.util;
19  
20  
21  import java.io.File;
22  import java.io.FileInputStream;
23  import java.io.InputStream;
24  import java.security.MessageDigest;
25  import org.apache.hadoop.fs.FSDataInputStream;
26  import org.apache.hadoop.fs.FileSystem;
27  import org.apache.hadoop.fs.Path;
28  
29  public class MD5 {
30    public static String checksum(File file) {
31      try {
32        InputStream fin = new FileInputStream(file);
33        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
34        byte[] buffer = new byte[1024];
35        int read;
36        do {
37          read = fin.read(buffer);
38          if (read > 0)
39            md5er.update(buffer, 0, read);
40        } while (read != -1);
41        fin.close();
42        byte[] digest = md5er.digest();
43        if (digest == null)
44          return null;
45        String strDigest = "0x";
46        for (int i = 0; i < digest.length; i++) {
47          strDigest += Integer.toString((digest[i] & 0xff) + 0x100, 16)
48              .substring(1).toUpperCase();
49        }
50        return strDigest;
51      } catch (Exception e) {
52        return null;
53      }
54    }
55  
56    public static String checksum(FileSystem fs, Path file) {
57      try {
58        FSDataInputStream fin = fs.open(file);
59        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
60        byte[] buffer = new byte[1024];
61        int read;
62        do {
63          read = fin.read(buffer);
64          if (read > 0)
65            md5er.update(buffer, 0, read);
66        } while (read != -1);
67        fin.close();
68        byte[] digest = md5er.digest();
69        if (digest == null)
70          return null;
71        String strDigest = "0x";
72        for (int i = 0; i < digest.length; i++) {
73          strDigest += Integer.toString((digest[i] & 0xff) + 0x100, 16)
74              .substring(1).toUpperCase();
75        }
76        return strDigest;
77      } catch (Exception e) {
78        return null;
79      }
80    }
81  }