Search in sources :

Example 1 with DocumentInformation

use of com.nedap.openehr.lsp.document.DocumentInformation in project archetype-languageserver by nedap.

the class ConvertToOptCommand method apply.

public void apply() {
    String documentUri = ((JsonPrimitive) params.getArguments().get(0)).getAsString();
    String format = ((JsonPrimitive) params.getArguments().get(1)).getAsString();
    String serializedOpt = null;
    Flattener flattener = new Flattener(storage, BuiltinReferenceModels.getMetaModels(), FlattenerConfiguration.forOperationalTemplate());
    DocumentInformation documentInformation = storage.getDocumentInformation(documentUri);
    Archetype archetype = storage.getArchetype(documentInformation.getArchetypeId());
    OperationalTemplate opt = (OperationalTemplate) flattener.flatten(archetype);
    String extension;
    switch(format) {
        case "adl":
            extension = ".opt2";
            serializedOpt = ADLArchetypeSerializer.serialize(opt);
            break;
        case "json":
            extension = "_opt.json";
            try {
                serializedOpt = JacksonUtil.getObjectMapper().writeValueAsString(opt);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            break;
        case "xml":
            {
                extension = "_opt.xml";
                StringWriter sw = new StringWriter();
                try {
                    Marshaller marshaller = JAXBUtil.getArchieJAXBContext().createMarshaller();
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    marshaller.marshal(opt, sw);
                } catch (JAXBException e) {
                    throw new RuntimeException(e);
                }
                serializedOpt = sw.toString();
                break;
            }
        // 
        default:
            throw new UnsupportedOperationException("unsupported format: " + format);
    }
    String uriToWrite = documentUri.substring(0, documentUri.lastIndexOf("/")) + "/opt/" + opt.getArchetypeId() + extension;
    textDocumentService.writeFile(uriToWrite, "opt in " + format, serializedOpt);
}
Also used : Marshaller(javax.xml.bind.Marshaller) StringWriter(java.io.StringWriter) JsonPrimitive(com.google.gson.JsonPrimitive) Archetype(com.nedap.archie.aom.Archetype) Flattener(com.nedap.archie.flattener.Flattener) DocumentInformation(com.nedap.openehr.lsp.document.DocumentInformation) JAXBException(javax.xml.bind.JAXBException) OperationalTemplate(com.nedap.archie.aom.OperationalTemplate) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with DocumentInformation

use of com.nedap.openehr.lsp.document.DocumentInformation in project archetype-languageserver by nedap.

the class BroadcastingArchetypeRepository method fileRemoved.

public void fileRemoved(String uri) {
    documents.remove(uri);
    DocumentInformation removedDocumentInfo = symbolsByUri.remove(uri);
    if (removedDocumentInfo != null && removedDocumentInfo.getArchetypeId() != null) {
        this.documentsByArchetypeId.remove(removedDocumentInfo.getArchetypeId());
        super.removeArchetype(removedDocumentInfo.getArchetypeId());
    }
    // incremental compile on remove is just remove all for now
    // TODO: replace with invalidate(archetype) only IF the archetype is available?
    invalidateAll();
}
Also used : DocumentInformation(com.nedap.openehr.lsp.document.DocumentInformation)

Example 3 with DocumentInformation

use of com.nedap.openehr.lsp.document.DocumentInformation in project archetype-languageserver by nedap.

the class ADL2TextDocumentService method codeAction.

/**
 * The code action request is sent from the client to the server to compute
 * commands for a given text document and range. These commands are
 * typically code fixes to either fix problems or to beautify/refactor code.
 *
 * Registration Options: TextDocumentRegistrationOptions
 */
@JsonRequest
@ResponseJsonAdapter(CodeActionResponseAdapter.class)
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
    DocumentInformation info = storage.getDocumentInformation(params.getTextDocument().getUri());
    if (info == null) {
        return CompletableFuture.completedFuture(new ArrayList<>());
    }
    if (info.getADLVersion() == ADLVersion.VERSION_1_4) {
        CodeAction action1 = new CodeAction("convert this file to ADL 2");
        action1.setKind(CodeActionKind.Source + ".convert.adl2");
        {
            Command command = new Command("Convert to ADL 2", ADL2_COMMAND);
            command.setArguments(Lists.newArrayList(params.getTextDocument().getUri()));
            action1.setCommand(command);
        }
        CodeAction actionAll = new CodeAction("convert all ADL 1.4 files to ADL 2");
        actionAll.setKind(CodeActionKind.Source + ".convert.adl2");
        {
            Command command = new Command("Convert all ADL 1.4 files to ADL 2", ALL_ADL2_COMMAND);
            command.setArguments(Lists.newArrayList(params.getTextDocument().getUri()));
            actionAll.setCommand(command);
        }
        return CompletableFuture.completedFuture(Lists.newArrayList(Either.forRight(action1), Either.forRight(actionAll)));
    } else {
        if (info.getDiagnostics() != null) {
            List<Diagnostic> missingTermsCodes = info.getDiagnostics().stream().filter(d -> d.getCode() != null && d.getCode().isLeft() && d.getCode().getLeft().startsWith(ErrorType.VATID.getCode()) && RangeUtils.rangesOverlap(params.getRange(), d.getRange())).collect(Collectors.toList());
            // TODO: store in intermediate list so we can add more code actions :)
            List<Either<Command, CodeAction>> codeActions = missingTermsCodes.stream().map(d -> {
                CodeAction action = new CodeAction("add to terminology");
                action.setKind(ADD_TO_TERMINOLOGY);
                action.setIsPreferred(true);
                action.setDiagnostics(Lists.newArrayList(d));
                Command c = new Command("add to terminology", ADD_TO_TERMINOLOGY);
                // TODO: store id/ac/at code here!
                c.setArguments(Lists.newArrayList(params.getTextDocument().getUri(), d.getMessage()));
                action.setCommand(c);
                return Either.<Command, CodeAction>forRight(action);
            }).collect(Collectors.toList());
            for (String format : Lists.newArrayList("adl", "json", "xml")) {
                CodeAction convertToOpt = new CodeAction("Convert to Opt (" + format + ")");
                convertToOpt.setKind(WRITE_OPT_COMMAND + "." + format);
                Command c = new Command("Write OPT", WRITE_OPT_COMMAND);
                c.setArguments(Lists.newArrayList(params.getTextDocument().getUri(), format));
                convertToOpt.setCommand(c);
                codeActions.add(Either.<Command, CodeAction>forRight(convertToOpt));
            }
            for (String format : Lists.newArrayList("json", "flat_json", "xml")) {
                CodeAction convertToOpt = new CodeAction("Generate example (" + format + ")");
                convertToOpt.setKind(WRITE_EXAMPLE_COMMAND + "." + format);
                Command c = new Command("Write example", WRITE_EXAMPLE_COMMAND);
                c.setArguments(Lists.newArrayList(params.getTextDocument().getUri(), format));
                convertToOpt.setCommand(c);
                codeActions.add(Either.<Command, CodeAction>forRight(convertToOpt));
            }
            return CompletableFuture.completedFuture(codeActions);
        }
    }
    return CompletableFuture.completedFuture(Collections.emptyList());
}
Also used : BroadcastingArchetypeRepository(com.nedap.openehr.lsp.repository.BroadcastingArchetypeRepository) ResponseJsonAdapter(org.eclipse.lsp4j.jsonrpc.json.ResponseJsonAdapter) LanguageClient(org.eclipse.lsp4j.services.LanguageClient) ADLVersion(com.nedap.openehr.lsp.document.ADLVersion) CodeActionResponseAdapter(org.eclipse.lsp4j.adapters.CodeActionResponseAdapter) CompletableFuture(java.util.concurrent.CompletableFuture) GenerateExampleCommand(com.nedap.openehr.lsp.commands.GenerateExampleCommand) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) JsonPrimitive(com.google.gson.JsonPrimitive) URI(java.net.URI) org.eclipse.lsp4j(org.eclipse.lsp4j) TextDocumentService(org.eclipse.lsp4j.services.TextDocumentService) JsonRequest(org.eclipse.lsp4j.jsonrpc.services.JsonRequest) DocumentInformation(com.nedap.openehr.lsp.document.DocumentInformation) AQLStorage(com.nedap.openehr.lsp.aql.AQLStorage) WorkspaceService(org.eclipse.lsp4j.services.WorkspaceService) AddTerminologyCommmand(com.nedap.openehr.lsp.commands.AddTerminologyCommmand) Collectors(java.util.stream.Collectors) File(java.io.File) List(java.util.List) ANTLRParserErrors(com.nedap.archie.antlr.errors.ANTLRParserErrors) ErrorType(com.nedap.archie.archetypevalidator.ErrorType) RangeUtils(com.nedap.openehr.lsp.utils.RangeUtils) ConvertToOptCommand(com.nedap.openehr.lsp.commands.ConvertToOptCommand) RemoteEndpoint(org.eclipse.lsp4j.jsonrpc.RemoteEndpoint) Collections(java.util.Collections) ValidationResult(com.nedap.archie.archetypevalidator.ValidationResult) GenerateExampleCommand(com.nedap.openehr.lsp.commands.GenerateExampleCommand) ConvertToOptCommand(com.nedap.openehr.lsp.commands.ConvertToOptCommand) DocumentInformation(com.nedap.openehr.lsp.document.DocumentInformation) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) JsonRequest(org.eclipse.lsp4j.jsonrpc.services.JsonRequest) ResponseJsonAdapter(org.eclipse.lsp4j.jsonrpc.json.ResponseJsonAdapter)

Example 4 with DocumentInformation

use of com.nedap.openehr.lsp.document.DocumentInformation in project archetype-languageserver by nedap.

the class AddTerminologyCommmand method apply.

public void apply() {
    String documentUri = ((JsonPrimitive) params.getArguments().get(0)).getAsString();
    JsonPrimitive message = (JsonPrimitive) params.getArguments().get(1);
    Matcher matcher = codePattern.matcher(message.getAsString());
    if (!matcher.matches()) {
        throw new IllegalArgumentException("First argument must have a valid id, at or ac code somewhere!");
    }
    DocumentInformation documentInformation = storage.getDocumentInformation(documentUri);
    List<DocumentSymbol> symbols = documentInformation.getSymbols().stream().map(e -> e.getRight()).collect(Collectors.toList());
    DocumentSymbol archetypeSymbol = getDocumentSymbolOrThrow(symbols, "archetype");
    DocumentSymbol terminology = getDocumentSymbolOrThrow(archetypeSymbol.getChildren(), DocumentInformation.TERMINOLOGY_SECTION_NAME);
    DocumentSymbol termDefinitions = getDocumentSymbolOrThrow(terminology.getChildren(), DocumentInformation.TERM_DEFINITIONS_NAME);
    List<TextEdit> editCommands = new ArrayList<>();
    for (DocumentSymbol languageSymbol : Lists.reverse(termDefinitions.getChildren())) {
        Position endOfTranslation = languageSymbol.getRange().getEnd();
        Position insertBefore = new Position(endOfTranslation.getLine(), Math.max(0, endOfTranslation.getCharacter() - 1));
        StringBuilder text = new StringBuilder();
        // TODO: better indenting :) perhaps retrieve from last character of symbol position in line?
        text.append("    [\"");
        text.append(matcher.group("code"));
        text.append("\"] = <");
        text.append("\n");
        text.append("                ");
        text.append("text =<\"Missing translation\">\n");
        text.append("                ");
        text.append("description =<\"Missing translation\">\n");
        text.append("            >\n");
        text.append("        ");
        TextEdit insertEdit = new TextEdit(new Range(insertBefore, insertBefore), text.toString());
        editCommands.add(insertEdit);
    }
    this.textDocumentService.applyEdits(documentUri, 0, "Add missing terminology code", editCommands);
}
Also used : BroadcastingArchetypeRepository(com.nedap.openehr.lsp.repository.BroadcastingArchetypeRepository) DocumentInformation(com.nedap.openehr.lsp.document.DocumentInformation) Range(org.eclipse.lsp4j.Range) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) Collectors(java.util.stream.Collectors) SymbolInformation(org.eclipse.lsp4j.SymbolInformation) ArrayList(java.util.ArrayList) List(java.util.List) Lists(com.google.common.collect.Lists) TextEdit(org.eclipse.lsp4j.TextEdit) Matcher(java.util.regex.Matcher) ExecuteCommandParams(org.eclipse.lsp4j.ExecuteCommandParams) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) Position(org.eclipse.lsp4j.Position) Optional(java.util.Optional) ADL2TextDocumentService(com.nedap.openehr.lsp.ADL2TextDocumentService) JsonPrimitive(com.google.gson.JsonPrimitive) Pattern(java.util.regex.Pattern) DocumentSymbolUtils.getDocumentSymbolOrThrow(com.nedap.openehr.lsp.utils.DocumentSymbolUtils.getDocumentSymbolOrThrow) DocumentSymbol(org.eclipse.lsp4j.DocumentSymbol) Collections(java.util.Collections) JsonPrimitive(com.google.gson.JsonPrimitive) Matcher(java.util.regex.Matcher) Position(org.eclipse.lsp4j.Position) DocumentInformation(com.nedap.openehr.lsp.document.DocumentInformation) ArrayList(java.util.ArrayList) Range(org.eclipse.lsp4j.Range) TextEdit(org.eclipse.lsp4j.TextEdit) DocumentSymbol(org.eclipse.lsp4j.DocumentSymbol)

Example 5 with DocumentInformation

use of com.nedap.openehr.lsp.document.DocumentInformation in project archetype-languageserver by nedap.

the class GenerateExampleCommand method apply.

public void apply() {
    String documentUri = ((JsonPrimitive) params.getArguments().get(0)).getAsString();
    String format = ((JsonPrimitive) params.getArguments().get(1)).getAsString();
    String serializedExample = null;
    Flattener flattener = new Flattener(storage, BuiltinReferenceModels.getMetaModels(), FlattenerConfiguration.forOperationalTemplate());
    DocumentInformation documentInformation = storage.getDocumentInformation(documentUri);
    Archetype archetype = storage.getArchetype(documentInformation.getArchetypeId());
    OperationalTemplate opt = (OperationalTemplate) flattener.flatten(archetype);
    ExampleJsonInstanceGenerator exampleJsonInstanceGenerator = new ExampleJsonInstanceGenerator(BuiltinReferenceModels.getMetaModels(), archetype.getOriginalLanguage().getCodeString());
    Map<String, Object> exampleMap = exampleJsonInstanceGenerator.generate(opt);
    String extension;
    ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
    String jsonRmObject = null;
    OpenEHRBase example;
    try {
        jsonRmObject = objectMapper.writeValueAsString(exampleMap);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    switch(format) {
        case "json":
            extension = "_example.json";
            serializedExample = jsonRmObject;
            break;
        case "flat_json":
            extension = "_flat_example.json";
            FlatJsonGenerator flatJsonGenerator = new FlatJsonGenerator(ArchieRMInfoLookup.getInstance(), FlatJsonFormatConfiguration.nedapInternalFormat());
            try {
                example = objectMapper.readValue(jsonRmObject, OpenEHRBase.class);
                Map<String, Object> flatExample = flatJsonGenerator.buildPathsAndValues(example);
                serializedExample = JacksonUtil.getObjectMapper().writeValueAsString(flatExample);
            } catch (JsonProcessingException | DuplicateKeyException e) {
                throw new RuntimeException(e);
            }
            break;
        case "xml":
            {
                extension = "_example.xml";
                try {
                    example = objectMapper.readValue(jsonRmObject, OpenEHRBase.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                StringWriter sw = new StringWriter();
                try {
                    Marshaller marshaller = JAXBUtil.getArchieJAXBContext().createMarshaller();
                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    marshaller.marshal(example, sw);
                } catch (JAXBException e) {
                    throw new RuntimeException(e);
                }
                serializedExample = sw.toString();
                break;
            }
        // 
        default:
            throw new UnsupportedOperationException("unsupported format: " + format);
    }
    String uriToWrite = documentUri.substring(0, documentUri.lastIndexOf("/")) + "/example/" + opt.getArchetypeId() + extension;
    textDocumentService.writeFile(uriToWrite, "opt in " + format, serializedExample);
}
Also used : FlatJsonGenerator(com.nedap.archie.json.flat.FlatJsonGenerator) Marshaller(javax.xml.bind.Marshaller) JsonPrimitive(com.google.gson.JsonPrimitive) Archetype(com.nedap.archie.aom.Archetype) Flattener(com.nedap.archie.flattener.Flattener) DocumentInformation(com.nedap.openehr.lsp.document.DocumentInformation) JAXBException(javax.xml.bind.JAXBException) DuplicateKeyException(com.nedap.archie.json.flat.DuplicateKeyException) StringWriter(java.io.StringWriter) OpenEHRBase(com.nedap.archie.base.OpenEHRBase) OperationalTemplate(com.nedap.archie.aom.OperationalTemplate) ExampleJsonInstanceGenerator(com.nedap.archie.creation.ExampleJsonInstanceGenerator) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

DocumentInformation (com.nedap.openehr.lsp.document.DocumentInformation)11 JsonPrimitive (com.google.gson.JsonPrimitive)4 Archetype (com.nedap.archie.aom.Archetype)4 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 Lists (com.google.common.collect.Lists)2 ArchieErrorListener (com.nedap.archie.antlr.errors.ArchieErrorListener)2 OperationalTemplate (com.nedap.archie.aom.OperationalTemplate)2 ValidationResult (com.nedap.archie.archetypevalidator.ValidationResult)2 Flattener (com.nedap.archie.flattener.Flattener)2 BroadcastingArchetypeRepository (com.nedap.openehr.lsp.repository.BroadcastingArchetypeRepository)2 Collections (java.util.Collections)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)2 ParseTreeWalker (org.antlr.v4.runtime.tree.ParseTreeWalker)2 Either (org.eclipse.lsp4j.jsonrpc.messages.Either)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ADLParseException (com.nedap.archie.adlparser.ADLParseException)1