001    /*
002     * Copyright 2010-2013 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.jet.lang.psi;
018    
019    import com.google.common.base.Function;
020    import com.google.common.collect.Collections2;
021    import com.google.common.collect.Maps;
022    import com.intellij.openapi.project.Project;
023    import org.jetbrains.annotations.NotNull;
024    import org.jetbrains.annotations.Nullable;
025    import org.jetbrains.jet.lang.resolve.ImportPath;
026    
027    import javax.inject.Inject;
028    import java.util.Collection;
029    import java.util.Map;
030    
031    import static org.jetbrains.jet.lang.psi.PsiPackage.JetPsiFactory;
032    
033    public class JetImportsFactory {
034        @NotNull
035        private Project project;
036    
037        private final Map<ImportPath, JetImportDirective> importsCache = Maps.newHashMap();
038    
039        @Inject
040        public void setProject(@NotNull Project project) {
041            importsCache.clear();
042            this.project = project;
043        }
044    
045        @NotNull
046        public JetImportDirective createImportDirective(@NotNull ImportPath importPath) {
047            JetImportDirective directive = importsCache.get(importPath);
048            if (directive != null) {
049                return directive;
050            }
051    
052            JetImportDirective createdDirective = JetPsiFactory(project).createImportDirective(importPath);
053            importsCache.put(importPath, createdDirective);
054    
055            return createdDirective;
056        }
057    
058        @NotNull
059        public Collection<JetImportDirective> createImportDirectives(@NotNull Collection<ImportPath> importPaths) {
060            return Collections2.transform(importPaths,
061                                          new Function<ImportPath, JetImportDirective>() {
062                                              @Override
063                                              public JetImportDirective apply(@Nullable ImportPath path) {
064                                                  assert path != null;
065                                                  return createImportDirective(path);
066                                              }
067                                          });
068        }
069    }