Example #1
0
 @Override
 public void setUp() throws Exception {
   super.setUp();
   modelAsText =
       "stuff mystuff\nstuff yourstuff refs _mystuff stuff hisstuff refs _yourstuff// Comment";
   IFile file = IResourcesSetupUtil.createFile("test/test.testlanguage", modelAsText);
   editor = openEditor(file);
   document = editor.getDocument();
   hover =
       Activator.getInstance()
           .getInjector(getEditorId())
           .getInstance(ProblemAnnotationHover.class);
   hover.setSourceViewer(editor.getInternalSourceViewer());
   List<Issue> issues =
       document.readOnly(
           new IUnitOfWork<List<Issue>, XtextResource>() {
             public List<Issue> exec(XtextResource state) throws Exception {
               return state
                   .getResourceServiceProvider()
                   .getResourceValidator()
                   .validate(state, CheckMode.ALL, null);
             }
           });
   MarkerCreator markerCreator =
       Activator.getInstance().getInjector(getEditorId()).getInstance(MarkerCreator.class);
   for (Issue issue : issues) {
     markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
   }
 }
  @Fix(DotJavaValidator.ATTRIBUTE__INVALID_VALUE__EDGE_STYLE)
  public void fixEdgeStyleAttributeValue(final Issue issue, IssueResolutionAcceptor acceptor) {
    for (String edgeStyle : DotProperties.EDGE_STYLE_VALUES) {
      // quote values if needed, otherwise use plain attribute value
      final String validValue =
          DotTerminalConverters.needsToBeQuoted(edgeStyle)
              ? DotTerminalConverters.quote(edgeStyle)
              : edgeStyle;
      acceptor.accept(
          issue,
          "Replace '"
              + issue.getData()[0]
              + "' with '"
              + validValue //$NON-NLS-1$ //$NON-NLS-2$
              + "'.", //$NON-NLS-1$
          "Use valid '"
              + validValue
              + "' instead of invalid '" //$NON-NLS-1$ //$NON-NLS-2$
              + issue.getData()[0]
              + "' edge style.", //$NON-NLS-1$
          null,
          new ISemanticModification() {

            @Override
            public void apply(EObject element, IModificationContext context) throws Exception {
              ((Attribute) element).setValue(validValue);
            }
          });
    }
  }
 @SuppressWarnings("unchecked")
 protected Severity getSeverity(XtextEditor xtextEditor) {
   if (xtextEditor == null || xtextEditor.getInternalSourceViewer() == null) return null;
   IAnnotationModel model = xtextEditor.getInternalSourceViewer().getAnnotationModel();
   if (model != null) {
     Iterator<Annotation> iterator = model.getAnnotationIterator();
     boolean hasWarnings = false;
     boolean hasInfos = false;
     while (iterator.hasNext()) {
       Annotation annotation = iterator.next();
       if (!annotation.isMarkedDeleted()) {
         Issue issue = issueUtil.getIssueFromAnnotation(annotation);
         if (issue != null) {
           if (issue.getSeverity() == Severity.ERROR) {
             return Severity.ERROR;
           } else if (issue.getSeverity() == Severity.WARNING) {
             hasWarnings = true;
           } else if (issue.getSeverity() == Severity.INFO) {
             hasInfos = true;
           }
         }
       }
     }
     if (hasWarnings) return Severity.WARNING;
     if (hasInfos) return Severity.INFO;
   }
   return null;
 }
 private void removeExpensiveXtextAnnotations(IProgressMonitor monitor) {
   List<Annotation> issues = Lists.newArrayList();
   Iterator<XtextAnnotation> xtext =
       Iterators.filter(fAnnotationModel.getAnnotationIterator(), XtextAnnotation.class);
   while (xtext.hasNext() && !monitor.isCanceled()) {
     final XtextAnnotation annotation = xtext.next();
     Issue issue = annotation.getIssue();
     if (!annotation.isMarkedDeleted()
         && isRelevantAnnotationType(annotation.getType())
         && issue.getType() == CheckType.EXPENSIVE) {
       issues.add(annotation);
     }
   }
   updateAnnotations(monitor, issues, Maps.<Annotation, Position>newHashMap());
 }
  @Fix(AdlJavaValidator.MISSING_PARAMETERS_ERROR_ID)
  public void addParameters(final Issue issue, IssueResolutionAcceptor acceptor) {
    String[] issueData = issue.getData();
    acceptor.accept(
        issue,
        "Add parameters",
        "Add parameters to the reference of the definition " + issueData[0],
        null,
        new ISemanticModification() {

          public void apply(EObject element, IModificationContext context) throws Exception {
            // TODO how to provide a template that allows to easily iterate over
            // parameter values
            DefinitionReference reference = (DefinitionReference) element;
            Definition referencedDefinition = (Definition) reference.getDefinition();
            List<ParameterDecl> parameters = AdlModelHelper.getParameters(referencedDefinition);
            if (parameters != null && parameters.size() > 0) {
              IXtextDocument document = context.getXtextDocument();
              int offset = issue.getOffset() + issue.getLength();
              String paramString = "(";
              for (int i = 0; i < parameters.size() - 1; i++) {
                paramString += ", ";
              }
              paramString += ")";
              document.replace(offset, 0, paramString);
            }
          }
        });
  }
Example #6
0
 private void printError(Issue issue) {
   DeltajFile file = getDeltajFileFromTmpLine(issue.getLineNumber());
   String s =
       ""
           + (issue.isSyntaxError() ? "SYNTAX " : "")
           + "ERROR"
           + "\n"
           + (file != null
               ? "LINE:\t\t" + (issue.getLineNumber() - file.getStartLine()) + "\n"
               : "")
           + (file != null ? "FILE:\t\t" + file.getMember().getFullPath() + "\n" : "")
           + "DESCRIPTION:\t"
           + issue.getMessage()
           + "\n\n";
   consoleMessageStream.print(s);
   this.errors++;
 }
Example #7
0
 public String apply(Object input) {
   if (input instanceof Issue) {
     Issue issue = (Issue) input;
     StringBuffer result = new StringBuffer();
     if (showSeverity) {
       result.append(issue.getSeverity().name());
       result.append(" ");
     }
     result.append('"');
     result.append(issue.getMessage());
     result.append('"');
     result.append(" at \"");
     result.append(getIssueLocationText(issue));
     result.append("\"");
     return result.toString();
   } else if (input == null) return "null";
   return input.getClass() + ": " + input.toString();
 }
 @Fix(IssueCodes.AMBIGUOUS_FEATURE_CALL)
 public void fixAmbiguousMethodCall(final Issue issue, IssueResolutionAcceptor acceptor) {
   String[] data = issue.getData();
   if (data == null || data.length == 0) {
     return;
   }
   for (String replacement : data) {
     String replaceLabel = "Change to '" + replacement + "'";
     acceptor.accept(
         issue, replaceLabel, replaceLabel, null, new ReplaceModification(issue, replacement));
   }
 }
  @Fix(IssueCodes.FEATURE_NOT_VISIBLE)
  public void fixInvisibleFeature(final Issue issue, IssueResolutionAcceptor acceptor) {
    if (issue.getData() != null
        && issue.getData().length >= 1
        && "subclass-context".equals(issue.getData()[0])) {
      String fixup;
      if (issue.getData().length == 1) fixup = "Add type cast.";
      else fixup = "Add cast to " + issue.getData()[1] + ".";
      acceptor.accept(
          issue,
          fixup,
          fixup,
          null,
          new ISemanticModification() {

            @Override
            public void apply(EObject element, IModificationContext context) throws Exception {
              if (!(element instanceof XAbstractFeatureCall)) return;
              XAbstractFeatureCall featureCall = (XAbstractFeatureCall) element;
              if (!(featureCall.getFeature() instanceof JvmMember)) return;
              JvmType declaringType = ((JvmMember) featureCall.getFeature()).getDeclaringType();
              if (featureCall instanceof XMemberFeatureCall) {
                addTypeCastToExplicitReceiver(
                    featureCall,
                    context,
                    declaringType,
                    XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_TARGET);
              } else if (featureCall instanceof XAssignment) {
                addTypeCastToExplicitReceiver(
                    featureCall,
                    context,
                    declaringType,
                    XbasePackage.Literals.XASSIGNMENT__ASSIGNABLE);
              } else if (featureCall instanceof XFeatureCall) {
                addTypeCastToImplicitReceiver((XFeatureCall) featureCall, context, declaringType);
              }
            }
          });
    }
  }
  /**
   * Find start and length of the element that <code>issue</code> represents in an array. The
   * resulting <code>bounds</code> will include preceeding or trailing comma (not both) if present
   * so that the syntax of the array is intact if the range is removed.
   *
   * @param txt The text containing the array
   * @param issue The issue that represents the array element
   * @param bounds A two element array where the start and lenght will be returned
   * @return <code>true</code> if the range could be deteremined or <code>false</code> to indicate
   *     that the tokens expected to precede and succeed the element could not be found.
   */
  public static boolean findArrayElementBounds(String txt, Issue issue, int[] bounds) {
    int start = issue.getOffset();
    int end = issue.getOffset() + issue.getLength();

    // Find preceding comma or start of array
    char c = 0;
    int cma = start;
    while (--cma >= 0) {
      c = txt.charAt(cma);
      if (c == ',' || c == '[') break;
    }

    if (c != ',') {
      if (c != '[')
        // Element must be preceeded by comma or start of array
        return false;

      // No preceding comma. Find trailing comma or end of array
      int eot = txt.length();
      cma = end;
      c = 0;
      while (cma < eot) {
        c = txt.charAt(cma);
        if (c == ',' || c == ']') break;
        ++cma;
      }
      if (c == ',') {
        end = cma + 1;
        // Also swallow whitespace after comma
        while (end < eot && Character.isWhitespace(txt.charAt(end))) end++;
      } else if (c == ']') end = cma;
      else
        // Neither comma nor array end follow after element.
        return false;

    } else start = cma;
    bounds[0] = start;
    bounds[1] = end - start;
    return true;
  }
 @Override
 public void createLinkingIssueResolutions(Issue issue, IssueResolutionAcceptor acceptor) {
   super.createLinkingIssueResolutions(issue, acceptor);
   Matcher m = REF_PATTERN.matcher(issue.getMessage());
   if (m.find()) {
     final String key = m.group(1);
     acceptor.accept(
         issue,
         "Import " + key + " from Puppet Forge",
         "Import the missing " + key + " module from the Puppet Forge repository",
         null,
         new ISemanticModification() {
           @Override
           public void apply(EObject element, IModificationContext context) throws Exception {
             IWizardDescriptor descriptor =
                 workbench
                     .getImportWizardRegistry()
                     .findWizard("com.puppetlabs.geppetto.ui.ImportPuppetModuleFromForgeWizard");
             IWorkbenchWizard wizard = descriptor.createWizard();
             WizardDialog wd =
                 new WizardDialog(workbench.getActiveWorkbenchWindow().getShell(), wizard);
             ((NewWithKeyword) wizard).startWithKeyword(key);
             wd.setTitle(wizard.getWindowTitle());
             wd.open();
           }
         });
     acceptor.accept(
         issue,
         "Import " + key + " from local disk",
         "Import the missing " + key + " module from a local source folder",
         null,
         new ISemanticModification() {
           @Override
           public void apply(EObject element, IModificationContext context) throws Exception {
             IWizardDescriptor descriptor =
                 workbench
                     .getImportWizardRegistry()
                     .findWizard("com.puppetlabs.geppetto.ui.ImportPuppetModuleFromSourceWizard");
             IWorkbenchWizard wizard = descriptor.createWizard();
             WizardDialog wd =
                 new WizardDialog(workbench.getActiveWorkbenchWindow().getShell(), wizard);
             wd.setTitle(wizard.getWindowTitle());
             wd.open();
           }
         });
   }
 }
 @Fix(IssueCodes.INVALID_TYPE_ARGUMENTS_ON_TYPE_LITERAL)
 public void fixTypeArguments(final Issue issue, IssueResolutionAcceptor acceptor) {
   String message = issue.getMessage();
   String fixup = "Remove invalid type arguments";
   if (message.contains("argument.")) {
     fixup = "Remove invalid type argument";
   }
   acceptor.accept(
       issue,
       fixup,
       fixup,
       null,
       new IModification() {
         @Override
         public void apply(IModificationContext context) throws Exception {
           IXtextDocument document = context.getXtextDocument();
           document.replace(issue.getOffset(), issue.getLength(), "");
         }
       });
 }
 @Fix(ModuleDiagnostics.ISSUE__MISSING_REQUIRED_ATTRIBUTE)
 public void addMissingAttribute(final Issue issue, IssueResolutionAcceptor acceptor) {
   String[] data = issue.getData();
   if (data == null || data.length == 0) return;
   final String key = data[0];
   acceptor.accept(
       issue,
       "Add entry for \"" + key + "\"",
       "Add missing entry for attribute \"" + key + "\"with template value",
       null,
       new ISemanticModification() {
         @Override
         public void apply(EObject element, IModificationContext context) throws Exception {
           IXtextDocument doc = context.getXtextDocument();
           StringBuilder bld = new StringBuilder();
           bld.append("\"");
           bld.append(key);
           bld.append("\": \"");
           context.getXtextDocument();
           if ("version".equals(key)) bld.append("0.1.0");
           else if ("version_requirement".equals(key)) bld.append(">=0.0.0");
           else if ("author".equals(key)) bld.append(getModuleOwner());
           else if ("name".equals(key)) {
             if ((element instanceof JsonMetadata)) {
               bld.append(getModuleOwner());
               bld.append("-");
               bld.append(
                   ModuleName.safeName(
                       doc.<IFile>getAdapter(IFile.class).getParent().getName(), false));
             }
           }
           bld.append("\",\n  ");
           doc.replace(issue.getOffset(), 0, bld.toString());
         }
       });
 }
Example #14
0
  public boolean runGenerator(String inputPath, Metadata metadata, String outputPath) {

    // load the resource
    resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
    Resource resource = resourceSet.getResource(URI.createFileURI(inputPath), true);

    if (metadata != null) {
      Map<String, Object> entitiesMap = new HashMap<String, Object>();
      for (State key :
          Iterables.<State>filter(
              IteratorExtensions.<EObject>toIterable(resource.getAllContents()), State.class)) {
        String entity = key.getEntity().getName();
        if (StringUtils.isNotEmpty(entity)) {
          try {
            EntityMetadata em = metadata.getEntityMetadata(entity);
            if (null != em) {
              Map<String, Object> entityPropMap = new HashMap<String, Object>();
              for (String propertySimple : em.getTopLevelProperties()) {
                if (!em.isPropertyList(propertySimple)) {

                  ArrayList<String> obj = new ArrayList<String>();

                  String propertyName = em.getSimplePropertyName(propertySimple);

                  if (em.isPropertyNumber(propertySimple)) {
                    obj.add(0, "double");
                  } else if (em.isPropertyDate(propertySimple)) {
                    obj.add(0, "date");
                  } else if (em.isPropertyTime(propertySimple)) {
                    obj.add(0, "dateTime");
                  } else if (em.isPropertyBoolean(propertySimple)) {
                    obj.add(0, "boolean");
                  } else {
                    obj.add(0, "string");
                  }

                  String description = em.getTermValue(propertySimple, "TERM_DESCRIPTION");
                  description = (null != description) ? description : "";
                  obj.add(1, description);

                  entityPropMap.put(propertyName, obj);

                } else {
                  String propertyName = em.getSimplePropertyName(propertySimple);
                  entityPropMap.put(propertyName, complexTypeHandler(propertySimple, em));
                }
              }
              entitiesMap.put(entity, entityPropMap);
            }
          } catch (Exception e) {
            System.out.println("Entity Not found: " + entity);
          }
        }
      }
      resource.getResourceSet().getLoadOptions().put("Metadata", entitiesMap);
    }

    // validate the resource
    List<Issue> list = validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
    if (!list.isEmpty()) {
      for (Issue issue : list) {
        listener.notify(issue.toString());
      }

      return false;
    }

    // configure and start the generator
    fileAccess.setOutputPath(outputPath);
    generator.doGenerate(resource, fileAccess);

    return true;
  }
Example #15
0
 protected String getIssueLocationText(Issue issue) {
   String text = resource.getParseResult().getRootNode().getText();
   String markertext = text.substring(issue.getOffset(), issue.getOffset() + issue.getLength());
   return markertext.replace('\n', ' ').replace('\r', ' ');
 }