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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.felix.bundleplugin;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.apache.maven.archiver.ManifestSection;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.archiver.MavenArchiver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.License;
import org.apache.maven.model.Model;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter;
import org.apache.maven.shared.osgi.Maven2OsgiConverter;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import aQute.lib.osgi.Analyzer;
import aQute.lib.osgi.Builder;
import aQute.lib.osgi.Constants;
import aQute.lib.osgi.EmbeddedResource;
import aQute.lib.osgi.FileResource;
import aQute.lib.osgi.Jar;
import aQute.lib.osgi.Processor;
/**
* Create an OSGi bundle from Maven project
*
* @goal bundle
* @phase package
* @requiresDependencyResolution test
* @description build an OSGi bundle jar
* @threadSafe
*/
public class BundlePlugin extends AbstractMojo
{
/**
* Directory where the manifest will be written
*
* @parameter expression="${manifestLocation}" default-value="${project.build.outputDirectory}/META-INF"
*/
protected File manifestLocation;
/**
* File where the BND instructions will be dumped
*
* @parameter expression="${dumpInstructions}"
*/
protected File dumpInstructions;
/**
* File where the BND class-path will be dumped
*
* @parameter expression="${dumpClasspath}"
*/
protected File dumpClasspath;
/**
* When true, unpack the bundle contents to the outputDirectory
*
* @parameter expression="${unpackBundle}"
*/
protected boolean unpackBundle;
/**
* Comma separated list of artifactIds to exclude from the dependency classpath passed to BND (use "true" to exclude everything)
*
* @parameter expression="${excludeDependencies}"
*/
protected String excludeDependencies;
/**
* Classifier type of the bundle to be installed. For example, "jdk14".
* Defaults to none which means this is the project's main bundle.
*
* @parameter
*/
protected String classifier;
/**
* @component
*/
private MavenProjectHelper m_projectHelper;
/**
* @component
*/
private ArchiverManager m_archiverManager;
/**
* @component
*/
private ArtifactHandlerManager m_artifactHandlerManager;
/**
* Project types which this plugin supports.
*
* @parameter
*/
protected List supportedProjectTypes = Arrays.asList( new String[]
{ "jar", "bundle" } );
/**
* The directory for the generated bundles.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File outputDirectory;
/**
* The directory for the generated JAR.
*
* @parameter expression="${project.build.directory}"
* @required
*/
private String buildDirectory;
/**
* The Maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The BND instructions for the bundle.
*
* @parameter
*/
private Map instructions = new LinkedHashMap();
/**
* Use locally patched version for now.
*/
private Maven2OsgiConverter m_maven2OsgiConverter = new DefaultMaven2OsgiConverter();
/**
* The archive configuration to use.
*
* @parameter
*/
private MavenArchiveConfiguration archive; // accessed indirectly in JarPluginConfiguration
/**
* @parameter default-value="${session}"
* @required
* @readonly
*/
private MavenSession m_mavenSession;
private static final String MAVEN_SYMBOLICNAME = "maven-symbolicname";
private static final String MAVEN_RESOURCES = "{maven-resources}";
private static final String LOCAL_PACKAGES = "{local-packages}";
private static final String MAVEN_SOURCES = "{maven-sources}";
private static final String[] EMPTY_STRING_ARRAY =
{};
private static final String[] DEFAULT_INCLUDES =
{ "**/**" };
private static final String NL = System.getProperty( "line.separator" );
protected Maven2OsgiConverter getMaven2OsgiConverter()
{
return m_maven2OsgiConverter;
}
protected void setMaven2OsgiConverter( Maven2OsgiConverter maven2OsgiConverter )
{
m_maven2OsgiConverter = maven2OsgiConverter;
}
protected MavenProject getProject()
{
return project;
}
/**
* @see org.apache.maven.plugin.AbstractMojo#execute()
*/
public void execute() throws MojoExecutionException
{
Properties properties = new Properties();
String projectType = getProject().getArtifact().getType();
// ignore unsupported project types, useful when bundleplugin is configured in parent pom
if ( !supportedProjectTypes.contains( projectType ) )
{
getLog().warn(
"Ignoring project type " + projectType + " - supportedProjectTypes = " + supportedProjectTypes );
return;
}
execute( getProject(), instructions, properties );
}
protected void execute( MavenProject currentProject, Map originalInstructions, Properties properties )
throws MojoExecutionException
{
try
{
execute( currentProject, originalInstructions, properties, getClasspath( currentProject ) );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error calculating classpath for project " + currentProject, e );
}
}
/* transform directives from their XML form to the expected BND syntax (eg. _include becomes -include) */
protected static Map transformDirectives( Map originalInstructions )
{
Map transformedInstructions = new LinkedHashMap();
for ( Iterator i = originalInstructions.entrySet().iterator(); i.hasNext(); )
{
Map.Entry e = ( Map.Entry ) i.next();
String key = ( String ) e.getKey();
if ( key.startsWith( "_" ) )
{
key = "-" + key.substring( 1 );
}
String value = ( String ) e.getValue();
if ( null == value )
{
value = "";
}
else
{
value = value.replaceAll( "\\p{Blank}*[\r\n]\\p{Blank}*", "" );
}
if ( Analyzer.WAB.equals( key ) && value.length() == 0 )
{
// provide useful default
value = "src/main/webapp/";
}
transformedInstructions.put( key, value );
}
return transformedInstructions;
}
protected boolean reportErrors( String prefix, Analyzer analyzer )
{
List errors = analyzer.getErrors();
List warnings = analyzer.getWarnings();
for ( Iterator w = warnings.iterator(); w.hasNext(); )
{
String msg = ( String ) w.next();
getLog().warn( prefix + " : " + msg );
}
boolean hasErrors = false;
String fileNotFound = "Input file does not exist: ";
for ( Iterator e = errors.iterator(); e.hasNext(); )
{
String msg = ( String ) e.next();
if ( msg.startsWith( fileNotFound ) && msg.endsWith( "~" ) )
{
// treat as warning; this error happens when you have duplicate entries in Include-Resource
String duplicate = Processor.removeDuplicateMarker( msg.substring( fileNotFound.length() ) );
getLog().warn( prefix + " : Duplicate path '" + duplicate + "' in Include-Resource" );
}
else
{
getLog().error( prefix + " : " + msg );
hasErrors = true;
}
}
return hasErrors;
}
protected void execute( MavenProject currentProject, Map originalInstructions, Properties properties,
Jar[] classpath ) throws MojoExecutionException
{
try
{
File jarFile = new File( getBuildDirectory(), getBundleName( currentProject ) );
Builder builder = buildOSGiBundle( currentProject, originalInstructions, properties, classpath );
boolean hasErrors = reportErrors( "Bundle " + currentProject.getArtifact(), builder );
if ( hasErrors )
{
String failok = builder.getProperty( "-failok" );
if ( null == failok || "false".equalsIgnoreCase( failok ) )
{
jarFile.delete();
throw new MojoFailureException( "Error(s) found in bundle configuration" );
}
}
// attach bundle to maven project
jarFile.getParentFile().mkdirs();
builder.getJar().write( jarFile );
Artifact mainArtifact = currentProject.getArtifact();
if ( "bundle".equals( mainArtifact.getType() ) )
{
// workaround for MNG-1682: force maven to install artifact using the "jar" handler
mainArtifact.setArtifactHandler( m_artifactHandlerManager.getArtifactHandler( "jar" ) );
}
if ( null == classifier || classifier.trim().length() == 0 )
{
mainArtifact.setFile( jarFile );
}
else
{
m_projectHelper.attachArtifact( currentProject, jarFile, classifier );
}
if ( unpackBundle )
{
unpackBundle( jarFile );
}
if ( manifestLocation != null )
{
File outputFile = new File( manifestLocation, "MANIFEST.MF" );
try
{
Manifest manifest = builder.getJar().getManifest();
ManifestPlugin.writeManifest( manifest, outputFile );
}
catch ( IOException e )
{
getLog().error( "Error trying to write Manifest to file " + outputFile, e );
}
}
// cleanup...
builder.close();
}
catch ( MojoFailureException e )
{
getLog().error( e.getLocalizedMessage() );
throw new MojoExecutionException( "Error(s) found in bundle configuration", e );
}
catch ( Exception e )
{
getLog().error( "An internal error occurred", e );
throw new MojoExecutionException( "Internal error in maven-bundle-plugin", e );
}
}
protected Builder getOSGiBuilder( MavenProject currentProject, Map originalInstructions, Properties properties,
Jar[] classpath ) throws Exception
{
properties.putAll( getDefaultProperties( currentProject ) );
properties.putAll( transformDirectives( originalInstructions ) );
Builder builder = new Builder();
builder.setBase( getBase( currentProject ) );
builder.setProperties( sanitize( properties ) );
if ( classpath != null )
{
builder.setClasspath( classpath );
}
return builder;
}
protected static Properties sanitize( Properties properties )
{
// convert any non-String keys/values to Strings
Properties sanitizedEntries = new Properties();
for ( Iterator itr = properties.entrySet().iterator(); itr.hasNext(); )
{
Map.Entry entry = ( Map.Entry ) itr.next();
if ( entry.getKey() instanceof String == false )
{
String key = sanitize( entry.getKey() );
if ( !properties.containsKey( key ) )
{
sanitizedEntries.setProperty( key, sanitize( entry.getValue() ) );
}
itr.remove();
}
else if ( entry.getValue() instanceof String == false )
{
entry.setValue( sanitize( entry.getValue() ) );
}
}
properties.putAll( sanitizedEntries );
return properties;
}
protected static String sanitize( Object value )
{
if ( value instanceof String )
{
return ( String ) value;
}
else if ( value instanceof Iterable )
{
String delim = "";
StringBuilder buf = new StringBuilder();
for ( Object i : ( Iterable<?> ) value )
{
buf.append( delim ).append( i );
delim = ", ";
}
return buf.toString();
}
else if ( value.getClass().isArray() )
{
String delim = "";
StringBuilder buf = new StringBuilder();
for ( int i = 0, len = Array.getLength( value ); i < len; i++ )
{
buf.append( delim ).append( Array.get( value, i ) );
delim = ", ";
}
return buf.toString();
}
else
{
return String.valueOf( value );
}
}
protected void addMavenInstructions( MavenProject currentProject, Builder builder ) throws Exception
{
if ( currentProject.getBasedir() != null )
{
// update BND instructions to add included Maven resources
includeMavenResources( currentProject, builder, getLog() );
// calculate default export/private settings based on sources
addLocalPackages( outputDirectory, builder );
// tell BND where the current project source resides
addMavenSourcePath( currentProject, builder, getLog() );
}
// update BND instructions to embed selected Maven dependencies
Collection embeddableArtifacts = getEmbeddableArtifacts( currentProject, builder );
new DependencyEmbedder( getLog(), embeddableArtifacts ).processHeaders( builder );
if ( dumpInstructions != null || getLog().isDebugEnabled() )
{
StringBuilder buf = new StringBuilder();
getLog().debug( "BND Instructions:" + NL + dumpInstructions( builder.getProperties(), buf ) );
if ( dumpInstructions != null )
{
getLog().info( "Writing BND instructions to " + dumpInstructions );
dumpInstructions.getParentFile().mkdirs();
FileUtils.fileWrite( dumpInstructions.getAbsolutePath(), "# BND instructions" + NL + buf );
}
}
if ( dumpClasspath != null || getLog().isDebugEnabled() )
{
StringBuilder buf = new StringBuilder();
getLog().debug( "BND Classpath:" + NL + dumpClasspath( builder.getClasspath(), buf ) );
if ( dumpClasspath != null )
{
getLog().info( "Writing BND classpath to " + dumpClasspath );
dumpClasspath.getParentFile().mkdirs();
FileUtils.fileWrite( dumpClasspath.getAbsolutePath(), "# BND classpath" + NL + buf );
}
}
}
protected Builder buildOSGiBundle( MavenProject currentProject, Map originalInstructions, Properties properties,
Jar[] classpath ) throws Exception
{
Builder builder = getOSGiBuilder( currentProject, originalInstructions, properties, classpath );
addMavenInstructions( currentProject, builder );
builder.build();
mergeMavenManifest( currentProject, builder );
return builder;
}
protected static StringBuilder dumpInstructions( Properties properties, StringBuilder buf )
{
try
{
buf.append( "#-----------------------------------------------------------------------" + NL );
Properties stringProperties = new Properties();
for ( Enumeration e = properties.propertyNames(); e.hasMoreElements(); )
{
// we can only store String properties
String key = ( String ) e.nextElement();
String value = properties.getProperty( key );
if ( value != null )
{
stringProperties.setProperty( key, value );
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
stringProperties.store( out, null ); // properties encoding is 8859_1
buf.append( out.toString( "8859_1" ) );
buf.append( "#-----------------------------------------------------------------------" + NL );
}
catch ( Throwable e )
{
// ignore...
}
return buf;
}
protected static StringBuilder dumpClasspath( List classpath, StringBuilder buf )
{
try
{
buf.append( "#-----------------------------------------------------------------------" + NL );
buf.append( "-classpath:\\" + NL );
for ( Iterator i = classpath.iterator(); i.hasNext(); )
{
File path = ( ( Jar ) i.next() ).getSource();
if ( path != null )
{
buf.append( ' ' + path.toString() + ( i.hasNext() ? ",\\" : "" ) + NL );
}
}
buf.append( "#-----------------------------------------------------------------------" + NL );
}
catch ( Throwable e )
{
// ignore...
}
return buf;
}
protected static StringBuilder dumpManifest( Manifest manifest, StringBuilder buf )
{
try
{
buf.append( "#-----------------------------------------------------------------------" + NL );
ByteArrayOutputStream out = new ByteArrayOutputStream();
Jar.writeManifest( manifest, out ); // manifest encoding is UTF8
buf.append( out.toString( "UTF8" ) );
buf.append( "#-----------------------------------------------------------------------" + NL );
}
catch ( Throwable e )
{
// ignore...
}
return buf;
}
protected static void includeMavenResources( MavenProject currentProject, Analyzer analyzer, Log log )
{
// pass maven resource paths onto BND analyzer
final String mavenResourcePaths = getMavenResourcePaths( currentProject );
final String includeResource = ( String ) analyzer.getProperty( Analyzer.INCLUDE_RESOURCE );
if ( includeResource != null )
{
if ( includeResource.indexOf( MAVEN_RESOURCES ) >= 0 )
{
// if there is no maven resource path, we do a special treatment and replace
// every occurance of MAVEN_RESOURCES and a following comma with an empty string
if ( mavenResourcePaths.length() == 0 )
{
String cleanedResource = removeTagFromInstruction( includeResource, MAVEN_RESOURCES );
if ( cleanedResource.length() > 0 )
{
analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, cleanedResource );
}
else
{
analyzer.unsetProperty( Analyzer.INCLUDE_RESOURCE );
}
}
else
{
String combinedResource = StringUtils
.replace( includeResource, MAVEN_RESOURCES, mavenResourcePaths );
analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, combinedResource );
}
}
else if ( mavenResourcePaths.length() > 0 )
{
log.warn( Analyzer.INCLUDE_RESOURCE + ": overriding " + mavenResourcePaths + " with " + includeResource
+ " (add " + MAVEN_RESOURCES + " if you want to include the maven resources)" );
}
}
else if ( mavenResourcePaths.length() > 0 )
{
analyzer.setProperty( Analyzer.INCLUDE_RESOURCE, mavenResourcePaths );
}
}
protected void mergeMavenManifest( MavenProject currentProject, Builder builder ) throws Exception
{
Jar jar = builder.getJar();
if ( getLog().isDebugEnabled() )
{
getLog().debug( "BND Manifest:" + NL + dumpManifest( jar.getManifest(), new StringBuilder() ) );
}
boolean addMavenDescriptor = currentProject.getBasedir() != null;
try
{
/*
* Grab customized manifest entries from the maven-jar-plugin configuration
*/
MavenArchiveConfiguration archiveConfig = JarPluginConfiguration.getArchiveConfiguration( currentProject );
String mavenManifestText = new MavenArchiver().getManifest( currentProject, archiveConfig ).toString();
addMavenDescriptor = addMavenDescriptor && archiveConfig.isAddMavenDescriptor();
Manifest mavenManifest = new Manifest();
// First grab the external manifest file (if specified and different to target location)
File externalManifestFile = archiveConfig.getManifestFile();
if ( null != externalManifestFile && externalManifestFile.exists()
&& !externalManifestFile.equals( new File( manifestLocation, "MANIFEST.MF" ) ) )
{
InputStream mis = new FileInputStream( externalManifestFile );
mavenManifest.read( mis );
mis.close();
}
// Then apply customized entries from the jar plugin; note: manifest encoding is UTF8
mavenManifest.read( new ByteArrayInputStream( mavenManifestText.getBytes( "UTF8" ) ) );
if ( !archiveConfig.isManifestSectionsEmpty() )
{
/*
* Add customized manifest sections (for some reason MavenArchiver doesn't do this for us)
*/
List sections = archiveConfig.getManifestSections();
for ( Iterator i = sections.iterator(); i.hasNext(); )
{
ManifestSection section = ( ManifestSection ) i.next();
Attributes attributes = new Attributes();
if ( !section.isManifestEntriesEmpty() )
{
Map entries = section.getManifestEntries();
for ( Iterator j = entries.entrySet().iterator(); j.hasNext(); )
{
Map.Entry entry = ( Map.Entry ) j.next();
attributes.putValue( ( String ) entry.getKey(), ( String ) entry.getValue() );
}
}
mavenManifest.getEntries().put( section.getName(), attributes );
}
}
Attributes mainMavenAttributes = mavenManifest.getMainAttributes();
mainMavenAttributes.putValue( "Created-By", "Apache Maven Bundle Plugin" );
String[] removeHeaders = builder.getProperty( Constants.REMOVEHEADERS, "" ).split( "," );
// apply -removeheaders to the custom manifest
for ( int i = 0; i < removeHeaders.length; i++ )
{
for ( Iterator j = mainMavenAttributes.keySet().iterator(); j.hasNext(); )
{
if ( j.next().toString().matches( removeHeaders[i].trim() ) )
{
j.remove();
}
}
}
/*
* Overlay generated bundle manifest with customized entries
*/
Manifest bundleManifest = jar.getManifest();
bundleManifest.getMainAttributes().putAll( mainMavenAttributes );
bundleManifest.getEntries().putAll( mavenManifest.getEntries() );
// adjust the import package attributes so that optional dependencies use
// optional resolution.
String importPackages = bundleManifest.getMainAttributes().getValue( "Import-Package" );
if ( importPackages != null )
{
Set optionalPackages = getOptionalPackages( currentProject );
Map<String, Map<String, String>> values = new Analyzer().parseHeader( importPackages );
for ( Map.Entry<String, Map<String, String>> entry : values.entrySet() )
{
String pkg = entry.getKey();
Map<String, String> options = entry.getValue();
if ( !options.containsKey( "resolution:" ) && optionalPackages.contains( pkg ) )
{
options.put( "resolution:", "optional" );
}
}
String result = Processor.printClauses( values );
bundleManifest.getMainAttributes().putValue( "Import-Package", result );
}
jar.setManifest( bundleManifest );
}
catch ( Exception e )
{
getLog().warn( "Unable to merge Maven manifest: " + e.getLocalizedMessage() );
}
if ( addMavenDescriptor )
{
doMavenMetadata( currentProject, jar );
}
if ( getLog().isDebugEnabled() )
{
getLog().debug( "Final Manifest:" + NL + dumpManifest( jar.getManifest(), new StringBuilder() ) );
}
builder.setJar( jar );
}
protected Set getOptionalPackages( MavenProject currentProject ) throws IOException, MojoExecutionException
{
ArrayList inscope = new ArrayList();
final Collection artifacts = getSelectedDependencies( currentProject.getArtifacts() );
for ( Iterator it = artifacts.iterator(); it.hasNext(); )
{
Artifact artifact = ( Artifact ) it.next();
if ( artifact.getArtifactHandler().isAddedToClasspath() )
{
if ( !Artifact.SCOPE_TEST.equals( artifact.getScope() ) )
{
inscope.add( artifact );
}
}
}
HashSet optionalArtifactIds = new HashSet();
for ( Iterator it = inscope.iterator(); it.hasNext(); )
{
Artifact artifact = ( Artifact ) it.next();
if ( artifact.isOptional() )
{
String id = artifact.toString();
if ( artifact.getScope() != null )
{
// strip the scope...
id = id.replaceFirst( ":[^:]*$", "" );
}
optionalArtifactIds.add( id );
}
}
HashSet required = new HashSet();
HashSet optional = new HashSet();
for ( Iterator it = inscope.iterator(); it.hasNext(); )
{
Artifact artifact = ( Artifact ) it.next();
File file = getFile( artifact );
if ( file == null )
{
continue;
}
Jar jar = new Jar( artifact.getArtifactId(), file );
if ( isTransitivelyOptional( optionalArtifactIds, artifact ) )
{
optional.addAll( jar.getPackages() );
}
else
{
required.addAll( jar.getPackages() );
}
jar.close();
}
optional.removeAll( required );
return optional;
}
/**
* Check to see if any dependency along the dependency trail of
* the artifact is optional.
*
* @param artifact
*/
protected boolean isTransitivelyOptional( HashSet optionalArtifactIds, Artifact artifact )
{
List trail = artifact.getDependencyTrail();
for ( Iterator iterator = trail.iterator(); iterator.hasNext(); )
{
String next = ( String ) iterator.next();
if ( optionalArtifactIds.contains( next ) )
{
return true;
}
}
return false;
}
private void unpackBundle( File jarFile )
{
File outputDir = getOutputDirectory();
if ( null == outputDir )
{
outputDir = new File( getBuildDirectory(), "classes" );
}
try
{
/*
* this directory must exist before unpacking, otherwise the plexus
* unarchiver decides to use the current working directory instead!
*/
if ( !outputDir.exists() )
{
outputDir.mkdirs();
}
UnArchiver unArchiver = m_archiverManager.getUnArchiver( "jar" );
unArchiver.setDestDirectory( outputDir );
unArchiver.setSourceFile( jarFile );
unArchiver.extract();
}
catch ( Exception e )
{
getLog().error( "Problem unpacking " + jarFile + " to " + outputDir, e );
}
}
protected static String removeTagFromInstruction( String instruction, String tag )
{
StringBuffer buf = new StringBuffer();
String[] clauses = instruction.split( "," );
for ( int i = 0; i < clauses.length; i++ )
{
String clause = clauses[i].trim();
if ( !tag.equals( clause ) )
{
if ( buf.length() > 0 )
{
buf.append( ',' );
}
buf.append( clause );
}
}
return buf.toString();
}
private static Map getProperties( Model projectModel, String prefix )
{
Map properties = new LinkedHashMap();
Method methods[] = Model.class.getDeclaredMethods();
for ( int i = 0; i < methods.length; i++ )
{
String name = methods[i].getName();
if ( name.startsWith( "get" ) )
{
try
{
Object v = methods[i].invoke( projectModel, null );
if ( v != null )
{
name = prefix + Character.toLowerCase( name.charAt( 3 ) ) + name.substring( 4 );
if ( v.getClass().isArray() )
properties.put( name, Arrays.asList( ( Object[] ) v ).toString() );
else
properties.put( name, v );
}
}
catch ( Exception e )
{
// too bad
}
}
}
return properties;
}
private static StringBuffer printLicenses( List licenses )
{
if ( licenses == null || licenses.size() == 0 )
return null;
StringBuffer sb = new StringBuffer();
String del = "";
for ( Iterator i = licenses.iterator(); i.hasNext(); )
{
License l = ( License ) i.next();
String url = l.getUrl();
if ( url == null )
continue;
sb.append( del );
sb.append( url );
del = ", ";
}
if ( sb.length() == 0 )
return null;
return sb;
}
/**
* @param jar
* @throws IOException
*/
private void doMavenMetadata( MavenProject currentProject, Jar jar ) throws IOException
{
String path = "META-INF/maven/" + currentProject.getGroupId() + "/" + currentProject.getArtifactId();
File pomFile = new File( currentProject.getBasedir(), "pom.xml" );
jar.putResource( path + "/pom.xml", new FileResource( pomFile ) );
Properties p = new Properties();
p.put( "version", currentProject.getVersion() );
p.put( "groupId", currentProject.getGroupId() );
p.put( "artifactId", currentProject.getArtifactId() );
ByteArrayOutputStream out = new ByteArrayOutputStream();
p.store( out, "Generated by org.apache.felix.bundleplugin" );
jar.putResource( path + "/pom.properties", new EmbeddedResource( out.toByteArray(), System.currentTimeMillis() ) );
}
protected Jar[] getClasspath( MavenProject currentProject ) throws IOException, MojoExecutionException
{
List list = new ArrayList();
if ( getOutputDirectory() != null && getOutputDirectory().exists() )
{
list.add( new Jar( ".", getOutputDirectory() ) );
}
final Collection artifacts = getSelectedDependencies( currentProject.getArtifacts() );
for ( Iterator it = artifacts.iterator(); it.hasNext(); )
{
Artifact artifact = ( Artifact ) it.next();
if ( artifact.getArtifactHandler().isAddedToClasspath() )
{
if ( !Artifact.SCOPE_TEST.equals( artifact.getScope() ) )
{
File file = getFile( artifact );
if ( file == null )
{
getLog().warn(
"File is not available for artifact " + artifact + " in project "
+ currentProject.getArtifact() );
continue;
}
Jar jar = new Jar( artifact.getArtifactId(), file );
list.add( jar );
}
}
}
Jar[] cp = new Jar[list.size()];
list.toArray( cp );
return cp;
}
private Collection getSelectedDependencies( Collection artifacts ) throws MojoExecutionException
{
if ( null == excludeDependencies || excludeDependencies.length() == 0 )
{
return artifacts;
}
else if ( "true".equalsIgnoreCase( excludeDependencies ) )
{
return Collections.EMPTY_LIST;
}
Collection selectedDependencies = new LinkedHashSet( artifacts );
DependencyExcluder excluder = new DependencyExcluder( artifacts );
excluder.processHeaders( excludeDependencies );
selectedDependencies.removeAll( excluder.getExcludedArtifacts() );
return selectedDependencies;
}
/**
* Get the file for an Artifact
*
* @param artifact
*/
protected File getFile( Artifact artifact )
{
return artifact.getFile();
}
private static void header( Properties properties, String key, Object value )
{
if ( value == null )
return;
if ( value instanceof Collection && ( ( Collection ) value ).isEmpty() )
return;
properties.put( key, value.toString().replaceAll( "[\r\n]", "" ) );
}
/**
* Convert a Maven version into an OSGi compliant version
*
* @param version Maven version
* @return the OSGi version
*/
protected String convertVersionToOsgi( String version )
{
return getMaven2OsgiConverter().getVersion( version );
}
/**
* TODO this should return getMaven2Osgi().getBundleFileName( project.getArtifact() )
*/
protected String getBundleName( MavenProject currentProject )
{
String extension;
try
{
extension = currentProject.getArtifact().getArtifactHandler().getExtension();
}
catch ( Throwable e )
{
extension = currentProject.getArtifact().getType();
}
if ( StringUtils.isEmpty( extension ) || "bundle".equals( extension ) || "pom".equals( extension ) )
{
extension = "jar"; // just in case maven gets confused
}
String finalName = currentProject.getBuild().getFinalName();
if ( null != classifier && classifier.trim().length() > 0 )
{
return finalName + '-' + classifier + '.' + extension;
}
return finalName + '.' + extension;
}
protected String getBuildDirectory()
{
return buildDirectory;
}
protected void setBuildDirectory( String _buildirectory )
{
buildDirectory = _buildirectory;
}
protected Properties getDefaultProperties( MavenProject currentProject )
{
Properties properties = new Properties();
String bsn;
try
{
bsn = getMaven2OsgiConverter().getBundleSymbolicName( currentProject.getArtifact() );
}
catch ( Exception e )
{
bsn = currentProject.getGroupId() + "." + currentProject.getArtifactId();
}
// Setup defaults
properties.put( MAVEN_SYMBOLICNAME, bsn );
properties.put( Analyzer.BUNDLE_SYMBOLICNAME, bsn );
properties.put( Analyzer.IMPORT_PACKAGE, "*" );
properties.put( Analyzer.BUNDLE_VERSION, getMaven2OsgiConverter().getVersion( currentProject.getVersion() ) );
// remove the extraneous Include-Resource and Private-Package entries from generated manifest
properties.put( Constants.REMOVEHEADERS, Analyzer.INCLUDE_RESOURCE + ',' + Analyzer.PRIVATE_PACKAGE );
header( properties, Analyzer.BUNDLE_DESCRIPTION, currentProject.getDescription() );
StringBuffer licenseText = printLicenses( currentProject.getLicenses() );
if ( licenseText != null )
{
header( properties, Analyzer.BUNDLE_LICENSE, licenseText );
}
header( properties, Analyzer.BUNDLE_NAME, currentProject.getName() );
if ( currentProject.getOrganization() != null )
{
if ( currentProject.getOrganization().getName() != null )
{
String organizationName = currentProject.getOrganization().getName();
header( properties, Analyzer.BUNDLE_VENDOR, organizationName );
properties.put( "project.organization.name", organizationName );
properties.put( "pom.organization.name", organizationName );
}
if ( currentProject.getOrganization().getUrl() != null )
{
String organizationUrl = currentProject.getOrganization().getUrl();
header( properties, Analyzer.BUNDLE_DOCURL, organizationUrl );
properties.put( "project.organization.url", organizationUrl );
properties.put( "pom.organization.url", organizationUrl );
}
}
properties.putAll( currentProject.getProperties() );
properties.putAll( currentProject.getModel().getProperties() );
if ( m_mavenSession != null )
{
try
{
// don't pass upper-case session settings to bnd as they end up in the manifest
Properties sessionProperties = m_mavenSession.getExecutionProperties();
for ( Enumeration e = sessionProperties.propertyNames(); e.hasMoreElements(); )
{
String key = ( String ) e.nextElement();
if ( key.length() > 0 && !Character.isUpperCase( key.charAt( 0 ) ) )
{
properties.put( key, sessionProperties.getProperty( key ) );
}
}
}
catch ( Exception e )
{
getLog().warn( "Problem with Maven session properties: " + e.getLocalizedMessage() );
}
}
properties.putAll( getProperties( currentProject.getModel(), "project.build." ) );
properties.putAll( getProperties( currentProject.getModel(), "pom." ) );
properties.putAll( getProperties( currentProject.getModel(), "project." ) );
properties.put( "project.baseDir", getBase( currentProject ) );
properties.put( "project.build.directory", getBuildDirectory() );
properties.put( "project.build.outputdirectory", getOutputDirectory() );
properties.put( "classifier", classifier == null ? "" : classifier );
return properties;
}
protected static File getBase( MavenProject currentProject )
{
return currentProject.getBasedir() != null ? currentProject.getBasedir() : new File( "" );
}
protected File getOutputDirectory()
{
return outputDirectory;
}
protected void setOutputDirectory( File _outputDirectory )
{
outputDirectory = _outputDirectory;
}
private static void addLocalPackages( File outputDirectory, Analyzer analyzer )
{
Collection packages = new TreeSet();
if ( outputDirectory != null && outputDirectory.isDirectory() )
{
// scan classes directory for potential packages
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( outputDirectory );
scanner.setIncludes( new String[]
{ "**/*.class" } );
scanner.addDefaultExcludes();
scanner.scan();
String[] paths = scanner.getIncludedFiles();
for ( int i = 0; i < paths.length; i++ )
{
packages.add( getPackageName( paths[i] ) );
}
}
StringBuffer exportedPkgs = new StringBuffer();
StringBuffer privatePkgs = new StringBuffer();
boolean noprivatePackages = "!*".equals( analyzer.getProperty( Analyzer.PRIVATE_PACKAGE ) );
for ( Iterator i = packages.iterator(); i.hasNext(); )
{
String pkg = ( String ) i.next();
// mark all source packages as private by default (can be overridden by export list)
if ( privatePkgs.length() > 0 )
{
privatePkgs.append( ';' );
}
privatePkgs.append( pkg );
// we can't export the default package (".") and we shouldn't export internal packages
if ( noprivatePackages || !( ".".equals( pkg ) || pkg.contains( ".internal" ) || pkg.contains( ".impl" ) ) )
{
if ( exportedPkgs.length() > 0 )
{
exportedPkgs.append( ';' );
}
exportedPkgs.append( pkg );
}
}
if ( analyzer.getProperty( Analyzer.EXPORT_PACKAGE ) == null )
{
if ( analyzer.getProperty( Analyzer.EXPORT_CONTENTS ) == null )
{
// no -exportcontents overriding the exports, so use our computed list
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, exportedPkgs + ";-split-package:=merge-first" );
}
else
{
// leave Export-Package empty (but non-null) as we have -exportcontents
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, "" );
}
}
else
{
String exported = analyzer.getProperty( Analyzer.EXPORT_PACKAGE );
if ( exported.indexOf( LOCAL_PACKAGES ) >= 0 )
{
String newExported = StringUtils.replace( exported, LOCAL_PACKAGES, exportedPkgs.toString() );
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, newExported );
}
}
String internal = analyzer.getProperty( Analyzer.PRIVATE_PACKAGE );
if ( internal == null )
{
if ( privatePkgs.length() > 0 )
{
analyzer.setProperty( Analyzer.PRIVATE_PACKAGE, privatePkgs + ";-split-package:=merge-first" );
}
else
{
// if there are really no private packages then use "!*" as this will keep the Bnd Tool happy
analyzer.setProperty( Analyzer.PRIVATE_PACKAGE, "!*" );
}
}
else if ( internal.indexOf( LOCAL_PACKAGES ) >= 0 )
{
String newInternal = StringUtils.replace( internal, LOCAL_PACKAGES, privatePkgs.toString() );
analyzer.setProperty( Analyzer.PRIVATE_PACKAGE, newInternal );
}
}
private static String getPackageName( String filename )
{
int n = filename.lastIndexOf( File.separatorChar );
return n < 0 ? "." : filename.substring( 0, n ).replace( File.separatorChar, '.' );
}
private static List getMavenResources( MavenProject currentProject )
{
List resources = new ArrayList( currentProject.getResources() );
if ( currentProject.getCompileSourceRoots() != null )
{
// also scan for any "packageinfo" files lurking in the source folders
List packageInfoIncludes = Collections.singletonList( "**/packageinfo" );
for ( Iterator i = currentProject.getCompileSourceRoots().iterator(); i.hasNext(); )
{
String sourceRoot = ( String ) i.next();
Resource packageInfoResource = new Resource();
packageInfoResource.setDirectory( sourceRoot );
packageInfoResource.setIncludes( packageInfoIncludes );
resources.add( packageInfoResource );
}
}
return resources;
}
protected static String getMavenResourcePaths( MavenProject currentProject )
{
final String basePath = currentProject.getBasedir().getAbsolutePath();
Set pathSet = new LinkedHashSet();
for ( Iterator i = getMavenResources( currentProject ).iterator(); i.hasNext(); )
{
Resource resource = ( Resource ) i.next();
final String sourcePath = resource.getDirectory();
final String targetPath = resource.getTargetPath();
// ignore empty or non-local resources
if ( new File( sourcePath ).exists() && ( ( targetPath == null ) || ( targetPath.indexOf( ".." ) < 0 ) ) )
{
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( sourcePath );
if ( resource.getIncludes() != null && !resource.getIncludes().isEmpty() )
{
scanner.setIncludes( ( String[] ) resource.getIncludes().toArray( EMPTY_STRING_ARRAY ) );
}
else
{
scanner.setIncludes( DEFAULT_INCLUDES );
}
if ( resource.getExcludes() != null && !resource.getExcludes().isEmpty() )
{
scanner.setExcludes( ( String[] ) resource.getExcludes().toArray( EMPTY_STRING_ARRAY ) );
}
scanner.addDefaultExcludes();
scanner.scan();
List includedFiles = Arrays.asList( scanner.getIncludedFiles() );
for ( Iterator j = includedFiles.iterator(); j.hasNext(); )
{
String name = ( String ) j.next();
String path = sourcePath + '/' + name;
// make relative to project
if ( path.startsWith( basePath ) )
{
if ( path.length() == basePath.length() )
{
path = ".";
}
else
{
path = path.substring( basePath.length() + 1 );
}
}
// replace windows backslash with a slash
// this is a workaround for a problem with bnd 0.0.189
if ( File.separatorChar != '/' )
{
name = name.replace( File.separatorChar, '/' );
path = path.replace( File.separatorChar, '/' );
}
// copy to correct place
path = name + '=' + path;
if ( targetPath != null )
{
path = targetPath + '/' + path;
}
// use Bnd filtering?
if ( resource.isFiltering() )
{
path = '{' + path + '}';
}
pathSet.add( path );
}
}
}
StringBuffer resourcePaths = new StringBuffer();
for ( Iterator i = pathSet.iterator(); i.hasNext(); )
{
resourcePaths.append( i.next() );
if ( i.hasNext() )
{
resourcePaths.append( ',' );
}
}
return resourcePaths.toString();
}
protected Collection getEmbeddableArtifacts( MavenProject currentProject, Analyzer analyzer )
throws MojoExecutionException
{
final Collection artifacts;
String embedTransitive = analyzer.getProperty( DependencyEmbedder.EMBED_TRANSITIVE );
if ( Boolean.valueOf( embedTransitive ).booleanValue() )
{
// includes transitive dependencies
artifacts = currentProject.getArtifacts();
}
else
{
// only includes direct dependencies
artifacts = currentProject.getDependencyArtifacts();
}
return getSelectedDependencies( artifacts );
}
protected static void addMavenSourcePath( MavenProject currentProject, Analyzer analyzer, Log log )
{
// pass maven source paths onto BND analyzer
StringBuilder mavenSourcePaths = new StringBuilder();
if ( currentProject.getCompileSourceRoots() != null )
{
for ( Iterator i = currentProject.getCompileSourceRoots().iterator(); i.hasNext(); )
{
if ( mavenSourcePaths.length() > 0 )
{
mavenSourcePaths.append( ',' );
}
mavenSourcePaths.append( ( String ) i.next() );
}
}
final String sourcePath = ( String ) analyzer.getProperty( Analyzer.SOURCEPATH );
if ( sourcePath != null )
{
if ( sourcePath.indexOf( MAVEN_SOURCES ) >= 0 )
{
// if there is no maven source path, we do a special treatment and replace
// every occurance of MAVEN_SOURCES and a following comma with an empty string
if ( mavenSourcePaths.length() == 0 )
{
String cleanedSource = removeTagFromInstruction( sourcePath, MAVEN_SOURCES );
if ( cleanedSource.length() > 0 )
{
analyzer.setProperty( Analyzer.SOURCEPATH, cleanedSource );
}
else
{
analyzer.unsetProperty( Analyzer.SOURCEPATH );
}
}
else
{
String combinedSource = StringUtils
.replace( sourcePath, MAVEN_SOURCES, mavenSourcePaths.toString() );
analyzer.setProperty( Analyzer.SOURCEPATH, combinedSource );
}
}
else if ( mavenSourcePaths.length() > 0 )
{
log.warn( Analyzer.SOURCEPATH + ": overriding " + mavenSourcePaths + " with " + sourcePath + " (add "
+ MAVEN_SOURCES + " if you want to include the maven sources)" );
}
}
else if ( mavenSourcePaths.length() > 0 )
{
analyzer.setProperty( Analyzer.SOURCEPATH, mavenSourcePaths.toString() );
}
}
}
|