001    /*
002     * Copyright 2010-2015 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.kotlin.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.kotlin.resolve.ImportPath;
026    
027    import javax.inject.Inject;
028    import java.util.Collection;
029    import java.util.Map;
030    
031    import static org.jetbrains.kotlin.psi.PsiPackage.JetPsiFactory;
032    
033    public class JetImportsFactory {
034        private Project project;
035    
036        private final Map<ImportPath, JetImportDirective> importsCache = Maps.newHashMap();
037    
038        @Inject
039        public void setProject(@NotNull Project project) {
040            importsCache.clear();
041            this.project = project;
042        }
043    
044        @NotNull
045        public JetImportDirective createImportDirective(@NotNull ImportPath importPath) {
046            JetImportDirective directive = importsCache.get(importPath);
047            if (directive != null) {
048                return directive;
049            }
050    
051            JetImportDirective createdDirective = JetPsiFactory(project).createImportDirective(importPath);
052            importsCache.put(importPath, createdDirective);
053    
054            return createdDirective;
055        }
056    
057        @NotNull
058        public Collection<JetImportDirective> createImportDirectives(@NotNull Collection<ImportPath> importPaths) {
059            return Collections2.transform(importPaths,
060                                          new Function<ImportPath, JetImportDirective>() {
061                                              @Override
062                                              public JetImportDirective apply(@Nullable ImportPath path) {
063                                                  assert path != null;
064                                                  return createImportDirective(path);
065                                              }
066                                          });
067        }
068    }