1 19 20 package org.netbeans.modules.projectimport.j2seimport; 21 22 import java.io.File ; 23 import java.io.IOException ; 24 import java.net.URL ; 25 import java.util.ArrayList ; 26 import java.util.Collection ; 27 import java.util.HashMap ; 28 import java.util.Iterator ; 29 import java.util.List ; 30 import java.util.Map ; 31 import java.util.logging.Logger ; 32 import org.netbeans.api.java.platform.JavaPlatform; 33 import org.netbeans.api.java.platform.JavaPlatformManager; 34 import org.netbeans.api.java.project.JavaProjectConstants; 35 import org.netbeans.api.progress.ProgressHandle; 36 import org.netbeans.api.progress.ProgressHandleFactory; 37 import org.netbeans.api.project.Project; 38 import org.netbeans.api.project.ProjectManager; 39 import org.netbeans.api.project.ant.AntArtifact; 40 import org.netbeans.api.project.ant.AntArtifactQuery; 41 import org.netbeans.modules.java.j2seplatform.platformdefinition.PlatformConvertor; 42 import org.netbeans.modules.java.j2seplatform.wizard.NewJ2SEPlatform; 43 import org.netbeans.modules.java.j2seproject.J2SEProject; 44 import org.netbeans.modules.java.j2seproject.J2SEProjectGenerator; 45 import org.netbeans.modules.java.j2seproject.J2SEProjectType; 46 import org.netbeans.modules.java.j2seproject.SourceRoots; 47 import org.netbeans.modules.java.j2seproject.ui.customizer.J2SEProjectProperties; 48 import org.netbeans.spi.java.project.classpath.ProjectClassPathExtender; 49 import org.netbeans.spi.project.support.ant.AntProjectHelper; 50 import org.netbeans.spi.project.support.ant.EditableProperties; 51 import org.netbeans.spi.project.support.ant.PropertyUtils; 52 import org.openide.filesystems.FileObject; 53 import org.openide.filesystems.FileUtil; 54 import org.openide.filesystems.Repository; 55 import org.openide.loaders.DataFolder; 56 import org.openide.loaders.DataObject; 57 import org.openide.util.NbBundle; 58 import org.openide.util.RequestProcessor; 59 import org.w3c.dom.Element ; 60 61 62 66 public final class ImportUtils { 67 public static final Logger logger = 68 LoggerFactory.getDefault().createLogger(ImportUtils.class); 69 70 ImportProcessImpl importProcess = null; 71 72 73 public static final ImportProcess createImportProcess(final FileObject projectDirectory, 74 final Collection allPrjDefs, boolean includeDependencies) { 75 return new ImportProcessImpl(projectDirectory, allPrjDefs, includeDependencies); 76 } 77 78 public static ImportUtils createInstance() { 80 return new ImportUtils(); 81 } 82 83 84 public final void importAllProjects(final FileObject projectDirectory, 85 final Collection allPrjDefs, WarningContainer warnings, boolean includeDependencies) throws IOException { 86 for (Iterator it = allPrjDefs.iterator(); it.hasNext();) { 87 ProjectModel projectDefinition = (ProjectModel)it.next(); 88 FileObject importLocation = FileUtil.createFolder(projectDirectory, projectDefinition.getName()); 89 if (includeDependencies) { 90 importProject(importLocation, projectDefinition, warnings, false); 91 } else { 92 J2SEProject nbProject = importProjectWithoutDependencies(importLocation, projectDefinition, warnings, false); 93 ProjectManager.getDefault().saveProject(nbProject); 94 } 95 } 96 } 97 98 99 public final J2SEProject importProject(final FileObject projectDirectory, 100 final ProjectModel projectDefinition, WarningContainer warnings, boolean isDependency) throws IOException { 101 102 J2SEProject nbProject = importProjectWithoutDependencies(projectDirectory, projectDefinition, warnings, isDependency); 103 104 for (Iterator it = projectDefinition.getDependencies().iterator(); it.hasNext();) { 105 ProjectModel subPrjDef = (ProjectModel)it.next(); 106 FileObject importLocation = FileUtil.createFolder(projectDirectory.getParent(), subPrjDef.getName()); 107 J2SEProject subJ2SEProject = importProject(importLocation, subPrjDef, warnings, true); 108 addDependency(nbProject, subJ2SEProject); 109 } 110 111 112 ProjectManager.getDefault().saveProject(nbProject); 113 return nbProject; 114 } 115 116 117 public final J2SEProject importProjectWithoutDependencies(final FileObject projectDirectory, 118 final ProjectModel projectDefinition, WarningContainer warnings, boolean isDependency) throws IOException { 119 120 J2SEProject nbProject = null; 121 { 122 Project prj = ProjectManager.getDefault().findProject(projectDirectory); 123 if (prj != null) { 124 if (prj instanceof J2SEProject) { 125 nbProject = (J2SEProject)prj; 126 logger.warning("Project already exists: " + projectDirectory.getPath()); 127 } else { 128 throw new IllegalStateException (); 129 } 130 } 131 } 132 133 if (nbProject == null) { 134 if (!projectDirectory.isFolder()) { 135 throw new IllegalArgumentException (); } 137 File [] srcFiles = getSourceRoots(projectDefinition); 138 File destination = FileUtil.toFile(projectDirectory); 139 140 if (!isDependency) { 141 addProgresInfo(projectDefinition.getName()); 142 } 143 AntProjectHelper helper = J2SEProjectGenerator.createProject(destination, projectDefinition.getName(), srcFiles, new File []{}, null); 144 145 assert helper != null; 146 nbProject = (J2SEProject)ProjectManager.getDefault().findProject(projectDirectory); 147 assert nbProject != null; 148 149 150 if (!isDependency) { 151 addProgresInfo(projectDefinition.getName()); 152 } 153 154 warnings.addAll(addSourceRoots(projectDefinition, nbProject)); 156 157 158 if (!isDependency) { 159 addProgresInfo(projectDefinition.getName()); 160 } 161 try { 163 warnings.addAll(addLibraries(projectDefinition, nbProject)); 164 } catch(IOException iex) { 165 ImportUtils.addWarning(warnings, iex.getLocalizedMessage()); 166 } 167 168 169 if (!isDependency) { 170 addProgresInfo(projectDefinition.getName()); 171 } 172 try { 174 warnings.addAll(addUserLibraries(projectDefinition, nbProject)); 175 } catch(IOException iex) { 176 ImportUtils.addWarning(warnings, iex.getLocalizedMessage()); 177 } 178 179 if (!isDependency) { 180 addProgresInfo(projectDefinition.getName()); 181 } 182 if (projectDefinition.getJDKDirectory() != null) { 183 warnings.addAll(addJavaPlatform(projectDefinition, helper)); 184 } 185 186 187 if (importProcess != null) { 188 importProcess.addWarnings(projectDefinition.getWarnings()); 189 importProcess.addProjectToOpen(nbProject); 190 } 191 192 193 } 194 return nbProject; 195 } 196 197 private WarningContainer addJavaPlatform(final ProjectModel prjDefinition, 198 final AntProjectHelper helper) { 199 200 WarningContainer warnings = new WarningContainer(); 201 JavaPlatform platform = null; 202 203 if (JavaPlatformManager.getDefault() == null) { 204 ImportUtils.addWarning(warnings,"critical error: default platform manager isn't reachable"); return warnings; 206 } 207 208 { 209 JavaPlatform defaultPlatform = JavaPlatformManager.getDefault().getDefaultPlatform(); 210 if (defaultPlatform != null && isRepresentationOfPlatform( 211 defaultPlatform,prjDefinition.getJDKDirectory(), warnings)) { 212 return warnings; 214 } 215 } 216 217 JavaPlatform[] platforms = JavaPlatformManager.getDefault().getInstalledPlatforms(); 218 for (int i = 0; i < platforms.length; i++) { 219 if (isRepresentationOfPlatform(platforms[i],prjDefinition.getJDKDirectory(), warnings)) { 220 platform = platforms[i]; 221 break; 222 } 223 } 224 225 if (platform == null) { 226 try{ 227 platform = createNewJavaPlatform(prjDefinition, warnings); 228 } catch(IOException iex) { 229 ImportUtils.addWarning(warnings,iex.getLocalizedMessage()); 230 } 231 } 232 233 if (platform != null) { 234 setJavaPlatform(platform, helper); 235 } else { 236 ImportUtils.addWarning(warnings,"Setting of platform for project \"" + prjDefinition.getName() + "\" failed."); } 239 240 return warnings; 241 } 242 243 private void setJavaPlatform(final JavaPlatform platform, final AntProjectHelper helper) { 244 Element pcd = helper.getPrimaryConfigurationData(true); 245 Element el = pcd.getOwnerDocument().createElementNS(J2SEProjectType.PROJECT_CONFIGURATION_NAMESPACE, 246 "explicit-platform"); 248 pcd.appendChild(el); 249 helper.putPrimaryConfigurationData(pcd, true); 250 EditableProperties prop = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH); 251 String ver = platform.getSpecification().getVersion().toString(); 252 String normalizedName = (String )platform.getProperties().get("platform.ant.name"); 254 prop.setProperty(J2SEProjectProperties.JAVAC_SOURCE, ver); 255 prop.setProperty(J2SEProjectProperties.JAVAC_TARGET, ver); 256 prop.setProperty(J2SEProjectProperties.JAVA_PLATFORM, normalizedName); 257 helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, prop); 258 } 259 260 private JavaPlatform createNewJavaPlatform(final ProjectModel prjDefinition, 261 final WarningContainer warnings) throws IOException { 262 JavaPlatform retVal = null; 263 FileObject foForJDKDirectory = FileUtil.toFileObject(prjDefinition.getJDKDirectory()); 264 265 if (foForJDKDirectory == null) { 266 addWarning(warnings, NbBundle.getMessage(ImportUtils.class, "MSG_JDKDoesnExistUseDefault", prjDefinition.getName(), prjDefinition.getJDKDirectory().getAbsolutePath()) ); 268 269 return null; 270 } 271 272 JavaPlatform[] installedPlatforms = JavaPlatformManager.getDefault().getInstalledPlatforms(); 273 NewJ2SEPlatform platform = NewJ2SEPlatform.create(foForJDKDirectory); 274 platform.run(); 275 276 if (platform.isValid() && platform.findTool("javac")!= null) { platform.setDisplayName(createPlatformDisplayName(platform)); 278 platform.setAntName(createPlatformAntName(platform.getDisplayName(), installedPlatforms)); 279 280 FileObject platformsFolder = Repository.getDefault().getDefaultFileSystem().findResource( 281 "Services/Platforms/org-netbeans-api-java-Platform"); assert platformsFolder != null; 283 284 DataObject dobj = PlatformConvertor.create(platform, 285 DataFolder.findFolder(platformsFolder), platform.getAntName()); 286 287 retVal = (JavaPlatform) dobj.getNodeDelegate().getLookup().lookup(JavaPlatform.class); 288 289 JavaPlatformManager.getDefault().getInstalledPlatforms(); 291 } 292 293 return retVal; 294 } 295 296 private String createPlatformDisplayName(JavaPlatform plat) { 297 Map m = plat.getSystemProperties(); 298 String vmName = (String )m.get("java.vm.name"); String vmVersion = (String )m.get("java.vm.version"); StringBuffer displayName = new StringBuffer (); 301 if (vmName != null) 302 displayName.append(vmName); 303 if (vmVersion != null) { 304 if (displayName.length()>0) { 305 displayName.append(" "); 306 } 307 displayName.append(vmVersion); 308 } 309 return displayName.toString(); 310 } 311 312 private String createPlatformAntName(String displayName, JavaPlatform[] installedPlatforms) { 313 assert displayName != null && displayName.length() > 0; 314 String antName = PropertyUtils.getUsablePropertyName(displayName); 315 if (platformExists(antName,installedPlatforms)) { 316 String baseName = antName; 317 int index = 1; 318 antName = baseName + Integer.toString(index); 319 while (platformExists(antName,installedPlatforms)) { 320 index ++; 321 antName = baseName + Integer.toString(index); 322 } 323 } 324 return antName; 325 } 326 327 330 private boolean platformExists(String antName, JavaPlatform[] installedPlatforms) { 331 assert antName != null && antName.length() > 0; 332 for (int i=0; i< installedPlatforms.length; i++) { 333 String otherName = (String ) installedPlatforms[i].getProperties().get("platform.ant.name"); if (antName.equals(otherName)) { 335 return true; 336 } 337 } 338 return false; 339 } 340 341 private boolean isRepresentationOfPlatform(final JavaPlatform platform, 342 final File jdkDirectory, final WarningContainer warnings) { 343 Collection installFolders = platform.getInstallFolders(); 344 345 boolean invalidDefaultPlatform = installFolders.isEmpty(); 347 348 if (invalidDefaultPlatform) { 349 addWarning(warnings, NbBundle.getMessage(ImportUtils.class, "MSG_NotValidPlatformsInNB")); } 351 352 return invalidDefaultPlatform ? false : 353 jdkDirectory.equals(FileUtil.toFile((FileObject) installFolders.toArray()[0])); 354 } 355 356 357 public void addDependency(final J2SEProject nbProject, 358 final J2SEProject nbSubProject) throws IOException { 359 ProjectClassPathExtender nbClsPath = (ProjectClassPathExtender) 360 nbProject.getLookup().lookup(ProjectClassPathExtender.class); 361 362 AntArtifact[] artifact = AntArtifactQuery.findArtifactsByType(nbSubProject, 363 JavaProjectConstants.ARTIFACT_TYPE_JAR); 364 365 nbClsPath.addAntArtifact(artifact[0], artifact[0].getArtifactLocations()[0]); 366 } 367 368 private WarningContainer addSourceRoots(final ProjectModel projectDefinition, 369 final J2SEProject nbProject) { 370 371 SourceRoots roots = nbProject.getSourceRoots(); 372 URL [] rootURLs = roots.getRootURLs(); 373 String [] labels = new String [rootURLs.length]; 374 Map srcRoots2import = new HashMap (); 375 376 for (Iterator it = projectDefinition.getSourceRoots().iterator(); it.hasNext(); ) { 377 ProjectModel.SourceRoot srcEntry = (ProjectModel.SourceRoot)it.next(); 378 File srcFolder = FileUtil.normalizeFile(srcEntry.getDirectory()); 379 srcRoots2import.put(srcFolder, srcEntry.getLabel()); 381 } 382 383 for (int i = 0; i < rootURLs.length; i++) { 384 File f = new File (rootURLs[i].getFile()); 385 String lb = (String ) srcRoots2import.get(f); 386 labels[i] = (lb != null) ? lb :f.getName(); 387 } 389 390 roots.putRoots(rootURLs, labels); 391 return WarningContainer.EMPTY; 392 } 393 394 395 396 private WarningContainer addUserLibraries( 397 final ProjectModel projectDefinition, final J2SEProject nbProject) throws IOException { 398 399 WarningContainer warnings = new WarningContainer(); 400 401 for (Iterator it = projectDefinition.getUserLibraries().iterator(); it.hasNext();) { 402 ProjectModel.UserLibrary userLibrary = (ProjectModel.UserLibrary)it.next(); 403 ProjectClassPathExtender nbClsPath = (ProjectClassPathExtender) nbProject.getLookup().lookup(ProjectClassPathExtender.class); 404 assert nbClsPath != null; 405 List allLibs = getAllLibraries(null, userLibrary); 406 407 for (Iterator itUL = allLibs.iterator(); itUL.hasNext();) { 408 ProjectModel.Library lEntry = (ProjectModel.Library)itUL.next(); 409 try { 410 warnings.addAll(addLibrary(nbClsPath, lEntry, projectDefinition)); 411 } catch(IOException iex) { 412 ImportUtils.addWarning(warnings,iex.getLocalizedMessage()); 413 } 414 415 } 416 } 417 418 419 return warnings; 420 } 421 422 private List getAllLibraries(List allLibs, final ProjectModel.UserLibrary userLibrary) { 423 allLibs = (allLibs == null) ? new ArrayList () : allLibs; 424 allLibs.addAll(userLibrary.getLibraries()); 425 for (Iterator it = userLibrary.getDependencies().iterator(); it.hasNext();) { 426 ProjectModel.UserLibrary uLDep = (ProjectModel.UserLibrary) it.next(); 427 getAllLibraries(allLibs, uLDep); 428 } 429 return allLibs; 430 } 431 432 private WarningContainer addLibraries(final ProjectModel projectDefinition, 433 final J2SEProject nbProject) throws IOException { 434 435 WarningContainer warnings = new WarningContainer(); 436 ProjectClassPathExtender nbClsPath = (ProjectClassPathExtender) nbProject.getLookup().lookup(ProjectClassPathExtender.class); 437 assert nbClsPath != null; 438 439 for (Iterator it = projectDefinition.getLibraries().iterator(); it.hasNext();) { 440 ProjectModel.Library lEntry = (ProjectModel.Library)it.next(); 441 try { 442 warnings.addAll(addLibrary(nbClsPath, lEntry, projectDefinition)); 443 } catch(IOException iex) { 444 ImportUtils.addWarning(warnings,iex.getLocalizedMessage()); 445 } 446 } 447 448 return warnings; 449 } 450 451 452 private WarningContainer addLibrary(final ProjectClassPathExtender nbClsPath, 453 final ProjectModel.Library lEntry, final ProjectModel projectDefinition) throws IOException { 454 WarningContainer warnings = new WarningContainer(); 455 FileObject archiv = FileUtil.toFileObject(lEntry.getArchiv()); 456 457 nbClsPath.addArchiveFile(archiv); 458 return warnings; 459 } 460 461 462 private static void addWarning(final WarningContainer warnings, final String warning) { 463 StringBuffer sbuf = new StringBuffer (NbBundle.getMessage(ImportUtils.class, "MSG_ImportWarning")); sbuf.append(" ").append(warning); 466 String warningPlusPrefix = sbuf.toString(); 467 warnings.add(warningPlusPrefix, false); 468 logger.warning(warningPlusPrefix); 469 } 470 471 private File [] getSourceRoots(final ProjectModel projectDefinition) { 472 Collection sourceRootEntries = projectDefinition.getSourceRoots(); 473 File [] retVal = new File [sourceRootEntries.size()]; 474 475 int i = 0; 476 for (Iterator it = sourceRootEntries.iterator(); it.hasNext();i++) { 477 ProjectModel.SourceRoot entry = (ProjectModel.SourceRoot)it.next(); 478 retVal[i] = entry.getDirectory(); 479 } 480 481 return retVal; 482 } 483 484 private void addProgresInfo(String projectName) { 485 if (importProcess != null) { 486 importProcess.increase(); 487 int step = importProcess.getCurrentStep(); 488 int idx = (step % ImportProcessImpl.PROGRESS_MESSAGES.length); 489 importProcess.setCurrentStatus(NbBundle.getMessage(ImportUtils.class, ImportProcessImpl.PROGRESS_MESSAGES[idx],projectName)); 490 logger.fine(importProcess.toString()); 491 } 492 } 493 494 495 496 private ImportUtils() {} 497 498 private static final class ImportProcessImpl implements ImportProcess { 499 final int numberOfSteps; 500 int currentStep = -1; 501 boolean isFinished; 502 String currentStatus = ""; final FileObject projectDirectory; 504 final Collection allPrjDefs; 505 final WarningContainer warnings; 506 final ImportUtils importer; 507 Collection projectsToOpen; 508 final ProgressHandle ph; 509 boolean includeDependencies; 510 static final String [] PROGRESS_MESSAGES = new String [] {"PRGS_ProjectImportStarted", 511 "PRGS_ImportSourceRoots", 512 "PRGS_ImportLibraries", 513 "PRGS_ImportUserLibraries", 514 "PRGS_ImportPlatform" 515 }; 516 517 private ImportProcessImpl(final FileObject projectDirectory, 518 final Collection allPrjDefs, boolean includeDependencies) { 519 this.projectDirectory = projectDirectory; 520 this.allPrjDefs = allPrjDefs; 521 this.warnings = new WarningContainer(); 522 this.importer = ImportUtils.createInstance(); 523 this.importer.importProcess = this; 524 this.numberOfSteps = allPrjDefs.size()*PROGRESS_MESSAGES.length; 525 projectsToOpen = new ArrayList (); 526 this.includeDependencies = includeDependencies; 527 this.ph = ProgressHandleFactory.createHandle(projectDirectory.getPath()); assert this.ph != null; 529 } 530 531 public synchronized int getNumberOfSteps() { 532 return numberOfSteps; 533 } 534 535 public synchronized int getCurrentStep() { 536 return currentStep; 537 } 538 539 public synchronized String getCurrentStatus() { 540 return currentStatus; 541 } 542 543 private synchronized void setCurrentStatus(String currentStatus) { 544 this.currentStatus = currentStatus; 545 } 546 547 548 public void startImport(boolean asynchronous) { 549 if (isFinished()) { 550 throw new IllegalStateException (); 551 } 552 553 ph.start(getNumberOfSteps()); 554 if (asynchronous) { 555 RequestProcessor.getDefault().post(new Runnable () { 556 public void run() { 557 ProjectManager.mutex().writeAccess(new Runnable () { 558 public void run() { 559 startImport(); 560 } 561 }); 562 } 563 }); 564 565 } else { 566 ProjectManager.mutex().writeAccess(new Runnable () { 567 public void run() { 568 startImport(); 569 }}); 570 } 571 } 572 573 private void startImport() { 574 increase(); 575 try { 576 importer.importAllProjects(projectDirectory, allPrjDefs, 577 warnings, includeDependencies); 578 } catch(IOException iex) { 579 addWarning(warnings, iex.getLocalizedMessage()); 581 } finally { 582 setFinished(); 583 } 584 } 585 586 public synchronized boolean isFinished() { 587 return isFinished; 588 } 589 590 private synchronized void increase() { 591 assert currentStep <= numberOfSteps; 592 593 this.currentStep = this.currentStep+1; 594 ph.progress(getCurrentStatus(),this.currentStep); 595 } 596 597 private synchronized void setFinished() { 598 ph.finish(); 599 currentStep = numberOfSteps; 600 isFinished = true; 601 } 602 603 public synchronized WarningContainer getWarnings() { 604 return warnings; 605 } 606 607 private synchronized void addWarnings(WarningContainer warnings) { 608 this.warnings.addAll(warnings); 609 } 610 611 public synchronized String toString() { 612 StringBuffer sb = new StringBuffer (); 613 sb.append("current step: ").append(new Integer (getCurrentStep()).toString()). append(" from: ").append(getNumberOfSteps()).append(" current info: ").append(getCurrentStatus()); return sb.toString(); 616 } 617 618 private void addProjectToOpen(Project prj) { 619 projectsToOpen.add(prj); 620 } 621 622 public Project[] getProjectsToOpen() { 623 return (Project[])projectsToOpen.toArray(new Project[projectsToOpen.size()]); 624 } 625 626 public ProgressHandle getProgressHandle() { 627 return ph; 628 } 629 } 630 } 631 | Popular Tags |