summaryrefslogtreecommitdiff
path: root/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java
blob: 66875895f2785b0f2b59f9328d28bda20e0820b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * 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 org.jetbrains.idea.maven.dom;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlTag;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.dom.model.MavenDomProfile;
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel;
import org.jetbrains.idea.maven.dom.model.MavenDomProperties;
import org.jetbrains.idea.maven.dom.references.MavenFilteredPropertyPsiReferenceProvider;
import org.jetbrains.idea.maven.model.MavenId;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.server.MavenServerUtil;
import org.jetbrains.idea.maven.utils.MavenJDOMUtil;
import org.jetbrains.idea.maven.utils.MavenUtil;
import org.jetbrains.jps.maven.compiler.MavenEscapeWindowsCharacterUtils;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MavenPropertyResolver {
  public static final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}|@(.+?)@");

  public static void doFilterText(Module module,
                                  String text,
                                  Properties additionalProperties,
                                  @Nullable String propertyEscapeString,
                                  Appendable out) throws IOException {
    MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject());
    MavenProject mavenProject = manager.findProject(module);
    if (mavenProject == null) {
      out.append(text);
      return;
    }

    Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin");
    String escapeWindowsPathsStr = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeWindowsPaths");
    boolean escapeWindowsPath = escapeWindowsPathsStr == null || Boolean.parseBoolean(escapeWindowsPathsStr);

    doFilterText(MavenFilteredPropertyPsiReferenceProvider.getDelimitersPattern(mavenProject),
                 manager,
                 mavenProject,
                 text,
                 additionalProperties,
                 propertyEscapeString,
                 escapeWindowsPath,
                 null,
                 out);
  }

  private static void doFilterText(Pattern pattern,
                                   MavenProjectsManager mavenProjectsManager,
                                   MavenProject mavenProject,
                                   String text,
                                   Properties additionalProperties,
                                   @Nullable String escapeString,
                                   boolean escapeWindowsPath,
                                   @Nullable Map<String, String> resolvedPropertiesParam,
                                   Appendable out) throws IOException {
    Map<String, String> resolvedProperties = resolvedPropertiesParam;
    
    Matcher matcher = pattern.matcher(text);
    int groupCount = matcher.groupCount();
    
    int last = 0;
    while (matcher.find()) {
      if (escapeString != null) {
        int escapeStringStartIndex = matcher.start() - escapeString.length();
        if (escapeStringStartIndex >= last) {
          if (text.startsWith(escapeString, escapeStringStartIndex)) {
            out.append(text, last, escapeStringStartIndex);
            out.append(matcher.group());
            last = matcher.end();
            continue;
          }
        }
      }

      out.append(text, last, matcher.start());
      last = matcher.end();

      String propertyName = null;

      for (int i = 0; i < groupCount; i++) {
        propertyName = matcher.group(i + 1);
        if (propertyName != null) {
          break;
        }
      }

      assert propertyName != null;

      if (resolvedProperties == null) {
        resolvedProperties = new HashMap<String, String>();
      }
      
      String propertyValue = resolvedProperties.get(propertyName);
      if (propertyValue == null) {
        if (resolvedProperties.containsKey(propertyName)) { // if cyclic property dependencies
          out.append(matcher.group());
          continue;
        }

        String resolved = doResolveProperty(propertyName, mavenProjectsManager, mavenProject, additionalProperties);
        if (resolved == null) {
          out.append(matcher.group());
          continue;
        }

        resolvedProperties.put(propertyName, null);

        StringBuilder sb = new StringBuilder();
        doFilterText(pattern, mavenProjectsManager, mavenProject, resolved, additionalProperties, null, escapeWindowsPath, resolvedProperties, sb);
        propertyValue = sb.toString();

        resolvedProperties.put(propertyName, propertyValue);
      }

      if (escapeWindowsPath) {
        MavenEscapeWindowsCharacterUtils.escapeWindowsPath(out, propertyValue);
      }
      else {
        out.append(propertyValue);
      }
    }
    
    out.append(text, last, text.length());
  }

  public static String resolve(String text, MavenDomProjectModel projectDom) {
    XmlElement element = projectDom.getXmlElement();
    if (element == null) return text;

    VirtualFile file = MavenDomUtil.getVirtualFile(element);
    if (file == null) return text;
    MavenProjectsManager manager = MavenProjectsManager.getInstance(projectDom.getManager().getProject());

    MavenProject mavenProject = manager.findProject(file);
    if (mavenProject == null) return text;

    StringBuilder res = new StringBuilder();
    try {
      doFilterText(PATTERN, manager, mavenProject, text, collectPropertiesFromDOM(mavenProject, projectDom), null, false, null, res);
    }
    catch (IOException e) {
      throw new RuntimeException(e); // never thrown
    }

    return res.toString();
  }

  private static Properties collectPropertiesFromDOM(MavenProject project, MavenDomProjectModel projectDom) {
    Properties result = new Properties();

    collectPropertiesFromDOM(projectDom.getProperties(), result);

    Collection<String> activePropfiles = project.getActivatedProfilesIds();
    for (MavenDomProfile each : projectDom.getProfiles().getProfiles()) {
      XmlTag idTag = each.getId().getXmlTag();
      if (idTag == null || !activePropfiles.contains(idTag.getValue().getTrimmedText())) continue;
      collectPropertiesFromDOM(each.getProperties(), result);
    }

    return result;
  }

  private static void collectPropertiesFromDOM(MavenDomProperties props, Properties result) {
    XmlTag propsTag = props.getXmlTag();
    if (propsTag != null) {
      for (XmlTag each : propsTag.getSubTags()) {
        result.setProperty(each.getName(), each.getValue().getTrimmedText());
      }
    }
  }

  @Nullable
  private static String doResolveProperty(String propName,
                                          MavenProjectsManager projectsManager,
                                          MavenProject mavenProject,
                                          Properties additionalProperties) {
    boolean hasPrefix = false;
    String unprefixed = propName;

    if (propName.startsWith("pom.")) {
      unprefixed = propName.substring("pom.".length());
      hasPrefix = true;
    }
    else if (propName.startsWith("project.")) {
      unprefixed = propName.substring("project.".length());
      hasPrefix = true;
    }

    MavenProject selectedProject = mavenProject;

    while (unprefixed.startsWith("parent.")) {
      MavenId parentId = selectedProject.getParentId();
      if (parentId == null) return null;

      unprefixed = unprefixed.substring("parent.".length());

      if (unprefixed.equals("groupId")) {
        return parentId.getGroupId();
      }
      if (unprefixed.equals("artifactId")) {
        return parentId.getArtifactId();
      }
      if (unprefixed.equals("version")) {
        return parentId.getVersion();
      }

      selectedProject = projectsManager.findProject(parentId);
      if (selectedProject == null) return null;
    }

    if (unprefixed.equals("basedir") || (hasPrefix && mavenProject == selectedProject && unprefixed.equals("baseUri"))) {
      return selectedProject.getDirectory();
    }

    if ("java.home".equals(propName)) {
      String jreDir = MavenUtil.getModuleJreHome(projectsManager, mavenProject);
      if (jreDir != null) {
        return jreDir;
      }
    }

    if ("java.version".equals(propName)) {
      String javaVersion = MavenUtil.getModuleJavaVersion(projectsManager, mavenProject);
      if (javaVersion != null) {
        return javaVersion;
      }
    }

    String result;

    result = MavenUtil.getPropertiesFromMavenOpts().get(propName);
    if (result != null) return result;

    result = MavenServerUtil.collectSystemProperties().getProperty(propName);
    if (result != null) return result;

    result = selectedProject.getModelMap().get(unprefixed);
    if (result != null) return result;

    result = additionalProperties.getProperty(propName);
    if (result != null) return result;

    result = mavenProject.getProperties().getProperty(propName);
    if (result != null) return result;

    if ("settings.localRepository".equals(propName)) {
      return mavenProject.getLocalRepository().getAbsolutePath();
    }

    return null;
  }
}