Java tutorial
/* * Copyright 2014 Objectos, Fbrica de Software LTDA. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package br.com.objectos.way.core.code.jdt; import static com.google.common.collect.Sets.newHashSet; import java.io.Reader; import java.net.URL; import java.util.Set; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import br.com.objectos.way.code.info.SourceFileInfo; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** * @author marcio.endo@objectos.com.br (Marcio Endo) */ public class AstReaderResource extends AstReader { private final String resourceName; private final Set<Class<?>> jarHints = newHashSet(); AstReaderResource(String resourceName) { this.resourceName = resourceName; } public AstReaderResource add(Class<?> jarHint) { jarHints.add(jarHint); return this; } @Override public SourceFileInfo toSourceFileInfo() { CompilationUnit unit = toCompilationUnit(); return CompilationUnitWrapper.wrapperOf(unit).toSourceFileInfo(); } @Override void setEnvironment(ASTParser parser) { String[] classpathEntries = FluentIterable.from(jarHints).transform(ToJar.INSTANCE).toArray(String.class); parser.setEnvironment(classpathEntries, null, null, true); } @Override void setSource(ASTParser parser) throws Exception { String name = resourceName.substring(resourceName.lastIndexOf('/')); parser.setUnitName(name); URL url = Resources.getResource(getClass(), resourceName); Reader reader = Resources.asCharSource(url, Charsets.UTF_8).openStream(); String source = CharStreams.toString(reader); char[] chars = source.toCharArray(); parser.setSource(chars); } private enum ToJar implements Function<Class<?>, String> { INSTANCE; @Override public String apply(Class<?> input) { return input.getProtectionDomain().getCodeSource().getLocation().getPath(); } } }