Ejemplo n.º 1
0
 /**
  *
  * <!-- begin-user-doc -->
  * Prints diagnostics with indentation.
  * <!--
  * end-user-doc -->
  *
  * @param diagnostic the diagnostic to print.
  * @param indent the indentation for printing.
  * @generated
  */
 protected static void printDiagnostic(Diagnostic diagnostic, String indent) {
   System.out.print(indent);
   System.out.println(diagnostic.getMessage());
   for (Diagnostic child : diagnostic.getChildren()) {
     printDiagnostic(child, indent + "  ");
   }
 }
Ejemplo n.º 2
0
 private RefactoringStatus validate(IProgressMonitor pm, EObject object) {
   RefactoringStatus refactoringStatus = RefactoringStatus.create(Status.OK_STATUS);
   EValidator.Registry validatorRegistry =
       extensions.getInstance(EValidator.Registry.class, object);
   EPackage epackage = object.eClass().getEPackage();
   EValidator validator = validatorRegistry.getEValidator(epackage);
   BasicDiagnostic diagnostics = new BasicDiagnostic();
   if (pm.isCanceled()) {
     refactoringStatus = RefactoringStatus.create(Status.CANCEL_STATUS);
     pm.done();
   } else {
     SubMonitor sm = SubMonitor.convert(pm, "Validating re-factoring.", IProgressMonitor.UNKNOWN);
     validator.validate(object, diagnostics, Maps.newHashMap());
     Iterator<Diagnostic> validationIterator =
         Iterables.filter(
                 diagnostics.getChildren(),
                 new Predicate<Diagnostic>() {
                   @Override
                   public boolean apply(Diagnostic diagnostic) {
                     if (diagnostic instanceof FeatureBasedDiagnostic) {
                       return FeatureBasedDiagnostic.ERROR
                           == ((FeatureBasedDiagnostic) diagnostic).getSeverity();
                     }
                     return false;
                   }
                 })
             .iterator();
     if (validationIterator.hasNext()) {
       Diagnostic diagnostic = validationIterator.next();
       refactoringStatus = RefactoringStatus.createFatalErrorStatus(diagnostic.getMessage());
     }
     sm.done();
   }
   return refactoringStatus;
 }
Ejemplo n.º 3
0
 public String isValid(Object object) {
   Object value;
   try {
     value =
         eDataType
             .getEPackage()
             .getEFactoryInstance()
             .createFromString(eDataType, (String) object);
   } catch (Exception exception) {
     String message = exception.getClass().getName();
     int index = message.lastIndexOf('.');
     if (index >= 0) {
       message = message.substring(index + 1);
     }
     if (exception.getLocalizedMessage() != null) {
       message = message + ": " + exception.getLocalizedMessage();
     }
     return message;
   }
   Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eDataType, value);
   if (diagnostic.getSeverity() == Diagnostic.OK) {
     return null;
   } else {
     return (diagnostic.getChildren().get(0))
         .getMessage()
         .replaceAll("'", "''")
         .replaceAll("\\{", "'{'"); // }}
   }
 }
Ejemplo n.º 4
0
  @Lock(LockType.WRITE)
  public void put(String id, EObject value) {
    if (store.get(id) == null) {
      EObject obj = getEObjectByID(id);
      store.put(id, obj);
    }

    EObject obj = store.get(id);
    EList<EAttribute> eAttributes = obj.eClass().getEAllAttributes();
    for (EAttribute eAttribute : eAttributes) {
      obj.eSet(eAttribute, value.eGet(eAttribute));
      store.remove(id);
    }
    if (validation.getFlag()) {
      Diagnostic d = Diagnostician.INSTANCE.validate(obj);
      if (d.getSeverity() == Diagnostic.ERROR)
        throw new WebApplicationException(Status.BAD_REQUEST);
    }
    try {
      resourceLoader.getResource().save(Collections.EMPTY_MAP);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 5
0
        @Override
        public void notifyChanged(Notification notification) {
          if (notification.getNotifier() instanceof Resource) {
            switch (notification.getFeatureID(Resource.class)) {
              case Resource.RESOURCE__IS_LOADED:
              case Resource.RESOURCE__ERRORS:
              case Resource.RESOURCE__WARNINGS:
                {
                  Resource resource = (Resource) notification.getNotifier();
                  Diagnostic diagnostic = analyzeResourceProblems(resource, null);
                  if (diagnostic.getSeverity() != Diagnostic.OK) {
                    resourceToDiagnosticMap.put(resource, diagnostic);
                  } else {
                    resourceToDiagnosticMap.remove(resource);
                  }

                  if (updateProblemIndication) {
                    getSite()
                        .getShell()
                        .getDisplay()
                        .asyncExec(
                            new Runnable() {
                              @Override
                              public void run() {
                                updateProblemIndication();
                              }
                            });
                  }
                  break;
                }
            }
          } else {
            super.notifyChanged(notification);
          }
        }
  @Override
  public IDecorator[] getDecorators(final PictogramElement pe) {
    IFeatureProvider featureProvider = getFeatureProvider();
    Object bo = featureProvider.getBusinessObjectForPictogramElement(pe);
    Integer objectId;
    if (bo instanceof Method) {
      System.out.println("CHECKING METHOD");
      objectId = System.identityHashCode(bo.getClass());
      try { // generate decorator and markers
        if (!XcoreValidator.INSTANCE.validateMethod((Method) bo, diagnosticChain, null)) {
          Diagnostic lastDiagnostic =
              diagnosticChain.getChildren().get(diagnosticChain.getChildren().size() - 1);
          markers.put(
              objectId,
              AtomicDesignUtils.createMarker(
                  lastDiagnostic.getMessage(),
                  IMarker.SEVERITY_ERROR,
                  ((Method) bo).getClass().getName()));
          return new ImageDecorator[] {
            AtomicDesignUtils.createImageDecorator(
                lastDiagnostic, lastDiagnostic.getMessage(), 20, 0)
          };

        } else {
          AtomicDesignUtils.destroyMarker(markers.get(objectId));
        }

      } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    if (bo instanceof ComputationUnit) {
      System.out.println("CHECKING CU");
      if (!XcoreValidator.INSTANCE.validateComputationUnit(
          (ComputationUnit) bo, diagnosticChain, null)) {
        System.out.println("CHECKING METHOD");
      }
    }
    if (bo instanceof DataElement) {
      System.out.println("CHECKING DATAELEMENT");
      if (!XcoreValidator.INSTANCE.validateDataElement((DataElement) bo, diagnosticChain, null)) {}
    }

    if (bo instanceof Service) {
      System.out.println("CHECKING SERVICE");
      if (!XcoreValidator.INSTANCE.validateService((Service) bo, diagnosticChain, null)) {}
    }

    if (bo instanceof Parameter) {
      System.out.println("CHECKING PARAMETER");
      if (!XcoreValidator.INSTANCE.validateParameter((Parameter) bo, diagnosticChain, null)) {}
    }

    return super.getDecorators(pe);
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
   */
  public void firePropertiesChanged(IPropertiesEditionEvent event) {
    if (!isInitializing()) {
      Diagnostic valueDiagnostic = validateValue(event);
      if (PropertiesEditionEvent.COMMIT == event.getState()
          && IPropertiesEditionComponent.LIVE_MODE.equals(editing_mode)
          && valueDiagnostic.getSeverity() == Diagnostic.OK) {
        CompoundCommand command = new CompoundCommand();
        if (TarotViewsRepository.GamePlayers.players == event.getAffectedEditor()) {
          if (PropertiesEditionEvent.SET == event.getKind()) {
            Player oldValue = (Player) event.getOldValue();
            Player newValue = (Player) event.getNewValue();
            // TODO: Complete the game update command
            for (EStructuralFeature feature : newValue.eClass().getEAllStructuralFeatures()) {
              if (feature.isChangeable()
                  && !(feature instanceof EReference && ((EReference) feature).isContainer())) {
                command.append(
                    SetCommand.create(
                        liveEditingDomain, oldValue, feature, newValue.eGet(feature)));
              }
            }
          } else if (PropertiesEditionEvent.ADD == event.getKind())
            command.append(
                AddCommand.create(
                    liveEditingDomain,
                    game,
                    TarotPackage.eINSTANCE.getGame_Players(),
                    event.getNewValue()));
          else if (PropertiesEditionEvent.REMOVE == event.getKind())
            command.append(DeleteCommand.create(liveEditingDomain, event.getNewValue()));
          else if (PropertiesEditionEvent.MOVE == event.getKind())
            command.append(
                MoveCommand.create(
                    liveEditingDomain,
                    game,
                    TarotPackage.eINSTANCE.getPlayer(),
                    event.getNewValue(),
                    event.getNewIndex()));
        }

        if (!command.isEmpty() && !command.canExecute()) {
          EEFRuntimePlugin.getDefault().logError("Cannot perform model change command.", null);
        } else {
          liveEditingDomain.getCommandStack().execute(command);
        }
      }
      if (valueDiagnostic.getSeverity() != Diagnostic.OK
          && valueDiagnostic instanceof BasicDiagnostic)
        super.firePropertiesChanged(new PropertiesValidationEditionEvent(event, valueDiagnostic));
      else {
        Diagnostic validate = validate();
        super.firePropertiesChanged(new PropertiesValidationEditionEvent(event, validate));
      }
      super.firePropertiesChanged(event);
    }
  }
 /**
  * Handle diagnostic.
  *
  * @param resultDiagnostic the result diagnostic
  */
 private void handleDiagnostic(
     final Diagnostic resultDiagnostic, final String message, final String resultFilePath) {
   if (resultDiagnostic.getSeverity() == Diagnostic.OK) {
     Display.getDefault()
         .syncExec(
             new Runnable() {
               public void run() {
                 MessageDialog.openInformation(
                     PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                     "Document generator",
                     "The document has been generated successfully: \n" + resultFilePath);
               }
             });
   } else {
     Display.getDefault()
         .syncExec(
             new Runnable() {
               public void run() {
                 ErrorDialog.openError(
                     PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                     "Document generator",
                     "Error generating documentation.\n",
                     BasicDiagnostic.toIStatus(resultDiagnostic));
               }
             });
   }
 }
Ejemplo n.º 9
0
  /**
   * Updates the problems indication with the information described in the specified diagnostic.
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   *
   * @generated
   */
  protected void updateProblemIndication() {
    if (updateProblemIndication) {
      BasicDiagnostic diagnostic =
          new BasicDiagnostic(
              Diagnostic.OK,
              "org.eclipse.buckminster.rmap.editor",
              0,
              null,
              new Object[] {editingDomain.getResourceSet()});
      for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
        if (childDiagnostic.getSeverity() != Diagnostic.OK) {
          diagnostic.add(childDiagnostic);
        }
      }

      int lastEditorPage = getPageCount() - 1;
      if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
        ((ProblemEditorPart) getEditor(lastEditorPage)).setDiagnostic(diagnostic);
        if (diagnostic.getSeverity() != Diagnostic.OK) {
          setActivePage(lastEditorPage);
        }
      } else if (diagnostic.getSeverity() != Diagnostic.OK) {
        ProblemEditorPart problemEditorPart = new ProblemEditorPart();
        problemEditorPart.setDiagnostic(diagnostic);
        problemEditorPart.setMarkerHelper(markerHelper);
        try {
          addPage(++lastEditorPage, problemEditorPart, getEditorInput());
          setPageText(lastEditorPage, problemEditorPart.getPartName());
          setActivePage(lastEditorPage);
          showTabs();
        } catch (PartInitException exception) {
          RmapEditorPlugin.INSTANCE.log(exception);
        }
      }

      if (markerHelper.hasMarkers(editingDomain.getResourceSet())) {
        markerHelper.deleteMarkers(editingDomain.getResourceSet());
        if (diagnostic.getSeverity() != Diagnostic.OK) {
          try {
            markerHelper.createMarkers(diagnostic);
          } catch (CoreException exception) {
            RmapEditorPlugin.INSTANCE.log(exception);
          }
        }
      }
    }
  }
Ejemplo n.º 10
0
  protected Diagnostic findProblem(Diagnostic diagnostic, EObject target) {
    if (ExpressionsValidator.DIAGNOSTIC_SOURCE.equals(diagnostic.getSource())
        && (diagnostic.getSeverity() != Diagnostic.OK)
        && diagnostic.getData().contains(target)) {
      return diagnostic;
    }

    for (Diagnostic child : diagnostic.getChildren()) {
      Diagnostic result = findProblem(child, target);

      if (result != null) {
        return result;
      }
    }

    return null;
  }
  private boolean validateDlimModel(UsageEvolutionAlternative alternative)
      throws ValidationException {
    List<Resource> resources = alternative.getModelResources(ToolchainUtils.KEY_FILE_LIMBO);
    alternative
        .getSelfStatus()
        .checkError(
            ERROR_DLIM_NOT_REGISTERED, !resources.isEmpty(), true, ERROR_DLIM_NOT_REGISTERED);

    Resource resource = resources.get(0);
    alternative
        .getSelfStatus()
        .checkError(ERROR_DLIM_EMPTY, resource != null, true, ERROR_DLIM_EMPTY);

    Diagnostic diagnostic = Diagnostician.INSTANCE.validate(resource.getContents().get(0));

    boolean modelValid = diagnostic.getSeverity() == Diagnostic.OK;

    return modelValid;
  }
Ejemplo n.º 12
0
  /**
   * This is the method called to load a resource into the editing domain's resource set based on
   * the editor's input.
   * <!-- begin-user-doc -->
   * <!--
   * end-user-doc -->
   *
   * @generated
   */
  public void createModel() {
    URI resourceURI = EditUIUtil.getURI(getEditorInput());
    Exception exception = null;
    Resource resource = null;
    try {
      // Load the resource through the editing domain.
      //
      resource = editingDomain.getResourceSet().getResource(resourceURI, true);
    } catch (Exception e) {
      exception = e;
      resource = editingDomain.getResourceSet().getResource(resourceURI, false);
    }

    Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
    if (diagnostic.getSeverity() != Diagnostic.OK) {
      resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
    }
    editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
  }
Ejemplo n.º 13
0
 protected Image getValidationOverlay(Image image, final EObject object) {
   // final Integer severity = validationResultCacheTree.getCachedValue(object);
   final VDiagnostic vDiagnostic = getVElement().getDiagnostic();
   int highestSeverity = Diagnostic.OK;
   if (vDiagnostic != null) {
     for (final Diagnostic diagnostic : vDiagnostic.getDiagnostics(object)) {
       if (diagnostic.getSeverity() > highestSeverity) {
         highestSeverity = diagnostic.getSeverity();
       }
     }
   }
   final ImageDescriptor overlay =
       SWTValidationHelper.INSTANCE.getValidationOverlayDescriptor(highestSeverity);
   if (overlay == null) {
     return image;
   }
   final OverlayImageDescriptor imageDescriptor =
       new OverlayImageDescriptor(image, overlay, OverlayImageDescriptor.LOWER_RIGHT);
   final Image resultImage = imageDescriptor.createImage();
   return resultImage;
 }
 public void add(Diagnostic diagnostic) {
   if (diagnostic == null) return;
   List<Diagnostic> kids = diagnostic.getChildren();
   if (!kids.isEmpty()) {
     for (Diagnostic kid : kids) add(kid);
   } else {
     List<?> objects = diagnostic.getData();
     CSTNode cstNode = null;
     if (!objects.isEmpty()) {
       Object object = objects.get(0);
       if (object != null) {
         if (environment != null) cstNode = environment.getASTMapping(object);
         else if (object instanceof CSTNode) cstNode = (CSTNode) object;
       }
     }
     int startOffset = cstNode != null ? cstNode.getStartOffset() : 0;
     int endOffset = cstNode != null ? cstNode.getEndOffset() : 0;
     Severity problemSeverity = Severity.INFO;
     if (diagnostic.getSeverity() >= Diagnostic.ERROR) problemSeverity = Severity.ERROR;
     else if (diagnostic.getSeverity() >= Diagnostic.WARNING) problemSeverity = Severity.WARNING;
     String problemMessage = diagnostic.getMessage();
     String problemContext = diagnostic.getSource();
     handleProblem(problemSeverity, problemMessage, problemContext, startOffset, endOffset);
   }
 }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
   */
  public void firePropertiesChanged(IPropertiesEditionEvent event) {
    if (!isInitializing()) {
      Diagnostic valueDiagnostic = validateValue(event);
      if (PropertiesEditionEvent.COMMIT == event.getState()
          && IPropertiesEditionComponent.LIVE_MODE.equals(editing_mode)
          && valueDiagnostic.getSeverity() == Diagnostic.OK) {
        CompoundCommand command = new CompoundCommand();
        if (NonregViewsRepository.Combo.combo == event.getAffectedEditor())
          command.append(
              SetCommand.create(
                  liveEditingDomain,
                  talk,
                  NonregPackage.eINSTANCE.getTalk_Presenter(),
                  event.getNewValue()));
        if (NonregViewsRepository.Combo.comboRO == event.getAffectedEditor())
          command.append(
              SetCommand.create(
                  liveEditingDomain,
                  talk,
                  NonregPackage.eINSTANCE.getTalk_Presenter(),
                  event.getNewValue()));

        if (!command.isEmpty() && !command.canExecute()) {
          EEFRuntimePlugin.getDefault().logError("Cannot perform model change command.", null);
        } else {
          liveEditingDomain.getCommandStack().execute(command);
        }
      }
      if (valueDiagnostic.getSeverity() != Diagnostic.OK
          && valueDiagnostic instanceof BasicDiagnostic)
        super.firePropertiesChanged(new PropertiesValidationEditionEvent(event, valueDiagnostic));
      else {
        Diagnostic validate = validate();
        super.firePropertiesChanged(new PropertiesValidationEditionEvent(event, validate));
      }
      super.firePropertiesChanged(event);
    }
  }
Ejemplo n.º 16
0
  @Lock(LockType.WRITE)
  public Object remove(String id) {
    if (store.get(id) == null) {
      EObject obj = getEObjectByID(id);
      store.put(id, obj);
    }
    EObject obj = store.get(id);
    if (validation.getFlag()) {
      Diagnostic d = Diagnostician.INSTANCE.validate(obj);
      if (d.getSeverity() == Diagnostic.ERROR)
        throw new WebApplicationException(Status.BAD_REQUEST);
    }

    EcoreUtil.delete(obj);
    store.remove(id);
    try {
      resourceLoader.getResource().save(Collections.EMPTY_MAP);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
Ejemplo n.º 17
0
  protected boolean adjustMarker(IMarker marker, Diagnostic diagnostic) throws CoreException {
    if (diagnostic.getData() != null) {
      for (Object element : diagnostic.getData()) {
        if (element instanceof Resource.Diagnostic) {
          Resource.Diagnostic resourceDiagnostic = (Resource.Diagnostic) element;
          if (resourceDiagnostic.getLocation() != null) {
            marker.setAttribute(
                IMarker.LOCATION,
                EMFEditUIPlugin.getPlugin()
                    .getString(
                        "_UI_MarkerLocation",
                        new String[] {
                          Integer.toString(resourceDiagnostic.getLine()),
                          Integer.toString(resourceDiagnostic.getColumn())
                        }));

            marker.setAttribute(IMarker.LINE_NUMBER, resourceDiagnostic.getLine());
            return true;
          }
        }
      }
    }
    return false;
  }
Ejemplo n.º 18
0
  public void invoke(IWorkflowContext ctx) {
    ResourceSet resSet = getResourceSet();
    Resource resource = resSet.getResource(URI.createURI(genModel), true);
    final GenModel genModel = (GenModel) resource.getContents().get(0);
    genModel.setCanGenerate(true);
    genModel.reconcile();
    createGenModelSetup().registerGenModel(genModel);

    Generator generator =
        new Generator() {
          @Override
          public JControlModel getJControlModel() {
            return new JControlModel() {
              @Override
              public boolean canMerge() {
                return false;
              }
            };
          }
        };
    log.info("generating EMF code for " + this.genModel);
    generator
        .getAdapterFactoryDescriptorRegistry()
        .addDescriptor(
            GenModelPackage.eNS_URI,
            new GeneratorAdapterDescriptor(getTypeMapper(), getLineDelimiter()));
    generator.setInput(genModel);

    Diagnostic diagnostic =
        generator.generate(
            genModel, GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE, new BasicMonitor());

    if (diagnostic.getSeverity() != Diagnostic.OK) log.info(diagnostic);

    if (generateEdit) {
      Diagnostic editDiag =
          generator.generate(
              genModel, GenBaseGeneratorAdapter.EDIT_PROJECT_TYPE, new BasicMonitor());
      if (editDiag.getSeverity() != Diagnostic.OK) log.info(editDiag);
    }

    if (generateEditor) {
      Diagnostic editorDiag =
          generator.generate(
              genModel, GenBaseGeneratorAdapter.EDITOR_PROJECT_TYPE, new BasicMonitor());
      if (editorDiag.getSeverity() != Diagnostic.OK) log.info(editorDiag);
    }
  }
Ejemplo n.º 19
0
  public MavenMetadata(URI uri) throws CoreException {
    Resource resource = getResourceSet().getResource(uri, true);
    EList<EObject> content = resource.getContents();
    if (content.size() != 1)
      throw ExceptionUtils.fromMessage(
          "ECore Resource did not contain one resource. It had %d",
          Integer.valueOf(content.size()));

    documentRoot = (DocumentRoot) content.get(0);
    Diagnostic diag = Diagnostician.INSTANCE.validate(documentRoot);
    if (diag.getSeverity() == Diagnostic.ERROR) {
      for (Diagnostic childDiag : diag.getChildren()) LogUtils.error(childDiag.getMessage());
      throw ExceptionUtils.fromMessage(
          "Maven Metadata model validation failed: %s", diag.getMessage());
    }
  }
Ejemplo n.º 20
0
  public void testBug370824() throws Exception {
    if (EMFPlugin.IS_ECLIPSE_RUNNING) {
      IWorkspace workspace = ResourcesPlugin.getWorkspace();
      IProject project = workspace.getRoot().getProject("org.eclipse.ocl.examples.xtext.tests");
      if (!project.exists()) {
        project.create(null);
      }
    }
    metaModelManager = new MetaModelManager();
    String oclinecoreFile =
        "package bug370824 : bug370824 = 'http://bug370824'\n"
            + "{\n"
            + "    class Clase1\n"
            + "    {\n"
            + "        invariant : self.name.size() > 0;\n"
            + "        attribute name : String[?] { ordered };\n"
            + "    }\n"
            + "}\n";
    createEcoreFile(metaModelManager, "Bug370824", oclinecoreFile);
    String genmodelFile =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<genmodel:GenModel xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:ecore=\"http://www.eclipse.org/emf/2002/Ecore\"\n"
            + "    xmlns:genmodel=\"http://www.eclipse.org/emf/2002/GenModel\" modelDirectory=\"/org.eclipse.ocl.examples.xtext.tests/src-gen\" modelPluginID=\"org.eclipse.ocl.examples.xtext.tests.bug370824\"\n"
            + "    modelName=\"Bug370824\" importerID=\"org.eclipse.emf.importer.ecore\" complianceLevel=\"5.0\"\n"
            + "    copyrightFields=\"false\">\n"
            + "  <foreignModel>Bug370824.ecore</foreignModel>\n"
            + "  <genPackages prefix=\"Bug370824\" disposableProviderFactory=\"true\" ecorePackage=\"Bug370824.ecore#/\">\n"
            + "  </genPackages>\n"
            + "</genmodel:GenModel>\n"
            + "\n";
    createGenModelFile("Bug370824.genmodel", genmodelFile);
    GeneratorAdapterFactory.Descriptor.Registry.INSTANCE.addDescriptor(
        GenModelPackage.eNS_URI, OCLGeneratorAdapterFactory.DESCRIPTOR);
    URI fileURI = getProjectFileURI("Bug370824.genmodel");
    //		System.out.println("Generating Ecore Model using '" + fileURI + "'");
    metaModelManager.dispose();
    metaModelManager = new MetaModelManager();
    ResourceSet resourceSet = metaModelManager.getExternalResourceSet();
    resourceSet.getPackageRegistry().put(GenModelPackage.eNS_URI, GenModelPackage.eINSTANCE);
    resourceSet
        .getResourceFactoryRegistry()
        .getExtensionToFactoryMap()
        .put("genmodel", new EcoreResourceFactoryImpl());
    GeneratorAdapterFactory.Descriptor.Registry.INSTANCE.addDescriptor(
        GenModelPackage.eNS_URI, GenModelGeneratorAdapterFactory.DESCRIPTOR);
    GeneratorAdapterFactory.Descriptor.Registry.INSTANCE.addDescriptor(
        GenModelPackage.eNS_URI, OCLGeneratorAdapterFactory.DESCRIPTOR);
    if (resourceSet instanceof ResourceSetImpl) {
      ResourceSetImpl resourceSetImpl = (ResourceSetImpl) resourceSet;
      Map<URI, Resource> uriResourceMap = resourceSetImpl.getURIResourceMap();
      if (uriResourceMap != null) {
        uriResourceMap.clear();
      }
    }
    resourceSet.getResources().clear();
    Resource resource = resourceSet.getResource(fileURI, true);
    // EcoreUtil.resolveAll(resourceSet); -- genModel can fail if
    // proxies resolved here
    // problem arises if genmodel has an obsolete feature for a feature
    // moved up the inheritance hierarchy
    // since the proxy seems to be successfully resolved giving a double
    // feature
    checkResourceSet(resourceSet);
    EObject eObject = resource.getContents().get(0);
    if (!(eObject instanceof GenModel)) {
      throw new ConfigurationException("No GenModel found in '" + resource.getURI() + "'");
    }
    GenModel genModel = (GenModel) eObject;
    genModel.reconcile();
    checkResourceSet(resourceSet);
    // genModel.setCanGenerate(true);
    // validate();

    genModel.setValidateModel(true); // The more checks the better
    //		genModel.setCodeFormatting(true); // Normalize layout
    genModel.setForceOverwrite(false); // Don't overwrite read-only
    // files
    genModel.setCanGenerate(true);
    // genModel.setFacadeHelperClass(null); // Non-null gives JDT
    // default NPEs
    //		genModel.setFacadeHelperClass(StandaloneASTFacadeHelper.class.getName()); // Bug 308069
    // genModel.setValidateModel(true);
    genModel.setBundleManifest(false); // New manifests should be
    // generated manually
    genModel.setUpdateClasspath(false); // New class-paths should be
    // generated manually
    genModel.setComplianceLevel(GenJDKLevel.JDK50_LITERAL);
    // genModel.setRootExtendsClass("org.eclipse.emf.ecore.impl.MinimalEObjectImpl$Container");
    Diagnostic diagnostic = genModel.diagnose();
    if (diagnostic.getSeverity() != Diagnostic.OK) {
      fail(diagnostic.toString());
    }

    /*
     * JavaModelManager.getJavaModelManager().initializePreferences();
     * new
     * JavaCorePreferenceInitializer().initializeDefaultPreferences();
     *
     * GenJDKLevel genSDKcomplianceLevel =
     * genModel.getComplianceLevel(); String complianceLevel =
     * JavaCore.VERSION_1_5; switch (genSDKcomplianceLevel) { case
     * JDK60_LITERAL: complianceLevel = JavaCore.VERSION_1_6; case
     * JDK14_LITERAL: complianceLevel = JavaCore.VERSION_1_4; default:
     * complianceLevel = JavaCore.VERSION_1_5; } // Hashtable<?,?>
     * defaultOptions = JavaCore.getDefaultOptions(); //
     * JavaCore.setComplianceOptions(complianceLevel, defaultOptions);
     * // JavaCore.setOptions(defaultOptions);
     */

    Generator generator = GenModelUtil.createGenerator(genModel);
    Monitor monitor = new BasicMonitor();
    diagnostic = generator.generate(genModel, GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE, monitor);
    if (diagnostic.getSeverity() != Diagnostic.OK) {
      fail(diagnostic.toString());
    }
  }
  @Override
  public void launch(
      ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    try {
      this.launch = launch;
      cleanup();

      final MitraLaunchConfigurationAdapter configAdapter =
          new MitraLaunchConfigurationAdapter(configuration);

      String consoleName = "Mitra Interpreter [" + configAdapter.getName() + "] " + mode;
      console = findConsole(consoleName);
      console.activate();
      initConsoleStream();

      clearConsole();

      final StandaloneExecutor executor =
          MitraStandaloneLaunchFactory.createExecutor(configAdapter);
      executor.getProjectContext().setMessageAcceptor(new ConsoleMessageAcceptor(console));

      console.addPatternMatchListener(new MitraConsoleTracker(executor.getProjectContext()));

      executor.getProjectContext().out = new PrintStream(createMessageStream(SWT.COLOR_BLACK));

      PrintStream err = new PrintStream(createMessageStream(SWT.COLOR_RED));
      executor.getProjectContext().err = err;

      executor.getProjectContext().log = new PrintStream(createMessageStream(SWT.COLOR_BLUE));

      try {
        executor.prepareInterpreter();
      } catch (Exception ex) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                MitraDebugPlugin.PLUGIN_ID,
                "Error preparing Mitra interpreter: " + ex.getMessage(),
                ex));
      }

      executor
          .getDebugable()
          .addInterpreterListener(
              new IDebugableListener() {

                @Override
                public void terminated() {

                  out("Mitra interpreter terminated.");
                  try {
                    for (String fileName : configAdapter.getOutputModelFilenames().values()) {
                      URI uri = URI.createFileURI(fileName);
                      refreshPath(uri);
                    }
                    for (String fileName : configAdapter.getInputModelFilenames().values()) {
                      URI uri = URI.createFileURI(fileName);
                      refreshPath(uri);
                    }
                    if (configAdapter.isSaveTraces()) {
                      URI uri = URI.createFileURI(configAdapter.getTraceModelFilename());
                      refreshPath(uri);
                    }
                  } catch (CoreException ex) {
                    out("Error refreshing project path: " + ex);
                  }
                }

                @Override
                public void processDebugableEvent(DebugEventType eventType) {
                  // not interested in
                }

                @Override
                public void suspended() {
                  // not interested in
                }
              });

      ResourceSet rs = executor.getProjectContext().getResourceSet();
      int errorCount = 0;
      int warningCount = 0;
      int moduleCount = 0;
      // iterate over copy, as new resources may be
      // added while resolving proxies
      List<Resource> resources = new ArrayList<Resource>(rs.getResources());
      for (Resource resource : resources) {
        errorCount += resource.getErrors().size();
        warningCount += resource.getWarnings().size();

        if (resource.getContents().size() > 0) {
          for (EObject model : resource.getContents()) {

            if (model instanceof Module) {
              moduleCount++;
            }
            Diagnostic diagnostic = Diagnostician.INSTANCE.validate(model);
            for (Diagnostic child : diagnostic.getChildren()) {
              switch (child.getSeverity()) {
                case Diagnostic.ERROR:
                  if (!(model instanceof Module)) {
                    err.println(model.eResource().getURI() + ": " + child.getMessage());
                  }
                  errorCount++;
                  break;
                case Diagnostic.WARNING:
                  warningCount++;
              }
            }
          }
        }
      }

      MessageFormat form = new MessageFormat("Loaded {0}{1}, {2}.");
      double[] limits = {0, 1, 2};
      String[] moduleparts = {"no module", "1 module", "{0,number} modules"};
      ChoiceFormat moduleform = new ChoiceFormat(limits, moduleparts);
      form.setFormatByArgumentIndex(0, moduleform);
      String[] errorparts = {" successfully: 0 errors", ": 1 error", ": {1,number} errors"};
      ChoiceFormat errorform = new ChoiceFormat(limits, errorparts);
      form.setFormatByArgumentIndex(1, errorform);
      String[] warningparts = {"0 warnings", "1 warning", "{2,number} warnings"};
      ChoiceFormat warningform = new ChoiceFormat(limits, warningparts);
      form.setFormatByArgumentIndex(2, warningform);

      String msg = form.format(new Object[] {moduleCount, errorCount, warningCount});
      if (errorCount > 0) {
        msg += " Cannot start Mitra intpreter.";
      }
      out(msg);
      if (errorCount > 0 || moduleCount == 0) {
        throw new CoreException(new Status(IStatus.ERROR, MitraDebugPlugin.PLUGIN_ID, msg));
      }

      IDebuggable debugable = executor.getDebugable(); // debugable
      // supports
      // listeners!

      if (debugable == null) {
        throw new CoreException(
            new Status(
                IStatus.ERROR, MitraDebugPlugin.PLUGIN_ID, "No debuggable interpreter prepared."));
      }

      RuleDeclaration decl = debugable.getCalledRule();

      if (decl == null) {
        throw new CoreException(
            new Status(IStatus.ERROR, MitraDebugPlugin.PLUGIN_ID, "No rule selected."));
      }
      IDebugTarget debugTarget =
          new MitraDebugTarget(
              launch, new MitraDebugProxy(debugable), decl.eResource().getURI().toFileString());

      Display display = Display.getCurrent();
      if (display == null) { // start in normal thread
        if (log.isLoggable(Level.INFO)) {
          log.info("Start mitra interpreter via new thread");
        }
        out("Start Mitra interpreter on new thread");

        Thread interpreterThread = new Thread(debugable);
        if (mode.equals(ILaunchManager.DEBUG_MODE)) {
          debugable.enableDebug(true);
          interpreterThread.setName("MitraInterpreter");
          interpreterThread.start();
          launch.addDebugTarget(debugTarget);
        } else {
          interpreterThread.start();
        }
      } else { // start via display
        if (log.isLoggable(Level.INFO)) {
          log.info("Start mitra interpreter via display.asyncExec");
        }
        out("Start Mitra interpreter on display thread");

        if (mode.equals(ILaunchManager.DEBUG_MODE)) {
          debugable.enableDebug(true);
          display.asyncExec(debugable);
          // interpreterThread.setName("MitraInterpreter");
          // interpreterThread.start();
          launch.addDebugTarget(debugTarget);
        } else {
          display.asyncExec(debugable);
        }
      }
      out("Interpreter running...");
    } finally {
      console = null;
    }
  }
Ejemplo n.º 22
0
 protected void assertProblem(Diagnostic diagnostic, EObject target, int code) {
   Diagnostic problem = findProblem(diagnostic, target, code);
   assertNotNull("Problem not found", problem);
   System.out.println("Found expected problem: " + problem.getMessage());
 }
 public void merge(Diagnostic diagnostic) {
   if (diagnostic.getChildren().isEmpty()) add(diagnostic);
   else addAll(diagnostic);
 }
 public void addAll(Diagnostic diagnostic) {
   for (Diagnostic child : diagnostic.getChildren()) add(child);
 }
Ejemplo n.º 25
0
  /**
   * Initializes me with a diagnostic obtained from a problem handler.
   *
   * @param problem the diagnostic
   * @since 1.2
   */
  public ParserException(Diagnostic problem) {
    super(problem.getMessage());

    this.diagnostic = problem;
  }
Ejemplo n.º 26
0
  /**
   *
   * <!-- begin-user-doc -->
   * Load all the argument file paths or URIs as instances of the model.
   * <!-- end-user-doc -->
   *
   * @param args the file paths or URIs.
   * @generated
   */
  public static void main(String[] args) {
    // Create a resource set to hold the resources.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    // Register the appropriate resource factory to handle all file extensions.
    //
    resourceSet
        .getResourceFactoryRegistry()
        .getExtensionToFactoryMap()
        .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());

    // Register the package to ensure it is available during loading.
    //
    resourceSet.getPackageRegistry().put(Mu2consolPackage.eNS_URI, Mu2consolPackage.eINSTANCE);

    // If there are no arguments, emit an appropriate usage message.
    //
    if (args.length == 0) {
      System.out.println("Enter a list of file paths or URIs that have content like this:");
      try {
        Resource resource = resourceSet.createResource(URI.createURI("http:///My.mu2consol"));
        GeneralHeaderConstraints root = Mu2consolFactory.eINSTANCE.createGeneralHeaderConstraints();
        resource.getContents().add(root);
        resource.save(System.out, null);
      } catch (IOException exception) {
        exception.printStackTrace();
      }
    } else {
      // Iterate over all the arguments.
      //
      for (int i = 0; i < args.length; ++i) {
        // Construct the URI for the instance file.
        // The argument is treated as a file path only if it denotes an existing file.
        // Otherwise, it's directly treated as a URL.
        //
        File file = new File(args[i]);
        URI uri =
            file.isFile() ? URI.createFileURI(file.getAbsolutePath()) : URI.createURI(args[i]);

        try {
          // Demand load resource for this file.
          //
          Resource resource = resourceSet.getResource(uri, true);
          System.out.println("Loaded " + uri);

          // Validate the contents of the loaded resource.
          //
          for (EObject eObject : resource.getContents()) {
            Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eObject);
            if (diagnostic.getSeverity() != Diagnostic.OK) {
              printDiagnostic(diagnostic, "");
            }
          }
        } catch (RuntimeException exception) {
          System.out.println("Problem loading " + uri);
          exception.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 27
0
 /**
  * Indicates that the given diagnostic is neither error or canceled.
  *
  * @param diagnostic the diagnostic to test
  * @return <code>true</code> in case of success, <code>false</code> otherwise
  */
 public static boolean isSuccess(Diagnostic diagnostic) {
   int severity = diagnostic.getSeverity();
   return severity != Diagnostic.ERROR && severity != Diagnostic.CANCEL;
 }