/testability-explorer/src/main/java/com/google/test/metric/report/SourceLoader.java
Java | 69 lines | 45 code | 9 blank | 15 comment | 10 complexity | fa106a52fa0ba55e3c5e9bf94d980690 MD5 | raw file
1/* 2 * Copyright 2007 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16package com.google.test.metric.report; 17 18import java.io.BufferedReader; 19import java.io.IOException; 20import java.io.InputStream; 21import java.io.InputStreamReader; 22import java.util.ArrayList; 23 24import com.google.classpath.ClassPath; 25 26public class SourceLoader { 27 28 private final ClassPath classPath; 29 30 public SourceLoader(ClassPath classPath) { 31 this.classPath = classPath; 32 } 33 34 public Source load(String name) { 35 InputStream is = getStream(name); 36 if (is == null) { 37 return new Source(new ArrayList<Source.Line>()); 38 } 39 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 40 ArrayList<Source.Line> lines = new ArrayList<Source.Line>(); 41 String line; 42 int lineNumber = 1; 43 try { 44 while ((line = reader.readLine()) != null) { 45 lines.add(new Source.Line(lineNumber, line)); 46 lineNumber ++; 47 } 48 reader.close(); 49 return new Source(lines); 50 } catch (IOException e) { 51 throw new RuntimeException(e); 52 } 53 54 } 55 56 private InputStream getStream(String name) { 57 String resource = name.replace(".", "/"); 58 InputStream is = null; 59 while (is == null && !resource.equals("")) { 60 is = classPath.getResourceAsStream(resource + ".java"); 61 if (is == null) { 62 int index = resource.lastIndexOf('/'); 63 resource = index == -1 ? "" : resource.substring(0, index); 64 } 65 } 66 return is; 67 } 68 69}