diff --git a/.gitignore b/.gitignore index 732cef1a9..22620c559 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ build/ *.iml /.idea/workspace.xml /.idea/sonar* + +/.idea/misc.xml diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index 4e322887b..000000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -mdclasses \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml index cae81d0c5..1797067dd 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -1,21 +1,16 @@ - - - - - - + + + + + \ No newline at end of file diff --git a/.idea/mdclasses.iml b/.idea/mdclasses.iml deleted file mode 100644 index 78b2cc53b..000000000 --- a/.idea/mdclasses.iml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 8f27022c6..000000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index fe30ffc7b..000000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/EmptyFormData.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/EmptyFormData.java index d468d8425..6fbb8794a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/EmptyFormData.java +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/EmptyFormData.java @@ -21,13 +21,11 @@ */ package com.github._1c_syntax.bsl.mdo.storage; -import lombok.Value; - /** - * Реализация пустого содержимого макета + * Реализация содержимого пустой формы */ -@Value public class EmptyFormData implements FormData { + private static final EmptyFormData EMPTY = new EmptyFormData(); /** diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/FormData.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/FormData.java index 0a40e1727..02286c39f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/FormData.java +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/FormData.java @@ -21,8 +21,14 @@ */ package com.github._1c_syntax.bsl.mdo.storage; -import javax.annotation.Nullable; -import java.nio.file.Path; +import com.github._1c_syntax.bsl.mdo.storage.form.FormAttribute; +import com.github._1c_syntax.bsl.mdo.storage.form.FormHandler; +import com.github._1c_syntax.bsl.mdo.storage.form.FormItem; +import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; /** * Интерфейс содержимого форм @@ -34,10 +40,39 @@ public interface FormData { boolean isEmpty(); /** - * Путь к файлу с содержимым. Может быть незаполнен + * Заголовок формы + */ + default MultiLanguageString getTitle() { + return MultiLanguageString.EMPTY; + } + + /** + * Обработчики событий формы + */ + default List getHandlers() { + return Collections.emptyList(); + } + + /** + * Список визуальных элементов формы первого уровня (т.е. с родителем - форма) + */ + default List getItems() { + return Collections.emptyList(); + } + + /** + * Список всех визуальных элементов формы + */ + default List getPlainItems() { + List allItems = new ArrayList<>(getItems()); + getItems().forEach(formItem -> allItems.addAll(formItem.getPlainItems())); + return allItems; + } + + /** + * Список реквизитов формы */ - @Nullable - default Path getDataPath() { - return null; + default List getAttributes() { + return Collections.emptyList(); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/ManagedFormData.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/ManagedFormData.java new file mode 100644 index 000000000..a31f7c75e --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/ManagedFormData.java @@ -0,0 +1,54 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.mdo.storage; + +import com.github._1c_syntax.bsl.mdo.storage.form.FormAttribute; +import com.github._1c_syntax.bsl.mdo.storage.form.FormHandler; +import com.github._1c_syntax.bsl.mdo.storage.form.FormItem; +import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; +import lombok.Builder; +import lombok.Builder.Default; +import lombok.Singular; +import lombok.Value; + +import java.util.List; + +/** + * Реализация содержимого управляемой формы + */ +@Value +@Builder +public class ManagedFormData implements FormData { + @Default + MultiLanguageString title = MultiLanguageString.EMPTY; + @Singular("addHandlers") + List handlers; + @Singular("addItems") + List items; + @Singular("addAttributes") + List attributes; + + @Override + public boolean isEmpty() { + return false; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormAttribute.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormAttribute.java new file mode 100644 index 000000000..935854046 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormAttribute.java @@ -0,0 +1,53 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.mdo.storage.form; + +import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; +import lombok.Builder; +import lombok.Builder.Default; +import lombok.Value; + +/** + * Хранит описание атрибута формы + */ +@Value +@Builder +public class FormAttribute { + + /** + * Идентификатор + */ + @Default + int id = -1; + + /** + * Имя + */ + @Default + String name = ""; + + /** + * Синоним + */ + @Default + MultiLanguageString title = MultiLanguageString.EMPTY; +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormDataPath.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormDataPath.java new file mode 100644 index 000000000..86b8aa0bb --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormDataPath.java @@ -0,0 +1,58 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.mdo.storage.form; + +import lombok.Getter; +import lombok.Value; + +/** + * Путь к реквизиту атрибута форма + */ +@Value +public class FormDataPath { + + /** + * ссылка на пустой элемент + */ + public static final FormDataPath EMPTY = new FormDataPath(); + + /** + * Путь к реквизиту + */ + String segments; + + /** + * Признак отсутствия пути + */ + @Getter + boolean empty; + + private FormDataPath() { + segments = ""; + empty = true; + } + + public FormDataPath(String segments) { + this.segments = segments; + this.empty = false; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormHandler.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormHandler.java new file mode 100644 index 000000000..564343021 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormHandler.java @@ -0,0 +1,31 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.mdo.storage.form; + +/** + * Обработчик события формы + * + * @param event Имя события + * @param name Имя обработчика (метода) формы + */ +public record FormHandler(String event, String name) { +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormItem.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormItem.java new file mode 100644 index 000000000..de44cacb7 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/FormItem.java @@ -0,0 +1,71 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.mdo.storage.form; + +import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; + +import java.util.ArrayList; +import java.util.List; + +/** + * Описание информации об элементе формы + */ +public interface FormItem { + /** + * Тип элемента (кнопка, группа и т.д.) // todo переделать на модель + */ + String getType(); + + /** + * Имя элемента формы + */ + String getName(); + + /** + * Идентификатор + */ + int getId(); + + /** + * Заголовок + */ + MultiLanguageString getTitle(); + + /** + * Путь к реквизиту + */ + FormDataPath getDataPath(); + + /** + * Список дочерних визуальных элементов (непосредственных потомков) + */ + List getItems(); + + /** + * Список всех визуальных элементов (со всеми дочерними) + */ + default List getPlainItems() { + List allItems = new ArrayList<>(getItems()); + getItems().forEach(formItem -> allItems.addAll(formItem.getPlainItems())); + return allItems; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/SimpleFormItem.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/SimpleFormItem.java new file mode 100644 index 000000000..f0a86be26 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/SimpleFormItem.java @@ -0,0 +1,50 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.mdo.storage.form; + +import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; +import lombok.Builder; +import lombok.Builder.Default; +import lombok.Singular; +import lombok.Value; + +import java.util.List; + +/** + * Сильно упрощенная реализация хранения информации элемента форм + */ +@Value +@Builder +public class SimpleFormItem implements FormItem { + @Default + String type = ""; + @Default + int id = -1; + @Default + String name = ""; + @Default + MultiLanguageString title = MultiLanguageString.EMPTY; + @Default + FormDataPath dataPath = FormDataPath.EMPTY; + @Singular("addItems") + List items; +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/package-info.java new file mode 100644 index 000000000..3f69d7920 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/storage/form/package-info.java @@ -0,0 +1,25 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +/** + * Пакет для хранения данных элементов форм + */ +package com.github._1c_syntax.bsl.mdo.storage.form; diff --git a/src/main/java/com/github/_1c_syntax/bsl/mdo/support/MultiLanguageString.java b/src/main/java/com/github/_1c_syntax/bsl/mdo/support/MultiLanguageString.java index 9365221b9..c5ffb29d9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/mdo/support/MultiLanguageString.java +++ b/src/main/java/com/github/_1c_syntax/bsl/mdo/support/MultiLanguageString.java @@ -27,6 +27,7 @@ import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -46,12 +47,32 @@ public class MultiLanguageString { */ Map content; - public MultiLanguageString(MultiLanguageString first, MultiLanguageString second) { + public MultiLanguageString(@NonNull MultiLanguageString first, @NonNull MultiLanguageString second) { var fullContent = new HashMap<>(first.getContent()); fullContent.putAll(second.getContent()); content = fullContent; } + /** + * Создание мультиязычной строки из списка (объединение). + * Если передан пустой список, то вернет ссылку на пустой объект. + * Если в параметрах передан список из одного элемента, то он и будет возвращен как результат. + * + * @param strings Список мультиязычных строк + * @return Объединенное значение + */ + public static MultiLanguageString of(@NonNull List strings) { + if (strings.isEmpty()) { + return EMPTY; + } else if (strings.size() == 1) { + return strings.get(0); + } else { + Map content = new HashMap<>(); + strings.forEach(string -> content.putAll(string.getContent())); + return new MultiLanguageString(content); + } + } + /** * Возвращает содержимое для указанного языка * diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/ReaderUtils.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/ReaderUtils.java index 3ad9d7c97..721b7618e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/common/ReaderUtils.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/ReaderUtils.java @@ -21,61 +21,32 @@ */ package com.github._1c_syntax.bsl.reader.common; -import lombok.Getter; +import com.github._1c_syntax.bsl.reader.common.context.MDReaderContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; import lombok.experimental.UtilityClass; -import org.apache.commons.io.FilenameUtils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; /** * Набор вспомогательных методов, используемых при чтении данных */ @UtilityClass public class ReaderUtils { - private static final byte[] PROTECTED_FILE_HEADER = new byte[]{-1, -1, -1, 127}; - - /** - * Читает информацию о "защищенности" модуля - * - * @param modulePath Путь к файлу модуля - * @return Параметы "защищенности" - */ - public ProtectedModuleInfo readProtectedModuleInfo(Path modulePath) { - return new ProtectedModuleInfo(modulePath); + public void unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, MDReaderContext readerContext) { + if (readerContext.isDesignerFormat()) { + com.github._1c_syntax.bsl.reader.designer.converter.Unmarshaller.unmarshal(reader, context, readerContext); + } else { + com.github._1c_syntax.bsl.reader.edt.converter.Unmarshaller.unmarshal(reader, context, readerContext); + } } /** - * Описание "защищенности" модуля + * Читает значение из файла + * + * @param context Контекст чтения файла + * @param clazz Класс для преобразования + * @return Прочитанное значение */ - public static class ProtectedModuleInfo { - @Getter - private boolean isProtected; - @Getter - private Path modulePath; - - private ProtectedModuleInfo(Path path) { - modulePath = path; - isProtected = false; - - if (!modulePath.toFile().exists()) { - var prtModulePath = Paths.get(FilenameUtils.removeExtension(modulePath.toFile().getPath()) + ".bin"); - if (prtModulePath.toFile().exists()) { - isProtected = true; - modulePath = prtModulePath; - } - } else { - var bytes = new byte[PROTECTED_FILE_HEADER.length]; - try (var fis = new FileInputStream(modulePath.toFile())) { - isProtected = (fis.read(bytes) == PROTECTED_FILE_HEADER.length - && Arrays.equals(bytes, PROTECTED_FILE_HEADER)); - } catch (IOException e) { - // ошибка чтения в данном случае неважна - } - } - } + public T readValue(UnmarshallingContext context, Class clazz) { + return (T) context.convertAnother(clazz, clazz); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/TransformationUtils.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/TransformationUtils.java index 9d804c7f8..9fb312874 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/common/TransformationUtils.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/TransformationUtils.java @@ -21,45 +21,23 @@ */ package com.github._1c_syntax.bsl.reader.common; -import com.github._1c_syntax.bsl.mdo.ChildrenOwner; -import com.github._1c_syntax.bsl.mdo.MD; -import com.github._1c_syntax.bsl.mdo.MDChild; -import com.github._1c_syntax.bsl.mdo.Module; -import com.github._1c_syntax.bsl.mdo.ModuleOwner; -import com.github._1c_syntax.bsl.mdo.Subsystem; -import com.github._1c_syntax.bsl.mdo.children.ObjectModule; -import com.github._1c_syntax.bsl.mdo.support.TemplateType; -import com.github._1c_syntax.bsl.reader.MDOReader; -import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; -import com.github._1c_syntax.bsl.reader.edt.EDTPaths; -import com.github._1c_syntax.bsl.support.CompatibilityMode; -import com.github._1c_syntax.bsl.support.SupportVariant; -import com.github._1c_syntax.bsl.types.ConfigurationSource; -import com.github._1c_syntax.bsl.types.MDOType; -import com.github._1c_syntax.bsl.types.MdoReference; -import com.github._1c_syntax.bsl.types.ModuleType; -import lombok.Data; import lombok.NonNull; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.map.CaseInsensitiveMap; +import javax.annotation.Nullable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; -import java.nio.file.Path; -import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; -import static java.util.Objects.requireNonNull; - /** * Вспомогательный класс для конвертирования значений между моделями */ @@ -72,7 +50,14 @@ public class TransformationUtils { private static final String BUILDER_METHOD_NAME = "builder"; private static final String LOGGER_MESSAGE_PREF = "Class {}, method {}"; - public void setValue(Object source, String methodName, Object value) { + /** + * Устанавливает значение в билдере объекта. Не устанавливаются значения равные null + * + * @param source Билдер-источник + * @param methodName Метод\свойство билдера + * @param value Устанавливаемое значение + */ + public void setValue(@NonNull Object source, @NonNull String methodName, Object value) { var method = getMethod(source.getClass(), methodName); if (method != null && value != null) { try { @@ -89,6 +74,14 @@ public void setValue(Object source, String methodName, Object value) { } } + /** + * Определяет тип значения поля\метода + * + * @param source Билдер-источник + * @param methodName Имя метода\поля + * @return Тип значения + */ + @Nullable public Type fieldType(Object source, String methodName) { var method = getMethod(source.getClass(), methodName); if (method != null) { @@ -97,7 +90,14 @@ public Type fieldType(Object source, String methodName) { return null; } - public Object builder(Class clazz) { + /** + * Возвращает объект-билдер для выбранного класса + * + * @param clazz Класс, для которого ищется билдер + * @return Найденный билдер + */ + @Nullable + public Object builder(@NonNull Class clazz) { var method = getMethod(clazz, BUILDER_METHOD_NAME); if (method != null) { try { @@ -109,7 +109,14 @@ public Object builder(Class clazz) { return null; } - public Object build(Object builder) { + /** + * Вызывает метод сборки билдера + * + * @param builder Собираемый билдер + * @return Собранный билдером объект + */ + @Nullable + public Object build(@NonNull Object builder) { var method = getMethod(builder.getClass(), BUILD_METHOD_NAME); if (method != null) { try { @@ -127,7 +134,7 @@ public Object build(Object builder) { * @param fieldClass Тип поля-коллекции * @return тип класса */ - public Class computeType(ParameterizedType fieldClass) { + public Class computeType(@NonNull ParameterizedType fieldClass) { var type = (fieldClass).getActualTypeArguments()[0]; if (type instanceof WildcardType) { return (Class) ((WildcardType) type).getUpperBounds()[0]; @@ -136,7 +143,8 @@ public Class computeType(ParameterizedType fieldClass) { } } - private Method getMethod(Class clazz, String methodName) { + @Nullable + private Method getMethod(@NonNull Class clazz, @NonNull String methodName) { var classMethods = methods.get(clazz); if (classMethods == null) { classMethods = new CaseInsensitiveMap<>(); @@ -160,221 +168,11 @@ private Method getMethod(Class clazz, String methodName) { return method; } - private static void saveMethod(Class builderClass, - Map classMethods, - Method method, - String builderMethodName) { + private static void saveMethod(@NonNull Class builderClass, + @NonNull Map classMethods, + @NonNull Method method, + @NonNull String builderMethodName) { classMethods.put(builderMethodName, method); methods.put(builderClass, classMethods); } - - /** - * Хранит вспомогательные данные, необходимые для дозаполнения моделей - */ - @Data - public static class Context { - - /** - * Имя прочитанного объекта - */ - String name; - - /** - * Список подсистем - */ - List subsystems = new ArrayList<>(); - - /** - * Ссылка на текущий объект - */ - MdoReference mdoReference = MdoReference.EMPTY; - - /** - * Ссылка на родительский объект - */ - MdoReference owner = MdoReference.EMPTY; - - /** - * Класс будущего объекта - */ - Class realClass; - - /** - * Строковое имя объекта - */ - String realClassName; - - /** - * Билдер объекта - */ - Object builder; - - /** - * Тип объекта ссылки - */ - MDOType mdoType; - - /** - * Коллекция билдеров для дочерних объектов, которые надо доделать - */ - Map> children; - - /** - * Режим поддержки - */ - SupportVariant supportVariant = SupportVariant.NONE; - - /** - * Путь к текущему, читаемому файлу - */ - Path currentPath; - - /** - * Тип макета - */ - TemplateType templateType; - - /** - * Режим совместимости - */ - CompatibilityMode compatibilityMode; - - /** - * Режим совместимости расширения - */ - CompatibilityMode configurationExtensionCompatibilityMode; - - /** - * Дочерние метаданные - */ - List childrenMetadata = new ArrayList<>(); - - public Context(@NonNull String name, @NonNull Class clazz, @NonNull Path path) { - realClassName = name; - realClass = clazz; - builder = TransformationUtils.builder(realClass); - requireNonNull(builder); - mdoType = MDOType.fromValue(realClassName).orElse(MDOType.UNKNOWN); - children = new HashMap<>(); - currentPath = path; - } - - public void setValue(String methodName, Object value) { - TransformationUtils.setValue(builder, methodName, value); - } - - public Class fieldType(String methodName) { - var fieldClass = TransformationUtils.fieldType(builder, methodName); - if (fieldClass instanceof ParameterizedType parameterizedType) { - fieldClass = TransformationUtils.computeType(parameterizedType); - } - return (Class) fieldClass; - } - - public void addChild(String collectionName, TransformationUtils.Context child) { - var collection = children.get(collectionName); - if (collection == null) { - collection = new ArrayList<>(); - } - collection.add(child); - children.put(collectionName, collection); - } - - public void addChildMetadata(String groupName, String childName) { - childrenMetadata.add(groupName + "." + childName); - } - - public void addChildMetadata(String fullName) { - childrenMetadata.add(fullName); - } - - public MD build() { - - if (owner != MdoReference.EMPTY) { - mdoReference = MdoReference.create(owner, mdoType, name); - } else { - mdoReference = MdoReference.create(mdoType, name); - } - setValue("mdoReference", mdoReference); - - if (MDChild.class.isAssignableFrom(realClass)) { - setValue("owner", owner); - } - - if (Subsystem.class.isAssignableFrom(realClass)) { - setValue("parentSubsystem", owner); - } - - if (ChildrenOwner.class.isAssignableFrom(realClass)) { - children.forEach((String collectionName, List collectionSource) -> { - if (collectionName.endsWith("s")) { - var collection = collectionSource.parallelStream().map((Context childContext) -> { - childContext.setOwner(mdoReference); - return childContext.build(); - }).toList(); - setValue(collectionName, collection); - } else { - collectionSource.stream() - .filter(Objects::nonNull) // исключаем не прочитанное - .forEach((Context childContext) -> { - childContext.setOwner(mdoReference); - setValue(collectionName, childContext.build()); - }); - } - }); - } - - if (ModuleOwner.class.isAssignableFrom(realClass)) { - addModules(); - } - - return (MD) TransformationUtils.build(builder); - } - - private void addModules() { - var moduleTypes = ModuleType.byMDOType(mdoType); - if (moduleTypes.isEmpty()) { - return; - } - - // todo переделать - Path folder; - boolean isDesigner = MDOReader.getConfigurationSourceByMDOPath(currentPath) == ConfigurationSource.DESIGNER; - if (isDesigner) { - folder = DesignerPaths.moduleFolder(currentPath, mdoType); - } else { - folder = EDTPaths.moduleFolder(currentPath, mdoType); - } - - if (!folder.toFile().exists()) { - return; - } - - List modules = new ArrayList<>(); - moduleTypes.forEach((ModuleType moduleType) -> { - Path modulePath; - // todo переделать - if (isDesigner) { - modulePath = DesignerPaths.modulePath(folder, name, moduleType); - } else if (mdoType == MDOType.CONFIGURATION) { - modulePath = EDTPaths.modulePath(folder, MDOType.CONFIGURATION.getName(), moduleType); - } else { - modulePath = EDTPaths.modulePath(folder, name, moduleType); - } - - var protectedModuleInfo = ReaderUtils.readProtectedModuleInfo(modulePath); - if (protectedModuleInfo.getModulePath().toFile().exists()) { - modules.add(ObjectModule.builder() - .moduleType(moduleType) - .uri(protectedModuleInfo.getModulePath().toUri()) - .owner(mdoReference) - .supportVariant(supportVariant) - .isProtected(protectedModuleInfo.isProtected()) - .build()); - } - } - ); - setValue("modules", modules); - } - } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/FormElementReaderContext.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/FormElementReaderContext.java new file mode 100644 index 000000000..fb1fd44d8 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/FormElementReaderContext.java @@ -0,0 +1,117 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.context; + +import com.github._1c_syntax.bsl.mdo.storage.ManagedFormData; +import com.github._1c_syntax.bsl.mdo.storage.form.FormAttribute; +import com.github._1c_syntax.bsl.mdo.storage.form.FormHandler; +import com.github._1c_syntax.bsl.mdo.storage.form.SimpleFormItem; +import com.github._1c_syntax.bsl.reader.MDOReader; +import com.github._1c_syntax.bsl.reader.common.TransformationUtils; +import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; +import com.github._1c_syntax.bsl.types.ConfigurationSource; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import lombok.Data; +import lombok.NonNull; + +import java.nio.file.Path; +import java.util.Map; + +import static java.util.Objects.requireNonNull; + +/** + * Для хранения контекста при чтении элементов форм + */ +@Data +public class FormElementReaderContext implements ReaderContext { + + private static final Map> CLASSES = Map.of( + "Form", ManagedFormData.class, + "attributes", FormAttribute.class, + "Attribute", FormAttribute.class, + "items", SimpleFormItem.class, + "Events", FormHandler.class, + "ChildItems", SimpleFormItem.class, + ManagedFormData.class.getName(), ManagedFormData.class + ); + + private static final Class DEFAULT_CLASS_FORM_ITEM = SimpleFormItem.class; + + String lastName; + Object lastValue; + + /** + * Строковое имя объекта + */ + String realClassName; + + /** + * Класс будущего объекта + */ + Class realClass; + + /** + * Билдер объекта + */ + Object builder; + + /** + * Путь к текущему, читаемому файлу + */ + Path currentPath; + + /** + * Вариант исходников в формате конфигуратора + */ + boolean isDesignerFormat; + + public FormElementReaderContext(@NonNull String name, @NonNull HierarchicalStreamReader reader) { + currentPath = ExtendXStream.getCurrentPath(reader); + realClassName = name; + isDesignerFormat = MDOReader.getConfigurationSourceByMDOPath(currentPath) == ConfigurationSource.DESIGNER; + + realClass = realClassByName(realClassName); + if (realClass == null) { + realClass = DEFAULT_CLASS_FORM_ITEM; + } + builder = TransformationUtils.builder(realClass); + requireNonNull(builder); + } + + @Override + public Object build() { + return TransformationUtils.build(builder); + } + + @Override + public Class fieldType(String fieldName) { + var clazz = ReaderContext.super.fieldType(fieldName); + if (clazz == null) { + clazz = realClassByName(fieldName); + } + return clazz; + } + + private static Class realClassByName(String name) { + return CLASSES.get(name); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/MDCReaderContext.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/MDCReaderContext.java new file mode 100644 index 000000000..e13cafa7b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/MDCReaderContext.java @@ -0,0 +1,222 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.context; + +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.Module; +import com.github._1c_syntax.bsl.mdo.children.ObjectModule; +import com.github._1c_syntax.bsl.reader.MDOReader; +import com.github._1c_syntax.bsl.reader.common.TransformationUtils; +import com.github._1c_syntax.bsl.reader.common.converter.ProtectedModuleInfo; +import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; +import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; +import com.github._1c_syntax.bsl.reader.edt.EDTPaths; +import com.github._1c_syntax.bsl.supconf.ParseSupportData; +import com.github._1c_syntax.bsl.support.CompatibilityMode; +import com.github._1c_syntax.bsl.support.SupportVariant; +import com.github._1c_syntax.bsl.types.ConfigurationSource; +import com.github._1c_syntax.bsl.types.MDOType; +import com.github._1c_syntax.bsl.types.MdoReference; +import com.github._1c_syntax.bsl.types.ModuleType; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import lombok.Data; +import lombok.NonNull; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import static java.util.Objects.requireNonNull; + +/** + * Служебный класс для хранения контекста при "сборке" объекта при чтении из файла + */ +@Data +public class MDCReaderContext implements ReaderContext { + + private static final String UUID_FIELD_NAME = "uuid"; + private static final String MDO_REFERENCE_FIELD_NAME = "mdoReference"; + private static final String SUPPORT_VALIANT_FIELD_NAME = "SupportVariant"; + private static final String CHILD_FILED_NAME = "child"; + private static final String COMPATIBILITY_MODE_FILED_NAME = "compatibilityMode"; + private static final String CONFIGURATION_SOURCE_MODE_FILED_NAME = "configurationSource"; + private static final String MODULES_FIELD_NAME = "modules"; + + /** + * Класс будущего объекта + */ + Class realClass; + + /** + * Билдер объекта + */ + Object builder; + + /** + * Путь к текущему, читаемому файлу + */ + Path currentPath; + + /** + * Вариант исходников в формате конфигуратора + */ + boolean isDesignerFormat; + + /** + * Режим поддержки + */ + SupportVariant supportVariant = SupportVariant.NONE; + + /** + * Имя прочитанного объекта + */ + String name; + + /** + * Режим совместимости + */ + CompatibilityMode compatibilityMode; + + /** + * Режим совместимости расширения + */ + CompatibilityMode configurationExtensionCompatibilityMode; + + /** + * Тип объекта ссылки + */ + MDOType mdoType; + + /** + * Дочерние метаданные + */ + List childrenNames; + + String lastName; + Object lastValue; + + public MDCReaderContext(@NonNull Class clazz, @NonNull HierarchicalStreamReader reader) { + currentPath = ExtendXStream.getCurrentPath(reader); + realClass = clazz; + builder = TransformationUtils.builder(realClass); + requireNonNull(builder); + + var uuid = reader.getAttribute(UUID_FIELD_NAME); + supportVariant = ParseSupportData.getSupportVariantByMDO(uuid, currentPath); + isDesignerFormat = MDOReader.getConfigurationSourceByMDOPath(currentPath) == ConfigurationSource.DESIGNER; + mdoType = MDOType.CONFIGURATION; + + setValue(UUID_FIELD_NAME, uuid); + setValue(SUPPORT_VALIANT_FIELD_NAME, supportVariant); + + childrenNames = new ArrayList<>(); + } + + @Override + public Object build() { + var mdoReference = MdoReference.create(mdoType, name); + setValue(MDO_REFERENCE_FIELD_NAME, mdoReference); + + if (compatibilityMode == null) { + setValue(COMPATIBILITY_MODE_FILED_NAME, configurationExtensionCompatibilityMode); + } + + if (isDesignerFormat) { + setValue(CONFIGURATION_SOURCE_MODE_FILED_NAME, ConfigurationSource.DESIGNER); + } else { + setValue(CONFIGURATION_SOURCE_MODE_FILED_NAME, ConfigurationSource.EDT); + } + + setValueModules(mdoReference); + setValueChildren(); + + return TransformationUtils.build(builder); + } + + @Override + public final void setValue(String methodName, Object value) { + if (value instanceof String string && MDOType.fromValue(methodName).isPresent()) { + childrenNames.add(string); + } else { + ReaderContext.super.setValue(methodName, value); + } + } + + private void setValueChildren() { + var reader = MDOReader.getReader(currentPath); + childrenNames + .forEach((String fullName) -> { + MD child = (MD) reader.read(fullName); + if (child != null) { + var fieldName = child.getMdoType().getName(); + setValue(fieldName, child); + setValue(CHILD_FILED_NAME, child); + } + }); + } + + private void setValueModules(MdoReference mdoReference) { + var folder = getModuleFolder(); + if (!folder.toFile().exists()) { + return; + } + + var moduleTypes = ModuleType.byMDOType(mdoType); + if (moduleTypes.isEmpty()) { + return; + } + + List modules = new ArrayList<>(); + moduleTypes.forEach((ModuleType moduleType) -> { + var protectedModuleInfo = getModuleInfo(folder, moduleType); + if (protectedModuleInfo.getModulePath().toFile().exists()) { + modules.add(ObjectModule.builder() + .moduleType(moduleType) + .uri(protectedModuleInfo.getModulePath().toUri()) + .owner(mdoReference) + .supportVariant(supportVariant) + .isProtected(protectedModuleInfo.isProtected()) + .build()); + } + } + ); + setValue(MODULES_FIELD_NAME, modules); + } + + private Path getModuleFolder() { + if (isDesignerFormat) { + return DesignerPaths.moduleFolder(currentPath, mdoType); + } else { + return EDTPaths.moduleFolder(currentPath, mdoType); + } + } + + private ProtectedModuleInfo getModuleInfo(Path folder, ModuleType moduleType) { + Path modulePath; + if (isDesignerFormat) { + modulePath = DesignerPaths.modulePath(folder, name, moduleType); + } else { + modulePath = EDTPaths.modulePath(folder, MDOType.CONFIGURATION.getName(), moduleType); + } + return new ProtectedModuleInfo(modulePath); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/MDReaderContext.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/MDReaderContext.java new file mode 100644 index 000000000..1b87f4f39 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/MDReaderContext.java @@ -0,0 +1,283 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.context; + +import com.github._1c_syntax.bsl.mdo.ChildrenOwner; +import com.github._1c_syntax.bsl.mdo.Form; +import com.github._1c_syntax.bsl.mdo.MDChild; +import com.github._1c_syntax.bsl.mdo.Module; +import com.github._1c_syntax.bsl.mdo.ModuleOwner; +import com.github._1c_syntax.bsl.mdo.Subsystem; +import com.github._1c_syntax.bsl.mdo.children.ObjectModule; +import com.github._1c_syntax.bsl.mdo.storage.EmptyFormData; +import com.github._1c_syntax.bsl.mdo.storage.FormData; +import com.github._1c_syntax.bsl.mdo.support.TemplateType; +import com.github._1c_syntax.bsl.reader.MDOReader; +import com.github._1c_syntax.bsl.reader.common.TransformationUtils; +import com.github._1c_syntax.bsl.reader.common.converter.ProtectedModuleInfo; +import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; +import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; +import com.github._1c_syntax.bsl.reader.edt.EDTPaths; +import com.github._1c_syntax.bsl.supconf.ParseSupportData; +import com.github._1c_syntax.bsl.support.SupportVariant; +import com.github._1c_syntax.bsl.types.ConfigurationSource; +import com.github._1c_syntax.bsl.types.MDOType; +import com.github._1c_syntax.bsl.types.MdoReference; +import com.github._1c_syntax.bsl.types.ModuleType; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import lombok.Data; +import lombok.NonNull; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static java.util.Objects.requireNonNull; + +/** + * Для хранения контекста при чтении MD и ExternalSource объектов + */ +@Data +public class MDReaderContext implements ReaderContext { + + private static final String MDO_REFERENCE_FIELD_NAME = "mdoReference"; + private static final String OWNER_FIELD_NAME = "owner"; + private static final String PARENT_SUBSYSTEM_FIELD_NAME = "parentSubsystem"; + private static final String URI_FIELD_NAME = "uri"; + private static final String IS_PROTECTED_FIELD_NAME = "isProtected"; + private static final String UUID_FIELD_NAME = "uuid"; + private static final String SUPPORT_VALIANT_FIELD_NAME = "SupportVariant"; + private static final String DATA_FIELD_NAME = "data"; + private static final String MODULES_FIELD_NAME = "modules"; + + /** + * Строковое имя объекта + */ + String realClassName; + + /** + * Класс будущего объекта + */ + Class realClass; + + /** + * Билдер объекта + */ + Object builder; + + /** + * Путь к текущему, читаемому файлу + */ + Path currentPath; + + /** + * Вариант исходников в формате конфигуратора + */ + boolean isDesignerFormat; + + /** + * Режим поддержки + */ + SupportVariant supportVariant = SupportVariant.NONE; + + /** + * Коллекция билдеров для дочерних объектов, которые надо доделать + */ + Map> childrenContexts; + + /** + * Имя прочитанного объекта + */ + String name; + + /** + * Тип макета + */ + TemplateType templateType; + + /** + * Тип объекта ссылки + */ + MDOType mdoType; + + /** + * Ссылка на текущий объект + */ + MdoReference mdoReference = MdoReference.EMPTY; + + /** + * Ссылка на родительский объект + */ + MdoReference owner = MdoReference.EMPTY; + + String lastName; + Object lastValue; + + public MDReaderContext(@NonNull HierarchicalStreamReader reader) { + currentPath = ExtendXStream.getCurrentPath(reader); + isDesignerFormat = MDOReader.getConfigurationSourceByMDOPath(currentPath) == ConfigurationSource.DESIGNER; + realClassName = reader.getNodeName(); + realClass = MDOReader.getReader(currentPath).getEXStream().getRealClass(realClassName); + + builder = TransformationUtils.builder(realClass); + requireNonNull(builder); + + mdoType = MDOType.fromValue(realClassName).orElse(MDOType.UNKNOWN); + childrenContexts = new HashMap<>(); + + var uuid = reader.getAttribute(UUID_FIELD_NAME); + supportVariant = ParseSupportData.getSupportVariantByMDO(uuid, currentPath); + + setValue(UUID_FIELD_NAME, uuid); + setValue(SUPPORT_VALIANT_FIELD_NAME, supportVariant); + } + + @Override + public final void setValue(String methodName, Object value) { + if (value instanceof MDReaderContext child) { + saveChildName(methodName, child); + } else { + ReaderContext.super.setValue(methodName, value); + } + } + + @Override + public Object build() { + mdoReference = MdoReference.create(owner, mdoType, name); + setValue(MDO_REFERENCE_FIELD_NAME, mdoReference); + + if (MDChild.class.isAssignableFrom(realClass)) { + setValue(OWNER_FIELD_NAME, owner); + } + + if (Subsystem.class.isAssignableFrom(realClass)) { + setValue(PARENT_SUBSYSTEM_FIELD_NAME, owner); + } + + if (Form.class.isAssignableFrom(realClass)) { + setValue(DATA_FIELD_NAME, readFormData()); + } + + if (ChildrenOwner.class.isAssignableFrom(realClass)) { + setValueChildren(); + } + + if (ModuleOwner.class.isAssignableFrom(realClass)) { + setValueModules(); + } + + return TransformationUtils.build(builder); + } + + private void saveChildName(String collectionName, MDReaderContext child) { + var collection = childrenContexts.get(collectionName); + if (collection == null) { + collection = new ArrayList<>(); + } + collection.add(child); + childrenContexts.put(collectionName, collection); + } + + private void setValueModules() { + var folder = getModuleFolder(); + if (!folder.toFile().exists()) { + return; + } + + var moduleTypes = ModuleType.byMDOType(mdoType); + if (moduleTypes.isEmpty()) { + return; + } + + List modules = new ArrayList<>(); + moduleTypes.forEach((ModuleType moduleType) -> { + var protectedModuleInfo = getModuleInfo(folder, moduleType); + if (protectedModuleInfo.getModulePath().toFile().exists()) { + modules.add(ObjectModule.builder() + .moduleType(moduleType) + .uri(protectedModuleInfo.getModulePath().toUri()) + .owner(mdoReference) + .supportVariant(supportVariant) + .isProtected(protectedModuleInfo.isProtected()) + .build()); + } + } + ); + setValue(MODULES_FIELD_NAME, modules); + } + + private void setValueChildren() { + childrenContexts.forEach((String collectionName, List collectionSource) -> { + if (collectionName.endsWith("s")) { + var collection = collectionSource.parallelStream() + .map((MDReaderContext childContext) -> { + childContext.setOwner(mdoReference); + return childContext.build(); + }).toList(); + setValue(collectionName, collection); + } else { + collectionSource.stream() + .filter(Objects::nonNull) // исключаем не прочитанное + .forEach((MDReaderContext childContext) -> { + childContext.setOwner(mdoReference); + setValue(collectionName, childContext.build()); + }); + } + }); + } + + private FormData readFormData() { + Path formDataPath; + if (isDesignerFormat) { + formDataPath = DesignerPaths.formDataPath(currentPath, name); + } else { + formDataPath = EDTPaths.formDataPath(currentPath, mdoType, name); + } + + if (!formDataPath.toFile().exists()) { + return EmptyFormData.getEmpty(); + } + + return (FormData) MDOReader.getReader(currentPath).read(formDataPath); + } + + private Path getModuleFolder() { + if (isDesignerFormat) { + return DesignerPaths.moduleFolder(currentPath, mdoType); + } else { + return EDTPaths.moduleFolder(currentPath, mdoType); + } + } + + private ProtectedModuleInfo getModuleInfo(Path folder, ModuleType moduleType) { + Path modulePath; + if (isDesignerFormat) { + modulePath = DesignerPaths.modulePath(folder, name, moduleType); + } else { + modulePath = EDTPaths.modulePath(folder, name, moduleType); + } + return new ProtectedModuleInfo(modulePath); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/ReaderContext.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/ReaderContext.java new file mode 100644 index 000000000..4e215cc4b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/ReaderContext.java @@ -0,0 +1,87 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.context; + +import com.github._1c_syntax.bsl.reader.common.TransformationUtils; + +import java.lang.reflect.ParameterizedType; + +/** + * Сохраняемый контекст при чтении файла + */ +public interface ReaderContext { + + /** + * Билдер читаемого объекта + */ + Object getBuilder(); + + + /** + * Имя последней прочитанной ноды + */ + String getLastName(); + + void setLastName(String lastName); + + /** + * Последнее прочитанное значение + */ + Object getLastValue(); + + void setLastValue(Object lastValue); + + /** + * Признак чтения файла в формате выгрузки из конфигуратора. + * Введено для сокращения копипасты в случае наличия общего алгоритма, но разных путей расположения файлоа + */ + boolean isDesignerFormat(); + + /** + * Для установки значения поля собираемого объекта + * + * @param methodName Имя поля\метода + * @param value устанавливаемое значение + */ + default void setValue(String methodName, Object value) { + TransformationUtils.setValue(getBuilder(), methodName, value); + } + + /** + * Получение класса типа поля + * + * @param fieldName Имя поля\метода + * @return Определенный класс + */ + default Class fieldType(String fieldName) { + var fieldClass = TransformationUtils.fieldType(getBuilder(), fieldName); + if (fieldClass instanceof ParameterizedType parameterizedType) { + fieldClass = TransformationUtils.computeType(parameterizedType); + } + return (Class) fieldClass; + } + + /** + * Сборка контекста в объект + */ + Object build(); +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/package-info.java new file mode 100644 index 000000000..d7f92bf8b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/context/package-info.java @@ -0,0 +1,25 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +/** + * Контексты, используемые при чтении файлов + */ +package com.github._1c_syntax.bsl.reader.common.context; diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractMDCReadConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractMDCReadConverter.java new file mode 100644 index 000000000..d1ea744ba --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractMDCReadConverter.java @@ -0,0 +1,76 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.converter; + +import com.github._1c_syntax.bsl.mdclasses.Configuration; +import com.github._1c_syntax.bsl.mdclasses.ConfigurationExtension; +import com.github._1c_syntax.bsl.mdclasses.ConfigurationTree; +import com.github._1c_syntax.bsl.reader.common.context.MDCReaderContext; +import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import lombok.SneakyThrows; + +import java.io.FileInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +/** + * Обобщенный конвертер для контейнеров конфигурации и расширения + */ +public abstract class AbstractMDCReadConverter implements ReadConverter { + + private final String configurationExtensionFilter; + + protected AbstractMDCReadConverter(String configurationExtensionFilter) { + this.configurationExtensionFilter = configurationExtensionFilter; + } + + @SneakyThrows + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + int count; + var fileInputStream = new FileInputStream(ExtendXStream.getCurrentPath(reader).toFile()); + try (var scanner = new Scanner(fileInputStream, StandardCharsets.UTF_8)) { + count = (int) scanner.findAll(configurationExtensionFilter).count(); + } + + Class realClass = Configuration.class; + if (count > 0) { + realClass = ConfigurationExtension.class; + } + + var readerContext = new MDCReaderContext(realClass, reader); + if (readerContext.isDesignerFormat()) { + com.github._1c_syntax.bsl.reader.designer.converter.Unmarshaller.unmarshal(reader, context, readerContext); + } else { + com.github._1c_syntax.bsl.reader.edt.converter.Unmarshaller.unmarshal(reader, context, readerContext); + } + return readerContext.build(); + } + + @Override + public boolean canConvert(Class type) { + return ConfigurationTree.class.isAssignableFrom(type); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/AbstractReadConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractReadConverter.java similarity index 59% rename from src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/AbstractReadConverter.java rename to src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractReadConverter.java index f691ef5c6..27f84eeac 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/AbstractReadConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractReadConverter.java @@ -19,29 +19,18 @@ * You should have received a copy of the GNU Lesser General Public * License along with MDClasses. */ -package com.github._1c_syntax.bsl.reader.edt.converter; +package com.github._1c_syntax.bsl.reader.common.converter; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; +import com.github._1c_syntax.bsl.reader.common.ReaderUtils; +import com.github._1c_syntax.bsl.reader.common.context.MDReaderContext; import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.reader.edt.EDTReader; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import java.nio.file.Path; - public abstract class AbstractReadConverter implements ReadConverter { - - protected String name; - protected Class realClass; - protected Path currentPath; - - protected TransformationUtils.Context read(HierarchicalStreamReader reader, UnmarshallingContext context) { - name = reader.getNodeName(); - realClass = EDTReader.getXstream().getRealClass(name); - currentPath = ExtendXStream.getCurrentPath(reader); - var readerContext = new TransformationUtils.Context(reader.getNodeName(), realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); + protected MDReaderContext read(HierarchicalStreamReader reader, UnmarshallingContext context) { + var readerContext = new MDReaderContext(reader); + ReaderUtils.unmarshal(reader, context, readerContext); return readerContext; } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractSubsystemConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractSubsystemConverter.java new file mode 100644 index 000000000..36393a1dd --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/AbstractSubsystemConverter.java @@ -0,0 +1,91 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.converter; + +import com.github._1c_syntax.bsl.mdo.Subsystem; +import com.github._1c_syntax.bsl.reader.MDOReader; +import com.github._1c_syntax.bsl.reader.common.ReaderUtils; +import com.github._1c_syntax.bsl.reader.common.context.MDReaderContext; +import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; +import com.github._1c_syntax.bsl.reader.edt.EDTPaths; +import com.github._1c_syntax.bsl.types.MDOType; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import org.apache.commons.io.FilenameUtils; + +import java.nio.file.Paths; + +import static java.util.Objects.requireNonNull; + +public abstract class AbstractSubsystemConverter implements ReadConverter { + + private static final String START_MDOREF_NAME = MDOType.SUBSYSTEM.getName() + "."; + private static final int COUNT_PARTS = 2; + + private final String subsystemsNodeName; + private final boolean isDesignerFormat; + + protected AbstractSubsystemConverter(String subsystemsNodeName, boolean isDesignerFormat) { + this.subsystemsNodeName = subsystemsNodeName; + this.isDesignerFormat = isDesignerFormat; + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + var name = reader.getNodeName(); + var currentPath = ExtendXStream.getCurrentPath(reader); + + if (subsystemsNodeName.equals(name) && reader.getAttributeCount() == 0) { // дочерняя подсистема строкой + String rootFolder; + if (isDesignerFormat) { + rootFolder = DesignerPaths.mdoTypeFolderPathByMDOPath(currentPath).toString(); + } else { + rootFolder = EDTPaths.mdoTypeFolderPathByMDOPath(currentPath).toString(); + } + var currentName = FilenameUtils.getBaseName(currentPath.toString()); + var folder = Paths.get(rootFolder, currentName, MDOType.SUBSYSTEM.getGroupName()); + return MDOReader.readMDObject(folder, START_MDOREF_NAME + reader.getValue()); + } else { // самостоятельная подсистема + var readerContext = new MDReaderContext(reader); + ReaderUtils.unmarshal(reader, context, readerContext); + + var prjPath = MDOReader.getReader(ExtendXStream.getCurrentPath(reader)).getRootPath(); + requireNonNull(prjPath); + var localRootPath = currentPath.toString().replace(prjPath.toString(), ""); + + // определим это самостоятельная или дочерняя + // у дочерней будет несколько вложенных папок подсистемы + if (localRootPath.split(MDOType.SUBSYSTEM.getName()).length > COUNT_PARTS) { + return readerContext; + } else { + return readerContext.build(); + } + } + } + + @Override + public boolean canConvert(Class type) { + return Subsystem.class.isAssignableFrom(type); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/CommonModuleConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/CommonModuleConverter.java similarity index 60% rename from src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/CommonModuleConverter.java rename to src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/CommonModuleConverter.java index 95c95cdc2..7d61a1a01 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/CommonModuleConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/CommonModuleConverter.java @@ -19,43 +19,44 @@ * You should have received a copy of the GNU Lesser General Public * License along with MDClasses. */ -package com.github._1c_syntax.bsl.reader.designer.converter; +package com.github._1c_syntax.bsl.reader.common.converter; import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; +import com.github._1c_syntax.bsl.reader.edt.EDTPaths; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.ModuleType; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import org.apache.commons.io.FilenameUtils; -import java.nio.file.Paths; +import java.nio.file.Path; -@DesignerConverter +@CommonConverter public class CommonModuleConverter extends AbstractReadConverter { - private static final String URI_FIELD = "uri"; - private static final String IS_PROTECTED_FIELD = "isProtected"; + private static final String URI_FIELD_NAME = "uri"; + private static final String IS_PROTECTED_FIELD_NAME = "isProtected"; @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - var folder = DesignerPaths.moduleFolder(currentPath, MDOType.COMMON_MODULE); - var modulePath = DesignerPaths.modulePath(folder, readerContext.getName(), ModuleType.CommonModule); - - var isProtected = false; - if (!modulePath.toFile().exists()) { - // возможно модуль защищен - var prtModulePath = Paths.get(FilenameUtils.removeExtension(modulePath.toFile().getPath()) + ".bin"); - if (prtModulePath.toFile().exists()) { - isProtected = true; - modulePath = prtModulePath; - } + Path modulePath; + if (readerContext.isDesignerFormat()) { + modulePath = DesignerPaths.modulePath( + DesignerPaths.moduleFolder(readerContext.getCurrentPath(), MDOType.COMMON_MODULE), + readerContext.getName(), + ModuleType.CommonModule + ); + } else { + modulePath = EDTPaths.modulePath( + EDTPaths.moduleFolder(readerContext.getCurrentPath(), MDOType.COMMON_MODULE), + readerContext.getName(), + ModuleType.CommonModule + ); } - - readerContext.setValue(URI_FIELD, modulePath.toUri()); - readerContext.setValue(IS_PROTECTED_FIELD, isProtected); - + var protectedModuleInfo = new ProtectedModuleInfo(modulePath); + readerContext.setValue(URI_FIELD_NAME, protectedModuleInfo.getModulePath().toUri()); + readerContext.setValue(IS_PROTECTED_FIELD_NAME, protectedModuleInfo.isProtected()); return readerContext.build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/ConverterParts.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/ConverterParts.java new file mode 100644 index 000000000..e38a66555 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/ConverterParts.java @@ -0,0 +1,109 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.converter; + +import com.github._1c_syntax.bsl.mdo.CommonAttribute; +import com.github._1c_syntax.bsl.mdo.ExchangePlan; +import com.github._1c_syntax.bsl.mdo.support.AutoRecordType; +import com.github._1c_syntax.bsl.mdo.support.UseMode; +import com.github._1c_syntax.bsl.reader.common.ReaderUtils; +import com.github._1c_syntax.bsl.types.MdoReference; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import lombok.experimental.UtilityClass; + +import java.util.AbstractMap; + +/** + * Содержит методы с общими частями методов конвертирования + */ +@UtilityClass +public class ConverterParts { + private static final String METADATA_NODE_NAME = "Metadata"; + private static final String USE_NODE_NAME = "Use"; + + public CommonAttribute.UseContent commonAttributeUseContent(HierarchicalStreamReader reader, + UnmarshallingContext context) { + if (!reader.hasMoreChildren()) { + return null; + } + + var builder = CommonAttribute.UseContent.builder(); + while (reader.hasMoreChildren()) { + reader.moveDown(); + var node = reader.getNodeName(); + if (METADATA_NODE_NAME.equalsIgnoreCase(node)) { + builder.metadata(MdoReference.create(reader.getValue())); + } else if (USE_NODE_NAME.equalsIgnoreCase(node)) { + builder.use(ReaderUtils.readValue(context, UseMode.class)); + } else { + // no-op + } + reader.moveUp(); + } + return builder.build(); + } + + public static ExchangePlan.RecordContent exchangePlanAutoRecord(HierarchicalStreamReader reader, + UnmarshallingContext context, + String mdoNodeName, + String autoRecordNodeName) { + if (!reader.hasMoreChildren()) { + return null; + } + + var builder = ExchangePlan.RecordContent.builder(); + while (reader.hasMoreChildren()) { + reader.moveDown(); + var node = reader.getNodeName(); + if (mdoNodeName.equals(node)) { + builder.metadata(MdoReference.create(reader.getValue())); + } else if (autoRecordNodeName.equals(node)) { + builder.autoRecord(ReaderUtils.readValue(context, AutoRecordType.class)); + } else { + // no-op + } + reader.moveUp(); + } + return builder.build(); + } + + public AbstractMap.SimpleEntry multiLanguageString(HierarchicalStreamReader reader, + String langNodeName, + String contentNodeName) { + var lang = ""; + var content = ""; + while (reader.hasMoreChildren()) { + reader.moveDown(); + var node = reader.getNodeName(); + if (langNodeName.equals(node)) { + lang = reader.getValue(); + } else if (contentNodeName.equals(node)) { + content = reader.getValue(); + } else { + // no-op + } + reader.moveUp(); + } + return new AbstractMap.SimpleEntry<>(lang, content); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/ProtectedModuleInfo.java b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/ProtectedModuleInfo.java new file mode 100644 index 000000000..5ec5ebcd0 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/ProtectedModuleInfo.java @@ -0,0 +1,71 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.common.converter; + +import lombok.Getter; +import org.apache.commons.io.FilenameUtils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; + +/** + * Описание "защищенности" модуля + */ +@Getter +public class ProtectedModuleInfo { + + private static final byte[] PROTECTED_FILE_HEADER = new byte[]{-1, -1, -1, 127}; + + /** + * Признак защищенности модуля + */ + private boolean isProtected; + + /** + * Путь к модулю + */ + private Path modulePath; + + public ProtectedModuleInfo(Path path) { + modulePath = path; + isProtected = false; + + if (!modulePath.toFile().exists()) { + var prtModulePath = Paths.get(FilenameUtils.removeExtension(modulePath.toFile().getPath()) + ".bin"); + if (prtModulePath.toFile().exists()) { + isProtected = true; + modulePath = prtModulePath; + } + } else { + var bytes = new byte[PROTECTED_FILE_HEADER.length]; + try (var fis = new FileInputStream(modulePath.toFile())) { + isProtected = (fis.read(bytes) == PROTECTED_FILE_HEADER.length + && Arrays.equals(bytes, PROTECTED_FILE_HEADER)); + } catch (IOException e) { + // ошибка чтения в данном случае неважна + } + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/DesignerReader.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/DesignerReader.java index be4641d6f..09c7f9aca 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/DesignerReader.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/DesignerReader.java @@ -44,6 +44,7 @@ import com.github._1c_syntax.bsl.mdo.children.TaskAddressingAttribute; import com.github._1c_syntax.bsl.mdo.children.WebServiceOperation; import com.github._1c_syntax.bsl.mdo.children.WebServiceOperationParameter; +import com.github._1c_syntax.bsl.mdo.storage.ManagedFormData; import com.github._1c_syntax.bsl.reader.MDReader; import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; import com.github._1c_syntax.bsl.reader.designer.converter.DesignerConverter; @@ -52,9 +53,11 @@ import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.mdclasses.wrapper.DesignerRootWrapper; import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.xml.QNameMap; import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import javax.xml.namespace.QName; import java.nio.file.Path; import java.util.Optional; @@ -125,7 +128,10 @@ public ExtendXStream getEXStream() { } private static ExtendXStream createXMLMapper() { - var xStream = new ExtendXStream(); + var qNameMap = new QNameMap(); + qNameMap.registerMapping(new QName("http://v8.1c.ru/8.3/xcf/logform", "Form"), ManagedFormData.class); + + var xStream = new ExtendXStream(qNameMap); // необходимо зарегистрировать все используемые классы registerClasses(xStream); @@ -139,7 +145,6 @@ private static ExtendXStream createXMLMapper() { private static void registerClasses(XStream xStream) { xStream.alias("MetaDataObject", DesignerRootWrapper.class); - xStream.alias("AccountingFlag", AccountingFlag.class); xStream.alias("AddressingAttribute", TaskAddressingAttribute.class); xStream.alias("Attribute", ObjectAttribute.class); diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/CommonAttributeUseContentConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/CommonAttributeUseContentConverter.java similarity index 64% rename from src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/CommonAttributeUseContentConverter.java rename to src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/CommonAttributeUseContentConverter.java index 7e6f724a8..7767a3c38 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/common/converter/CommonAttributeUseContentConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/CommonAttributeUseContentConverter.java @@ -1,66 +1,54 @@ -/* - * This file is a part of MDClasses. - * - * Copyright (c) 2019 - 2023 - * Tymko Oleg , Maximov Valery and contributors - * - * SPDX-License-Identifier: LGPL-3.0-or-later - * - * MDClasses is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3.0 of the License, or (at your option) any later version. - * - * MDClasses is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with MDClasses. - */ -package com.github._1c_syntax.bsl.reader.common.converter; - -import com.github._1c_syntax.bsl.mdo.CommonAttribute; -import com.github._1c_syntax.bsl.mdo.support.UseMode; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.types.MdoReference; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; - -/** - * Конвертер для состава общего реквизита - */ -@CommonConverter -public class CommonAttributeUseContentConverter implements ReadConverter { - - private static final String METADATA_NODE_NAME = "Metadata"; - private static final String USE_NODE_NAME = "Use"; - - @Override - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - if (!reader.hasMoreChildren()) { - return null; - } - - var builder = CommonAttribute.UseContent.builder(); - while (reader.hasMoreChildren()) { - reader.moveDown(); - var node = reader.getNodeName(); - if (METADATA_NODE_NAME.equalsIgnoreCase(node)) { - builder.metadata(MdoReference.create(reader.getValue())); - } else if (USE_NODE_NAME.equalsIgnoreCase(node)) { - builder.use((UseMode) context.convertAnother(reader.getValue(), UseMode.class)); - } else { - // no-op - } - reader.moveUp(); - } - return builder.build(); - } - - @Override - public boolean canConvert(Class type) { - return CommonAttribute.UseContent.class.isAssignableFrom(type); - } -} +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.designer.converter; + +import com.github._1c_syntax.bsl.mdo.CommonAttribute; +import com.github._1c_syntax.bsl.reader.common.converter.ConverterParts; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +import java.util.ArrayList; +import java.util.List; + +/** + * Конвертер для состава общего реквизита + */ +@DesignerConverter +public class CommonAttributeUseContentConverter implements ReadConverter { + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + List contents = new ArrayList<>(); + while (reader.hasMoreChildren()) { + reader.moveDown(); + contents.add(ConverterParts.commonAttributeUseContent(reader, context)); + reader.moveUp(); + } + return contents; + } + + @Override + public boolean canConvert(Class type) { + return CommonAttribute.UseContent.class.isAssignableFrom(type); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ConfigurationConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ConfigurationConverter.java index 08a1c76ac..872dac6ea 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ConfigurationConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ConfigurationConverter.java @@ -21,75 +21,14 @@ */ package com.github._1c_syntax.bsl.reader.designer.converter; -import com.github._1c_syntax.bsl.mdclasses.Configuration; -import com.github._1c_syntax.bsl.mdclasses.ConfigurationExtension; -import com.github._1c_syntax.bsl.mdclasses.ConfigurationTree; -import com.github._1c_syntax.bsl.mdo.MD; -import com.github._1c_syntax.bsl.reader.MDOReader; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; -import com.github._1c_syntax.bsl.types.ConfigurationSource; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import lombok.SneakyThrows; - -import java.io.FileInputStream; -import java.nio.charset.StandardCharsets; -import java.util.Scanner; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractMDCReadConverter; @DesignerConverter -public class ConfigurationConverter implements ReadConverter { - - private static final String CHILD_FILED = "child"; - - @SneakyThrows - @Override - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - int count; - var fileInputStream = new FileInputStream(ExtendXStream.getCurrentPath(reader).toFile()); - try (var scanner = new Scanner(fileInputStream, StandardCharsets.UTF_8)) { - count = (int) scanner.findAll("()").count(); - } - - Class realClass = Configuration.class; - - if (count > 0) { - realClass = ConfigurationExtension.class; - } - - var currentPath = ExtendXStream.getCurrentPath(reader); - var readerContext = new TransformationUtils.Context(reader.getNodeName(), realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); +public class ConfigurationConverter extends AbstractMDCReadConverter { - if (readerContext.getCompatibilityMode() == null) { - readerContext.setValue("compatibilityMode", - readerContext.getConfigurationExtensionCompatibilityMode()); - } - - readChildren(readerContext); - - readerContext.setValue("configurationSource", ConfigurationSource.DESIGNER); - return readerContext.build(); - } - - @Override - public boolean canConvert(Class type) { - return ConfigurationTree.class.isAssignableFrom(type); - } + private static final String CONFIGURATION_EXTENSION_FILTER = "()"; - private static void readChildren(TransformationUtils.Context readerContext) { - var rootPath = DesignerPaths.rootPathByConfigurationMDO(readerContext.getCurrentPath()); - var reader = MDOReader.getReader(rootPath); - readerContext.getChildrenMetadata() - .forEach((String fullName) -> { - MD child = (MD) reader.read(fullName); - if (child != null) { - var fieldName = child.getMdoType().getName(); - readerContext.setValue(fieldName, child); - readerContext.setValue(CHILD_FILED, child); - } - }); + public ConfigurationConverter() { + super(CONFIGURATION_EXTENSION_FILTER); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanAutoRecordConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanAutoRecordConverter.java index 94937ab4c..c7d614d9c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanAutoRecordConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanAutoRecordConverter.java @@ -22,9 +22,8 @@ package com.github._1c_syntax.bsl.reader.designer.converter; import com.github._1c_syntax.bsl.mdo.ExchangePlan; -import com.github._1c_syntax.bsl.mdo.support.AutoRecordType; +import com.github._1c_syntax.bsl.reader.common.converter.ConverterParts; import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.types.MdoReference; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -47,23 +46,11 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co } List content = new ArrayList<>(); - while (reader.hasMoreChildren()) { // root reader.moveDown(); - var builder = ExchangePlan.RecordContent.builder(); - while (reader.hasMoreChildren()) { // item - reader.moveDown(); - var node = reader.getNodeName(); - if (METADATA_NODE_NAME.equals(node)) { - builder.metadata(MdoReference.create(reader.getValue())); - } else if (AUTO_RECORD_NODE_NAME.equals(node)) { - builder.autoRecord((AutoRecordType) context.convertAnother(reader.getValue(), AutoRecordType.class)); - } else { - // no-op - } - reader.moveUp(); - } - content.add(builder.build()); + content.add( + ConverterParts.exchangePlanAutoRecord(reader, context, METADATA_NODE_NAME, AUTO_RECORD_NODE_NAME) + ); reader.moveUp(); } return content; diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanConverter.java index efea0b94c..dca7359c8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExchangePlanConverter.java @@ -23,6 +23,7 @@ import com.github._1c_syntax.bsl.mdo.ExchangePlan; import com.github._1c_syntax.bsl.reader.MDOReader; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -35,10 +36,8 @@ public class ExchangePlanConverter extends AbstractReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - - var contentPath = DesignerPaths.exchangePlanContentPath(currentPath, readerContext.getName()); + var contentPath = DesignerPaths.exchangePlanContentPath(readerContext.getCurrentPath(), readerContext.getName()); readerContext.setValue(DATA_FIELD, MDOReader.read(contentPath)); - return readerContext.build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExternalDataSourceConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExternalSourceConverter.java similarity index 91% rename from src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExternalDataSourceConverter.java rename to src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExternalSourceConverter.java index 6a462227a..c60285d85 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExternalDataSourceConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ExternalSourceConverter.java @@ -22,13 +22,14 @@ package com.github._1c_syntax.bsl.reader.designer.converter; import com.github._1c_syntax.bsl.mdclasses.ExternalSource; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.types.ConfigurationSource; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import lombok.SneakyThrows; @DesignerConverter -public class ExternalDataSourceConverter extends AbstractReadConverter { +public class ExternalSourceConverter extends AbstractReadConverter { @SneakyThrows @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormDataPathConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormDataPathConverter.java new file mode 100644 index 000000000..2eee98c6f --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormDataPathConverter.java @@ -0,0 +1,42 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.designer.converter; + +import com.github._1c_syntax.bsl.mdo.storage.form.FormDataPath; +import com.thoughtworks.xstream.converters.basic.StringConverter; + +/** + * Конвертор пути элемента формы в формате конфигуратора + */ +@DesignerConverter +public class FormDataPathConverter extends StringConverter { + + @Override + public Object fromString(String string) { + return new FormDataPath(string); + } + + @Override + public boolean canConvert(Class type) { + return type == FormDataPath.class; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormElementConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormElementConverter.java new file mode 100644 index 000000000..132637a86 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormElementConverter.java @@ -0,0 +1,52 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.designer.converter; + +import com.github._1c_syntax.bsl.mdo.storage.form.FormAttribute; +import com.github._1c_syntax.bsl.mdo.storage.form.FormItem; +import com.github._1c_syntax.bsl.reader.common.context.FormElementReaderContext; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +/** + * Конвертор элемента формы в формате конфигуратора + */ +@DesignerConverter +public class FormElementConverter implements ReadConverter { + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + var readerContext = new FormElementReaderContext(reader.getNodeName(), reader); + readerContext.setValue("type", reader.getNodeName()); + readerContext.setValue("id", Integer.parseInt(reader.getAttribute("id"))); + readerContext.setValue("name", reader.getAttribute("name")); + Unmarshaller.unmarshal(reader, context, readerContext); + return readerContext.build(); + } + + @Override + public boolean canConvert(Class type) { + return FormItem.class.isAssignableFrom(type) + || type == FormAttribute.class; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormHandlerConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormHandlerConverter.java new file mode 100644 index 000000000..cbd4dd4db --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/FormHandlerConverter.java @@ -0,0 +1,45 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.designer.converter; + +import com.github._1c_syntax.bsl.mdo.storage.form.FormHandler; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +/** + * Конвертор обработчика события формы в формате конфигуратора + */ +@DesignerConverter +public class FormHandlerConverter implements ReadConverter { + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + var event = reader.getAttribute("name"); + var name = reader.getValue(); + return new FormHandler(event, name); + } + + @Override + public boolean canConvert(Class type) { + return type == FormHandler.class; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDChildConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDChildConverter.java index d7fafb23f..d2ddb0f7d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDChildConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDChildConverter.java @@ -27,11 +27,10 @@ import com.github._1c_syntax.bsl.mdo.children.ObjectTemplate; import com.github._1c_syntax.bsl.mdo.children.Recalculation; import com.github._1c_syntax.bsl.reader.MDOReader; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; +import com.github._1c_syntax.bsl.reader.common.ReaderUtils; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; -import com.github._1c_syntax.bsl.reader.designer.DesignerReader; import com.github._1c_syntax.bsl.types.MDOType; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -44,27 +43,25 @@ * Конвертер для дочерних элементов (атрибуты, операции и т.д.) */ @DesignerConverter -public class MDChildConverter implements ReadConverter { +public class MDChildConverter extends AbstractReadConverter { private static final Map, MDOType> TYPES_BY_CLASSES = computeTypes(); @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - var name = reader.getNodeName(); - var realClass = DesignerReader.getXstream().getRealClass(name); var currentPath = ExtendXStream.getCurrentPath(reader); + var realClassName = reader.getNodeName(); + var realClass = MDOReader.getReader(currentPath).getEXStream().getRealClass(realClassName); if (TYPES_BY_CLASSES.containsKey(realClass) && reader.getAttributeCount() == 0) { var mdoType = TYPES_BY_CLASSES.get(realClass); var childrenFolder = DesignerPaths.childrenFolder(currentPath, mdoType); - var childName = context.convertAnother(String.class, String.class); + var childName = ReaderUtils.readValue(context, String.class); var childPath = Paths.get(childrenFolder.toString(), childName + DesignerPaths.EXTENSION_DOT); return MDOReader.read(childPath); + } else { + return super.read(reader, context); } - - var readerContext = new TransformationUtils.Context(name, realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); - return readerContext; } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDConverter.java index 73b0d0145..cee61db05 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MDConverter.java @@ -28,6 +28,7 @@ import com.github._1c_syntax.bsl.mdo.Role; import com.github._1c_syntax.bsl.mdo.Subsystem; import com.github._1c_syntax.bsl.mdo.XDTOPackage; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -36,8 +37,7 @@ public class MDConverter extends AbstractReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - var readerContext = super.read(reader, context); - return readerContext.build(); + return super.read(reader, context).build(); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/AbstractReadConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ManagedFormDataConverter.java similarity index 59% rename from src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/AbstractReadConverter.java rename to src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ManagedFormDataConverter.java index f6f788acf..71c526910 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/AbstractReadConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/ManagedFormDataConverter.java @@ -1,47 +1,47 @@ -/* - * This file is a part of MDClasses. - * - * Copyright (c) 2019 - 2023 - * Tymko Oleg , Maximov Valery and contributors - * - * SPDX-License-Identifier: LGPL-3.0-or-later - * - * MDClasses is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3.0 of the License, or (at your option) any later version. - * - * MDClasses is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with MDClasses. - */ -package com.github._1c_syntax.bsl.reader.designer.converter; - -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.reader.designer.DesignerReader; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; - -import java.nio.file.Path; - -public abstract class AbstractReadConverter implements ReadConverter { - - protected String name; - protected Class realClass; - protected Path currentPath; - - protected TransformationUtils.Context read(HierarchicalStreamReader reader, UnmarshallingContext context) { - name = reader.getNodeName(); - realClass = DesignerReader.getXstream().getRealClass(name); - currentPath = ExtendXStream.getCurrentPath(reader); - var readerContext = new TransformationUtils.Context(reader.getNodeName(), realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); - return readerContext; - } -} +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.designer.converter; + +import com.github._1c_syntax.bsl.mdo.storage.ManagedFormData; +import com.github._1c_syntax.bsl.reader.common.context.FormElementReaderContext; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +/** + * Конвертор данных управляемой формы в формате конфигуратора + */ +@DesignerConverter +public class ManagedFormDataConverter implements ReadConverter { + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + var readerContext = new FormElementReaderContext(reader.getNodeName(), reader); + Unmarshaller.unmarshal(reader, context, readerContext); + return readerContext.build(); + } + + @Override + public boolean canConvert(Class type) { + return type == ManagedFormData.class; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MdoReferenceConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MdoReferenceConverter.java index 4b1fc28bf..dde2a5f0f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MdoReferenceConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MdoReferenceConverter.java @@ -40,7 +40,6 @@ public class MdoReferenceConverter implements ReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - // todo надо обработать разные типы var nodeName = reader.getNodeName(); var value = ""; if (ITEM_NODE_NAME.equals(nodeName) && reader.hasMoreChildren()) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MetaDataObjectConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MetaDataObjectConverter.java index 2be4db7d0..b10a7dae4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MetaDataObjectConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MetaDataObjectConverter.java @@ -55,5 +55,4 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co public boolean canConvert(Class type) { return DesignerRootWrapper.class.isAssignableFrom(type); } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MultiLanguageStringConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MultiLanguageStringConverter.java index 84a60c52d..86b6a95c8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MultiLanguageStringConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/MultiLanguageStringConverter.java @@ -1,75 +1,63 @@ -/* - * This file is a part of MDClasses. - * - * Copyright (c) 2019 - 2023 - * Tymko Oleg , Maximov Valery and contributors - * - * SPDX-License-Identifier: LGPL-3.0-or-later - * - * MDClasses is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3.0 of the License, or (at your option) any later version. - * - * MDClasses is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with MDClasses. - */ -package com.github._1c_syntax.bsl.reader.designer.converter; - -import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import lombok.extern.slf4j.Slf4j; - -import java.util.HashMap; - -/** - * Конвертер для строк на нескольких языках - */ -@Slf4j -@DesignerConverter -public class MultiLanguageStringConverter implements ReadConverter { - - private static final String LANG_NODE_NAME = "lang"; - private static final String CONTENT_NODE_NAME = "content"; - - @Override - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - if (!reader.hasMoreChildren()) { - return MultiLanguageString.EMPTY; - } - HashMap langContent = new HashMap<>(); - - while (reader.hasMoreChildren()) { // v8:item - reader.moveDown(); - var lang = ""; - var content = ""; - while (reader.hasMoreChildren()) { - reader.moveDown(); - var node = reader.getNodeName(); - if (LANG_NODE_NAME.equals(node)) { - lang = reader.getValue(); - } else if (CONTENT_NODE_NAME.equals(node)) { - content = reader.getValue(); - } else { - // no-op - } - reader.moveUp(); - } - reader.moveUp(); - langContent.put(lang, content); - } - return new MultiLanguageString(langContent); - } - - @Override - public boolean canConvert(Class type) { - return type == MultiLanguageString.class; - } -} +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.designer.converter; + +import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; +import com.github._1c_syntax.bsl.reader.common.converter.ConverterParts; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import lombok.extern.slf4j.Slf4j; + +import java.util.HashMap; + +/** + * Конвертер для строк на нескольких языках + */ +@Slf4j +@DesignerConverter +public class MultiLanguageStringConverter implements ReadConverter { + + private static final String LANG_NODE_NAME = "lang"; + private static final String CONTENT_NODE_NAME = "content"; + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + if (!reader.hasMoreChildren()) { + return MultiLanguageString.EMPTY; + } + HashMap langContent = new HashMap<>(); + + while (reader.hasMoreChildren()) { // v8:item + reader.moveDown(); + var result = ConverterParts.multiLanguageString(reader, LANG_NODE_NAME, CONTENT_NODE_NAME); + langContent.put(result.getKey(), result.getValue()); + reader.moveUp(); + } + return new MultiLanguageString(langContent); + } + + @Override + public boolean canConvert(Class type) { + return type == MultiLanguageString.class; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/RoleConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/RoleConverter.java index 9330ff51e..819144af1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/RoleConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/RoleConverter.java @@ -23,6 +23,7 @@ import com.github._1c_syntax.bsl.mdo.Role; import com.github._1c_syntax.bsl.mdo.storage.RoleData; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -35,10 +36,8 @@ public class RoleConverter extends AbstractReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - readerContext.setValue(DATA_FIELD, - RoleData.create(DesignerPaths.roleDataPath(currentPath, readerContext.getName()))); - + RoleData.create(DesignerPaths.roleDataPath(readerContext.getCurrentPath(), readerContext.getName()))); return readerContext.build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/SubsystemConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/SubsystemConverter.java index e193dce98..fe674b81b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/SubsystemConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/SubsystemConverter.java @@ -21,63 +21,14 @@ */ package com.github._1c_syntax.bsl.reader.designer.converter; -import com.github._1c_syntax.bsl.mdo.Subsystem; -import com.github._1c_syntax.bsl.reader.MDOReader; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; -import com.github._1c_syntax.bsl.reader.designer.DesignerReader; -import com.github._1c_syntax.bsl.types.MDOType; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import org.apache.commons.io.FilenameUtils; - -import java.nio.file.Paths; - -import static java.util.Objects.requireNonNull; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractSubsystemConverter; @DesignerConverter -public class SubsystemConverter implements ReadConverter { - - private static final String START_MDOREF_NAME = MDOType.SUBSYSTEM.getName() + "."; - private static final String SUBSYSTEM_NODE = "Subsystem"; - - @Override - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - var name = reader.getNodeName(); - var currentPath = ExtendXStream.getCurrentPath(reader); - - if (SUBSYSTEM_NODE.equals(name) && reader.getAttributeCount() == 0) { // дочерняя подсистема строкой - - var rootFolder = DesignerPaths.mdoTypeFolderPathByMDOPath(currentPath).toString(); - var currentName = FilenameUtils.getBaseName(currentPath.toString()); - var folder = Paths.get(rootFolder, currentName, MDOType.SUBSYSTEM.getGroupName()); - return MDOReader.readMDObject(folder, START_MDOREF_NAME + reader.getValue()); +public class SubsystemConverter extends AbstractSubsystemConverter { - } else { // самостоятельная подсистема - - var realClass = DesignerReader.getXstream().getRealClass(name); - var readerContext = new TransformationUtils.Context(reader.getNodeName(), realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); - - var prjPath = MDOReader.getReader(ExtendXStream.getCurrentPath(reader)).getRootPath(); - requireNonNull(prjPath); - var localRootPath = currentPath.toString().replace(prjPath.toString(), ""); - - // определим это самостоятельная или дочерняя - // у дочерней будет несколько вложенных папок подсистемы - if (localRootPath.split(MDOType.SUBSYSTEM.getName()).length > 2) { - return readerContext; - } else { - return readerContext.build(); - } - } - - } + private static final String SUBSYSTEMS_NODE = "Subsystem"; - @Override - public boolean canConvert(Class type) { - return Subsystem.class.isAssignableFrom(type); + public SubsystemConverter() { + super(SUBSYSTEMS_NODE, true); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/TemplateConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/TemplateConverter.java index af3998941..0f3792209 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/TemplateConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/TemplateConverter.java @@ -27,7 +27,8 @@ import com.github._1c_syntax.bsl.mdo.storage.TemplateData; import com.github._1c_syntax.bsl.mdo.support.TemplateType; import com.github._1c_syntax.bsl.reader.MDOReader; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; +import com.github._1c_syntax.bsl.reader.common.ReaderUtils; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; import com.github._1c_syntax.bsl.reader.designer.DesignerReader; @@ -45,28 +46,23 @@ public class TemplateConverter extends AbstractReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - TransformationUtils.Context readerContext; - name = reader.getNodeName(); + var name = reader.getNodeName(); var realClass = DesignerReader.getXstream().getRealClass(name); - if (realClass.isAssignableFrom(CommonTemplate.class)) { - readerContext = super.read(reader, context); - } else { - currentPath = ExtendXStream.getCurrentPath(reader); + if (!realClass.isAssignableFrom(CommonTemplate.class)) { + var currentPath = ExtendXStream.getCurrentPath(reader); if (reader.getAttributeCount() == 0) { var childrenFolder = DesignerPaths.childrenFolder(currentPath, MDOType.TEMPLATE); - var childName = context.convertAnother(String.class, String.class); + var childName = ReaderUtils.readValue(context, String.class); var childPath = Paths.get(childrenFolder.toString(), childName + DesignerPaths.EXTENSION_DOT); return MDOReader.read(childPath); } - - readerContext = new TransformationUtils.Context(name, realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); } + var readerContext = super.read(reader, context); TemplateData templateData = EmptyTemplateData.getEmpty(); if (readerContext.getTemplateType() == TemplateType.DATA_COMPOSITION_SCHEME) { - var path = DesignerPaths.templateDataPath(currentPath, readerContext.getName()); + var path = DesignerPaths.templateDataPath(readerContext.getCurrentPath(), readerContext.getName()); var data = MDOReader.read(path); if (data instanceof TemplateData templData) { templateData = templData; diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/Unmarshaller.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/Unmarshaller.java index d33c8a3c2..428c936fc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/Unmarshaller.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/Unmarshaller.java @@ -22,15 +22,17 @@ package com.github._1c_syntax.bsl.reader.designer.converter; import com.github._1c_syntax.bsl.mdo.support.TemplateType; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.supconf.ParseSupportData; +import com.github._1c_syntax.bsl.reader.common.ReaderUtils; +import com.github._1c_syntax.bsl.reader.common.context.FormElementReaderContext; +import com.github._1c_syntax.bsl.reader.common.context.MDCReaderContext; +import com.github._1c_syntax.bsl.reader.common.context.MDReaderContext; +import com.github._1c_syntax.bsl.reader.common.context.ReaderContext; import com.github._1c_syntax.bsl.support.CompatibilityMode; -import com.github._1c_syntax.bsl.types.MDOType; +import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import lombok.experimental.UtilityClass; -import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; @@ -38,138 +40,159 @@ * Выполняет базовое чтение файлов */ @UtilityClass -class Unmarshaller { +public class Unmarshaller { private static final String PROPERTIES_NODE = "Properties"; private static final String CHILD_OBJECTS_NODE = "ChildObjects"; + private static final String CHILD_ITEMS_NODE = "ChildItems"; + private static final String ITEMS_NODE = "items"; + + private static final String EVENTS_NODE = "Events"; + private static final String HANDLES_NODE = "Handlers"; + private static final String ATTRIBUTES_NODE = "Attributes"; + private static final String NAME_NODE = "Name"; private static final String TEMPLATE_TYPE_NODE = "TemplateType"; private static final String CP_MODE_NODE = "CompatibilityMode"; private static final String CP_EXT_MODE_NODE = "ConfigurationExtensionCompatibilityMode"; - private static final String UUID_FIELD = "uuid"; - private static final String SUPPORT_VALIANT_FIELD = "SupportVariant"; /** - * Читает общую информацию из файла + * Читает информацию из файлов форм */ public void unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, - TransformationUtils.Context readerContext) { - var uuid = reader.getAttribute(UUID_FIELD); - readerContext.setValue(UUID_FIELD, uuid); - - var supportVariant = ParseSupportData.getSupportVariantByMDO(uuid, readerContext.getCurrentPath()); - readerContext.setValue(SUPPORT_VALIANT_FIELD, supportVariant); - readerContext.setSupportVariant(supportVariant); - + FormElementReaderContext readerContext) { while (reader.hasMoreChildren()) { reader.moveDown(); var name = reader.getNodeName(); - if (PROPERTIES_NODE.equals(name)) { - readProperties(reader, context, readerContext); - } else if (CHILD_OBJECTS_NODE.equals(name) && readerContext.getMdoType() == MDOType.CONFIGURATION) { - readChildObjectsConfiguration(reader, readerContext); - } else if (CHILD_OBJECTS_NODE.equals(name)) { - readChildObjects(reader, context, readerContext); + if (CHILD_ITEMS_NODE.equals(name)) { + readItemNode(reader, context, readerContext, ITEMS_NODE); + } else if (ATTRIBUTES_NODE.equals(name)) { + readItemNode(reader, context, readerContext, ATTRIBUTES_NODE); + } else if (EVENTS_NODE.equals(name)) { + readItemNode(reader, context, readerContext, HANDLES_NODE); + } else { + readNode(reader.getNodeName(), context, readerContext); } reader.moveUp(); } } - private void readProperties(HierarchicalStreamReader reader, - UnmarshallingContext context, - TransformationUtils.Context readerContext) { + /** + * Читает информацию из файлов объектов метаданных и внешних отчетов и обработок + */ + public void unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, MDReaderContext readerContext) { while (reader.hasMoreChildren()) { reader.moveDown(); var name = reader.getNodeName(); - Object value = null; - var fieldClass = TransformationUtils.fieldType(readerContext.getBuilder(), name); - - // не стоит тратить время - if (fieldClass == null) { - reader.moveUp(); - continue; - } - - if (fieldClass instanceof ParameterizedType) { - if (reader.hasMoreChildren()) { - value = readCollection(reader, context, readerContext, name); - } - } else { - value = context.convertAnother(fieldClass, (Class) fieldClass); + if (PROPERTIES_NODE.equals(name) || CHILD_OBJECTS_NODE.equals(name)) { + readPropertiesNode(reader, context, readerContext); } + reader.moveUp(); + } + } - if (value instanceof TransformationUtils.Context trContext) { - readerContext.addChild(name, trContext); - } else if (value instanceof List - && !((List) value).isEmpty() - && ((List) value).get(0) instanceof TransformationUtils.Context) { - - ((List) value).forEach(child -> readerContext.addChild(name, (TransformationUtils.Context) child)); - - } else if (name.equals(NAME_NODE) && value instanceof String string) { - readerContext.setName(string); - } else if (name.equals(TEMPLATE_TYPE_NODE) && value instanceof TemplateType templateType) { - readerContext.setTemplateType(templateType); - } else if (name.equals(CP_MODE_NODE) && value instanceof CompatibilityMode compatibilityMode) { - readerContext.setCompatibilityMode(compatibilityMode); - } else if (name.equals(CP_EXT_MODE_NODE) && value instanceof CompatibilityMode compatibilityMode) { - readerContext.setConfigurationExtensionCompatibilityMode(compatibilityMode); + /** + * Читает информацию из файлов контейнеров конфигурации и расширений + */ + public void unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, MDCReaderContext readerContext) { + while (reader.hasMoreChildren()) { + reader.moveDown(); + var name = reader.getNodeName(); + if (PROPERTIES_NODE.equals(name)) { + readPropertiesNode(reader, context, readerContext); + } else if (CHILD_OBJECTS_NODE.equals(name)) { + readChildrenNames(reader, readerContext); } + reader.moveUp(); + } + } - readerContext.setValue(name, value); + private void readItemNode(HierarchicalStreamReader reader, + UnmarshallingContext context, + FormElementReaderContext readerContext, + String nodeName) { + var fieldClass = readerContext.fieldType(nodeName); + while (reader.hasMoreChildren()) { + reader.moveDown(); + readerContext.setValue(nodeName, ReaderUtils.readValue(context, fieldClass)); reader.moveUp(); } } - private void readChildObjects(HierarchicalStreamReader reader, - UnmarshallingContext context, - TransformationUtils.Context readerContext) { + private void readNode(String name, UnmarshallingContext context, FormElementReaderContext readerContext) { + var fieldClass = readerContext.fieldType(name); + if (fieldClass == null) { + return; + } + readerContext.setValue(name, ReaderUtils.readValue(context, fieldClass)); + } + + private void readPropertiesNode(HierarchicalStreamReader reader, + UnmarshallingContext context, + ReaderContext readerContext) { while (reader.hasMoreChildren()) { reader.moveDown(); var name = reader.getNodeName(); var fieldClass = readerContext.fieldType(name); - - // не стоит тратить время if (fieldClass == null) { reader.moveUp(); continue; } - var value = (TransformationUtils.Context) context.convertAnother(fieldClass, fieldClass); - readerContext.addChild(name, value); + var value = readValue(reader, context, fieldClass); + + if (readerContext instanceof MDReaderContext mdReaderContext) { + saveExtra(mdReaderContext, name, value); + } else if (readerContext instanceof MDCReaderContext mdcReaderContext) { + saveExtra(mdcReaderContext, name, value); + } + readerContext.setValue(name, value); reader.moveUp(); } } - private void readChildObjectsConfiguration(HierarchicalStreamReader reader, - TransformationUtils.Context readerContext) { - while (reader.hasMoreChildren()) { - reader.moveDown(); - var name = reader.getNodeName(); - readerContext.addChildMetadata(name, reader.getValue()); - reader.moveUp(); + private void saveExtra(MDReaderContext mdReaderContext, String name, Object value) { + if (name.equals(NAME_NODE) && value instanceof String string) { + mdReaderContext.setName(string); + } else if (name.equals(TEMPLATE_TYPE_NODE) && value instanceof TemplateType templateType) { + mdReaderContext.setTemplateType(templateType); } } - private List readCollection(HierarchicalStreamReader reader, - UnmarshallingContext context, - TransformationUtils.Context readerContext, - String fieldName) { - List result = new ArrayList<>(); - var valueClass = readerContext.fieldType(fieldName); - - // не стоит тратить время - if (valueClass == null) { - return result; + private void saveExtra(MDCReaderContext mdcReaderContext, String name, Object value) { + if (name.equals(NAME_NODE) && value instanceof String string) { + mdcReaderContext.setName(string); + } else if (name.equals(CP_MODE_NODE) && value instanceof CompatibilityMode compatibilityMode) { + mdcReaderContext.setCompatibilityMode(compatibilityMode); + } else if (name.equals(CP_EXT_MODE_NODE) && value instanceof CompatibilityMode compatibilityMode) { + mdcReaderContext.setConfigurationExtensionCompatibilityMode(compatibilityMode); } + } + private void readChildrenNames(HierarchicalStreamReader reader, ReaderContext readerContext) { while (reader.hasMoreChildren()) { reader.moveDown(); - var value = context.convertAnother(valueClass, valueClass); - result.add(value); + var name = reader.getNodeName(); + var value = name + "." + reader.getValue(); + readerContext.setValue(name, value); reader.moveUp(); } - return result; + } + + private Object readValue(HierarchicalStreamReader reader, + UnmarshallingContext context, + Class fieldClass) { + try { + return ReaderUtils.readValue(context, fieldClass); + } catch (ConversionException e) { + List result = new ArrayList<>(); + while (reader.hasMoreChildren()) { + reader.moveDown(); + result.add(ReaderUtils.readValue(context, fieldClass)); + reader.moveUp(); + } + return result; + } } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/XDTOPackageConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/XDTOPackageConverter.java index d3369e3c6..4fa0bb6c3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/XDTOPackageConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/designer/converter/XDTOPackageConverter.java @@ -23,6 +23,7 @@ import com.github._1c_syntax.bsl.mdo.XDTOPackage; import com.github._1c_syntax.bsl.mdo.storage.XdtoPackageData; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.designer.DesignerPaths; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -35,10 +36,8 @@ public class XDTOPackageConverter extends AbstractReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - readerContext.setValue(DATA_FIELD, - XdtoPackageData.create(DesignerPaths.packageDataPath(currentPath, readerContext.getName()))); - + XdtoPackageData.create(DesignerPaths.packageDataPath(readerContext.getCurrentPath(), readerContext.getName()))); return readerContext.build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/EDTReader.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/EDTReader.java index 4e7280009..63c203b74 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/EDTReader.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/EDTReader.java @@ -44,6 +44,7 @@ import com.github._1c_syntax.bsl.mdo.children.TaskAddressingAttribute; import com.github._1c_syntax.bsl.mdo.children.WebServiceOperation; import com.github._1c_syntax.bsl.mdo.children.WebServiceOperationParameter; +import com.github._1c_syntax.bsl.mdo.storage.ManagedFormData; import com.github._1c_syntax.bsl.reader.MDReader; import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; import com.github._1c_syntax.bsl.reader.edt.converter.EDTConverter; @@ -138,7 +139,6 @@ private static ExtendXStream createXMLMapper() { } private static void registerClasses(XStream xStream) { - xStream.alias("accountingFlags", AccountingFlag.class); xStream.alias("addressingAttributes", TaskAddressingAttribute.class); xStream.alias("attributes", ObjectAttribute.class); @@ -161,5 +161,6 @@ private static void registerClasses(XStream xStream) { xStream.alias("tabularSections", ObjectTabularSection.class); xStream.alias("templates", ObjectTemplate.class); xStream.alias("urlTemplates", HTTPServiceURLTemplate.class); + xStream.alias("Form", ManagedFormData.class); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/CommonAttributeUseContentConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/CommonAttributeUseContentConverter.java new file mode 100644 index 000000000..fbd0b53ce --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/CommonAttributeUseContentConverter.java @@ -0,0 +1,45 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.edt.converter; + +import com.github._1c_syntax.bsl.mdo.CommonAttribute; +import com.github._1c_syntax.bsl.reader.common.converter.ConverterParts; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +/** + * Конвертер для состава общего реквизита + */ +@EDTConverter +public class CommonAttributeUseContentConverter implements ReadConverter { + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + return ConverterParts.commonAttributeUseContent(reader, context); + } + + @Override + public boolean canConvert(Class type) { + return CommonAttribute.UseContent.class.isAssignableFrom(type); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ConfigurationConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ConfigurationConverter.java index ab537ee1b..51eaa596d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ConfigurationConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ConfigurationConverter.java @@ -21,75 +21,14 @@ */ package com.github._1c_syntax.bsl.reader.edt.converter; -import com.github._1c_syntax.bsl.mdclasses.Configuration; -import com.github._1c_syntax.bsl.mdclasses.ConfigurationExtension; -import com.github._1c_syntax.bsl.mdclasses.ConfigurationTree; -import com.github._1c_syntax.bsl.mdo.MD; -import com.github._1c_syntax.bsl.reader.MDOReader; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.reader.edt.EDTPaths; -import com.github._1c_syntax.bsl.types.ConfigurationSource; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import lombok.SneakyThrows; - -import java.io.FileInputStream; -import java.nio.charset.StandardCharsets; -import java.util.Scanner; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractMDCReadConverter; @EDTConverter -public class ConfigurationConverter implements ReadConverter { - - private static final String CHILD_FILED = "child"; - - @SneakyThrows - @Override - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - int count; - var fileInputStream = new FileInputStream(ExtendXStream.getCurrentPath(reader).toFile()); - try (var scanner = new Scanner(fileInputStream, StandardCharsets.UTF_8)) { - count = (int) scanner.findAll("()").count(); - } - - Class realClass = Configuration.class; - - if (count > 0) { - realClass = ConfigurationExtension.class; - } - - var currentPath = ExtendXStream.getCurrentPath(reader); - var readerContext = new TransformationUtils.Context(reader.getNodeName(), realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); +public class ConfigurationConverter extends AbstractMDCReadConverter { - if (readerContext.getCompatibilityMode() == null) { - readerContext.setValue("compatibilityMode", - readerContext.getConfigurationExtensionCompatibilityMode()); - } - - readChildren(readerContext); - - readerContext.setValue("configurationSource", ConfigurationSource.EDT); - return readerContext.build(); - } - - @Override - public boolean canConvert(Class type) { - return ConfigurationTree.class.isAssignableFrom(type); - } + private static final String CONFIGURATION_EXTENSION_FILTER = "()"; - private static void readChildren(TransformationUtils.Context readerContext) { - var rootPath = EDTPaths.rootPathByConfigurationMDO(readerContext.getCurrentPath()); - var reader = MDOReader.getReader(rootPath); - readerContext.getChildrenMetadata() - .forEach((String fullName) -> { - MD child = (MD) reader.read(fullName); - if (child != null) { - var fieldName = child.getMdoType().getName(); - readerContext.setValue(fieldName, child); - readerContext.setValue(CHILD_FILED, child); - } - }); + public ConfigurationConverter() { + super(CONFIGURATION_EXTENSION_FILTER); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExchangePlanAutoRecordConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExchangePlanAutoRecordConverter.java index b8a71ce22..e5db2033c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExchangePlanAutoRecordConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExchangePlanAutoRecordConverter.java @@ -1,69 +1,47 @@ -/* - * This file is a part of MDClasses. - * - * Copyright (c) 2019 - 2023 - * Tymko Oleg , Maximov Valery and contributors - * - * SPDX-License-Identifier: LGPL-3.0-or-later - * - * MDClasses is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3.0 of the License, or (at your option) any later version. - * - * MDClasses is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with MDClasses. - */ -package com.github._1c_syntax.bsl.reader.edt.converter; +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.edt.converter; import com.github._1c_syntax.bsl.mdo.ExchangePlan; -import com.github._1c_syntax.bsl.mdo.support.AutoRecordType; -import com.github._1c_syntax.bsl.types.MdoReference; -import com.thoughtworks.xstream.converters.Converter; -import com.thoughtworks.xstream.converters.MarshallingContext; +import com.github._1c_syntax.bsl.reader.common.converter.ConverterParts; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * Конвертер для состава плана обмена */ @EDTConverter -public class ExchangePlanAutoRecordConverter implements Converter { +public class ExchangePlanAutoRecordConverter implements ReadConverter { private static final String MD_OBJECT_NODE_NAME = "mdObject"; private static final String AUTO_RECORD_NODE_NAME = "autoRecord"; - @Override - public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { - // no-op - } - @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { if (!reader.hasMoreChildren()) { return null; } - - var builder = ExchangePlan.RecordContent.builder(); - while (reader.hasMoreChildren()) { - reader.moveDown(); - var node = reader.getNodeName(); - if (MD_OBJECT_NODE_NAME.equals(node)) { - builder.metadata(MdoReference.create(reader.getValue())); - } else if (AUTO_RECORD_NODE_NAME.equals(node)) { - builder.autoRecord((AutoRecordType) context.convertAnother(reader.getValue(), AutoRecordType.class)); - } else { - // no-op - } - reader.moveUp(); - } - return builder.build(); + return ConverterParts.exchangePlanAutoRecord(reader, context, MD_OBJECT_NODE_NAME, AUTO_RECORD_NODE_NAME); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalDataSourceTableConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalDataSourceTableConverter.java index 197df250c..95b14ca85 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalDataSourceTableConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalDataSourceTableConverter.java @@ -1,28 +1,29 @@ -/* - * This file is a part of MDClasses. - * - * Copyright (c) 2019 - 2023 - * Tymko Oleg , Maximov Valery and contributors - * - * SPDX-License-Identifier: LGPL-3.0-or-later - * - * MDClasses is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3.0 of the License, or (at your option) any later version. - * - * MDClasses is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with MDClasses. - */ -package com.github._1c_syntax.bsl.reader.edt.converter; +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.edt.converter; import com.github._1c_syntax.bsl.mdo.children.ExternalDataSourceTable; import com.github._1c_syntax.bsl.reader.MDOReader; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; import com.github._1c_syntax.bsl.reader.edt.EDTPaths; import com.github._1c_syntax.bsl.types.MDOType; @@ -37,11 +38,13 @@ @EDTConverter public class ExternalDataSourceTableConverter extends AbstractReadConverter { + private static final int POSITION_CHILD_NAME = 3; + @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { if (reader.getAttributeCount() == 0) { // здесь только имя после третьей точки - var childName = reader.getValue().split("\\.")[3]; + var childName = reader.getValue().split("\\.")[POSITION_CHILD_NAME]; var childrenFolder = EDTPaths.childrenFolder(ExtendXStream.getCurrentPath(reader), MDOType.EXTERNAL_DATA_SOURCE_TABLE); var childPath = Paths.get(childrenFolder.toString(), childName, childName + EDTPaths.EXTENSION_DOT); diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalSourceConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalSourceConverter.java index e14b54ee0..fcc5e2426 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalSourceConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ExternalSourceConverter.java @@ -22,6 +22,7 @@ package com.github._1c_syntax.bsl.reader.edt.converter; import com.github._1c_syntax.bsl.mdclasses.ExternalSource; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.types.ConfigurationSource; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -30,11 +31,13 @@ @EDTConverter public class ExternalSourceConverter extends AbstractReadConverter { + private static final String CONFIGURATION_SOURCE_FIELD_NAME = "configurationSource"; + @SneakyThrows @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - readerContext.setValue("configurationSource", ConfigurationSource.EDT); + readerContext.setValue(CONFIGURATION_SOURCE_FIELD_NAME, ConfigurationSource.EDT); return readerContext.build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/FormDataPathConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/FormDataPathConverter.java new file mode 100644 index 000000000..53bcb028e --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/FormDataPathConverter.java @@ -0,0 +1,60 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.edt.converter; + +import com.github._1c_syntax.bsl.mdo.storage.form.FormDataPath; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +/** + * Конвертор пути элемента формы в формате ЕДТ + */ +@EDTConverter +public class FormDataPathConverter implements ReadConverter { + + private static final String SEGMENTS_NODE_NAME = "segments"; + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + var value = ""; + while (reader.hasMoreChildren()) { + reader.moveDown(); + var node = reader.getNodeName(); + if (SEGMENTS_NODE_NAME.equals(node)) { + value = reader.getValue().intern(); + } + reader.moveUp(); + } + + if (value.isEmpty()) { + return null; + } + + return new FormDataPath(value); + } + + @Override + public boolean canConvert(Class type) { + return type == FormDataPath.class; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/FormHandlerConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/FormHandlerConverter.java new file mode 100644 index 000000000..47fbfbab3 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/FormHandlerConverter.java @@ -0,0 +1,66 @@ +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.edt.converter; + +import com.github._1c_syntax.bsl.mdo.storage.form.FormHandler; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +/** + * Конвертор обработчика события формы в формате ЕДТ + */ +@EDTConverter +public class FormHandlerConverter implements ReadConverter { + + private static final String NAME_NODE_NAME = "name"; + private static final String EVENT_NODE_NAME = "event"; + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + var event = ""; + var name = ""; + while (reader.hasMoreChildren()) { + reader.moveDown(); + var node = reader.getNodeName(); + if (NAME_NODE_NAME.equals(node)) { + name = reader.getValue().intern(); + } else if (EVENT_NODE_NAME.equals(node)) { + event = reader.getValue().intern(); + } else { + // no-op + } + reader.moveUp(); + } + + if (event.isEmpty() && name.isEmpty()) { + return null; + } + + return new FormHandler(event, name); + } + + @Override + public boolean canConvert(Class type) { + return type == FormHandler.class; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDChildConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDChildConverter.java index 026bfa069..fbb826d5c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDChildConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDChildConverter.java @@ -24,10 +24,9 @@ import com.github._1c_syntax.bsl.mdo.MDChild; import com.github._1c_syntax.bsl.mdo.children.ExternalDataSourceTable; import com.github._1c_syntax.bsl.mdo.children.ObjectTemplate; -import com.thoughtworks.xstream.converters.MarshallingContext; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * Конвертер для дочерних элементов (атрибуты, операции и т.д.) @@ -35,14 +34,9 @@ @EDTConverter public class MDChildConverter extends AbstractReadConverter { - @Override - public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { - // noop - } - @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - return super.read(reader, context); + return super.read(reader, context); // внимание! возвращается контекст, а не объект! } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDConverter.java index 22c16942e..3865bf83c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MDConverter.java @@ -27,6 +27,7 @@ import com.github._1c_syntax.bsl.mdo.Role; import com.github._1c_syntax.bsl.mdo.Subsystem; import com.github._1c_syntax.bsl.mdo.XDTOPackage; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -35,9 +36,7 @@ public class MDConverter extends AbstractReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - var readerContext = super.read(reader, context); - - return readerContext.build(); + return super.read(reader, context).build(); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/CommonModuleConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ManagedFormDataConverter.java similarity index 53% rename from src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/CommonModuleConverter.java rename to src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ManagedFormDataConverter.java index 923724e86..7a3f137e3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/CommonModuleConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/ManagedFormDataConverter.java @@ -1,56 +1,51 @@ -/* - * This file is a part of MDClasses. - * - * Copyright (c) 2019 - 2023 - * Tymko Oleg , Maximov Valery and contributors - * - * SPDX-License-Identifier: LGPL-3.0-or-later - * - * MDClasses is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3.0 of the License, or (at your option) any later version. - * - * MDClasses is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with MDClasses. - */ -package com.github._1c_syntax.bsl.reader.edt.converter; - -import com.github._1c_syntax.bsl.mdo.CommonModule; -import com.github._1c_syntax.bsl.reader.common.ReaderUtils; -import com.github._1c_syntax.bsl.reader.edt.EDTPaths; -import com.github._1c_syntax.bsl.types.MDOType; -import com.github._1c_syntax.bsl.types.ModuleType; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; - -@EDTConverter -public class CommonModuleConverter extends AbstractReadConverter { - - private static final String URI_FIELD = "uri"; - private static final String IS_PROTECTED_FIELD = "isProtected"; - - private static final byte[] PROTECTED_FILE_HEADER = new byte[]{-1, -1, -1, 127}; - - @Override - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - var readerContext = super.read(reader, context); - var folder = EDTPaths.moduleFolder(currentPath, MDOType.COMMON_MODULE); - var modulePath = EDTPaths.modulePath(folder, readerContext.getName(), ModuleType.CommonModule); - - var protectedModuleInfo = ReaderUtils.readProtectedModuleInfo(modulePath); - readerContext.setValue(URI_FIELD, protectedModuleInfo.getModulePath().toUri()); - readerContext.setValue(IS_PROTECTED_FIELD, protectedModuleInfo.isProtected()); - return readerContext.build(); - } - - @Override - public boolean canConvert(Class type) { - return CommonModule.class.isAssignableFrom(type); - } -} +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.edt.converter; + +import com.github._1c_syntax.bsl.mdo.storage.ManagedFormData; +import com.github._1c_syntax.bsl.mdo.storage.form.FormAttribute; +import com.github._1c_syntax.bsl.mdo.storage.form.FormItem; +import com.github._1c_syntax.bsl.reader.common.context.FormElementReaderContext; +import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; + +/** + * Конвертор данных управляемой формы в формате ЕДТ + */ +@EDTConverter +public class ManagedFormDataConverter implements ReadConverter { + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + var readerContext = new FormElementReaderContext(reader.getNodeName(), reader); + Unmarshaller.unmarshal(reader, context, readerContext); + return readerContext.build(); + } + + @Override + public boolean canConvert(Class type) { + return type == ManagedFormData.class + || FormItem.class.isAssignableFrom(type) + || FormAttribute.class.isAssignableFrom(type); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MdoReferenceConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MdoReferenceConverter.java index 32542a4e2..46eae1c1d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MdoReferenceConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MdoReferenceConverter.java @@ -36,7 +36,6 @@ public class MdoReferenceConverter implements ReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - // todo надо обработать разные типы var nodeName = reader.getNodeName(); var value = ""; if (PICTURE_NODE_NAME.equals(nodeName) && reader.hasMoreChildren()) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MultiLanguageStringConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MultiLanguageStringConverter.java index 34c80c173..7b8c36f90 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MultiLanguageStringConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/MultiLanguageStringConverter.java @@ -1,27 +1,28 @@ -/* - * This file is a part of MDClasses. - * - * Copyright (c) 2019 - 2023 - * Tymko Oleg , Maximov Valery and contributors - * - * SPDX-License-Identifier: LGPL-3.0-or-later - * - * MDClasses is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3.0 of the License, or (at your option) any later version. - * - * MDClasses is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with MDClasses. - */ -package com.github._1c_syntax.bsl.reader.edt.converter; +/* + * This file is a part of MDClasses. + * + * Copyright (c) 2019 - 2023 + * Tymko Oleg , Maximov Valery and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * MDClasses is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * MDClasses is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with MDClasses. + */ +package com.github._1c_syntax.bsl.reader.edt.converter; import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; +import com.github._1c_syntax.bsl.reader.common.converter.ConverterParts; import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -45,22 +46,8 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co return MultiLanguageString.EMPTY; } HashMap langContent = new HashMap<>(); - - var lang = ""; - var content = ""; - while (reader.hasMoreChildren()) { - reader.moveDown(); - var node = reader.getNodeName(); - if (LANG_NODE_NAME.equals(node)) { - lang = reader.getValue(); - } else if (CONTENT_NODE_NAME.equals(node)) { - content = reader.getValue(); - } else { - // no-op - } - reader.moveUp(); - } - langContent.put(lang, content); + var result = ConverterParts.multiLanguageString(reader, LANG_NODE_NAME, CONTENT_NODE_NAME); + langContent.put(result.getKey(), result.getValue()); return new MultiLanguageString(langContent); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/RoleConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/RoleConverter.java index c274ef6b3..f37a1deb5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/RoleConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/RoleConverter.java @@ -23,7 +23,7 @@ import com.github._1c_syntax.bsl.mdo.Role; import com.github._1c_syntax.bsl.mdo.storage.RoleData; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.edt.EDTPaths; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -33,14 +33,10 @@ public class RoleConverter extends AbstractReadConverter { private static final String DATA_FIELD = "data"; - @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - - TransformationUtils.setValue(readerContext.getBuilder(), - DATA_FIELD, RoleData.create(EDTPaths.roleDataPath(currentPath))); - + readerContext.setValue(DATA_FIELD, RoleData.create(EDTPaths.roleDataPath(readerContext.getCurrentPath()))); return readerContext.build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/SubsystemConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/SubsystemConverter.java index 83d80f66d..740b69127 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/SubsystemConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/SubsystemConverter.java @@ -21,62 +21,14 @@ */ package com.github._1c_syntax.bsl.reader.edt.converter; -import com.github._1c_syntax.bsl.mdo.Subsystem; -import com.github._1c_syntax.bsl.reader.MDOReader; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.reader.common.xstream.ExtendXStream; -import com.github._1c_syntax.bsl.reader.common.xstream.ReadConverter; -import com.github._1c_syntax.bsl.reader.edt.EDTPaths; -import com.github._1c_syntax.bsl.reader.edt.EDTReader; -import com.github._1c_syntax.bsl.types.MDOType; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import org.apache.commons.io.FilenameUtils; - -import java.nio.file.Paths; - -import static java.util.Objects.requireNonNull; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractSubsystemConverter; @EDTConverter -public class SubsystemConverter implements ReadConverter { +public class SubsystemConverter extends AbstractSubsystemConverter { - private static final String START_MDOREF_NAME = MDOType.SUBSYSTEM.getName() + "."; private static final String SUBSYSTEMS_NODE = "subsystems"; - @Override - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - var name = reader.getNodeName(); - var currentPath = ExtendXStream.getCurrentPath(reader); - - if (SUBSYSTEMS_NODE.equals(name) && reader.getAttributeCount() == 0) { // дочерняя подсистема строкой - - var rootFolder = EDTPaths.mdoTypeFolderPathByMDOPath(currentPath).toString(); - var currentName = FilenameUtils.getBaseName(currentPath.toString()); - var folder = Paths.get(rootFolder, currentName, MDOType.SUBSYSTEM.getGroupName()); - return MDOReader.readMDObject(folder, START_MDOREF_NAME + reader.getValue()); - - } else { // самостоятельная подсистема - - var realClass = EDTReader.getXstream().getRealClass(name); - var readerContext = new TransformationUtils.Context(reader.getNodeName(), realClass, currentPath); - Unmarshaller.unmarshal(reader, context, readerContext); - - var prjPath = MDOReader.getReader(ExtendXStream.getCurrentPath(reader)).getRootPath(); - requireNonNull(prjPath); - var localRootPath = currentPath.toString().replace(prjPath.toString(), ""); - - // определим это самостоятельная или дочерняя - // у дочерней будет несколько вложенных папок подсистемы - if (localRootPath.split(MDOType.SUBSYSTEM.getName()).length > 2) { - return readerContext; - } else { - return readerContext.build(); - } - } - } - - @Override - public boolean canConvert(Class type) { - return Subsystem.class.isAssignableFrom(type); + public SubsystemConverter() { + super(SUBSYSTEMS_NODE, false); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/TemplateConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/TemplateConverter.java index ea6a2d24e..0d28b8d55 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/TemplateConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/TemplateConverter.java @@ -26,6 +26,7 @@ import com.github._1c_syntax.bsl.mdo.storage.EmptyTemplateData; import com.github._1c_syntax.bsl.mdo.storage.TemplateData; import com.github._1c_syntax.bsl.reader.MDOReader; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.edt.EDTPaths; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -39,15 +40,16 @@ public class TemplateConverter extends AbstractReadConverter { public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - TemplateData templateData = EmptyTemplateData.getEmpty(); - var path = EDTPaths.templateDataPath(currentPath, readerContext.getName(), readerContext.getMdoType()); + var path = EDTPaths.templateDataPath( + readerContext.getCurrentPath(), readerContext.getName(), readerContext.getMdoType()); var data = MDOReader.read(path); if (data instanceof TemplateData templData) { templateData = templData; } + readerContext.setValue(DATA_FIELD, templateData); - if (realClass.isAssignableFrom(CommonTemplate.class)) { + if (readerContext.getRealClass().isAssignableFrom(CommonTemplate.class)) { return readerContext.build(); } else { return readerContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/Unmarshaller.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/Unmarshaller.java index 546fa4c11..7c28ed2e4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/Unmarshaller.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/Unmarshaller.java @@ -21,13 +21,14 @@ */ package com.github._1c_syntax.bsl.reader.edt.converter; -import com.github._1c_syntax.bsl.mdclasses.CF; import com.github._1c_syntax.bsl.mdo.Language; import com.github._1c_syntax.bsl.mdo.children.ExternalDataSourceTableField; import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; import com.github._1c_syntax.bsl.mdo.support.TemplateType; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; -import com.github._1c_syntax.bsl.supconf.ParseSupportData; +import com.github._1c_syntax.bsl.reader.common.ReaderUtils; +import com.github._1c_syntax.bsl.reader.common.context.MDCReaderContext; +import com.github._1c_syntax.bsl.reader.common.context.MDReaderContext; +import com.github._1c_syntax.bsl.reader.common.context.ReaderContext; import com.github._1c_syntax.bsl.support.CompatibilityMode; import com.github._1c_syntax.bsl.types.MDOType; import com.thoughtworks.xstream.converters.UnmarshallingContext; @@ -38,181 +39,107 @@ * Выполняет базовое чтение файлов */ @UtilityClass -class Unmarshaller { +public class Unmarshaller { private static final String NAME_NODE = "name"; private static final String TEMPLATE_TYPE_NODE = "templateType"; private static final String CP_MODE_NODE = "compatibilityMode"; private static final String CP_EXT_MODE_NODE = "configurationExtensionCompatibilityMode"; - private static final String UUID_FIELD = "uuid"; private static final String LANGUAGE_NODE = "languages"; private static final String LANGUAGE_METHOD_NAME = "language"; private static final String TABLE_FIELDS_NODE = "tableFields"; - private static final String SUPPORT_VALIANT_FIELD = "SupportVariant"; - private static final String CHILD_FILED = "child"; private static final String TABLE_FIELDS_FIELD = "fields"; /** - * Читает общую информацию из файла + * Читают общую информацию из файла */ - public void unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context, - TransformationUtils.Context readerContext) { - var uuid = reader.getAttribute(UUID_FIELD); - readerContext.setValue(UUID_FIELD, uuid); - - var supportVariant = ParseSupportData.getSupportVariantByMDO(uuid, readerContext.getCurrentPath()); - readerContext.setValue(SUPPORT_VALIANT_FIELD, supportVariant); - readerContext.setSupportVariant(supportVariant); - - if (CF.class.isAssignableFrom(readerContext.getRealClass())) { - unmarshalMDC(reader, context, readerContext); - } else { - unmarshalMD(reader, context, readerContext); - } - } - - public void unmarshalMD(HierarchicalStreamReader reader, - UnmarshallingContext context, - TransformationUtils.Context readerContext) { + public void unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, ReaderContext readerContext) { + readerContext.setLastValue(null); + readerContext.setLastName(""); - Object lastValue = null; - var lastName = ""; while (reader.hasMoreChildren()) { reader.moveDown(); - var name = reader.getNodeName(); - var fieldClass = readerContext.fieldType(name); - - // не стоит тратить время - if (fieldClass == null && TABLE_FIELDS_NODE.equals(name)) { - name = TABLE_FIELDS_FIELD; - fieldClass = ExternalDataSourceTableField.class; - } else if (fieldClass == null) { - reader.moveUp(); - continue; - } else { - // no-op - } - - var value = context.convertAnother(fieldClass, fieldClass); - - if (value instanceof TransformationUtils.Context trContext) { - readerContext.addChild(name, trContext); - lastValue = null; - lastName = ""; - } else { - readExtra(readerContext, name, value); - - if (isMultiLanguageString(lastValue, lastName, name, value)) { - lastValue = readMultiLanguageString(readerContext, lastValue, name, value); - } else { - readerContext.setValue(name, value); - lastValue = value; - } - lastName = name; - } + readNode(reader.getNodeName(), context, readerContext); reader.moveUp(); } } - public void unmarshalMDC(HierarchicalStreamReader reader, - UnmarshallingContext context, - TransformationUtils.Context readerContext) { - - Object lastValue = null; - var lastName = ""; - while (reader.hasMoreChildren()) { - reader.moveDown(); - var name = reader.getNodeName(); - Class fieldClass; - var isChild = false; - - var mdoType = MDOType.fromValue(name); - if (mdoType.isEmpty()) { - fieldClass = readerContext.fieldType(name); - } else if (LANGUAGE_NODE.equals(name)) { - fieldClass = Language.class; - name = LANGUAGE_METHOD_NAME; - } else { - fieldClass = String.class; - isChild = true; - } - - // не стоит тратить время - if (fieldClass == null) { - reader.moveUp(); - continue; - } + public void unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, MDReaderContext readerContext) { + unmarshal(reader, context, (ReaderContext) readerContext); + } - var value = context.convertAnother(fieldClass, fieldClass); + public void unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, MDCReaderContext readerContext) { + unmarshal(reader, context, (ReaderContext) readerContext); + } - if (value instanceof TransformationUtils.Context trContext) { - readerContext.addChild(name, trContext); - lastValue = null; - lastName = ""; - } else { - readExtra(readerContext, name, value); + private void readNode(String name, UnmarshallingContext context, ReaderContext readerContext) { - if (isMultiLanguageString(lastValue, lastName, name, value)) { - lastValue = readMultiLanguageString(readerContext, lastValue, name, value); - } else if (isChildMD(isChild, value)) { - readerContext.addChildMetadata((String) value); - lastValue = value; + Class fieldClass = null; + if (readerContext instanceof MDCReaderContext) { + var mdoType = MDOType.fromValue(name); + if (mdoType.isPresent()) { + if (LANGUAGE_NODE.equals(name)) { + fieldClass = Language.class; + name = LANGUAGE_METHOD_NAME; } else { - readerContext.setValue(name, value); - lastValue = value; + fieldClass = String.class; } - lastName = name; } - reader.moveUp(); } - } - private static boolean isChildMD(boolean isChild, Object value) { - return isChild && value instanceof String; - } - - private static boolean isCPExtModeNode(String name, Object value) { - return name.equals(CP_EXT_MODE_NODE) && value instanceof CompatibilityMode; - } + if (fieldClass == null) { + fieldClass = readerContext.fieldType(name); + } - private static boolean isCPModeNode(String name, Object value) { - return name.equals(CP_MODE_NODE) && value instanceof CompatibilityMode; - } + if (fieldClass == null && TABLE_FIELDS_NODE.equals(name)) { + name = TABLE_FIELDS_FIELD; + fieldClass = ExternalDataSourceTableField.class; + } - private static boolean isTemplateNode(String name, Object value) { - return name.equals(TEMPLATE_TYPE_NODE) && value instanceof TemplateType; - } + if (fieldClass == null) { + return; + } - private static boolean isNameNode(String name, Object value) { - return isChildMD(name.equals(NAME_NODE), value); + var value = ReaderUtils.readValue(context, fieldClass); + if (readerContext instanceof MDReaderContext mdReaderContext) { + saveExtra(mdReaderContext, name, value); + } else if (readerContext instanceof MDCReaderContext mdcReaderContext) { + saveExtra(mdcReaderContext, name, value); + } + readerContext.setValue(name, transformMultiLanguageString(readerContext, name, value)); } - private static boolean isMultiLanguageString(Object lastValue, String lastName, String name, Object value) { - return lastName.equals(name) && lastValue instanceof MultiLanguageString && value instanceof MultiLanguageString; + private Object transformMultiLanguageString(ReaderContext readerContext, String name, Object value) { + var newVal = value; + if (readerContext.getLastName().equals(name) + && readerContext.getLastValue() instanceof MultiLanguageString lastValue + && value instanceof MultiLanguageString newValue) { + newVal = new MultiLanguageString(lastValue, newValue); + } + readerContext.setLastName(name); + readerContext.setLastValue(newVal); + return newVal; } - private static MultiLanguageString readMultiLanguageString(TransformationUtils.Context readerContext, - Object lastValue, - String name, - Object value) { - var newValue = new MultiLanguageString((MultiLanguageString) lastValue, (MultiLanguageString) value); - readerContext.setValue(name, newValue); - return newValue; + private static void saveExtra(MDReaderContext readerContext, String name, Object value) { + if (name.equals(NAME_NODE) && value instanceof String string) { + readerContext.setName(string); + } else if (name.equals(TEMPLATE_TYPE_NODE) && value instanceof TemplateType templateType) { + readerContext.setTemplateType(templateType); + } else { + // no-op + } } - - private static void readExtra(TransformationUtils.Context readerContext, String name, Object value) { - if (isNameNode(name, value)) { - readerContext.setName((String) value); - } else if (isTemplateNode(name, value)) { - readerContext.setTemplateType((TemplateType) value); - } else if (isCPModeNode(name, value)) { - readerContext.setCompatibilityMode((CompatibilityMode) value); - } else if (isCPExtModeNode(name, value)) { - readerContext.setConfigurationExtensionCompatibilityMode((CompatibilityMode) value); + private static void saveExtra(MDCReaderContext readerContext, String name, Object value) { + if (name.equals(NAME_NODE) && value instanceof String string) { + readerContext.setName(string); + } else if (name.equals(CP_MODE_NODE) && value instanceof CompatibilityMode compatibilityMode) { + readerContext.setCompatibilityMode(compatibilityMode); + } else if (name.equals(CP_EXT_MODE_NODE) && value instanceof CompatibilityMode compatibilityMode) { + readerContext.setConfigurationExtensionCompatibilityMode(compatibilityMode); } else if (value instanceof Language) { readerContext.setValue(CHILD_FILED, value); } else { diff --git a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/XDTOPackageConverter.java b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/XDTOPackageConverter.java index 529038b60..bd3b13016 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/XDTOPackageConverter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/reader/edt/converter/XDTOPackageConverter.java @@ -23,7 +23,7 @@ import com.github._1c_syntax.bsl.mdo.XDTOPackage; import com.github._1c_syntax.bsl.mdo.storage.XdtoPackageData; -import com.github._1c_syntax.bsl.reader.common.TransformationUtils; +import com.github._1c_syntax.bsl.reader.common.converter.AbstractReadConverter; import com.github._1c_syntax.bsl.reader.edt.EDTPaths; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; @@ -36,10 +36,8 @@ public class XDTOPackageConverter extends AbstractReadConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { var readerContext = super.read(reader, context); - - TransformationUtils.setValue(readerContext.getBuilder(), - DATA_FIELD, XdtoPackageData.create(EDTPaths.packageDataPath(currentPath))); - + readerContext.setValue(DATA_FIELD, + XdtoPackageData.create(EDTPaths.packageDataPath(readerContext.getCurrentPath()))); return readerContext.build(); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ConfigurationTest.java index a4c89c93d..b13df3281 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ConfigurationTest.java @@ -22,6 +22,8 @@ package com.github._1c_syntax.bsl.mdclasses; import com.github._1c_syntax.bsl.mdo.BusinessProcess; +import com.github._1c_syntax.bsl.mdo.Form; +import com.github._1c_syntax.bsl.mdo.Module; import com.github._1c_syntax.bsl.mdo.children.ObjectForm; import com.github._1c_syntax.bsl.mdo.support.DataLockControlMode; import com.github._1c_syntax.bsl.mdo.support.UseMode; @@ -155,6 +157,16 @@ void testFullSSL(ArgumentsAccessor argumentsAccessor) { ; assertThat(cf.findChild(commonModule.getUri())) .contains(commonModule); + + assertThat(cf.getModules().stream().filter(Module::isProtected)).isEmpty(); + assertThat(cf.getAllModules().stream().filter(Module::isProtected)).isEmpty(); + + assertThat(cf.getChildren().stream().filter(md -> md instanceof Form form && !form.getData().isEmpty())) + .hasSize(cf.getCommonForms().size()); + assertThat(cf.getPlainChildren().stream().filter(md -> md instanceof Form form && !form.getData().isEmpty())) + .hasSize(726); + assertThat(cf.getPlainChildren().stream().filter(md -> md instanceof Form form && form.getData().isEmpty())) + .isEmpty(); } @ParameterizedTest @@ -183,6 +195,16 @@ void testFullMdclasses(ArgumentsAccessor argumentsAccessor) { assertThat(cf.getPlainChildren()) .hasSize(124 + cf.getInterfaces().size() + cf.getStyles().size()) .allMatch(md -> md.getSupportVariant().equals(SupportVariant.NONE)); + + assertThat(cf.getModules().stream().filter(Module::isProtected)).isEmpty(); + assertThat(cf.getAllModules().stream().filter(Module::isProtected)).hasSize(2); + + assertThat(cf.getChildren().stream().filter(md -> md instanceof Form form && !form.getData().isEmpty())) + .hasSize(cf.getCommonForms().size()); + assertThat(cf.getPlainChildren().stream().filter(md -> md instanceof Form form && !form.getData().isEmpty())) + .hasSize(11); + assertThat(cf.getPlainChildren().stream().filter(md -> md instanceof Form form && form.getData().isEmpty())) + .isEmpty(); } private static void checkChildrenSSL(Configuration cf) { diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalDataProcessorTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalDataProcessorTest.java index 5a480fa96..afa892074 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalDataProcessorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalDataProcessorTest.java @@ -21,6 +21,8 @@ */ package com.github._1c_syntax.bsl.mdclasses; +import com.github._1c_syntax.bsl.mdo.Module; +import com.github._1c_syntax.bsl.support.SupportVariant; import com.github._1c_syntax.bsl.test_utils.MDTestUtils; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.aggregator.ArgumentsAccessor; @@ -39,5 +41,29 @@ class ExternalDataProcessorTest { void test(ArgumentsAccessor argumentsAccessor) { var mdc = MDTestUtils.readExternalSourceWithSimpleTest(argumentsAccessor); assertThat(mdc).isInstanceOf(ExternalDataProcessor.class); + + var epf = (ExternalDataProcessor) mdc; + + assertThat(epf.getModules()) + .hasSize(1) + .allMatch(module -> module.getSupportVariant().equals(SupportVariant.NONE)); + assertThat(epf.getModules().stream().filter(Module::isProtected)).isEmpty(); + + assertThat(epf.getAllModules()) + .hasSize(2) + .allMatch(module -> module.getSupportVariant().equals(SupportVariant.NONE)); + assertThat(epf.getAllModules().stream().filter(Module::isProtected)).isEmpty(); + + assertThat(epf.getChildren()) + .hasSize(5) + .allMatch(md -> md.getSupportVariant().equals(SupportVariant.NONE)); + + assertThat(epf.getPlainChildren()) + .hasSize(6) + .allMatch(md -> md.getSupportVariant().equals(SupportVariant.NONE)); + + assertThat(epf.getForms()).hasSize(2); + assertThat(epf.getForms().stream().filter(form -> !form.getData().isEmpty())).hasSize(1); + assertThat(epf.getForms().stream().filter(form -> form.getData().isEmpty())).hasSize(1); } -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalReportTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalReportTest.java index e679b9a45..412bd1f95 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalReportTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdclasses/ExternalReportTest.java @@ -21,6 +21,12 @@ */ package com.github._1c_syntax.bsl.mdclasses; +import com.github._1c_syntax.bsl.mdo.Module; +import com.github._1c_syntax.bsl.mdo.storage.ManagedFormData; +import com.github._1c_syntax.bsl.mdo.support.FormType; +import com.github._1c_syntax.bsl.mdo.support.MultiLanguageString; +import com.github._1c_syntax.bsl.mdo.support.UsePurposes; +import com.github._1c_syntax.bsl.support.SupportVariant; import com.github._1c_syntax.bsl.test_utils.MDTestUtils; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.aggregator.ArgumentsAccessor; @@ -39,5 +45,57 @@ class ExternalReportTest { void test(ArgumentsAccessor argumentsAccessor) { var mdc = MDTestUtils.readExternalSourceWithSimpleTest(argumentsAccessor); assertThat(mdc).isInstanceOf(ExternalReport.class); + + var erf = (ExternalReport) mdc; + + assertThat(erf.getModules()) + .hasSize(1) + .allMatch(module -> module.getSupportVariant().equals(SupportVariant.NONE)); + assertThat(erf.getModules().stream().filter(Module::isProtected)).isEmpty(); + + assertThat(erf.getAllModules()) + .hasSize(2) + .allMatch(module -> module.getSupportVariant().equals(SupportVariant.NONE)); + assertThat(erf.getAllModules().stream().filter(Module::isProtected)).isEmpty(); + + assertThat(erf.getChildren()) + .hasSize(8) + .allMatch(md -> md.getSupportVariant().equals(SupportVariant.NONE)); + + assertThat(erf.getPlainChildren()) + .hasSize(9) + .allMatch(md -> md.getSupportVariant().equals(SupportVariant.NONE)); + + assertThat(erf.getForms()).hasSize(5); + assertThat(erf.getForms().stream().filter(form -> !form.getData().isEmpty())).hasSize(3); + assertThat(erf.getForms().stream().filter(form -> form.getData().isEmpty())).hasSize(2); + + var form = erf.getForms().stream().filter(objForm -> objForm.getName().equals("ФормаОтчета")) + .findFirst().get(); + assertThat(form.getUsePurposes()) + .hasSize(2) + .contains(UsePurposes.MOBILE_PLATFORM_APPLICATION) + .contains(UsePurposes.PLATFORM_APPLICATION); + assertThat(form.getFormType()).isEqualTo(FormType.MANAGED); + + assertThat(form.getData().isEmpty()).isFalse(); + assertThat(form.getData()).isInstanceOf(ManagedFormData.class); + assertThat(form.getData().getHandlers()).isEmpty(); + assertThat(form.getData().getItems()).isEmpty(); + assertThat(form.getData().getTitle()).isEqualTo(MultiLanguageString.EMPTY); + assertThat(form.getData().getAttributes()) + .hasSize(1) + .allMatch(attr -> attr.getId() == 1) + .allMatch(attr -> attr.getName().equals("Отчет")); + + form = erf.getForms().stream().filter(objForm -> objForm.getName().equals("ФормаОтчета1")) + .findFirst().get(); + assertThat(form.getUsePurposes()) + .hasSize(2) + .contains(UsePurposes.MOBILE_PLATFORM_APPLICATION) + .contains(UsePurposes.PLATFORM_APPLICATION); + assertThat(form.getFormType()).isEqualTo(FormType.ORDINARY); + + assertThat(form.getData().isEmpty()).isTrue(); } -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java index 2afc0fe5f..1d583e7ca 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java @@ -37,4 +37,4 @@ class AccountingRegisterTest { void test(ArgumentsAccessor argumentsAccessor) { var mdo = MDTestUtils.getMDWithSimpleTest(argumentsAccessor); } -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdo/BusinessProcessTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdo/BusinessProcessTest.java index 4052b12d5..33d67f0fa 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdo/BusinessProcessTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdo/BusinessProcessTest.java @@ -39,5 +39,4 @@ class BusinessProcessTest { void test(ArgumentsAccessor argumentsAccessor) { var mdo = MDTestUtils.getMDWithSimpleTest(argumentsAccessor); } - -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdo/CalculationRegisterTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdo/CalculationRegisterTest.java index 704063427..9bcbbac65 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdo/CalculationRegisterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdo/CalculationRegisterTest.java @@ -51,5 +51,8 @@ void test(ArgumentsAccessor argumentsAccessor) { .hasSize(1) .allMatch(Module::isProtected) ; + + assertThat(calculationRegister.getModules().stream().filter(Module::isProtected)).isEmpty(); + assertThat(calculationRegister.getAllModules().stream().filter(Module::isProtected)).hasSize(1); } -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdo/DocumentTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdo/DocumentTest.java index 8951d4186..02825b3de 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdo/DocumentTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdo/DocumentTest.java @@ -26,17 +26,54 @@ import org.junit.jupiter.params.aggregator.ArgumentsAccessor; import org.junit.jupiter.params.provider.CsvSource; +import static org.assertj.core.api.Assertions.assertThat; + class DocumentTest { @ParameterizedTest @CsvSource( { - "true, mdclasses, Documents.Документ1, _edt", - "false, mdclasses, Documents.Документ1", "true, ssl_3_1, Documents.Анкета, _edt", "false, ssl_3_1, Documents.Анкета" } ) + void testSSL(ArgumentsAccessor argumentsAccessor) { + var mdo = MDTestUtils.getMDWithSimpleTest(argumentsAccessor); + } + + @ParameterizedTest + @CsvSource( + { + "true, mdclasses, Documents.Документ1, _edt", + "false, mdclasses, Documents.Документ1" + } + ) void test(ArgumentsAccessor argumentsAccessor) { var mdo = MDTestUtils.getMDWithSimpleTest(argumentsAccessor); + + var doc = (Document) mdo; + assertThat(doc.getModules().stream().filter(Module::isProtected)).isEmpty(); + assertThat(doc.getAllModules().stream().filter(Module::isProtected)).isEmpty(); + + assertThat(doc.getForms().stream().filter(form -> !form.getData().isEmpty())).hasSize(3); + + var formData = doc.getForms().stream().filter(form -> form.getName().equals("ФормаДокумента")) + .findFirst().get().getData(); + + assertThat(formData.getAttributes()).hasSize(1); + assertThat(formData.getItems()) + .hasSize(6) + .anyMatch(item -> item.getName().equals("Реквизит1")) + .anyMatch(item -> item.getId() == 13); + + assertThat(formData.getHandlers()) + .hasSize(1) + .allMatch(formHandler -> formHandler.event().equals("NewWriteProcessing")); + + assertThat(formData.getPlainItems()) + .hasSize(9) + .anyMatch(item -> item.getName().equals("ТабличнаяЧасть1НомерСтроки")) + .anyMatch(item -> item.getId() == 35) + .anyMatch(item -> item.getType().equals("InputField")) + .anyMatch(item -> item.getDataPath().getSegments().startsWith("~")); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/mdo/FilterCriterionTest.java b/src/test/java/com/github/_1c_syntax/bsl/mdo/FilterCriterionTest.java index 2077d20e2..cd29c079f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/mdo/FilterCriterionTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/mdo/FilterCriterionTest.java @@ -32,7 +32,7 @@ class FilterCriterionTest { { "true, mdclasses, FilterCriteria.КритерийОтбора1, _edt", "false, mdclasses, FilterCriteria.КритерийОтбора1", - "true, ssl_3_1, FilterCriteria.ФайлыВТоме", + "true, ssl_3_1, FilterCriteria.ФайлыВТоме, _edt", "false, ssl_3_1, FilterCriteria.ФайлыВТоме" } ) diff --git a/src/test/java/com/github/_1c_syntax/bsl/test_utils/MDTestUtils.java b/src/test/java/com/github/_1c_syntax/bsl/test_utils/MDTestUtils.java index cf7b260be..814285026 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/test_utils/MDTestUtils.java +++ b/src/test/java/com/github/_1c_syntax/bsl/test_utils/MDTestUtils.java @@ -43,7 +43,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; @@ -65,11 +64,6 @@ public class MDTestUtils { * @param path Путь к файлу * @return Содержимое файла */ - @SneakyThrows - public String getFixture(String path) { - return getFixture(Paths.get(path)); - } - @SneakyThrows public String getFixture(Path path) { return Files.readString(path, StandardCharsets.UTF_8); @@ -78,51 +72,18 @@ public String getFixture(Path path) { /** * Генерация Json представления объекта * - * @param md Контейнер или объект метаданных - * @return Сериализованное в Json представление объекта - */ - public String createJson(Object md) { - XStream xstream = new XStream(new JsonHierarchicalStreamDriver()); - xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES); - xstream.registerConverter(new TestURIConverter()); - xstream.registerConverter(new JavaBeanConverter(xstream.getMapper(), getBeanProvider(), md.getClass()), -20); - return xstream.toXML(md); - } - - /** - * Генерация Json представления объекта со стертыми путями к файлу - * - * @param md Контейнер или объект метаданных - * @return Сериализованное в Json представление объекта - */ - public String createJsonWithEmptyPath(Object md) { - XStream xstream = new XStream(new JsonHierarchicalStreamDriver()); - xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES); - xstream.registerConverter(new TestURIConverter()); - xstream.registerConverter(new JavaBeanConverter(xstream.getMapper(), getBeanProvider(), md.getClass()), -20); - xstream.registerConverter(new TestMDOPathConverter()); - return xstream.toXML(md); - } - - /** - * Генерация Json представления объекта - * - * @param md Контейнер или объект метаданных + * @param obj сериализуемое значение * @return Сериализованное в Json представление объекта */ - public String createJson(Object md, boolean useRefs) { + public String createJson(Object obj) { XStream xstream = new XStream(new JsonHierarchicalStreamDriver()); - if (useRefs) { - xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES); - } else { - xstream.setMode(XStream.NO_REFERENCES); - } + xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); xstream.registerConverter(new TestURIConverter()); - xstream.registerConverter(new JavaBeanConverter(xstream.getMapper(), getBeanProvider(), md.getClass()), -20); - if (md instanceof MDClass) { + xstream.registerConverter(new JavaBeanConverter(xstream.getMapper(), getBeanProvider(), obj.getClass()), -20); + if (obj instanceof MDClass) { xstream.registerConverter(new TestCollectionConverter(xstream.getMapper())); } - return xstream.toXML(md); + return xstream.toXML(obj); } public MD getMDWithSimpleTest(ArgumentsAccessor argumentsAccessor) { @@ -150,15 +111,7 @@ public MD getMDWithSimpleTest(ArgumentsAccessor argumentsAccessor) { } else { fixturePath = Path.of(FIXTURES_PATH, examplePackName, mdoRef + ".json"); } - var fixture = getFixture(fixturePath); - - var useRef = false; - if (argumentsAccessor.size() > 4) { - useRef = argumentsAccessor.getBoolean(4); - } - var current = createJson(mdo, useRef); - Assertions.assertThat(fixRusYi(current), true).isEqual(fixRusYi(fixture)); - + objectEqualJson(mdo, fixturePath); return (MD) mdo; } @@ -178,7 +131,6 @@ public MDClass getMDCWithSimpleTest(ArgumentsAccessor argumentsAccessor, boolean assertThat(mdc).isNotNull(); assertThat(mdc).isInstanceOf(MDClass.class); - var current = createJson(mdc, false); Path fixturePath; if (argumentsAccessor.size() > 2) { var fixturePostfix = argumentsAccessor.getString(2); @@ -186,10 +138,8 @@ public MDClass getMDCWithSimpleTest(ArgumentsAccessor argumentsAccessor, boolean } else { fixturePath = Path.of(FIXTURES_PATH, examplePackName, mdoRef + ".json"); } - var fixture = getFixture(fixturePath); - - Assertions.assertThat(fixRusYi(current), true).isEqual(fixRusYi(fixture)); + objectEqualJson(mdc, fixturePath); return mdc; } @@ -212,30 +162,6 @@ public CF readConfiguration(ArgumentsAccessor argumentsAccessor, boolean skipSup return (CF) mdc; } - public ExternalSource readExternalSource(ArgumentsAccessor argumentsAccessor) { - var isEDT = argumentsAccessor.getBoolean(0); - var name = argumentsAccessor.getString(1); - var isReport = argumentsAccessor.getBoolean(2); - - Path externalSourcePath; - if (isEDT) { - var sourceTypeName = (isReport) - ? MDOType.EXTERNAL_REPORT.getGroupName() - : MDOType.EXTERNAL_DATA_PROCESSOR.getGroupName(); - externalSourcePath = Path.of(EXAMPLES_PATH, EDT_PATH, EXTERNAL_SOURCE_PATH, sourceTypeName, name, name + ".mdo"); - } else { - var sourceTypeName = (isReport) ? "erf" : "epf"; - externalSourcePath = Path.of(EXAMPLES_PATH, DESIGNER_PATH, EXTERNAL_SOURCE_PATH, sourceTypeName, name + ".xml"); - } - - var mdc = MDClasses.createExternalSource(externalSourcePath); - assertThat(mdc).isNotNull(); - assertThat(mdc).isInstanceOf(MDClass.class); - assertThat(mdc).isInstanceOf(ExternalSource.class); - - return (ExternalSource) mdc; - } - public ExternalSource readExternalSourceWithSimpleTest(ArgumentsAccessor argumentsAccessor) { var isEDT = argumentsAccessor.getBoolean(0); var name = argumentsAccessor.getString(1); @@ -257,7 +183,6 @@ public ExternalSource readExternalSourceWithSimpleTest(ArgumentsAccessor argumen assertThat(mdc).isInstanceOf(MDClass.class); assertThat(mdc).isInstanceOf(ExternalSource.class); - var current = createJson(mdc, false); Path fixturePath; if (argumentsAccessor.size() > 3) { var fixturePostfix = argumentsAccessor.getString(3); @@ -265,13 +190,17 @@ public ExternalSource readExternalSourceWithSimpleTest(ArgumentsAccessor argumen } else { fixturePath = Path.of(FIXTURES_PATH, EXTERNAL_PATH, name + ".json"); } - var fixture = getFixture(fixturePath); - - Assertions.assertThat(fixRusYi(current), true).isEqual(fixRusYi(fixture)); + objectEqualJson(mdc, fixturePath); return (ExternalSource) mdc; } + private void objectEqualJson(Object obj, Path fixturePath) { + var fixture = getFixture(fixturePath); + var current = createJson(obj); + Assertions.assertThat(fixRusYi(current), true).isEqual(fixRusYi(fixture)); + } + private BeanProvider getBeanProvider() { return new BeanProvider() { private final Objenesis objenesis = new ObjenesisStd(); diff --git "a/src/test/resources/ext/designer/mdclasses/src/cf/DataProcessors/\320\236\320\261\321\200\320\260\320\261\320\276\321\202\320\272\320\2601/Forms/\320\226\321\203\321\200\320\275\320\260\320\273\320\240\320\265\320\263\320\270\321\201\321\202\321\200\320\260\321\206\320\270\320\270/Ext/Form.xml" "b/src/test/resources/ext/designer/mdclasses/src/cf/DataProcessors/\320\236\320\261\321\200\320\260\320\261\320\276\321\202\320\272\320\2601/Forms/\320\226\321\203\321\200\320\275\320\260\320\273\320\240\320\265\320\263\320\270\321\201\321\202\321\200\320\260\321\206\320\270\320\270/Ext/Form.xml" index c159294ee..1897cb8de 100644 --- "a/src/test/resources/ext/designer/mdclasses/src/cf/DataProcessors/\320\236\320\261\321\200\320\260\320\261\320\276\321\202\320\272\320\2601/Forms/\320\226\321\203\321\200\320\275\320\260\320\273\320\240\320\265\320\263\320\270\321\201\321\202\321\200\320\260\321\206\320\270\320\270/Ext/Form.xml" +++ "b/src/test/resources/ext/designer/mdclasses/src/cf/DataProcessors/\320\236\320\261\321\200\320\260\320\261\320\276\321\202\320\272\320\2601/Forms/\320\226\321\203\321\200\320\275\320\260\320\273\320\240\320\265\320\263\320\270\321\201\321\202\321\200\320\260\321\206\320\270\320\270/Ext/Form.xml" @@ -1,5 +1,5 @@  -
+ <v8:item> <v8:lang>ru</v8:lang> @@ -57,8 +57,6 @@ </v8:item> </ToolTip> <HorizontalAlign>Right</HorizontalAlign> - <ContextMenu name="КоличествоПоказываемыхСобытийКонтекстноеМеню" id="102"/> - <ExtendedTooltip name="КоличествоПоказываемыхСобытийExtendedTooltip" id="136"/> <Width>8</Width> <Wrap>false</Wrap> <DropListButton>true</DropListButton> @@ -127,14 +125,14 @@ </xr:Item> </ChoiceList> <BorderColor>style:BorderColor</BorderColor> + <ContextMenu name="КоличествоПоказываемыхСобытийКонтекстноеМеню" id="102"/> + <ExtendedTooltip name="КоличествоПоказываемыхСобытийExtendedTooltip" id="136"/> <Events> <Event name="OnChange">КоличествоПоказываемыхСобытийПриИзменении</Event> </Events> </InputField> <InputField name="Критичность" id="170"> <DataPath>Критичность</DataPath> - <ContextMenu name="КритичностьКонтекстноеМеню" id="171"/> - <ExtendedTooltip name="КритичностьРасширеннаяПодсказка" id="172"/> <Width>15</Width> <HorizontalStretch>false</HorizontalStretch> <DropListButton>true</DropListButton> @@ -207,6 +205,8 @@ </xr:Value> </xr:Item> </ChoiceList> + <ContextMenu name="КритичностьКонтекстноеМеню" id="171"/> + <ExtendedTooltip name="КритичностьРасширеннаяПодсказка" id="172"/> <Events> <Event name="OnChange">КритичностьПриИзменении</Event> <Event name="Clearing">КритичностьОчистка</Event> @@ -221,9 +221,9 @@ </v8:item> Left + true - true ПредставлениеОтбораНажатие @@ -258,6 +258,7 @@ true End Enable + AsFile Журнал Журнал.НомерРисунка @@ -334,6 +335,7 @@