View Javadoc

1   /*--------------------------------------------------------------------------
2    *  Copyright 2010 utgenome.org
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  // utgb-core Project
18  //
19  // SAMReadIterator.java
20  // Since: 2010/10/13
21  //
22  //--------------------------------------
23  package org.utgenome.format.sam;
24  
25  import java.io.File;
26  import java.util.Iterator;
27  import java.util.NoSuchElementException;
28  
29  import net.sf.samtools.SAMFileReader;
30  import net.sf.samtools.SAMRecord;
31  import net.sf.samtools.SAMRecordIterator;
32  
33  import org.utgenome.gwt.utgb.client.bio.ChrLoc;
34  import org.utgenome.gwt.utgb.client.bio.SAMRead;
35  
36  /**
37   * Iterator for SAM entries
38   * 
39   * @author leo
40   * 
41   */
42  public class SAMReadIterator implements Iterator<SAMRead> {
43  
44  	private final SAMFileReader sam;
45  	private SAMRecordIterator it;
46  
47  	public SAMReadIterator(File bamFile, String chr) {
48  		this(bamFile, chr, 0, 0);
49  	}
50  
51  	public SAMReadIterator(File bamFile, String chr, int start, int end) {
52  		sam = new SAMFileReader(bamFile, SAMReader.getBamIndexFile(bamFile));
53  		it = sam.queryOverlapping(chr, start, end);
54  	}
55  
56  	public boolean hasNext() {
57  		if (it == null)
58  			return false;
59  
60  		boolean hasNext = it.hasNext();
61  		if (hasNext == false) {
62  			it.close();
63  			sam.close();
64  			it = null;
65  		}
66  		return hasNext;
67  	}
68  
69  	public SAMRead next() {
70  		SAMRecord r = (it != null) ? it.next() : null;
71  		if (r == null)
72  			throw new NoSuchElementException();
73  
74  		return SAM2SilkReader.convertToSAMRead(r);
75  	}
76  
77  	public void remove() {
78  		throw new UnsupportedOperationException("remove");
79  	}
80  
81  	public static Iterator<SAMRead> getIteratorOnChr(File bamFile, String chr) {
82  		return new SAMReadIterator(bamFile, chr);
83  	}
84  
85  	public static Iterator<SAMRead> getOverlappingIterator(File bamFile, ChrLoc loc) {
86  		return new SAMReadIterator(bamFile, loc.chr, loc.start, loc.end);
87  	}
88  
89  }