1. /*
  2. * Copyright 2003-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.types.selectors.modifiedselector;
  18. import java.io.File;
  19. /**
  20. * Computes a 'hashvalue' for the content of file using String.hashValue().
  21. * Use of this algorithm doesn't require any additional nested <param>s and
  22. * doesn't support any.
  23. *
  24. * @version 2003-09-13
  25. * @since Ant 1.6
  26. */
  27. public class HashvalueAlgorithm implements Algorithm {
  28. /**
  29. * This algorithm doesn't need any configuration.
  30. * Therefore it's always valid.
  31. * @return always true
  32. */
  33. public boolean isValid() {
  34. return true;
  35. }
  36. /**
  37. * Computes a 'hashvalue' for a file content.
  38. * It reads the content of a file, convert that to String and use the
  39. * String.hashCode() method.
  40. * @param file The file for which the value should be computed
  41. * @return the hashvalue or <i>null</i> if the file couldn't be read
  42. */
  43. // Because the content is only read the file will not be damaged. I tested
  44. // with JPG, ZIP and PDF as binary files.
  45. public String getValue(File file) {
  46. try {
  47. if (!file.canRead()) {
  48. return null;
  49. }
  50. java.io.FileInputStream fis = new java.io.FileInputStream(file);
  51. byte[] content = new byte[fis.available()];
  52. fis.read(content);
  53. fis.close();
  54. String s = new String(content);
  55. int hash = s.hashCode();
  56. return Integer.toString(hash);
  57. } catch (Exception e) {
  58. return null;
  59. }
  60. }
  61. /**
  62. * Override Object.toString().
  63. * @return information about this comparator
  64. */
  65. public String toString() {
  66. return "HashvalueAlgorithm";
  67. }
  68. }