001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package org.apache.hadoop.hdfs;
020
021 import java.io.IOException;
022 import java.util.NoSuchElementException;
023
024 import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
025 import org.apache.hadoop.fs.Path;
026 import org.apache.hadoop.fs.RemoteIterator;
027
028 /**
029 * Provides an iterator interface for listCorruptFileBlocks.
030 * This class is used by DistributedFileSystem and Hdfs.
031 */
032 public class CorruptFileBlockIterator implements RemoteIterator<Path> {
033 private final DFSClient dfs;
034 private String path;
035
036 private String[] files = null;
037 private int fileIdx = 0;
038 private String cookie = null;
039 private Path nextPath = null;
040
041 private int callsMade = 0;
042
043 public CorruptFileBlockIterator(DFSClient dfs, Path path) throws IOException {
044 this.dfs = dfs;
045 this.path = path2String(path);
046 loadNext();
047 }
048
049 /**
050 * @return the number of calls made to the DFSClient.
051 * This is for debugging and testing purposes.
052 */
053 public int getCallsMade() {
054 return callsMade;
055 }
056
057 private String path2String(Path path) {
058 return path.toUri().getPath();
059 }
060
061 private Path string2Path(String string) {
062 return new Path(string);
063 }
064
065 private void loadNext() throws IOException {
066 if (files == null || fileIdx >= files.length) {
067 CorruptFileBlocks cfb = dfs.listCorruptFileBlocks(path, cookie);
068 files = cfb.getFiles();
069 cookie = cfb.getCookie();
070 fileIdx = 0;
071 callsMade++;
072 }
073
074 if (fileIdx >= files.length) {
075 // received an empty response
076 // there are no more corrupt file blocks
077 nextPath = null;
078 } else {
079 nextPath = string2Path(files[fileIdx]);
080 fileIdx++;
081 }
082 }
083
084
085 @Override
086 public boolean hasNext() {
087 return nextPath != null;
088 }
089
090
091 @Override
092 public Path next() throws IOException {
093 if (!hasNext()) {
094 throw new NoSuchElementException("No more corrupt file blocks");
095 }
096
097 Path result = nextPath;
098 loadNext();
099
100 return result;
101 }
102 }