protected XtextResource createExpectedResource() {
   XtextResource _xblockexpression = null;
   {
     XtextResourceSet resourceSet = this.createFreshResourceSet();
     VirtualFile _virtualFile = this.myFile.getVirtualFile();
     String _url = _virtualFile.getUrl();
     final URI uri = URI.createURI(_url);
     Resource _createResource = resourceSet.createResource(uri);
     final Procedure1<XtextResource> _function =
         new Procedure1<XtextResource>() {
           @Override
           public void apply(final XtextResource it) {
             try {
               String _text = AbstractLanguageParsingTestCase.this.myFile.getText();
               byte[] _bytes = _text.getBytes();
               ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_bytes);
               it.load(_byteArrayInputStream, null);
             } catch (Throwable _e) {
               throw Exceptions.sneakyThrow(_e);
             }
           }
         };
     _xblockexpression =
         ObjectExtensions.<XtextResource>operator_doubleArrow(
             ((XtextResource) _createResource), _function);
   }
   return _xblockexpression;
 }
Exemplo n.º 2
0
 public Class<?> getRawType(JvmType jvmType) {
   if (jvmType == null || jvmType.eIsProxy()) return null;
   XtextResourceSet resourceSet = (XtextResourceSet) jvmType.eResource().getResourceSet();
   if (resourceSet.getClasspathURIContext() instanceof ClassLoader) {
     JavaReflectAccess access = new JavaReflectAccess();
     access.setClassLoader((ClassLoader) resourceSet.getClasspathURIContext());
     return access.getRawType(jvmType);
   }
   if (!(jvmType.eResource() instanceof TypeResource)) return null;
   IMirror typeMirror = ((TypeResource) jvmType.eResource()).getMirror();
   Bundle bundle = null;
   if (typeMirror instanceof JdtTypeMirror) bundle = getBundle((JdtTypeMirror) typeMirror);
   if (typeMirror instanceof ClassMirror) bundle = getBundle((ClassMirror) typeMirror);
   if (bundle == null) return null;
   String className = jvmType.getQualifiedName();
   try {
     return bundle.loadClass(className);
   } catch (ClassNotFoundException e) {
     LOG.error(
         "Could not find Java class for "
             + jvmType.eClass().getName()
             + " "
             + jvmType.getIdentifier(),
         e);
     return null;
   }
 }
Exemplo n.º 3
0
 private static Program parse(String input) throws ParseException {
   try {
     if (injector == null) {
       injector = new PrologStandaloneSetupGenerated().createInjectorAndDoEMFRegistration();
     }
     XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
     resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
     Resource resource = resourceSet.createResource(URI.createURI("null:/prolog.pl"));
     InputStream in = new ByteArrayInputStream(input.getBytes());
     resource.load(in, resourceSet.getLoadOptions());
     if (resource.getErrors().size() > 0) {
       Diagnostic d = resource.getErrors().get(0);
       String l = d.getLocation();
       if (l == null) {
         try {
           l = "line and column: " + d.getLine() + "," + d.getColumn();
         } catch (UnsupportedOperationException e) {
           if (d instanceof AbstractDiagnostic) {
             l = "offset: " + ((AbstractDiagnostic) d).getOffset();
           }
         }
       }
       throw new ParseException(
           resource.getErrors().get(0).getMessage() + " at " + l + " for: " + input);
     }
     return (Program) resource.getContents().get(0);
   } catch (Throwable e) {
     throw new ParseException("Parse exception for: " + input, e);
   }
 }
Exemplo n.º 4
0
  @Override
  public AttributedFeatureModel parseFile(String fileName) throws Exception {
    Injector injector = new VMStandaloneSetup().createInjectorAndDoEMFRegistration();
    XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
    resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
    if (models != null) {
      for (String s : models) {
        resourceSet.getResource(URI.createURI(s), true);
      }
    }

    Resource resource = resourceSet.getResource(URI.createURI(fileName), true);

    Model model = (Model) resource.getContents().get(0);

    fm = new AttributedFeatureModel();

    VmBlock relationships = null;
    VmBlock attsblock = null;
    VmBlock constratins = null;

    EList<VmBlock> bl = model.getBlocks();
    for (VmBlock block : bl) {
      if (block instanceof Relationships) {
        relationships = block;
      } else if (block instanceof Attributes) {
        attsblock = block;
      } else if (block instanceof Constraints) {
        constratins = block;
      } else if (block instanceof PackageDeclaration) {
        for (VmBlock blockinpkg : ((PackageDeclaration) block).getBlocks()) {
          if (blockinpkg instanceof Relationships) {
            relationships = blockinpkg;
          } else if (blockinpkg instanceof Attributes) {
            attsblock = blockinpkg;

          } else if (blockinpkg instanceof Constraints) {
            constratins = blockinpkg;
          }
        }
      }
    }
    if (((Relationships) relationships) != null) {
      FeatureHierarchy fhs = ((Relationships) relationships).getRoot();
      fr.familiar.attributedfm.Feature ffeat =
          new fr.familiar.attributedfm.Feature(fhs.getParent().getName());
      visitFeatureHierarchy(ffeat, fhs);
      fm.setRoot(ffeat);
    }
    if ((Attributes) attsblock != null) {
      visitAttributes(((Attributes) attsblock).getAttrDefs(), fm);
    }
    if ((Constraints) constratins != null) {
      visitConstraints(((Constraints) constratins).getConstraints(), fm);
    }
    return fm;
  }
 public Query parse(String input) {
   resourceSet.getResources().clear();
   Resource resource = resourceSet.createResource(createURI("MyQuery.__query"));
   try {
     resource.load(new StringInputStream(input), null);
     EcoreUtil.resolveAll(resource);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return filter(resource.getContents(), Query.class).iterator().next();
 }
 public XtendFile file(final String string, final boolean validate) throws Exception {
   XtextResourceSet _resourceSet = this.getResourceSet();
   URI _createURI = URI.createURI("abcdefg.xtend");
   final Resource resource = _resourceSet.createResource(_createURI);
   StringInputStream _stringInputStream = new StringInputStream(string);
   resource.load(_stringInputStream, null);
   EList<EObject> _contents = resource.getContents();
   EObject _head = IterableExtensions.<EObject>head(_contents);
   final XtendFile file = ((XtendFile) _head);
   return file;
 }
Exemplo n.º 7
0
 public boolean runGeneratorDir(String inputDirPath, Metadata metadata, String outputPath) {
   List<String> files = getFiles(inputDirPath, ".rim");
   for (String modelPath : files) {
     resourceSet.getResources().add(resourceSet.getResource(URI.createFileURI(modelPath), true));
   }
   boolean result = true;
   for (String modelPath : files) {
     boolean fileResult = runGenerator(modelPath, metadata, outputPath);
     if (!fileResult) {
       result = fileResult;
     }
   }
   return result;
 }
 public ClassLoader getClassLoader(ResourceSet resourceSet) {
   if (resourceSet instanceof XtextResourceSet) {
     XtextResourceSet xtextResourceSet = (XtextResourceSet) resourceSet;
     Object ctx = xtextResourceSet.getClasspathURIContext();
     if (ctx != null) {
       if (ctx instanceof Class<?>) {
         return ((Class<?>) ctx).getClassLoader();
       }
       if (!(ctx instanceof ClassLoader)) {
         return ctx.getClass().getClassLoader();
       }
       return (ClassLoader) ctx;
     }
   }
   return classLoader;
 }
Exemplo n.º 9
0
 protected XtendFile file(String string, boolean validate) throws Exception {
   XtextResourceSet set = resourceSetProvider.get();
   String fileName = getFileName(string);
   Resource resource = set.createResource(URI.createURI(fileName + ".xtend"));
   resource.load(new StringInputStream(string), null);
   assertEquals(resource.getErrors().toString(), 0, resource.getErrors().size());
   if (validate) {
     List<Issue> issues =
         ((XtextResource) resource)
             .getResourceServiceProvider()
             .getResourceValidator()
             .validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
     assertTrue("Resource contained errors : " + issues.toString(), issues.isEmpty());
   }
   XtendFile file = (XtendFile) resource.getContents().get(0);
   return file;
 }
  @Test
  public void testGenerateWithExpressionContext() throws Exception {
    EDataType dataType = EcorePackage.eINSTANCE.getEBigDecimal();

    EPackage pkg = helper.createPackage("tests");
    EClass clazz = helper.createClass(pkg, "NumericTests");
    helper.addAttribute(clazz, dataType, "a");

    EObject instance = helper.createInstance(clazz);

    XtextResourceSet resourceSet =
        expressionFactory.getInjector().getInstance(XtextResourceSet.class);
    Resource resource = resourceSet.createResource(URI.createURI("__synthetic.testData.expr"));
    resource.getContents().add(instance);

    // TODO could use TypeReferences getTypeForName() instead JvmTypesBuilder newTypeRef() ..

    Injector injector = expressionFactory.getInjector();
    JvmTypesBuilder jvmTypesBuilder = injector.getInstance(JvmTypesBuilder.class);
    JvmTypeReferenceBuilder.Factory factory =
        injector.getInstance(JvmTypeReferenceBuilder.Factory.class);
    JvmTypeReferenceBuilder jvmTypeReferenceBuilder =
        factory.create(instance.eResource().getResourceSet());

    JvmGenericType type = jvmTypesBuilder.toClass(instance, "tests.NumericTests");
    resource.getContents().add(type);

    JvmField field =
        jvmTypesBuilder.toField(
            instance,
            "a",
            jvmTypeReferenceBuilder.typeRef(
                dataType.getInstanceClassName() /*"java.math.BigDecimal"*/));
    field.setVisibility(JvmVisibility.PUBLIC);
    type.getMembers().add(field);

    ExpressionContext context = new ExpressionContext(resource);
    context.setType(jvmTypeReferenceBuilder.typeRef(Boolean.TYPE));
    context.addVariable("t", jvmTypeReferenceBuilder.typeRef(type));

    checkGeneration(
        "t.a == 5",
        Boolean.TYPE,
        context,
        "com.google.common.base.Objects.equal(t.a, new java.math.BigDecimal(\"5\"))");
  }
 protected XtextResource createActualResource() {
   XtextResource _xblockexpression = null;
   {
     PsiToEcoreTransformator _get = this.psiToEcoreTransformatorProvider.get();
     final Procedure1<PsiToEcoreTransformator> _function =
         new Procedure1<PsiToEcoreTransformator>() {
           @Override
           public void apply(final PsiToEcoreTransformator it) {
             it.setXtextFile(((BaseXtextFile) AbstractLanguageParsingTestCase.this.myFile));
           }
         };
     final PsiToEcoreTransformator psiToEcoreTransformator =
         ObjectExtensions.<PsiToEcoreTransformator>operator_doubleArrow(_get, _function);
     VirtualFile _virtualFile = this.myFile.getVirtualFile();
     String _url = _virtualFile.getUrl();
     final URI uri = URI.createURI(_url);
     XtextResourceSet _createFreshResourceSet = this.createFreshResourceSet();
     Resource _createResource = _createFreshResourceSet.createResource(uri);
     final Procedure1<XtextResource> _function_1 =
         new Procedure1<XtextResource>() {
           @Override
           public void apply(final XtextResource it) {
             try {
               it.setParser(psiToEcoreTransformator);
               byte[] _newByteArrayOfSize = new byte[0];
               ByteArrayInputStream _byteArrayInputStream =
                   new ByteArrayInputStream(_newByteArrayOfSize);
               it.load(_byteArrayInputStream, null);
               PsiToEcoreAdapter _adapter = psiToEcoreTransformator.getAdapter();
               _adapter.attachToEmfObject(it);
             } catch (Throwable _e) {
               throw Exceptions.sneakyThrow(_e);
             }
           }
         };
     _xblockexpression =
         ObjectExtensions.<XtextResource>operator_doubleArrow(
             ((XtextResource) _createResource), _function_1);
   }
   return _xblockexpression;
 }
Exemplo n.º 12
0
 @Override
 public void processFile(String data) throws Exception {
   byte[] hash = ((MessageDigest) messageDigest.clone()).digest(data.getBytes("UTF-8"));
   if (seen.add(new BigInteger(hash))) {
     XtextResourceSet resourceSet = resourceSetProvider.get();
     resourceSet.setClasspathURIContext(classLoader);
     XtendFile file = parseHelper.parse(data, resourceSet);
     if (file != null) {
       try {
         XtextResource resource = (XtextResource) file.eResource();
         ITextRegionAccess regions = regionBuilder.get().forNodeModel(resource).create();
         FormatterRequest request = new FormatterRequest().setTextRegionAccess(regions);
         request.setExceptionHandler(ExceptionAcceptor.IGNORING);
         formatter.format(request);
       } catch (Exception e) {
         e.printStackTrace();
         ComparisonFailure error = new ComparisonFailure(e.getMessage(), data, "");
         error.setStackTrace(e.getStackTrace());
         throw error;
       }
     }
   }
 }
Exemplo n.º 13
0
 @Override
 public void testTwoChapters() throws Exception {
   XtextResourceSet set = get(XtextResourceSet.class);
   Resource res =
       set.getResource(URI.createURI(ParserTest.TEST_FILE_DIR + "01-twoChapters.xdoc"), true);
   Chapter chapter0 = (Chapter) ((XdocFile) getModel((XtextResource) res)).getMainSection();
   res = set.getResource(URI.createURI(ParserTest.TEST_FILE_DIR + "02-twoChapters.xdoc"), true);
   Chapter chapter1 = (Chapter) ((XdocFile) getModel((XtextResource) res)).getMainSection();
   XdocFile file =
       (XdocFile)
           getModel(
               (XtextResource)
                   set.getResource(
                       URI.createURI(ParserTest.TEST_FILE_DIR + "twoChaptersDoc.xdoc"), true));
   Document doc = (Document) file.getMainSection();
   for (int i = 0; i < doc.getChapters().size(); i++) {
     Chapter chapter = doc.getChapters().get(i);
     generate(chapter);
   }
   generate(doc);
   validate("01-twoChapters.html", name(chapter0));
   validate("02-twoChapters.html", name(chapter1));
   validate("twoChaptersDoc.html", name(doc));
 }
  @Override
  protected IResource createElementResource(IProgressMonitor monitor, IPath path) {
    try {

      if (monitor == null) {
        monitor = new NullProgressMonitor();
      }

      monitor.beginTask(Messages.NewMechanoidOpsFileWizard_Progress_Message, 1);

      URI newEmfResourceURI =
          URI.createURI(
              "platform:/resource"
                  + //$NON-NLS-1$
                  path.toPortableString());

      Resource emfResource = mResourceSet.createResource(newEmfResourceURI);

      Model model = OpServiceModelFactory.eINSTANCE.createModel();
      model.setPackageName(mSelectedPackageName);

      emfResource.getContents().add(model);

      ServiceBlock service = (ServiceBlock) OpServiceModelFactory.eINSTANCE.createServiceBlock();
      service.setName(mSelectedElementName);
      model.setService(service);

      emfResource.save(Collections.EMPTY_MAP);

      IResource resource =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .findMember(newEmfResourceURI.toPlatformString(true));

      monitor.worked(1);

      return resource;

    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
Exemplo n.º 15
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;
  }
 @Override
 public ClassLoader getClassLoader(final EObject ctx) {
   Resource _eResource = ctx.eResource();
   ResourceSet _resourceSet = _eResource.getResourceSet();
   final XtextResourceSet rs = ((XtextResourceSet) _resourceSet);
   ResourceSetContext _get = ResourceSetContext.get(rs);
   final boolean isBuilder = _get.isBuilder();
   ResourceSetContext _get_1 = ResourceSetContext.get(rs);
   final boolean isEditor = _get_1.isEditor();
   if (isBuilder) {
     EList<Adapter> _eAdapters = rs.eAdapters();
     Iterable<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter> _filter =
         Iterables.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>filter(
             _eAdapters, ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter.class);
     final ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter adapter =
         IterableExtensions.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>head(
             _filter);
     boolean _notEquals = (!Objects.equal(adapter, null));
     if (_notEquals) {
       return adapter.getClassLoader();
     }
   }
   if (isEditor) {
     Resource _editorResource = this.getEditorResource(ctx);
     EList<Adapter> _eAdapters_1 = _editorResource.eAdapters();
     Iterable<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter> _filter_1 =
         Iterables.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>filter(
             _eAdapters_1, ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter.class);
     final ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter adapter_1 =
         IterableExtensions.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>head(
             _filter_1);
     boolean _notEquals_1 = (!Objects.equal(adapter_1, null));
     if (_notEquals_1) {
       ClassLoader _classLoader = adapter_1.getClassLoader();
       boolean _equals = Objects.equal(_classLoader, null);
       if (_equals) {
         Resource _editorResource_1 = this.getEditorResource(ctx);
         EList<Adapter> _eAdapters_2 = _editorResource_1.eAdapters();
         _eAdapters_2.remove(adapter_1);
       } else {
         return adapter_1.getClassLoader();
       }
     }
   }
   Object _classpathURIContext = rs.getClasspathURIContext();
   final IJavaProject project = ((IJavaProject) _classpathURIContext);
   final URLClassLoader classloader = this.createClassLoaderForJavaProject(project);
   if (isBuilder) {
     EList<Adapter> _eAdapters_3 = rs.eAdapters();
     ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter _processorClassloaderAdapter =
         new ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter(classloader);
     _eAdapters_3.add(_processorClassloaderAdapter);
   }
   if (isEditor) {
     Resource _editorResource_2 = this.getEditorResource(ctx);
     EList<Adapter> _eAdapters_4 = _editorResource_2.eAdapters();
     ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter
         _processorClassloaderAdapter_1 =
             new ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter(classloader);
     _eAdapters_4.add(_processorClassloaderAdapter_1);
   }
   return classloader;
 }