1 17 package org.eclipse.emf.codegen.ecore.genmodel.impl; 18 19 20 import java.io.ByteArrayInputStream ; 21 import java.io.ByteArrayOutputStream ; 22 import java.io.DataInputStream ; 23 import java.io.DataOutputStream ; 24 import java.io.IOException ; 25 import java.io.InputStream ; 26 import java.text.MessageFormat ; 27 import java.util.ArrayList ; 28 import java.util.Arrays ; 29 import java.util.Collection ; 30 import java.util.Collections ; 31 import java.util.HashMap ; 32 import java.util.HashSet ; 33 import java.util.Iterator ; 34 import java.util.List ; 35 import java.util.Map ; 36 import java.util.Set ; 37 38 import org.eclipse.core.resources.IContainer; 39 import org.eclipse.core.resources.IFile; 40 import org.eclipse.core.resources.IFolder; 41 import org.eclipse.core.resources.IProject; 42 import org.eclipse.core.resources.IWorkspace; 43 import org.eclipse.core.resources.ResourceAttributes; 44 import org.eclipse.core.resources.ResourcesPlugin; 45 import org.eclipse.core.runtime.CoreException; 46 import org.eclipse.core.runtime.IPath; 47 import org.eclipse.core.runtime.IProgressMonitor; 48 import org.eclipse.core.runtime.Path; 49 import org.eclipse.core.runtime.SubProgressMonitor; 50 import org.eclipse.jdt.core.IJavaProject; 51 import org.eclipse.jdt.core.JavaCore; 52 import org.eclipse.jdt.core.formatter.CodeFormatter; 53 import org.eclipse.jface.text.Document; 54 import org.eclipse.jface.text.IDocument; 55 import org.eclipse.text.edits.TextEdit; 56 57 import org.eclipse.emf.codegen.ecore.CodeGenEcorePlugin; 58 import org.eclipse.emf.codegen.ecore.Generator; 59 import org.eclipse.emf.codegen.ecore.genmodel.GenBase; 60 import org.eclipse.emf.codegen.ecore.genmodel.GenClass; 61 import org.eclipse.emf.codegen.ecore.genmodel.GenClassifier; 62 import org.eclipse.emf.codegen.ecore.genmodel.GenDataType; 63 import org.eclipse.emf.codegen.ecore.genmodel.GenEnum; 64 import org.eclipse.emf.codegen.ecore.genmodel.GenFeature; 65 import org.eclipse.emf.codegen.ecore.genmodel.GenModel; 66 import org.eclipse.emf.codegen.ecore.genmodel.GenModelPackage; 67 import org.eclipse.emf.codegen.ecore.genmodel.GenOperation; 68 import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; 69 import org.eclipse.emf.codegen.jet.JETCompiler; 70 import org.eclipse.emf.codegen.jet.JETEmitter; 71 import org.eclipse.emf.codegen.jet.JETException; 72 import org.eclipse.emf.codegen.jmerge.JMerger; 73 import org.eclipse.emf.codegen.jmerge.PropertyMerger; 74 import org.eclipse.emf.codegen.util.CodeGenUtil; 75 import org.eclipse.emf.codegen.util.ImportManager; 76 import org.eclipse.emf.common.util.URI; 77 import org.eclipse.emf.common.util.UniqueEList; 78 import org.eclipse.emf.common.util.WrappedException; 79 import org.eclipse.emf.ecore.EAnnotation; 80 import org.eclipse.emf.ecore.EClass; 81 import org.eclipse.emf.ecore.EClassifier; 82 import org.eclipse.emf.ecore.EDataType; 83 import org.eclipse.emf.ecore.EEnum; 84 import org.eclipse.emf.ecore.EModelElement; 85 import org.eclipse.emf.ecore.ENamedElement; 86 import org.eclipse.emf.ecore.EObject; 87 import org.eclipse.emf.ecore.EOperation; 88 import org.eclipse.emf.ecore.EPackage; 89 import org.eclipse.emf.ecore.EParameter; 90 import org.eclipse.emf.ecore.EStructuralFeature; 91 import org.eclipse.emf.ecore.EcorePackage; 92 import org.eclipse.emf.ecore.impl.EObjectImpl; 93 import org.eclipse.emf.ecore.util.EcoreUtil; 94 import org.eclipse.emf.ecore.util.ExtendedMetaData; 95 import org.eclipse.emf.ecore.xml.namespace.XMLNamespacePackage; 96 import org.eclipse.emf.ecore.xml.type.XMLTypePackage; 97 98 99 108 public abstract class GenBaseImpl extends EObjectImpl implements GenBase 109 { 110 115 protected GenBaseImpl() 116 { 117 super(); 118 } 119 120 125 protected EClass eStaticClass() 126 { 127 return GenModelPackage.eINSTANCE.getGenBase(); 128 } 129 130 public GenModel getGenModel() 131 { 132 if (this instanceof GenModel) 133 return (GenModel)this; 134 else 135 return ((GenBase)eContainer()).getGenModel(); 136 } 137 138 public abstract String getName(); 139 140 public String capName(String name) 141 { 142 return CodeGenUtil.capName(name); 143 } 144 145 public String uncapName(String name) 146 { 147 return CodeGenUtil.uncapName(name); 148 } 149 150 public String uncapPrefixedName(String name) 151 { 152 return CodeGenUtil.uncapPrefixedName(name, false); 153 154 } 155 156 public String uncapPrefixedName(String name, boolean forceDifferent) 157 { 158 return CodeGenUtil.uncapPrefixedName(name, forceDifferent); 159 } 160 161 public String safeName(String name) 162 { 163 return CodeGenUtil.safeName(name); 164 } 165 166 protected String getImplClassName(String interfaceName) 167 { 168 return interfaceName + "Impl"; 169 } 170 171 public boolean canGenerate() 172 { 173 return getGenModel() != null && getGenModel().canGenerate() && hasModelContribution(); 174 } 175 176 protected boolean hasModelContribution() 177 { 178 return false; 179 } 180 181 public void generate(IProgressMonitor progressMonitor) 182 { 183 } 184 185 protected void generate(IProgressMonitor progressMonitor, int style, List pluginVariables, String outputFilePath, JETEmitter jetEmitter) 186 { 187 try 188 { 189 IPath outputPath = new Path(outputFilePath.substring(0, outputFilePath.lastIndexOf("/"))); 190 progressMonitor.beginTask("", 3); 191 progressMonitor.subTask(CodeGenEcorePlugin.INSTANCE.getString("_UI_GeneratingFile_message", new Object [] { outputFilePath })); 192 IContainer container = findOrCreateContainer(new SubProgressMonitor(progressMonitor, 1), style, pluginVariables, outputPath, false); 193 if (container != null) 194 { 195 IFile targetFile = container.getFile(new Path(outputFilePath.substring(outputFilePath.lastIndexOf("/") + 1))); 196 if (targetFile.exists() && (outputFilePath.endsWith("/build.properties") || !outputFilePath.endsWith(".properties"))) 197 { 198 return; 199 } 200 201 if (outputFilePath.endsWith("/META-INF/MANIFEST.MF") && targetFile.getParent().getParent().exists(new Path("plugin.xml"))) 204 { 205 return; 206 } 207 208 boolean changed = false; 209 boolean isUnicodeEscapeEncoded = outputFilePath.endsWith(".properties"); 210 String emitterResult = jetEmitter.generate(new SubProgressMonitor(progressMonitor, 1), new Object [] { this }); 211 if (isUnicodeEscapeEncoded) 212 { 213 emitterResult = unicodeEscapeEncode(emitterResult); 214 } 215 216 progressMonitor.worked(1); 217 InputStream contents = new ByteArrayInputStream (emitterResult.toString().getBytes(isUnicodeEscapeEncoded ? "ISO-8859-1" : "UTF-8")); 218 if (targetFile.exists()) 219 { 220 PropertyMerger propertyMerger = new PropertyMerger(); 222 propertyMerger.setSourceProperties(emitterResult); 223 progressMonitor.subTask 224 (CodeGenEcorePlugin.INSTANCE.getString("_UI_ExaminingOld_message", new Object [] { targetFile.getFullPath() })); 225 String oldProperties = propertyMerger.createPropertiesForInputStream(targetFile.getContents(true)); 226 propertyMerger.setTargetProperties(oldProperties); 227 progressMonitor.subTask 228 (CodeGenEcorePlugin.INSTANCE.getString("_UI_PreparingNew_message", new Object [] { targetFile.getFullPath() })); 229 propertyMerger.merge(); 230 progressMonitor.worked(1); 231 232 String mergedResult = propertyMerger.getTargetProperties(); 233 changed = !mergedResult.equals(oldProperties); 234 if (changed) 235 { 236 if (targetFile.isReadOnly() && 237 targetFile.getWorkspace().validateEdit(new IFile [] { targetFile }, new SubProgressMonitor(progressMonitor, 1)).isOK()) 238 { 239 propertyMerger.setTargetProperties(propertyMerger.createPropertiesForInputStream(targetFile.getContents(true))); 240 propertyMerger.merge(); 241 mergedResult = propertyMerger.getTargetProperties(); 242 } 243 244 contents = new ByteArrayInputStream (mergedResult.getBytes(isUnicodeEscapeEncoded ? "ISO-8859-1" : "UTF-8")); 245 } 246 } 247 else 248 { 249 changed = true; 250 } 251 252 if (changed) 253 { 254 String redirection = getGenModel().getRedirection(); 255 boolean redirect = redirection != null && redirection.indexOf("{0}") != -1; 256 257 if (redirect) 260 { 261 String baseName = MessageFormat.format(redirection, new Object [] { targetFile.getName() }); 262 targetFile = container.getFile(new Path(baseName)); 263 progressMonitor.subTask 264 (CodeGenEcorePlugin.INSTANCE.getString("_UI_UsingAlternate_message", new Object [] { targetFile.getFullPath() })); 265 } 266 267 if (targetFile.isReadOnly()) 268 { 269 if (getGenModel().isForceOverwrite()) 270 { 271 ResourceAttributes resourceAttributes = targetFile.getResourceAttributes(); 272 if (resourceAttributes != null) 273 { 274 resourceAttributes.setReadOnly(false); 275 targetFile.setResourceAttributes(resourceAttributes); 276 } 277 } 278 else 279 { 280 targetFile = container.getFile(new Path("." + targetFile.getName() + ".new")); 281 progressMonitor.subTask 282 (CodeGenEcorePlugin.INSTANCE.getString("_UI_UsingDefaultAlternate_message", new Object [] { targetFile.getFullPath() })); 283 } 284 } 285 286 if (targetFile.exists()) 287 { 288 targetFile.setContents(contents, true, true, new SubProgressMonitor(progressMonitor, 1)); 289 } 290 else 291 { 292 targetFile.create(contents, true, new SubProgressMonitor(progressMonitor, 1)); 293 } 294 } 295 } 296 } 297 catch (Exception exception) 298 { 299 CodeGenEcorePlugin.INSTANCE.log(exception); 300 } 301 finally 302 { 303 progressMonitor.done(); 304 } 305 } 306 307 protected void generate 308 (IProgressMonitor progressMonitor, 309 int style, 310 List pluginVariables, 311 String outputFilePath, 312 GIFEmitter gifEmitter, 313 String key) 314 { 315 generate(progressMonitor, style, pluginVariables, outputFilePath, gifEmitter, key, null); 316 } 317 318 protected void generate 319 (IProgressMonitor progressMonitor, 320 int style, 321 List pluginVariables, 322 String outputFilePath, 323 GIFEmitter gifEmitter, 324 String parentKey, 325 String childKey) 326 { 327 try 328 { 329 IPath outputPath = new Path(outputFilePath.substring(0, outputFilePath.lastIndexOf("/"))); 330 progressMonitor.beginTask("", 3); 331 progressMonitor.subTask(CodeGenEcorePlugin.INSTANCE.getString("_UI_GeneratingImage_message", new Object [] { outputFilePath })); 332 IContainer container = 333 findOrCreateContainer(new SubProgressMonitor(progressMonitor, 1), style, pluginVariables, outputPath, false); 334 if (container != null) 335 { 336 IFile targetFile = container.getFile(new Path(outputFilePath.substring(outputFilePath.lastIndexOf("/") + 1))); 337 if (targetFile.exists()) 338 { 339 } 341 else 342 { 343 byte[] emitterResult = gifEmitter.generateGIF(parentKey, childKey); 344 progressMonitor.worked(1); 345 InputStream contents = new ByteArrayInputStream (emitterResult); 346 targetFile.create(contents, true, new SubProgressMonitor(progressMonitor, 1)); 347 } 348 } 349 } 350 catch (Exception exception) 351 { 352 CodeGenEcorePlugin.INSTANCE.log(exception); 353 } 354 progressMonitor.done(); 355 } 356 357 protected void generate 358 (IProgressMonitor progressMonitor, 359 int style, 360 List pluginVariables, 361 String targetDirectory, 362 String packageName, 363 String className, 364 JETEmitter jetEmitter) 365 { 366 try 367 { 368 IPath outputPath = new Path(targetDirectory + "/" + packageName.replace('.','/')); 369 progressMonitor.beginTask("", 4); 370 IContainer container = findOrCreateContainer(new SubProgressMonitor(progressMonitor, 1), style, pluginVariables, outputPath, false); 371 if (container != null) 372 { 373 ImportManager importManager = new ImportManager(packageName); 375 importManager.addMasterImport(packageName, className); 376 setImportManager(importManager); 377 378 CodeFormatter codeFormatter = getGenModel().isCodeFormatting() ? getGenModel().createCodeFormatter() : null; 380 381 String emitterResult = jetEmitter.generate(new SubProgressMonitor(progressMonitor, 1), new Object [] { this }); 382 progressMonitor.worked(1); 383 384 boolean changed = true; 385 IFile targetFile = container.getFile(new Path(className + ".java")); 386 progressMonitor.subTask 387 (CodeGenEcorePlugin.INSTANCE.getString("_UI_Generating_message", new Object [] { targetFile.getFullPath()})); 388 JMerger jMerger = new JMerger(); 389 jMerger.setControlModel(getGenModel().getJControlModel()); 390 jMerger.setSourceCompilationUnit(jMerger.createCompilationUnitForContents(emitterResult)); 391 String newContents = null; 392 if (targetFile.exists()) 393 { 394 progressMonitor.subTask 395 (CodeGenEcorePlugin.INSTANCE.getString("_UI_ExaminingOld_message", new Object [] { targetFile.getFullPath() })); 396 jMerger.setTargetCompilationUnit(jMerger.createCompilationUnitForInputStream(targetFile.getContents(true))); 397 String oldContents = jMerger.getTargetCompilationUnitContents(); 398 399 progressMonitor.subTask 400 (CodeGenEcorePlugin.INSTANCE.getString("_UI_PreparingNew_message", new Object [] { targetFile.getFullPath() })); 401 jMerger.merge(); 402 progressMonitor.worked(1); 403 404 newContents = formatCode(jMerger.getTargetCompilationUnitContents(), codeFormatter); 405 changed = !oldContents.equals(newContents); 406 if (changed) 407 { 408 if (targetFile.isReadOnly() && 409 targetFile.getWorkspace().validateEdit(new IFile [] { targetFile }, new SubProgressMonitor(progressMonitor, 1)).isOK()) 410 { 411 jMerger.setTargetCompilationUnit(jMerger.createCompilationUnitForInputStream(targetFile.getContents(true))); 412 jMerger.remerge(); 413 newContents = formatCode(jMerger.getTargetCompilationUnitContents(), codeFormatter); 414 } 415 } 416 } 417 else 418 { 419 changed = true; 420 progressMonitor.subTask 421 (CodeGenEcorePlugin.INSTANCE.getString("_UI_PreparingNew_message", new Object [] { targetFile.getFullPath() })); 422 jMerger.merge(); 423 progressMonitor.worked(1); 424 newContents = formatCode(jMerger.getTargetCompilationUnitContents(), codeFormatter); 425 } 426 427 if (changed) 428 { 429 String encoding = null; 436 try 437 { 438 encoding = targetFile.getCharset(); 439 } 440 catch (CoreException ce) 441 { 442 } 444 byte[] bytes = encoding == null 445 ? newContents.getBytes() 446 : newContents.getBytes(encoding); 447 448 InputStream contents = new ByteArrayInputStream (bytes); 449 450 String redirection = getGenModel().getRedirection(); 451 boolean redirect = redirection != null && redirection.indexOf("{0}") != -1; 452 453 if (redirect) 456 { 457 String baseName = MessageFormat.format(redirection, new Object [] { className + ".java" }); 458 targetFile = container.getFile(new Path(baseName)); 459 progressMonitor.subTask 460 (CodeGenEcorePlugin.INSTANCE.getString("_UI_UsingAlternate_message", new Object [] { targetFile.getFullPath() })); 461 } 462 463 if (targetFile.isReadOnly()) 464 { 465 if (getGenModel().isForceOverwrite()) 466 { 467 ResourceAttributes resourceAttributes = targetFile.getResourceAttributes(); 468 if (resourceAttributes != null) 469 { 470 resourceAttributes.setReadOnly(false); 471 targetFile.setResourceAttributes(resourceAttributes); 472 } 473 } 474 else 475 { 476 targetFile = container.getFile(new Path("." + className + ".java.new")); 477 progressMonitor.subTask 478 (CodeGenEcorePlugin.INSTANCE.getString("_UI_UsingDefaultAlternate_message", new Object [] { targetFile.getFullPath() })); 479 } 480 } 481 482 if (targetFile.exists()) 483 { 484 targetFile.setContents(contents, true, true, new SubProgressMonitor(progressMonitor, 1)); 485 } 486 else 487 { 488 targetFile.create(contents, true, new SubProgressMonitor(progressMonitor, 1)); 489 } 490 } 491 } 492 } 493 catch (JETException exception) 494 { 495 CodeGenEcorePlugin.INSTANCE.log(exception); 496 } 497 catch (Exception exception) 498 { 499 CodeGenEcorePlugin.INSTANCE.log(exception); 500 } 501 502 setImportManager(null); 504 505 progressMonitor.done(); 506 } 507 508 protected ImportManager getImportManager() 509 { 510 return ((GenBaseImpl)getGenModel()).getImportManager(); 511 } 512 513 protected void setImportManager(ImportManager importManager) 514 { 515 GenModelImpl genModel = (GenModelImpl)getGenModel(); 516 if (genModel != null) 517 { 518 genModel.setImportManager(importManager); 519 520 if (ecoreGenPackage != null && ((GenPackageImpl)ecoreGenPackage).getImportManager() != importManager) 523 { 524 ((GenPackageImpl)ecoreGenPackage).setImportManager(getImportManager()); 525 } 526 if (xmlTypeGenPackage != null && ((GenPackageImpl)xmlTypeGenPackage).getImportManager() != importManager) 527 { 528 ((GenPackageImpl)xmlTypeGenPackage).setImportManager(getImportManager()); 529 } 530 if (xmlNamespaceGenPackage != null && ((GenPackageImpl)xmlNamespaceGenPackage).getImportManager() != importManager) 531 { 532 ((GenPackageImpl)xmlNamespaceGenPackage).setImportManager(getImportManager()); 533 } 534 } 535 } 536 537 protected IContainer findOrCreateContainer 538 (IProgressMonitor progressMonitor, int style, List pluginVariables, IPath outputPath, boolean forceStyle) 539 { 540 IContainer container = null; 541 try 542 { 543 progressMonitor.beginTask("", outputPath.segmentCount() + 1); 544 progressMonitor.subTask(CodeGenEcorePlugin.INSTANCE.getString("_UI_OpeningFolder_message", new Object [] { outputPath })); 545 if (outputPath.isAbsolute()) 546 { 547 IWorkspace workspace = ResourcesPlugin.getWorkspace(); 548 IProject project = workspace.getRoot().getProject(outputPath.segment(0)); 549 if (forceStyle || !project.exists()) 550 { 551 IPath projectLocation = null; 552 553 List referencedProjects = new UniqueEList(); 554 if (project.exists()) 555 { 556 referencedProjects.addAll(Arrays.asList(project.getDescription().getReferencedProjects())); 557 projectLocation = project.getDescription().getLocation(); 558 } 559 else 560 { 561 URI genModelURI = getGenModel().eResource().getURI(); 562 if (genModelURI.toString().startsWith("platform:/resource/")) 563 { 564 IProject genModelProject = workspace.getRoot().getProject(genModelURI.segments()[1]); 565 projectLocation = genModelProject.getDescription().getLocation(); 566 } 567 } 568 569 IProject modelProject = workspace.getRoot().getProject(getGenModel().getModelProjectDirectory()); 570 IPath javaSource = new Path(getGenModel().getModelDirectory()); 571 572 if ((style & Generator.EMF_TESTS_PROJECT_STYLE) != 0) 573 { 574 IProject testsProject = workspace.getRoot().getProject(getGenModel().getTestsProjectDirectory()); 575 576 if (!getGenModel().sameModelTestsProject()) 577 { 578 javaSource = new Path(getGenModel().getTestsDirectory()); 579 580 if (testsProject.exists()) 581 { 582 projectLocation = testsProject.getDescription().getLocation(); 583 } 584 585 referencedProjects.add(modelProject); 586 referencedProjects.addAll(Arrays.asList(modelProject.getDescription().getReferencedProjects())); 587 } 588 } 589 else if ((style & Generator.EMF_MODEL_PROJECT_STYLE) == 0 && getGenModel().hasEditSupport()) 590 { 591 IProject editProject = workspace.getRoot().getProject(getGenModel().getEditProjectDirectory()); 592 593 if (!getGenModel().sameModelEditProject()) 594 { 595 javaSource = new Path(getGenModel().getEditDirectory()); 596 if (editProject.exists()) 597 { 598 projectLocation = editProject.getDescription().getLocation(); 599 } 600 601 referencedProjects.add(modelProject); 602 } 603 604 for (Iterator i = getGenModel().getUsedGenPackages().iterator(); i.hasNext(); ) 605 { 606 GenModel otherGenModel = ((GenPackage)i.next()).getGenModel(); 607 if (otherGenModel.hasEditSupport()) 608 { 609 IProject otherEditProject = workspace.getRoot().getProject(otherGenModel.getEditProjectDirectory()); 610 if (otherEditProject.exists()) 611 { 612 referencedProjects.add(otherEditProject); 613 referencedProjects.addAll(Arrays.asList(otherEditProject.getDescription().getReferencedProjects())); 614 } 615 } 616 } 617 618 if ((style & Generator.EMF_EDIT_PROJECT_STYLE) == 0 && getGenModel().hasEditorSupport()) 619 { 620 javaSource = new Path(getGenModel().getEditorDirectory()); 621 if (!getGenModel().sameEditEditorProject()) 622 { 623 referencedProjects.add(editProject); 624 referencedProjects.addAll(Arrays.asList(editProject.getDescription().getReferencedProjects())); 625 } 626 } 627 } 628 629 for (Iterator i = referencedProjects.iterator(); i.hasNext(); ) 632 { 633 IProject referencedProject = (IProject)i.next(); 634 IJavaProject referencedJavaProject = JavaCore.create(referencedProject); 635 if (!referencedJavaProject.exists()) 636 { 637 i.remove(); 638 } 639 } 640 641 if (projectLocation != null) 642 { 643 projectLocation = projectLocation.removeLastSegments(1).append(javaSource.segment(0)); 644 } 645 646 if (getGenModel().hasXMLDependency()) 647 { 648 style |= Generator.EMF_XML_PROJECT_STYLE; 649 } 650 651 if ((style & Generator.EMF_MODEL_PROJECT_STYLE) == 0 || getGenModel().hasPluginSupport()) 652 { 653 style |= Generator.EMF_PLUGIN_PROJECT_STYLE; 654 } 655 656 Generator.createEMFProject 657 (javaSource, 658 projectLocation, 659 referencedProjects, 660 progressMonitor, 661 style, 662 pluginVariables); 663 } 664 else 665 { 666 if (!project.isOpen()) 667 { 668 project.open(new SubProgressMonitor(progressMonitor, 1)); 669 } 670 } 671 672 container = project; 673 for (int i = 1, length = outputPath.segmentCount(); i < length; ++ i) 674 { 675 IFolder folder = container.getFolder(new Path(outputPath.segment(i))); 676 if (!folder.exists()) 677 { 678 folder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); 679 } 680 container = folder; 681 } 682 } 683 } 684 catch (Exception exception) 685 { 686 CodeGenEcorePlugin.INSTANCE.log(exception); 687 } 688 progressMonitor.done(); 689 return container; 690 } 691 692 697 protected String formatCode(String contents, CodeFormatter codeFormatter) 698 { 699 if (getGenModel().isCodeFormatting()) 700 { 701 if (codeFormatter == null) 702 { 703 codeFormatter = getGenModel().createCodeFormatter(); 704 } 705 706 IDocument doc = new Document(contents); 707 TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, doc.get(), 0, doc.get().length(), 0, null); 708 709 try 710 { 711 edit.apply(doc); 712 contents = doc.get(); 713 } 714 catch (Exception exception) 715 { 716 CodeGenEcorePlugin.INSTANCE.log(exception); 717 } 718 } 719 return contents; 720 } 721 722 public String format(String name, char separator, String prefix, boolean includePrefix) 723 { 724 return CodeGenUtil.format(name, separator, prefix, includePrefix); 725 } 726 727 732 protected final List parseName(String sourceName, char sourceSeparator) 733 { 734 return Collections.EMPTY_LIST; 735 } 736 737 protected List getAllGenPackages() 738 { 739 List result = new ArrayList (); 740 result.addAll(getGenModel().getGenPackages()); 741 result.addAll(getGenModel().getUsedGenPackages()); 742 result.addAll(getGenModel().getStaticGenPackages()); 743 return result; 744 } 745 746 749 protected GenPackage findGenPackageHelper(GenPackage genPackage, EPackage ePackage) 750 { 751 if (ePackage.getNsURI() == null ? 752 genPackage.getEcorePackage().getNsURI() == null : 753 ePackage.getNsURI().equals(genPackage.getEcorePackage().getNsURI())) { 755 return genPackage; 756 } 757 758 for (Iterator nestedGenPackages = genPackage.getNestedGenPackages().iterator(); nestedGenPackages.hasNext(); ) 759 { 760 GenPackage nestedGenPackage = (GenPackage)nestedGenPackages.next(); 761 GenPackage nestedResult = findGenPackageHelper(nestedGenPackage, ePackage); 762 if (nestedResult != null) 763 { 764 return nestedResult; 765 } 766 } 767 768 return null; 769 } 770 771 protected static GenPackage ecoreGenPackage; 772 protected static GenPackage xmlTypeGenPackage; 773 protected static GenPackage xmlNamespaceGenPackage; 774 775 public GenPackage findGenPackage(EPackage ePackage) 776 { 777 if (ePackage == EcorePackage.eINSTANCE) 778 { 779 if (ecoreGenPackage == null) 780 { 781 GenModel ecoreGenModel = getGenModel().createGenModel(); 782 ecoreGenModel.initialize(Collections.singleton(EcorePackage.eINSTANCE)); 783 ecoreGenPackage = (GenPackage)ecoreGenModel.getGenPackages().get(0); 784 ecoreGenPackage.setPrefix("Ecore"); 785 ecoreGenPackage.setBasePackage("org.eclipse.emf"); 786 ((GenPackageImpl)ecoreGenPackage).setImportManager(getImportManager()); 787 } 788 return ecoreGenPackage; 789 } 790 791 if (ePackage == XMLTypePackage.eINSTANCE) 792 { 793 if (xmlTypeGenPackage == null) 794 { 795 GenModel xmlTypeGenModel = getGenModel().createGenModel(); 796 xmlTypeGenModel.initialize(Collections.singleton(XMLTypePackage.eINSTANCE)); 797 xmlTypeGenPackage = (GenPackage)xmlTypeGenModel.getGenPackages().get(0); 798 xmlTypeGenPackage.setPrefix("XMLType"); 799 xmlTypeGenPackage.setBasePackage("org.eclipse.emf.ecore.xml"); 800 ((GenPackageImpl)xmlTypeGenPackage).setImportManager(getImportManager()); 801 } 802 return xmlTypeGenPackage; 803 } 804 805 if (ePackage == XMLNamespacePackage.eINSTANCE) 806 { 807 if (xmlNamespaceGenPackage == null) 808 { 809 GenModel xmlNamespaceGenModel = getGenModel().createGenModel(); 810 xmlNamespaceGenModel.initialize(Collections.singleton(XMLNamespacePackage.eINSTANCE)); 811 xmlNamespaceGenPackage = (GenPackage)xmlNamespaceGenModel.getGenPackages().get(0); 812 xmlNamespaceGenPackage.setPrefix("XMLNamespace"); 813 xmlNamespaceGenPackage.setBasePackage("org.eclipse.emf.ecore.xml"); 814 ((GenPackageImpl)xmlNamespaceGenPackage).setImportManager(getImportManager()); 815 } 816 return xmlNamespaceGenPackage; 817 } 818 819 for (Iterator pIter = getAllGenPackages().iterator(); pIter.hasNext(); ) 820 { 821 GenPackage genPackage = (GenPackage)pIter.next(); 822 GenPackage resultGenPackage = findGenPackageHelper(genPackage, ePackage); 823 if (resultGenPackage != null) 824 { 825 return resultGenPackage; 826 } 827 } 828 829 return null; 830 } 831 832 protected GenClass findGenClass(EClass eClass) 833 { 834 GenPackage genPackage = findGenPackage(eClass.getEPackage()); 835 if (genPackage != null) 836 { 837 for (Iterator iter = genPackage.getGenClasses().iterator(); iter.hasNext(); ) 838 { 839 GenClass genClass = (GenClass)iter.next(); 840 if (eClass.getName().equals(genClass.getEcoreClass().getName())) { 842 return genClass; 843 } 844 } 845 } 846 return null; 847 } 848 849 protected GenEnum findGenEnum(EEnum eEnum) 850 { 851 GenPackage genPackage = findGenPackage(eEnum.getEPackage()); 852 if (genPackage != null) 853 { 854 for (Iterator iter = genPackage.getGenEnums().iterator(); iter.hasNext(); ) 855 { 856 GenEnum genEnum = (GenEnum)iter.next(); 857 if (eEnum.getName().equals(genEnum.getEcoreEnum().getName())) { 859 return genEnum; 860 } 861 } 862 } 863 return null; 864 } 865 866 protected GenDataType findGenDataType(EDataType eDataType) 867 { 868 GenPackage genPackage = findGenPackage(eDataType.getEPackage()); 869 if (genPackage != null) 870 { 871 for (Iterator iter = genPackage.getGenDataTypes().iterator(); iter.hasNext(); ) 872 { 873 GenDataType genDataType = (GenDataType)iter.next(); 874 if (eDataType.getName().equals(genDataType.getEcoreDataType().getName())) { 876 return genDataType; 877 } 878 } 879 } 880 return null; 881 } 882 883 protected GenClassifier findGenClassifier(EClassifier eClassifier) 884 { 885 if (eClassifier instanceof EClass) 886 { 887 return findGenClass((EClass)eClassifier); 888 } 889 else if (eClassifier instanceof EEnum) 890 { 891 return findGenEnum((EEnum)eClassifier); 892 } 893 else if (eClassifier instanceof EDataType) 894 { 895 return findGenDataType((EDataType)eClassifier); 896 } 897 else 898 { 899 return null; 900 } 901 } 902 903 protected GenFeature findGenFeature(EStructuralFeature eStructuralFeature) 904 { 905 GenClass genClass = findGenClass(eStructuralFeature.getEContainingClass()); 906 for (Iterator i = genClass.getGenFeatures().iterator(); i.hasNext(); ) 907 { 908 GenFeature genFeature = (GenFeature)i.next(); 909 if (eStructuralFeature.getName().equals(genFeature.getEcoreFeature().getName())) { 911 return genFeature; 912 } 913 } 914 915 return null; 916 } 917 918 protected GenOperation findGenOperation(EOperation eOperation) 919 { 920 GenClass genClass = findGenClass(eOperation.getEContainingClass()); 921 genOperationsLoop: for (Iterator i = genClass.getGenOperations().iterator(); i.hasNext();) 922 { 923 GenOperation genOperation = (GenOperation)i.next(); 924 EOperation ecoreOperation = genOperation.getEcoreOperation(); 925 if (eOperation.getName().equals(ecoreOperation.getName()) 926 && eOperation.getEParameters().size() == ecoreOperation.getEParameters().size()) 927 { 928 for (int j = 0; j < eOperation.getEParameters().size(); j++) 929 { 930 EParameter ecoreParameter = (EParameter)eOperation.getEParameters().get(j); 931 932 if (!ecoreParameter.getEType().getName().equals(((EParameter)ecoreOperation.getEParameters().get(j)).getEType().getName())) 933 { 934 continue genOperationsLoop; 935 } 936 } 937 938 return genOperation; 939 } 940 } 941 942 return null; 943 } 944 945 protected boolean isEffectiveSuppressEMFTypes() 946 { 947 return getGenModel().isSuppressEMFTypes(); 948 } 949 950 protected String getEffectiveMapType() 951 { 952 return isEffectiveSuppressEMFTypes() ? "java.util.Map" : "org.eclipse.emf.common.util.EMap"; 953 } 954 955 protected String getEffectiveListType() 956 { 957 return isEffectiveSuppressEMFTypes() ? "java.util.List" : "org.eclipse.emf.common.util.EList"; 958 } 959 960 protected String getEffectiveEObjectType() 961 { 962 return isEffectiveSuppressEMFTypes() ? "java.lang.Object" : "org.eclipse.emf.ecore.EObject"; 963 } 964 965 protected String getEffectiveFeatureMapWrapperInterface() 966 { 967 String result = getGenModel().getFeatureMapWrapperInterface(); 968 return isBlank(result) ? "org.eclipse.emf.ecore.util.FeatureMap" : result; 969 } 970 971 protected String getImportedEffectiveFeatureMapWrapperInternalInterface() 972 { 973 String result = getGenModel().getFeatureMapWrapperInternalInterface(); 974 return getGenModel().getImportedName(isBlank(result) ? "org.eclipse.emf.ecore.util.FeatureMap" : result); 975 } 976 977 protected String getImportedEffectiveFeatureMapWrapperClass() 978 { 979 String result = getGenModel().getFeatureMapWrapperClass(); 980 return getGenModel().getImportedName(isBlank(result) ? "org.eclipse.emf.ecore.util.FeatureMap" : result); 981 } 982 983 protected Class getInstanceClass(EClassifier eType) 984 { 985 try 986 { 987 Class instanceClass = eType.getInstanceClass(); 988 return instanceClass; 989 } 990 catch (Exception e) 991 { 992 return null; 993 } 994 } 995 996 protected boolean isPrimitiveType(EClassifier eType) 997 { 998 try 999 { 1000 Object result = eType.getInstanceClass(); 1003 if (result == null) 1004 { 1005 return false; 1006 } 1007 Class instanceClass = (Class )result; 1008 return instanceClass.isPrimitive(); 1009 } 1010 catch (Exception e) 1011 { 1012 return false; 1013 } 1014 } 1015 1016 protected String getPrimitiveObjectType(EClassifier eType) 1017 { 1018 Class instanceClass = getInstanceClass(eType); 1019 if (instanceClass == java.lang.Boolean.TYPE) 1020 return "java.lang.Boolean"; 1021 if (instanceClass == java.lang.Byte.TYPE) 1022 return "java.lang.Byte"; 1023 if (instanceClass == java.lang.Character.TYPE) 1024 return "java.lang.Character"; 1025 if (instanceClass == java.lang.Double.TYPE) 1026 return "java.lang.Double"; 1027 if (instanceClass == java.lang.Float.TYPE) 1028 return "java.lang.Float"; 1029 if (instanceClass == java.lang.Integer.TYPE) 1030 return "java.lang.Integer"; 1031 if (instanceClass == java.lang.Long.TYPE) 1032 return "java.lang.Long"; 1033 if (instanceClass == java.lang.Short.TYPE) 1034 return "java.lang.Short"; 1035 return null; 1036 } 1037 1038 protected String getPrimitiveDefault(EClassifier eType) 1039 { 1040 if (isPrimitiveType(eType)) 1041 { 1042 Class instanceClass = eType.getInstanceClass(); 1043 if (instanceClass == java.lang.Boolean.TYPE) 1044 return "false"; 1045 if (instanceClass == java.lang.Byte.TYPE || 1046 instanceClass == java.lang.Integer.TYPE || 1047 instanceClass == java.lang.Long.TYPE || 1048 instanceClass == java.lang.Short.TYPE) 1049 return "0"; 1050 if (instanceClass == java.lang.Character.TYPE) 1051 return "'\\u0000'"; 1052 if (instanceClass == java.lang.Double.TYPE) 1053 return "0.0"; 1054 if (instanceClass == java.lang.Float.TYPE) 1055 return "0.0F"; 1056 } 1057 return null; 1058 } 1059 1060 1066 protected String getType(EClassifier eType, boolean primitiveAsObject) 1067 { 1068 if (eType instanceof EClass) 1069 { 1070 return findGenClass((EClass)eType).getQualifiedInterfaceName(); 1071 } 1072 1073 if (eType instanceof EEnum) 1074 { 1075 return findGenEnum((EEnum)eType).getQualifiedName(); 1076 } 1077 1078 if (primitiveAsObject && isPrimitiveType(eType)) 1080 { 1081 return getPrimitiveObjectType(eType); 1082 } 1083 1084 if ("org.eclipse.emf.common.util.Enumerator".equals(eType.getInstanceClassName())) 1085 { 1086 EDataType baseType = getExtendedMetaData().getBaseType((EDataType)eType); 1087 if (baseType instanceof EEnum) 1088 { 1089 GenEnum genEnum = findGenEnum((EEnum)baseType); 1090 if (genEnum != null) 1091 { 1092 return genEnum.getQualifiedName(); 1093 } 1094 } 1095 } 1096 1097 return eType.getInstanceClassName(); 1098 } 1099 1100 1107 protected String getImportedType(EClassifier eType, boolean primitiveAsObject) 1108 { 1109 String t = getType(eType, primitiveAsObject); 1110 return !primitiveAsObject && isPrimitiveType(eType) ? t : getGenModel().getImportedName(t); 1111 } 1112 1113 1122 protected List getTypeGenClasses(EClassifier eType, GenPackage firstGenPackage, List genPackages, int max) 1123 { 1124 if (max == 0 || !(eType instanceof EClass)) return Collections.EMPTY_LIST; 1125 1126 boolean hasMax = max > -1; 1127 List result = new ArrayList (); 1128 EClass baseClass = (EClass)eType; 1129 1130 ExtendedMetaData extendedMetaData = getExtendedMetaData(); 1131 if (extendedMetaData.isAnonymous(baseClass)) 1132 { 1133 result.add(findGenClass(baseClass)); 1134 return result; 1135 } 1136 1137 List orderedGenPackages = genPackages; 1139 if (firstGenPackage != null) 1140 { 1141 orderedGenPackages = new ArrayList (genPackages.size() + 1); 1142 orderedGenPackages.add(firstGenPackage); 1143 for (Iterator iter = genPackages.iterator(); iter.hasNext(); ) 1144 { 1145 GenPackage genPackage = (GenPackage)iter.next(); 1146 if (genPackage != firstGenPackage) orderedGenPackages.add(genPackage); 1147 } 1148 } 1149 1150 for (Iterator pIter = orderedGenPackages.iterator(); pIter.hasNext(); ) 1151 { 1152 if (baseClass == EcorePackage.eINSTANCE.getEObject()) 1153 { 1154 for (Iterator cIter = ((GenPackage)pIter.next()).getOrderedGenClasses().iterator(); cIter.hasNext(); ) 1155 { 1156 GenClass genClass = (GenClass)cIter.next(); 1157 if (!genClass.isAbstract() && !extendedMetaData.isAnonymous(genClass.getEcoreClass())) 1158 { 1159 result.add(genClass); 1160 if (hasMax && result.size() >= max) return result; 1161 } 1162 } 1163 } 1164 else 1165 { 1166 for (Iterator cIter = ((GenPackage)pIter.next()).getOrderedGenClasses().iterator(); cIter.hasNext(); ) 1167 { 1168 GenClass genClass = (GenClass)cIter.next(); 1169 if (!genClass.isAbstract() && 1170 baseClass.isSuperTypeOf(genClass.getEcoreClass()) && 1171 !extendedMetaData.isAnonymous(genClass.getEcoreClass())) 1172 { 1173 result.add(genClass); 1174 if (hasMax && result.size() >= max) return result; 1175 } 1176 } 1177 } 1178 } 1179 return result; 1180 } 1181 1182 1187 protected static Set getJavaReservedWords() 1188 { 1189 return CodeGenUtil.getJavaReservedWords(); 1190 } 1191 1192 1195 protected static Set getJavaLangTypes() 1196 { 1197 return CodeGenUtil.getJavaDefaultTypes(); 1198 } 1199 1200 protected static interface GenClassFilter 1201 { 1202 boolean accept(GenClass genClass); 1203 } 1204 1205 protected static interface GenFeatureFilter 1206 { 1207 boolean accept(GenFeature genFeature); 1208 } 1209 1210 protected static interface GenOperationFilter 1211 { 1212 boolean accept(GenOperation genOperation); 1213 } 1214 1215 protected static interface GenConstraintFilter 1216 { 1217 boolean accept(String genConstraint); 1218 } 1219 1220 1224 protected List filterGenClasses(List genClasses, GenClassFilter filter) 1225 { 1226 List result = new ArrayList (); 1227 for (Iterator iter = genClasses.iterator(); iter.hasNext(); ) 1228 { 1229 GenClass genClass = (GenClass)iter.next(); 1230 if (filter == null || filter.accept(genClass)) 1231 { 1232 result.add(genClass); 1233 } 1234 } 1235 return result; 1236 } 1237 1238 1243 protected List collectGenClasses(List eClasses, GenClassFilter filter) 1244 { 1245 List result = new ArrayList (); 1246 for (Iterator iter = eClasses.iterator(); iter.hasNext(); ) 1247 { 1248 GenClass genClass = findGenClass((EClass)iter.next()); 1249 if (filter == null || filter.accept(genClass)) 1250 { 1251 result.add(genClass); 1252 } 1253 } 1254 return result; 1255 } 1256 1257 1263 protected List collectGenFeatures(List genClasses, List genFeatures, GenFeatureFilter filter) 1264 { 1265 List result = new ArrayList (); 1266 1267 if (genClasses != null) 1268 { 1269 for (Iterator iter = genClasses.iterator(); iter.hasNext(); ) 1270 { 1271 GenClass genClass = (GenClass)iter.next(); 1272 for (Iterator sIter = genClass.getGenFeatures().iterator(); sIter.hasNext(); ) 1273 { 1274 GenFeature genFeature = (GenFeature)sIter.next(); 1275 if (filter == null || filter.accept(genFeature)) 1276 { 1277 result.add(genFeature); 1278 } 1279 } 1280 } 1281 } 1282 1283 if (genFeatures != null) 1284 { 1285 for (Iterator iter = genFeatures.iterator(); iter.hasNext(); ) 1286 { 1287 GenFeature genFeature = (GenFeature)iter.next(); 1288 if (filter == null || filter.accept(genFeature)) 1289 { 1290 result.add(genFeature); 1291 } 1292 } 1293 } 1294 return result; 1295 } 1296 1297 1303 protected List collectGenOperations(List genClasses, List genOperations, GenOperationFilter filter) 1304 { 1305 List result = new ArrayList (); 1306 1307 if (genClasses != null) 1308 { 1309 for (Iterator iter = genClasses.iterator(); iter.hasNext(); ) 1310 { 1311 GenClass genClass = (GenClass)iter.next(); 1312 for (Iterator sIter = genClass.getGenOperations().iterator(); sIter.hasNext(); ) 1313 { 1314 GenOperation genOperation = (GenOperation)sIter.next(); 1315 if (filter == null || filter.accept(genOperation)) 1316 { 1317 result.add(genOperation); 1318 } 1319 } 1320 } 1321 } 1322 1323 if (genOperations != null) 1324 { 1325 for (Iterator iter = genOperations.iterator(); iter.hasNext(); ) 1326 { 1327 GenOperation genOperation = (GenOperation)iter.next(); 1328 if (filter == null || filter.accept(genOperation)) 1329 { 1330 result.add(genOperation); 1331 } 1332 } 1333 } 1334 return result; 1335 } 1336 1337 1343 protected List collectGenConstraints(List genClassifiers, List genConstraints, GenConstraintFilter filter) 1344 { 1345 List result = new UniqueEList(); 1346 1347 if (genClassifiers != null) 1348 { 1349 for (Iterator iter = genClassifiers.iterator(); iter.hasNext(); ) 1350 { 1351 GenClassifier genClassifier = (GenClassifier)iter.next(); 1352 for (Iterator sIter = genClassifier.getGenConstraints().iterator(); sIter.hasNext(); ) 1353 { 1354 String genConstraint = (String )sIter.next(); 1355 if (filter == null || filter.accept(genConstraint)) 1356 { 1357 result.add(genConstraint); 1358 } 1359 } 1360 } 1361 } 1362 1363 if (genConstraints != null) 1364 { 1365 for (Iterator iter = genConstraints.iterator(); iter.hasNext(); ) 1366 { 1367 String genConstraint = (String )iter.next(); 1368 if (filter == null || filter.accept(genConstraint)) 1369 { 1370 result.add(genConstraint); 1371 } 1372 } 1373 } 1374 return result; 1375 } 1376 1377 public String getModelInfo() 1378 { 1379 return ""; 1380 } 1381 1382 protected static interface AnnotationFilter 1383 { 1384 boolean accept(EModelElement eModelElement, String source, String key, String value); 1385 } 1386 1387 protected static class AnnotationFilterImpl implements AnnotationFilter 1388 { 1389 public AnnotationFilterImpl() 1390 { 1391 } 1392 1393 public boolean accept(EModelElement eModelElement, String source, String key, String value) 1394 { 1395 return !(GenModelPackage.eNS_URI.equals(source) && "documentation".equals(key)); 1396 } 1397 } 1398 1399 protected static final AnnotationFilter DEFAULT_ANNOTATION_FILTER = new AnnotationFilterImpl(); 1400 1401 protected List getAnnotationInfo(EModelElement eModelElement) 1402 { 1403 return getAnnotationInfo(eModelElement, DEFAULT_ANNOTATION_FILTER); 1404 } 1405 1406 protected List getAnnotationInfo(EModelElement eModelElement, AnnotationFilter annotationFilter) 1407 { 1408 List result = Collections.EMPTY_LIST; 1409 for (Iterator i = eModelElement.getEAnnotations().iterator(); i.hasNext(); ) 1410 { 1411 EAnnotation eAnnotation = (EAnnotation)i.next(); 1412 String source = eAnnotation.getSource(); 1413 if (source != null) 1414 { 1415 StringBuffer stringBuffer = null; 1416 for (Iterator j = eAnnotation.getDetails().iterator(); j.hasNext(); ) 1417 { 1418 Map.Entry mapEntry = (Map.Entry )j.next(); 1419 String key = (String )mapEntry.getKey(); 1420 String value = (String )mapEntry.getValue(); 1421 if (annotationFilter.accept(eModelElement, source, key, value)) 1422 { 1423 if (stringBuffer == null) 1424 { 1425 stringBuffer = new StringBuffer (escapeString(source, " =")); 1426 } 1427 stringBuffer.append(' '); 1428 stringBuffer.append(escapeString(key, " =")); 1429 stringBuffer.append("=\'"); 1430 stringBuffer.append(escapeString(value, "")); 1431 stringBuffer.append('\''); 1432 } 1433 } 1434 if (stringBuffer != null) 1435 { 1436 if (result.size() == 0) 1437 { 1438 result = new ArrayList (); 1439 } 1440 result.add(stringBuffer.toString()); 1441 } 1442 } 1443 } 1444 return result; 1445 } 1446 1447 protected void appendAnnotationInfo(StringBuffer result, EModelElement eModelElement) 1448 { 1449 appendAnnotationInfo(result, eModelElement, DEFAULT_ANNOTATION_FILTER); 1450 } 1451 1452 protected void appendAnnotationInfo(StringBuffer result, EModelElement eModelElement, AnnotationFilter annotationFilter) 1453 { 1454 appendAnnotationInfo(result, false, eModelElement, annotationFilter); 1455 } 1456 1457 protected void appendAnnotationInfo(StringBuffer result, boolean qualified, EModelElement eModelElement, AnnotationFilter annotationFilter) 1458 { 1459 for (Iterator i = getAnnotationInfo(eModelElement, annotationFilter).iterator(); i.hasNext(); ) 1460 { 1461 String annotationInfo = (String )i.next(); 1462 appendLineBreak(result); 1463 String qualifier = qualified && eModelElement instanceof ENamedElement ? ((ENamedElement)eModelElement).getName() : null; 1464 if (annotationInfo.startsWith(ExtendedMetaData.ANNOTATION_URI)) 1465 { 1466 appendModelSetting(result, qualifier, "extendedMetaData", annotationInfo.substring(ExtendedMetaData.ANNOTATION_URI.length() + 1)); 1467 } 1468 else 1469 { 1470 appendModelSetting(result, qualifier, "annotation", annotationInfo); 1471 } 1472 } 1473 } 1474 1475 protected static String escapeString(String s, String additionalCharactersToEscape) 1476 { 1477 if (s == null) return null; 1478 1479 int len = s.length(); 1480 StringBuffer result = new StringBuffer (len + 16); 1481 for (int i = 0; i < len; i++) 1482 { 1483 char c = s.charAt(i); 1484 if (c == '\b') result.append("\\b"); 1485 else if (c == '\t') result.append("\\t"); 1486 else if (c == '\n') result.append("\\n"); 1487 else if (c == '\f') result.append("\\f"); 1488 else if (c == '\r') result.append("\\r"); 1489 else if (c == '\"') result.append("\\\""); 1490 else if (c == '\'') result.append("\\\'"); 1491 else if (c == '\\') result.append("\\\\"); 1492 else if (additionalCharactersToEscape.indexOf(c) == -1 && c >= 32 && c < 127) 1493 { 1494 result.append(c); 1495 } 1496 else if (c < 256) 1497 { 1498 String num = Integer.toOctalString(c); 1499 switch(num.length()) 1500 { 1501 case 1: result.append("\\00"); break; 1502 case 2: result.append("\\0"); break; 1503 default: result.append("\\"); break; 1504 } 1505 result.append(num); 1506 } 1507 else 1508 { 1509 String num = Integer.toHexString(c); 1510 switch(num.length()) 1511 { 1512 case 1: result.append("\\u000"); break; 1513 case 2: result.append("\\u00"); break; 1514 case 3: result.append("\\u0"); break; 1515 default: result.append("\\u"); break; 1516 } 1517 result.append(num); 1518 } 1519 } 1520 1521 return result.toString(); 1522 } 1523 1524 protected void appendLineBreak(StringBuffer result) 1525 { 1526 for (int i = result.length(); --i >= 0; ) 1527 { 1528 if (Character.isWhitespace(result.charAt(i))) 1529 { 1530 result.deleteCharAt(i); 1531 } 1532 else 1533 { 1534 break; 1535 } 1536 } 1537 result.append(System.getProperty("line.separator")); 1538 } 1539 1540 protected void appendModelSetting(StringBuffer result, String qualifier, String name, String value) 1541 { 1542 if (qualifier != null) 1543 { 1544 result.append(qualifier); 1545 result.append(capName(name)); 1546 } 1547 else 1548 { 1549 result.append(name); 1550 } 1551 result.append("=\""); 1552 result.append(value); 1553 result.append("\" "); 1554 } 1555 1556 protected void appendModelSetting(StringBuffer result, String name, String value) 1557 { 1558 result.append(name); 1559 result.append("=\""); 1560 result.append(value); 1561 result.append("\" "); 1562 } 1563 1564 protected static boolean isJavaUtilMapEntry(String name) 1565 { 1566 return "java.util.Map.Entry".equals(name) || "java.util.Map$Entry".equals(name); 1567 } 1568 1569 protected static boolean isBlank(String string) 1570 { 1571 return string == null || string.length() == 0; 1572 } 1573 1574 protected abstract class UniqueNameHelper 1575 { 1576 private Map nameToObjectMap; 1577 private Map objectToNameMap; 1578 1579 protected UniqueNameHelper() 1580 { 1581 nameToObjectMap = new HashMap (); 1582 objectToNameMap = new HashMap (); 1583 } 1584 1585 protected UniqueNameHelper(int initialMapCapacity) 1586 { 1587 nameToObjectMap = new HashMap (initialMapCapacity); 1588 objectToNameMap = new HashMap (initialMapCapacity); 1589 } 1590 1591 protected abstract String getName(Object o); 1592 1593 protected List getAlternateNames(Object o) 1594 { 1595 return Collections.EMPTY_LIST; 1596 } 1597 1598 public String getUniqueName(Object o) 1599 { 1600 if (!contains(o)) add(o); 1601 return (String )objectToNameMap.get(o); 1602 } 1603 1604 protected boolean add(Object o) 1605 { 1606 if (contains(o)) return false; 1607 1608 String name = getName(o); 1609 1610 if (containsName(name)) 1611 { 1612 List alternates = getAlternateNames(o); 1613 for (Iterator i = alternates.iterator(); i.hasNext(); ) 1614 { 1615 name = (String )i.next(); 1616 if (!containsName(name)) break; 1617 } 1618 } 1619 1620 if (containsName(name)) 1621 { 1622 for (int i = 1; true; i++) 1623 { 1624 String newName = name + "_" + i; 1625 if (!containsName(newName)) 1626 { 1627 name = newName; 1628 break; 1629 } 1630 if (i == Integer.MAX_VALUE) throw new IllegalArgumentException ( 1631 "too many objects named " + name); 1632 } 1633 } 1634 1635 nameToObjectMap.put(name, o); 1636 objectToNameMap.put(o, name); 1637 return true; 1638 } 1639 1640 public boolean addAll(Collection c) 1641 { 1642 boolean result = false; 1643 for (Iterator i = c.iterator(); i.hasNext(); ) 1644 { 1645 if (add(i.next())) result = true; 1646 } 1647 return result; 1648 } 1649 1650 public final boolean contains(Object o) 1651 { 1652 return objectToNameMap.containsKey(o); 1653 } 1654 1655 public final boolean containsName(String name) 1656 { 1657 return nameToObjectMap.containsKey(name); 1658 } 1659 } 1660 1661 public boolean canGenerateEdit() 1665 { 1666 return getGenModel().canGenerateEdit() && hasModelContribution(); 1667 } 1668 1669 public void generateEdit(IProgressMonitor progressMonitor) 1670 { 1671 } 1672 1673 public boolean canGenerateEditor() 1674 { 1675 return getGenModel().canGenerateEditor() && hasModelContribution(); 1676 } 1677 1678 public void generateEditor(IProgressMonitor progressMonitor) 1679 { 1680 } 1681 1682 public boolean canGenerateSchema() 1683 { 1684 return false; 1685 } 1686 1687 public void generateSchema(IProgressMonitor progressMonitor) 1688 { 1689 } 1690 1691 public boolean canGenerateTests() 1692 { 1693 return false; 1694 } 1695 1696 public void generateTests(IProgressMonitor progressMonitor) 1697 { 1698 } 1699 1700 protected static class GIFEmitter 1701 { 1702 protected String inputFile; 1703 1704 protected static final int tableOffset1 = 49; 1705 protected static final int tableOffset2 = 25; 1706 1707 public GIFEmitter(String inputFile) 1708 { 1709 this.inputFile = inputFile; 1710 } 1711 1712 protected int code(String code) 1713 { 1714 int result = 0; 1715 for (int i = 0; i < code.length(); ++ i) 1716 { 1717 result += code.charAt(i) - 32; 1718 } 1719 return result; 1720 } 1721 1722 protected byte[] generateGIF(String key1, String key2) 1723 { 1724 ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); 1725 try 1726 { 1727 byte [] content = new byte [5000]; 1728 int result = getContents(content, inputFile); 1729 1730 ColorInformation info1 = ColorInformation.getColor(code(key1)); 1732 ColorInformation info2 = key2 == null ? null : ColorInformation.getColor(code(key2)); 1733 1734 1735 for (int j = 0; j < result; ++j) 1736 { 1737 if (j == tableOffset1 || j == tableOffset1 + 3 || j == tableOffset1 + 6 || j == tableOffset1 + 9) 1738 { 1739 int index = (j - tableOffset1) / 3; 1740 if (!info1.rainbow || info1.which == index - 1) 1741 { 1742 content[j] = info1.scale(info1.red, info1.factor[index]); 1743 } 1744 } 1745 else if (j == tableOffset1 + 1 || j == tableOffset1 + 4 || j == tableOffset1 + 7 || j == tableOffset1 + 10) 1746 { 1747 int index = (j - tableOffset1 - 1) / 3; 1748 if (!info1.rainbow || info1.which == index - 1) 1749 { 1750 content[j] = info1.scale(info1.green, info1.factor[index]); 1751 } 1752 } 1753 else if (j == tableOffset1 + 2 || j == tableOffset1 + 5 || j == tableOffset1 + 8 || j == tableOffset1 + 11) 1754 { 1755 int index = (j - tableOffset1 - 2) / 3; 1756 if (!info1.rainbow || info1.which == index - 1) 1757 { 1758 content[j] = info1.scale(info1.blue, info1.factor[index]); 1759 } 1760 } 1761 1762 if (info2 != null) 1763 { 1764 if (j == tableOffset2 || j == tableOffset2 + 3 || j == tableOffset2 + 6 || j == tableOffset2 + 9) 1765 { 1766 int index = (j - tableOffset2) / 3; 1767 if (!info2.rainbow || info2.which == index - 1) 1768 { 1769 content[j] = info2.scale(info2.red, info2.factor[index]); 1770 } 1771 } 1772 else if (j == tableOffset2 + 1 || j == tableOffset2 + 4 || j == tableOffset2 + 7 || j == tableOffset2 + 10) 1773 { 1774 int index = (j - tableOffset2 - 1) / 3; 1775 if (!info2.rainbow || info2.which == index - 1) 1776 { 1777 content[j] = info2.scale(info2.green, info2.factor[index]); 1778 } 1779 } 1780 else if (j == tableOffset2 + 2 || j == tableOffset2 + 5 || j == tableOffset2 + 8 || j == tableOffset2 + 11) 1781 { 1782 int index = (j - tableOffset2 - 2) / 3; 1783 if (!info2.rainbow || info2.which == index - 1) 1784 { 1785 content[j] = info2.scale(info2.blue, info2.factor[index]); 1786 } 1787 } 1788 } 1789 } 1790 1791 DataOutputStream writer = new DataOutputStream (outputStream); 1792 writer.write(content, 0, result); 1793 writer.close(); 1794 } 1795 catch (Exception exception) 1796 { 1797 CodeGenEcorePlugin.INSTANCE.log(exception); 1798 } 1799 1800 return outputStream.toByteArray(); 1801 } 1802 1803 protected int getContents(byte [] content, String gifFile) throws JETException, IOException 1804 { 1805 DataInputStream reader = new DataInputStream (JETCompiler.openStream(gifFile)); 1806 int result = reader.read(content, 0, content.length); 1807 reader.close(); 1808 return result; 1809 } 1810 } 1811 1812 public static class ColorInformation 1813 { 1814 public static ColorInformation getColor(int index) 1815 { 1816 index = Math.abs(index) % 61; 1817 while (entries.size() <= index) 1818 { 1819 instance.generateColor(); 1820 1821 ColorInformation entry = new ColorInformation(); 1822 entry.red = instance.red; 1823 entry.green = instance.green; 1824 entry.blue = instance.blue; 1825 entry.which = instance.which; 1826 entry.factor = new double [] { instance.factor[0], instance.factor[1], instance.factor[2], instance.factor[3] }; 1827 entry.rainbow = instance.rainbow; 1828 entries.add(entry); 1829 instance.fixFactor(); 1830 } 1831 return (ColorInformation)entries.get(index); 1832 } 1833 1834 protected static ColorInformation instance = new ColorInformation(); 1835 1836 protected static List entries = new ArrayList (1000); 1837 1838 public int red = 192; 1839 public int green = 64; 1840 public int blue = 64; 1841 1842 public int which = 2; 1843 public int change = 64; 1844 1845 public double [] factor = { 0.35, 0.1, -0.1, -0.3 }; 1846 public boolean rainbow; 1847 1848 public byte scale(int value, double factor) 1849 { 1850 if (factor > 0.0) 1851 { 1852 return (byte)(value + (255 - value) * factor); 1853 } 1854 else 1855 { 1856 return (byte)(value + value * factor); 1857 } 1858 } 1859 1860 protected void generateColor() 1861 { 1862 switch (which) 1863 { 1864 case 0: 1865 { 1866 red += change; 1867 if (red <= 64) 1868 { 1869 which = 1; 1870 change = -change; 1871 } 1872 else if (red >= 192) 1873 { 1874 which = 1; 1875 change = -change; 1876 } 1877 break; 1878 } 1879 case 1: 1880 { 1881 green += change; 1882 if (green >= 192) 1883 { 1884 which = 2; 1885 change = -change; 1886 } 1887 else if (green <= 64) 1888 { 1889 which = 2; 1890 change = -change; 1891 } 1892 break; 1893 } 1894 case 2: 1895 { 1896 blue += change; 1897 if (blue >= 192) 1898 { 1899 which = 0; 1900 change = -change; 1901 } 1902 else if (blue <=64) 1903 { 1904 which = 0; 1905 change = -change; 1906 } 1907 break; 1908 } 1909 } 1910 } 1911 1912 protected void fixFactor() 1913 { 1914 if (red == 192 && green == 64 && blue == 64) 1915 { 1916 for (int j = 0; j < factor.length; ++j) 1917 { 1918 factor[j] += 0.3; 1919 } 1920 if (factor[0] >= 1.0) 1921 { 1922 rainbow = true; 1923 for (int j = 0; j < factor.length; ++j) 1924 { 1925 factor[j] -= 0.8; 1926 } 1927 } 1928 } 1929 } 1930 } 1931 1932 public String eURIFragmentSegment(EStructuralFeature eStructuralFeature, EObject eObject) 1933 { 1934 if (eObject instanceof GenBaseImpl) 1935 { 1936 GenBaseImpl genBaseImpl = (GenBaseImpl)eObject; 1937 String name = genBaseImpl.getName(); 1938 if (name != null) 1939 { 1940 int count = 0; 1941 for (Iterator i = eContents().iterator(); i.hasNext(); ) 1942 { 1943 Object otherEObject = i.next(); 1944 if (otherEObject == eObject) 1945 { 1946 break; 1947 } 1948 if (otherEObject instanceof GenBaseImpl) 1949 { 1950 GenBaseImpl otherGenBaseImpl = (GenBaseImpl)otherEObject; 1951 if (name.equals(otherGenBaseImpl.getName())) 1952 { 1953 ++count; 1954 } 1955 } 1956 } 1957 return 1958 count > 0 ? 1959 name + "." + count : 1960 name; 1961 } 1962 } 1963 return super.eURIFragmentSegment(eStructuralFeature, eObject); 1964 } 1965 1966 public EObject eObjectForURIFragmentSegment(String uriFragmentSegment) 1967 { 1968 if (!uriFragmentSegment.startsWith("@")) 1969 { 1970 int index = uriFragmentSegment.indexOf("."); 1971 String name = index == -1 ? uriFragmentSegment : uriFragmentSegment.substring(0, index); 1972 int count = 0; 1973 if (index != -1) 1974 { 1975 try 1976 { 1977 count = Integer.parseInt(uriFragmentSegment.substring(index + 1)); 1978 } 1979 catch (NumberFormatException exception) 1980 { 1981 throw new WrappedException(exception); 1982 } 1983 } 1984 1985 for (Iterator i = eContents().iterator(); i.hasNext(); ) 1986 { 1987 Object object = i.next(); 1988 if (object instanceof GenBaseImpl) 1989 { 1990 GenBaseImpl genBaseImpl = (GenBaseImpl)object; 1991 if (name.equals(genBaseImpl.getName()) && count-- == 0) 1992 { 1993 return genBaseImpl; 1994 } 1995 } 1996 } 1997 1998 return null; 1999 } 2000 else 2001 { 2002 return super.eObjectForURIFragmentSegment(uriFragmentSegment); 2003 } 2004 } 2005 2006 protected static String unicodeEscapeEncode(String unicode) 2007 { 2008 StringBuffer result = new StringBuffer (unicode.length()); 2009 for (int i = 0, size = unicode.length(); i < size; ++i) 2010 { 2011 char character = unicode.charAt(i); 2012 if (character > '\u00ff') 2013 { 2014 result.append("\\u"); 2015 String hex = Integer.toString(character, 16); 2016 for (int j = hex.length(); j < 4; ++j) 2017 { 2018 result.append("0"); 2019 } 2020 result.append(hex); 2021 } 2022 else 2023 { 2024 result.append(character); 2025 } 2026 } 2027 2028 return result.toString(); 2029 } 2030 2031 public abstract EModelElement getEcoreModelElement(); 2032 2033 protected String getDocumentation() 2034 { 2035 return EcoreUtil.getDocumentation(getEcoreModelElement()); 2036 } 2037 2038 public boolean hasDocumentation() 2039 { 2040 return getDocumentation() != null; 2041 } 2042 2043 public String getDocumentation(String indentation) 2044 { 2045 return indent(getDocumentation(), indentation); 2046 } 2047 2048 protected String indent(String text, String indentation) 2049 { 2050 if (text == null) 2051 { 2052 return null; 2053 } 2054 else 2055 { 2056 String separator = System.getProperty("line.separator") + indentation; 2057 int increment = separator.length() - 1; 2058 StringBuffer stringBuffer = new StringBuffer (text); 2059 for (int i = 0; i < stringBuffer.length(); ++i) 2060 { 2061 switch (stringBuffer.charAt(i)) 2062 { 2063 case '\n': 2064 { 2065 stringBuffer.replace(i, i + (i + 1 < stringBuffer.length() && stringBuffer.charAt(i + 1) == '\r' ? 2 : 1), separator); 2066 i += increment; 2067 break; 2068 } 2069 case '\r': 2070 { 2071 stringBuffer.replace(i, i + (i + 1 < stringBuffer.length() && stringBuffer.charAt(i + 1) == '\n' ? 2 : 1), separator); 2072 i += increment; 2073 break; 2074 } 2075 } 2076 } 2077 return stringBuffer.toString(); 2078 } 2079 } 2080 2081 protected ExtendedMetaData getExtendedMetaData() 2082 { 2083 return eContainer() == null ? ExtendedMetaData.INSTANCE : ((GenBaseImpl)eContainer()).getExtendedMetaData(); 2084 } 2085 2086 protected void addNonDuplicates(Collection target, Collection source, Set noDupSet) 2087 { 2088 if (noDupSet == null) 2089 { 2090 noDupSet = new HashSet (target); 2091 } 2092 2093 for (Iterator iter = source.iterator(); iter.hasNext(); ) 2094 { 2095 Object o = iter.next(); 2096 if (noDupSet.add(o)) 2097 { 2098 target.add(o); 2099 } 2100 } 2101 } 2102} 2103 | Popular Tags |