Я учусь использовать Xtext
В модульном тесте есть функция с именем parseHelper.parse()
для получения результата анализа в формате объекта:
@RunWith(XtextRunner)
@InjectWith(MyDslInjectorProvider)
class MyDslParsingTest {
@Inject
ParseHelper<Model> parseHelper
@Test
def void loadModel() {
val result = parseHelper.parse('''
Hello Xtext!
''')
Assert.assertNotNull(result)
Assert.assertTrue(result.eResource.errors.isEmpty)
}
}
Я хочу получить результат анализа при интеграции с веб-интерфейсом, поэтому добавляю следующий код в файл /org.xtext.example.mydsl.web/xtend-gen/org/xtext/example/mydsl/web/MyDslServlet.java
MyDslParser myDslParser = new MyDslParser();
CharSequence cs = "Hello Xtext!";
IParseResult iParseResult = myDslParser.doParse(cs);
log.info(iParseResult.getRootASTElement().toString());
Полный код:
package org.xtext.example.mydsl.web;
import com.google.inject.Injector;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.xtext.util.DisposableRegistry;
import org.eclipse.xtext.web.server.XtextServiceDispatcher;
import org.eclipse.xtext.web.servlet.XtextServlet;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.xtext.example.mydsl.web.MyDslWebSetup;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jetty.util.log.Slf4jLog;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.parser.antlr.*;
import com.google.gson.Gson;
import org.xtext.example.mydsl.myDsl.Model;
import org.xtext.example.mydsl.parser.antlr.MyDslParser;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.parser.antlr.AbstractAntlrParser;
import org.eclipse.xtext.parser.ParseResult;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
/**
* Deploy this class into a servlet container to enable DSL-specific services.
*/
@WebServlet(name = "XtextServices", urlPatterns = "/xtext-service/*")
@SuppressWarnings("all")
public class MyDslServlet extends XtextServlet {
private DisposableRegistry disposableRegistry;
final Slf4jLog log = new Slf4jLog("datpm");
private static Pattern _pattern2 = Pattern.compile("/parser/(\\w+)");
private XtextResourceSet resourceSet = new XtextResourceSet();
@Override
public void init() {
log.info("init");
try {
super.init();
final Injector injector = new MyDslWebSetup().createInjectorAndDoEMFRegistration();
this.disposableRegistry = injector.<DisposableRegistry>getInstance(DisposableRegistry.class);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Override
public void destroy() {
if ((this.disposableRegistry != null)) {
this.disposableRegistry.dispose();
this.disposableRegistry = null;
}
super.destroy();
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = req.getRequestURL().toString();
Matcher _matcher = _pattern2.matcher(url);
// parser
if (_matcher.find()) {
resp.setContentType("text/x-json");
Gson gson = new Gson();
MyDslParser myDslParser = new MyDslParser();
// Reader reader = new StringReader("Hello Xtext!");
CharSequence cs = "Hello Xtext!";
IParseResult iParseResult = myDslParser.doParse(cs);
log.info(iParseResult.getRootASTElement().toString());
gson.toJson(iParseResult.getRootASTElement().toString(), resp.getWriter());
} else {
XtextServiceDispatcher.ServiceDescriptor service = getService(req);
if (!service.isHasConflict() && service.isHasSideEffects()) {
super.doGet(req, resp);
} else {
doService(service, resp);
}
}
}
}
Когда я запускаюServerLauncher.java
и доступ http://localhost:8080/xtext-service/parser/aaaaaaaa
, это дает мне эту ошибку:
[main] INFO org.eclipse.jetty.util.log - Logging initialized @91ms
[main] INFO org.eclipse.jetty.server.Server - jetty-9.3.8.v20160314
[main] INFO org.eclipse.jetty.webapp.StandardDescriptorProcessor - NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet
[main] INFO org.eclipse.jetty.server.handler.ContextHandler - Started o.e.j.w.WebAppContext@3a5ed7a6{/,[file:///home/thangld_anm/eclipse-workspace/org.xtext.example.mydsl.parent/org.xtext.example.mydsl.web/WebRoot/, jar:file:///home/thangld_anm/.gradle/caches/modules-2/files-2.1/org.webjars/requirejs/2.3.2/f70d2efec834af46229ffd92231acc18fa7856a/requirejs-2.3.2.jar!/META-INF/resources, jar:file:///home/thangld_anm/.gradle/caches/modules-2/files-2.1/org.webjars/jquery/2.2.4/c3dc40b1b5f24c56afa36fd9a463bb9f378ac4ab/jquery-2.2.4.jar!/META-INF/resources, jar:file:///home/thangld_anm/.gradle/caches/modules-2/files-2.1/org.eclipse.xtext/org.eclipse.xtext.web/2.12.0/b51418291a072d6c7520b0237e447cb30eb9b711/org.eclipse.xtext.web-2.12.0.jar!/META-INF/resources, jar:file:///home/thangld_anm/.gradle/caches/modules-2/files-2.1/org.webjars/ace/1.2.3/c027fca9e205f9f4a6b154a725cf41dbeff21a89/ace-1.2.3.jar!/META-INF/resources],AVAILABLE}
[main] INFO org.eclipse.jetty.server.ServerConnector - Started ServerConnector@3cef309d{HTTP/1.1,[http/1.1]}{localhost:8080}
[main] INFO org.eclipse.jetty.server.Server - Started @1960ms
[main] INFO org.xtext.example.mydsl.web.ServerLauncher - Server started http://localhost:8080/...
[Thread-11] INFO org.xtext.example.mydsl.web.ServerLauncher - Press enter to stop the server...
[qtp1558600329-10] INFO datpm - init
[qtp1558600329-10] WARN org.eclipse.jetty.servlet.ServletHandler - /xtext-service/parser/aaaaaaaa
java.lang.NullPointerException
at org.eclipse.xtext.parser.antlr.AbstractAntlrParser.parse(AbstractAntlrParser.java:84)
at org.eclipse.xtext.parser.antlr.AbstractAntlrParser.doParse(AbstractAntlrParser.java:62)
at org.eclipse.xtext.parser.antlr.AbstractAntlrParser.doParse(AbstractAntlrParser.java:70)
at org.xtext.example.mydsl.web.MyDslServlet.doGet(MyDslServlet.java:87)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.eclipse.xtext.web.servlet.XtextServlet.service(XtextServlet.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:837)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1160)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1092)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:518)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:244)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:246)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:156)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
at java.lang.Thread.run(Thread.java:748)
Можете ли вы сказать мне, как получить результат анализа?Является ли IParseResult подходящим модулем для работы?Большое вам спасибо.