modelComboBox;
+
+ private static final String DEFAULT_PROMPT = Messages.getString("P2T.prompt.text");
+
+ public P2TUI() {
+ initialize();
+ }
+
+ public P2TUI(AbstractApplicationMediator mediator) {
+ this(null, mediator);
+ }
+
+ public P2TUI(Frame owner, AbstractApplicationMediator mediator) throws HeadlessException {
+ super(owner, true);
+ initialize();
+ }
+
+ /**
+ * Initialize the dialog
+ *
+ * The dialog is initialized with a switch button panel at the top and a single button panel at the bottom.
+ * The switch button panel contains a radio button group to switch between the old and new services.
+ * The single button panel contains a single button to execute the action.
+ * The dialog is initially hidden.
+ */
+ void initialize() {
+ this.setVisible(false);
+ this.getContentPane().setLayout(new BorderLayout());
+ this.setUndecorated(false);
+ this.setResizable(true);
+ this.setTitle(Messages.getString("P2T.openP2T.text"));
+
+ // Add switch button panel to the top
+ this.getContentPane().add(initializeSwitchButtonPanel(), BorderLayout.NORTH);
+
+ // Add a single button to the bottom center
+ this.getContentPane().add(initializeSingleButtonPanel(), BorderLayout.SOUTH);
+
+ this.pack();
+ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ this.setLocation((screenSize.width - this.getWidth()) / 3, (screenSize.height - this.getHeight()) / 3);
+
+ Dimension size = new Dimension(600, 375);
+ this.setSize(size);
+
+ LoggerManager.info(Constants.EDITOR_LOGGER, "P2TUI initialized");
+
+ }
+
+ /**
+ * Initialize the switch button panel
+ *
+ * The switch button panel contains a radio button group to switch between the old and new services.
+ * The new service requires an API key and a prompt text.
+ * The prompt text is disabled by default and can be enabled by checking the enable prompt checkbox.
+ * The prompt text is a text area with a default text.
+ * The panel also contains a JComboBox to select the GPT model.
+ * The panel also contains a button to fetch the available models.
+ * The panel also contains a checkbox to show the popup again.
+ * The panel is initially hidden.
+ * @return JPanel containing the switch button panel
+ */
+ JPanel initializeSwitchButtonPanel() {
+ JPanel switchButtonPanel = new JPanel(new GridBagLayout());
+ GridBagConstraints gbc = new GridBagConstraints();
+
+ JPanel radioPanel = new JPanel(new GridBagLayout());
+ GridBagConstraints gbcRadio = new GridBagConstraints();
+
+ oldRadioButton = new JRadioButton(Messages.getString("P2T.oldservice.title"));
+ newRadioButton = new JRadioButton(Messages.getString("P2T.newservice.title"));
+ ButtonGroup group = new ButtonGroup();
+ group.add(oldRadioButton);
+ group.add(newRadioButton);
+
+ gbcRadio.gridx = 0;
+ gbcRadio.gridy = 0;
+ gbcRadio.insets = new Insets(5, 5, 5, 5);
+ radioPanel.add(oldRadioButton, gbcRadio);
+
+ gbcRadio.gridx = 1;
+ gbcRadio.insets = new Insets(5, 0, 5, 5);
+ radioPanel.add(newRadioButton, gbcRadio);
+
+ gbc.gridx = 0;
+ gbc.gridy = 0;
+ gbc.insets = new Insets(5, 5, 5, 5);
+ gbc.anchor = GridBagConstraints.CENTER;
+ switchButtonPanel.add(radioPanel, gbc);
+
+ JPanel fieldsPanel = new JPanel(new GridBagLayout());
+
+ JLabel apiKeyLabel = new JLabel(Messages.getString("P2T.apikey.title") + ":");
+ apiKeyField = new JTextField();
+ apiKeyField.setPreferredSize(new Dimension(300, 25));
+
+ JLabel promptLabel = new JLabel(Messages.getString("P2T.prompt.title") + ":");
+ promptField = new JTextArea(DEFAULT_PROMPT);
+ promptField.setLineWrap(true);
+ promptField.setWrapStyleWord(true);
+ promptField.setRows(5);
+ promptField.setEnabled(false);
+
+ promptField.setText(ConfigurationManager.getConfiguration().getGptPrompt());
+
+ JScrollPane promptScrollPane = new JScrollPane(promptField);
+ promptScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
+ promptScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+ promptScrollPane.setPreferredSize(new Dimension(200, 100));
+
+ enablePromptCheckBox = new JCheckBox(Messages.getString("P2T.prompt.checkbox.enable.title"));
+ enablePromptCheckBox.setSelected(false);
+ enablePromptCheckBox.addActionListener(e -> {
+ promptField.setEnabled(enablePromptCheckBox.isSelected());
+ if (!enablePromptCheckBox.isSelected()) {
+ promptField.revalidate();
+ LoggerManager.info(Constants.EDITOR_LOGGER, "Prompt Editing Disabled");
+ } else {
+ LoggerManager.info(Constants.EDITOR_LOGGER, "Prompt Editing Enabled");
+ }
+
+ });
+
+ // Add JComboBox
+ JLabel gptModelLabel = new JLabel(Messages.getString("P2T.get.GPTmodel.title"));
+ gptModelLabel.setVisible(false); // Initially hidden
+ modelComboBox = new JComboBox<>();
+ modelComboBox.setPreferredSize(new Dimension(150, 25));
+ modelComboBox.setVisible(false); // Initially hidden
+
+ // Add fetchModels Button
+ JButton fetchModelsButton = new JButton(Messages.getString("P2T.fetchmodels.button"));
+ fetchModelsButton.setPreferredSize(new Dimension(120, 25));
+ fetchModelsButton.setVisible(false); // Initially hidden
+ fetchModelsButton.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ fetchAndFillModels();
+ }
+ }
+ );
+
+ showAgainCheckBox = new JCheckBox(Messages.getString("P2T.popup.show.again.title"));
+ showAgainCheckBox.setToolTipText("Durch das Entfernen dieses Hakens wird das Popup-Fenster nicht erneut angezeigt, der Client merkt sich jedoch den zuletzt ausgewählten Modus," +
+ "unter den NLP Einstellungen kann das Fenster wieder aktiviert werden");
+ showAgainCheckBox.setSelected(ConfigurationManager.getConfiguration().getGptShowAgain());
+ showAgainCheckBox.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (showAgainCheckBox.isSelected()) {
+ LoggerManager.info(Constants.EDITOR_LOGGER,"Show Again Checkbox Selected");
+ }
+ else {
+ LoggerManager.info(Constants.EDITOR_LOGGER,"Show Again Checkbox not Selected");
+ }
+ }
+ });
+ apiKeyLabel.setVisible(false);
+ apiKeyField.setText(ConfigurationManager.getConfiguration().getGptApiKey());
+ apiKeyField.setVisible(false);
+ promptLabel.setVisible(false);
+ promptScrollPane.setVisible(false);
+ enablePromptCheckBox.setVisible(false);
+
+ showAgainCheckBox.setVisible(true);
+
+ newRadioButton.addActionListener(e -> {
+ apiKeyLabel.setVisible(true);
+ apiKeyField.setVisible(true);
+ promptLabel.setVisible(true);
+ promptScrollPane.setVisible(true);
+ enablePromptCheckBox.setVisible(true);
+ gptModelLabel.setVisible(true);
+ modelComboBox.setVisible(true);
+ fetchModelsButton.setVisible(true);
+ for (int i = 0; i < modelComboBox.getItemCount(); i++) {
+ if (modelComboBox.getItemAt(i).equals(ConfigurationManager.getConfiguration().getGptModel())) {
+ modelComboBox.setSelectedIndex(i);
+ break;
+ }
+ }
+ showAgainCheckBox.setVisible(true);
+
+ apiKeyField.requestFocusInWindow();
+
+ LoggerManager.info(Constants.EDITOR_LOGGER, "LLM Service Selected");
+ });
+
+ oldRadioButton.addActionListener(e -> {
+ apiKeyLabel.setVisible(false);
+ apiKeyField.setVisible(false);
+ promptLabel.setVisible(false);
+ promptScrollPane.setVisible(false);
+ enablePromptCheckBox.setVisible(false);
+ gptModelLabel.setVisible(false);
+ modelComboBox.setVisible(false);
+ fetchModelsButton.setVisible(false);
+
+ showAgainCheckBox.setVisible(true);
+
+ LoggerManager.info(Constants.EDITOR_LOGGER, "Algorithm Service Selected");
+ });
+
+ oldRadioButton.setSelected(true);
+
+ gbc.gridx = 0;
+ gbc.gridy = 1;
+ gbc.anchor = GridBagConstraints.WEST;
+ gbc.insets = new Insets(5, 5, 5, 5);
+ fieldsPanel.add(apiKeyLabel, gbc);
+
+ gbc.gridx = 1;
+ gbc.weightx = 1.0;
+ gbc.fill = GridBagConstraints.HORIZONTAL;
+ fieldsPanel.add(apiKeyField, gbc);
+
+ gbc.gridx = 0;
+ gbc.gridy = 2;
+ gbc.fill = GridBagConstraints.NONE;
+ gbc.weightx = 0;
+ fieldsPanel.add(promptLabel, gbc);
+
+ gbc.gridx = 1;
+ gbc.weightx = 1.0;
+ gbc.fill = GridBagConstraints.BOTH;
+ fieldsPanel.add(promptScrollPane, gbc);
+
+ gbc.gridx = 0;
+ gbc.gridy = 3;
+ gbc.gridwidth = 2;
+ gbc.weightx = 1.0;
+ fieldsPanel.add(enablePromptCheckBox, gbc);
+
+ gbc.gridx = 0;
+ gbc.gridy = 4;
+ gbc.gridwidth = 1;
+ gbc.weightx = 0;
+ fieldsPanel.add(gptModelLabel, gbc); // Add label before JComboBox
+
+ gbc.gridx = 1;
+ gbc.gridy = 4;
+ gbc.gridwidth = 1;
+ gbc.weightx = 0.5;
+ gbc.fill = GridBagConstraints.HORIZONTAL;
+ fieldsPanel.add(modelComboBox, gbc); // Add JComboBox to the panel
+
+ gbc.gridx = 2;
+ gbc.gridy = 4;
+ gbc.gridwidth = 1;
+ gbc.weightx = 0.5;
+ fieldsPanel.add(fetchModelsButton, gbc); // Add fetchModels button to the panel
+
+ gbc.gridx = 0;
+ gbc.gridy = 5;
+ gbc.gridwidth = 2;
+ gbc.weightx = 1.0;
+ fieldsPanel.add(showAgainCheckBox, gbc); // Add "Show Again" checkbox
+
+ gbc.gridx = 0;
+ gbc.gridy = 1;
+ gbc.gridwidth = 2;
+ gbc.insets = new Insets(10, 0, 0, 0);
+ gbc.fill = GridBagConstraints.BOTH;
+ gbc.weightx = 1.0;
+ gbc.weighty = 1.0;
+ switchButtonPanel.add(fieldsPanel, gbc);
+
+ return switchButtonPanel;
+ }
+
+ /**
+ * Initialize the single button panel
+ *
+ * The single button panel contains a single button to execute the action.
+ * @return JPanel containing the single button panel
+ */
+ JPanel initializeSingleButtonPanel() {
+ JPanel buttonPanel = new JPanel(new BorderLayout());
+ buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
+
+ JButton singleButton = new JButton();
+
+ singleButton.setMnemonic(KeyEvent.VK_A);
+ singleButton.setText(Messages.getString("P2T.text"));
+
+ buttonPanel.add(singleButton, BorderLayout.CENTER);
+
+ singleButton.addActionListener(e -> {
+ if (newRadioButton.isSelected()) {
+ if (validateAPIKey()) {
+
+ ConfigurationManager.getConfiguration().setGptApiKey(apiKeyField.getText());
+ ConfigurationManager.getConfiguration().setGptPrompt(promptField.getText());
+ ConfigurationManager.getConfiguration().setGptModel(modelComboBox.getSelectedItem().toString());
+ ConfigurationManager.getConfiguration().setGptUseNew(true);
+
+ if (!showAgainCheckBox.isSelected()) {
+ ConfigurationManager.getConfiguration().setGptShowAgain(false);
+ ConfigurationManager.getConfiguration().setGptUseNew(true);
+ }
+ executeAction();
+ dispose();
+ }
+ } else {
+ ConfigurationManager.getConfiguration().setGptUseNew(false);
+ if (!showAgainCheckBox.isSelected()) {
+ ConfigurationManager.getConfiguration().setGptShowAgain(false);
+ ConfigurationManager.getConfiguration().setGptUseNew(false);
+
+ }
+ executeAction();
+ dispose();
+ }
+ });
+ return buttonPanel;
+ }
+
+ /**
+ * Execute the action
+ *
+ * The action is executed based on the selected radio button.
+ */
+ void executeAction() {
+ WoPeDAction action = ActionFactory.getStaticAction(ActionFactory.ACTIONID_P2T_OLD);
+ action.actionPerformed(new ViewEvent(this, AbstractViewEvent.VIEWEVENTTYPE_GUI, AbstractViewEvent.P2T, null));
+ }
+
+ /**
+ * Fetch and fill the models
+ *
+ * Fetch the models from the API and fill the models in the JComboBox.
+ * If the models cannot be fetched, an error message is displayed.
+ */
+ void fetchAndFillModels() {
+ new Thread(() -> {
+ try {
+ List models = ApiHelper.fetchModels(apiKeyField.getText());
+ SwingUtilities.invokeLater(() -> {
+ for (String model : models) {
+ modelComboBox.addItem(model);
+ }
+ modelComboBox.setSelectedItem(ConfigurationManager.getConfiguration().getGptModel());
+ });
+ } catch (IOException | ParseException e) {
+ SwingUtilities.invokeLater(() -> {
+ JOptionPane.showMessageDialog(this, Messages.getString("P2T.exception.fail.fetch.models") + e.getMessage(), Messages.getString("P2T.exception.fetch.models"), JOptionPane.ERROR_MESSAGE);
+ });
+ }
+ }).start();
+ }
+
+ /**
+ * Validate the API key
+ *
+ * Validate the API key by sending a request to the API.
+ * If the API key is invalid, an error message is displayed.
+ * If the API key is valid, return true.
+ * @return
+ */
+ boolean validateAPIKey() {
+ String apiKey = apiKeyField.getText();
+ boolean apiKeyValid = isAPIKeyValid(apiKey);
+ if (!apiKeyValid) {
+ JOptionPane.showMessageDialog(this, Messages.getString("P2T.apikey.invalid"), Messages.getString("P2T.apikey.invalid.title"), JOptionPane.ERROR_MESSAGE);
+ }
+ return apiKeyValid;
+ }
+
+ /**
+ * Check if the API key is valid
+ * @param apiKey API key
+ * @return true if the API key is valid, false otherwise
+ */
+ public static boolean isAPIKeyValid(String apiKey) {
+ final String TEST_URL = "https://api.openai.com/v1/engines";
+ try {
+ URL url = new URL(TEST_URL);
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod("GET");
+ connection.setRequestProperty("Authorization", "Bearer " + apiKey);
+
+ int responseCode = connection.getResponseCode();
+
+ return responseCode == 200;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+ }
+
+}
diff --git a/WoPeD-FileInterface/src/test/java/org/woped/file/p2t/P2TUITest.java b/WoPeD-FileInterface/src/test/java/org/woped/file/p2t/P2TUITest.java
new file mode 100644
index 000000000..931eec906
--- /dev/null
+++ b/WoPeD-FileInterface/src/test/java/org/woped/file/p2t/P2TUITest.java
@@ -0,0 +1,191 @@
+package org.woped.file.p2t;
+
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.woped.core.config.ConfigurationManager;
+import org.woped.gui.translations.Messages;
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.KeyEvent;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+public class P2TUITest {
+
+ private P2TUI p2tui;
+ private MockedStatic messagesMock;
+
+ // This method is called before each test
+ @BeforeEach
+ public void setUp() {
+ p2tui = new P2TUI();
+
+ initializeMockMessages();
+ }
+
+ // This method initializes the mock for the Messages class
+ private void initializeMockMessages() {
+ messagesMock = mockStatic(Messages.class);
+ messagesMock.when(() -> Messages.getString("P2T.openP2T.text")).thenReturn("Prozess zu Text");
+ messagesMock.when(() -> Messages.getString("P2T.oldservice.title")).thenReturn("Algorithmus");
+ messagesMock.when(() -> Messages.getString("P2T.newservice.title")).thenReturn("LLM");
+ messagesMock.when(() -> Messages.getString("P2T.apikey.title")).thenReturn("API Schl\\u00FCssel");
+ messagesMock.when(() -> Messages.getString("P2T.prompt.title")).thenReturn("Prompt");
+ messagesMock.when(() -> Messages.getString("P2T.prompt.checkbox.enable.title")).thenReturn("Bearbeitung aktivieren");
+ messagesMock.when(() -> Messages.getString("P2T.get.GPTmodel.title")).thenReturn("GPT-Model:");
+ messagesMock.when(() -> Messages.getString("P2T.popup.show.again.title")).thenReturn("Erneut anzeigen");
+ }
+
+ // This method is called after each test
+ @AfterEach
+ public void tearDown() {
+ // Close the static mock
+ messagesMock.close();
+ }
+
+ // This method tests the initialize method
+ @Test
+ public void testInitialize() {
+ assertFalse(p2tui.isVisible(), "P2TUI should be visible");
+ assertTrue(p2tui.getLayout() instanceof BorderLayout, "P2TUI layout should be BorderLayout");
+ assertFalse(p2tui.isUndecorated(), "P2TUI shouldn't be undecorated");
+ assertTrue(p2tui.isResizable(), "P2TUI should be resizable");
+
+ assertEquals(Messages.getString("P2T.openP2T.text"), p2tui.getTitle(), "P2TUI title should be 'Open P2T'");
+
+ assertEquals(new Dimension(600, 375), p2tui.getSize(), "Dialog should have size 600x375");
+
+ }
+
+ // This method tests the initializeSwitchButtonPanel method
+ @Test
+ public void initializeSwitchButtonPanel() {
+ JPanel switchButtonPanel = p2tui.initializeSwitchButtonPanel();
+ assertNotNull(switchButtonPanel, "SwitchButtonPanel should be null");
+ assertTrue(switchButtonPanel.getLayout() instanceof GridBagLayout, "Layout should be GridBagLayout");
+
+ Component[] components = switchButtonPanel.getComponents();
+ assertEquals(2, components.length, "SwitchButtonPanel should have 2 components");
+
+ JPanel radioPanel = (JPanel) components[0];
+ assertEquals(2, radioPanel.getComponentCount());
+
+ JRadioButton oldRadioButton = (JRadioButton) radioPanel.getComponent(0);
+ JRadioButton newRadioButton = (JRadioButton) radioPanel.getComponent(1);
+
+ assertEquals(Messages.getString("P2T.oldservice.title"), oldRadioButton.getText(), "Old service radio button should have text 'Algorithmus'");
+ assertEquals(Messages.getString("P2T.newservice.title"), newRadioButton.getText(), "New service radio button should have text 'LLM'");
+
+ JPanel fieldsPanel = (JPanel) components[1];
+ assertTrue(fieldsPanel.getComponentCount() > 0, "Fields panel should have at least one component");
+
+ JLabel apiKeyLabel = (JLabel) fieldsPanel.getComponent(0);
+ assertNotNull(apiKeyLabel, "apiKeyLabel should not be null");
+ assertEquals(Messages.getString("P2T.apikey.title") + ":", apiKeyLabel.getText(), "apiKeyLabel text should be correct");
+
+ JTextField apiKeyField = (JTextField) fieldsPanel.getComponent(1);
+ assertNotNull(apiKeyField, "apiKeyField should not be null");
+ assertEquals(new Dimension(300, 25), apiKeyField.getPreferredSize(), "apiKeyField preferred size should be correct");
+
+ JLabel promptLabel = (JLabel) fieldsPanel.getComponent(2);
+ assertNotNull(promptLabel, "promptLabel should not be null");
+ assertEquals(Messages.getString("P2T.prompt.title") + ":", promptLabel.getText(), "promptLabel text should be correct");
+
+ JScrollPane promptScrollPane = (JScrollPane) fieldsPanel.getComponent(3);
+ assertNotNull(promptScrollPane, "promptScrollPane should not be null");
+ assertEquals(new Dimension(200, 100), promptScrollPane.getPreferredSize(), "promptScrollPane preferred size should be correct");
+
+ JTextArea promptField = (JTextArea) promptScrollPane.getViewport().getView();
+ assertNotNull(promptField, "promptField should not be null");
+
+ assertTrue(promptField.getLineWrap(), "promptField line wrap should be enabled");
+ assertTrue(promptField.getWrapStyleWord(), "promptField wrap style should be word");
+
+ assertFalse(promptField.isEnabled(), "promptField should be disabled");
+ assertEquals(5, promptField.getRows(), "promptField rows should be 5");
+
+
+ JCheckBox enablePromptCheckBox = (JCheckBox) fieldsPanel.getComponent(4);
+ assertNotNull(enablePromptCheckBox, "enablePromptCheckBox should not be null");
+ assertFalse(enablePromptCheckBox.isSelected(), "enablePromptCheckBox should not be selected");
+
+ JLabel gptModelLabel = (JLabel) fieldsPanel.getComponent(5);
+ assertNotNull(gptModelLabel, "gptModelLabel should not be null");
+
+ JComboBox> modelComboBox = (JComboBox>) fieldsPanel.getComponent(6);
+ assertNotNull(modelComboBox, "modelComboBox should not be null");
+
+ JButton fetchModelsButton = (JButton) fieldsPanel.getComponent(7);
+ assertNotNull(fetchModelsButton, "fetchModelsButton should not be null");
+ assertEquals("fetchModels", fetchModelsButton.getText(), "fetchModelsButton text should be correct");
+
+ JCheckBox showAgainCheckBox = (JCheckBox) fieldsPanel.getComponent(8);
+ assertNotNull(showAgainCheckBox, "showAgainCheckBox should not be null");
+ assertEquals(Messages.getString("P2T.popup.show.again.title"), showAgainCheckBox.getText(), "showAgainCheckBox text should be correct");
+ assertEquals(ConfigurationManager.getConfiguration().getGptShowAgain(), showAgainCheckBox.isSelected(), "showAgainCheckBox selected state should be correct");
+
+ // Simulate selecting the new radio button
+ newRadioButton.doClick();
+ assertTrue(apiKeyLabel.isVisible(), "apiKeyLabel should be visible after selecting new service");
+ assertTrue(apiKeyField.isVisible(), "apiKeyField should be visible after selecting new service");
+ assertTrue(promptLabel.isVisible(), "promptLabel should be visible after selecting new service");
+ assertTrue(promptScrollPane.isVisible(), "promptScrollPane should be visible after selecting new service");
+ assertTrue(enablePromptCheckBox.isVisible(), "enablePromptCheckBox should be visible after selecting new service");
+ assertTrue(gptModelLabel.isVisible(), "gptModelLabel should be visible after selecting new service");
+ assertTrue(modelComboBox.isVisible(), "modelComboBox should be visible after selecting new service");
+ assertTrue(fetchModelsButton.isVisible(), "fetchModelsButton should be visible after selecting new service");
+
+ // Simulate selecting the old radio button
+ oldRadioButton.doClick();
+ assertFalse(apiKeyLabel.isVisible(), "apiKeyLabel should be hidden after selecting old service");
+ assertFalse(apiKeyField.isVisible(), "apiKeyField should be hidden after selecting old service");
+ assertFalse(promptLabel.isVisible(), "promptLabel should be hidden after selecting old service");
+ assertFalse(promptScrollPane.isVisible(), "promptScrollPane should be hidden after selecting old service");
+ assertFalse(enablePromptCheckBox.isVisible(), "enablePromptCheckBox should be hidden after selecting old service");
+ assertFalse(gptModelLabel.isVisible(), "gptModelLabel should be hidden after selecting old service");
+ assertFalse(modelComboBox.isVisible(), "modelComboBox should be hidden after selecting old service");
+ assertFalse(fetchModelsButton.isVisible(), "fetchModelsButton should be hidden after selecting old service");
+
+ // Simulate clicking the showAgainCheckBox
+ showAgainCheckBox.doClick();
+ assertFalse(showAgainCheckBox.isSelected(), "showAgainCheckBox should be unchecked after click");
+ showAgainCheckBox.doClick();
+ assertTrue(showAgainCheckBox.isSelected(), "showAgainCheckBox should be checked after click");
+
+ // Test enablePromptCheckBox
+ // Simulate enabling prompt editing
+ enablePromptCheckBox.doClick();
+ assertTrue(promptField.isEnabled(), "promptField should be enabled after checking enablePromptCheckBox");
+ // Simulate disabling prompt editing
+ enablePromptCheckBox.doClick();
+ assertFalse(promptField.isEnabled(), "promptField should be disabled after unchecking enablePromptCheckBox");
+ }
+
+ // This method tests the initializeButtonPanel method
+ @Test
+ public void testInitializeSingleButtonPanel(){
+ JPanel buttonPanel = p2tui.initializeSingleButtonPanel();
+ assertNotNull(buttonPanel, "ButtonPanel should not be null");
+ assertTrue(buttonPanel.getLayout() instanceof BorderLayout, "ButtonPanel layout should be BorderLayout");
+
+ JButton singleButton = (JButton) buttonPanel.getComponent(0);
+ assertNotNull(singleButton, "SingleButton should not be null");
+ assertTrue(singleButton.getMnemonic() == KeyEvent.VK_A, "SingleButton mnemonic should be correct");
+ assertEquals(Messages.getString("P2T.text"), singleButton.getText(), "SingleButton text should be correct");
+
+ }
+
+ // This method tests the isAPIKeyValid method with an invalid key
+ @Test
+ public void testIsAPIKeyValid_withInvalidKey() {
+ String invalidApiKey = "invalidApiKey";
+
+ boolean isValid = p2tui.isAPIKeyValid(invalidApiKey);
+
+ assertFalse(isValid);
+ }
+
+}
\ No newline at end of file
diff --git a/WoPeD-GUI/src/main/resources/Messages.properties b/WoPeD-GUI/src/main/resources/Messages.properties
index b2cc69c07..66a86212c 100644
--- a/WoPeD-GUI/src/main/resources/Messages.properties
+++ b/WoPeD-GUI/src/main/resources/Messages.properties
@@ -870,9 +870,22 @@ P2T.loading = Generating text...
P2T.ArcError = <>Model has arc weights - no text can be generated
P2T.SoundError = Modell is not sound - no text can be generated
P2T.SizeError = Modell has too few nodes - no text can be generated
-
P2T.Error.ArcWeights.title = Text generation failed
P2T.Error.ArcWeights.message = The net contains arc weights.\nArc weights are not supported by the process 2 text feature.
+P2T.oldservice.title = Algorithm
+P2T.newservice.title = LLM
+P2T.apikey.title = API Key
+P2T.apikey.invalid = API Key is not valid
+P2T.apikey.invalid.title = Validation Error
+P2T.prompt.title = Prompt
+P2T.prompt.checkbox.enable.title = Enable editing
+P2T.popup.show.again.title = Show again
+P2T.get.GPTmodel.title = GPT-Model:
+P2T.popup.tool.tip.text = Placeholder
+P2T.prompt.text = Create a clearly structured and comprehensible continuous text from the given BPMN that is understandable for an uninformed reader. The text should be easy to read in the summary and contain all important content; if there are subdivided points, these are integrated into the text with suitable sentence beginnings in order to obtain a well-structured and easy-to-read text. Under no circumstances should the output contain sub-items or paragraphs, but should cover all processes in one piece!
+P2T.exception.fail.fetch.models = Failed to fetch models:
+P2T.exception.fetch.models = Fetch Models
+P2T.fetchmodels.button = Fetch GPT Models
#*************
! Text2Process
#*************
@@ -1271,6 +1284,21 @@ Configuration.P2T.Label.ServerPort = Port
Configuration.P2T.Label.ServerURI = URI
Configuration.P2T.Label.Use = Enable NLP Tools
Configuration.P2T.Settings.Panel.Title = Process2Text server settings
+Configuration.GPT.apikey.Title = API Key
+Configuration.GPT.prompt.Title = Prompt
+Configuration.GPT.show.again.Title = Show again
+Configuration.GPT.standard.Title = Reset to standard
+Configuration.GPT.connection.Title = Test connection
+Configuration.GPT.settings.Title = GPT-Settings
+Configuration.GPT.model.Title = GPT-Model
+Configuration.GPT.tool.tip.text.Title = Test
+Configuration.GPT.connection.successful.Title = GPT connection successful. Response Code:
+Configuration.GPT.connection.failed.Title = GPT connection failed. Response Code:
+Configuration.GPT.connection.test.Title = Connection Test
+Configuration.GPT.connection.test.failed.Title = GPT connection test failed:
+
+
+
Configuration.T2P.Settings.Panel.Title = Text2Process server settings
Configuration.T2P.Dialog.Restart.Title = Restart
Configuration.T2P.Label.ServerHost = Server Host
diff --git a/WoPeD-GUI/src/main/resources/Messages_de.properties b/WoPeD-GUI/src/main/resources/Messages_de.properties
index b3c3fe8eb..6a6971587 100644
--- a/WoPeD-GUI/src/main/resources/Messages_de.properties
+++ b/WoPeD-GUI/src/main/resources/Messages_de.properties
@@ -467,17 +467,31 @@ DataOutput.textBandTitle = Ausgabe
#*************
! Process 2 Text
#*************
-P2T.textBandTitle = NLP Tools
-P2T.text = In Text umwandeln
-P2T.openP2T.text = Process zu Text
-P2T.openP2T.header = Eingabetext
-P2T.tooltip = Textuelle Beschreibung erzeugen
-P2T.loading = Erzeuge Text...
-P2T.ArcError = Modell hat Kantengewichte - kein Text generierbar
-P2T.SoundError = Modell ist nicht sound - kein Text generierbar
-P2T.SizeError = Modell hat zuwenige Knoten - kein Text generierbar
-P2T.Error.ArcWeights.title = Textgenerierung fehlgeschlagen
-P2T.Error.ArcWeights.message = Das Netz verwendet Kantengewichte. \nKantengewichte werden bei der Textgenerierung nicht unterst\u00FCtzt.
+P2T.textBandTitle = NLP Tools
+P2T.text = In Text umwandeln
+P2T.openP2T.text = Prozess zu Text
+P2T.openP2T.header = Eingabetext
+P2T.tooltip = Textuelle Beschreibung erzeugen
+P2T.loading = Erzeuge Text...
+P2T.ArcError = Modell hat Kantengewichte - kein Text generierbar
+P2T.SoundError = Modell ist nicht sound - kein Text generierbar
+P2T.SizeError = Modell hat zuwenige Knoten - kein Text generierbar
+P2T.Error.ArcWeights.title = Textgenerierung fehlgeschlagen
+P2T.Error.ArcWeights.message = Das Netz verwendet Kantengewichte. \nKantengewichte werden bei der Textgenerierung nicht unterst\u00FCtzt.
+P2T.oldservice.title = Algorithmus
+P2T.newservice.title = LLM
+P2T.apikey.title = API-Schl\u00FCssel
+P2T.apikey.invalid = API-Schl\u00FCssel ist nicht valide
+P2T.apikey.invalid.title = Validierungsfehler
+P2T.prompt.title = Prompt
+P2T.prompt.checkbox.enable.title = Bearbeitung aktivieren
+P2T.popup.show.again.title = Erneut anzeigen
+P2T.get.GPTmodel.title = GPT-Modell:
+P2T.popup.tool.tip.text = Platzhalter
+P2T.prompt.text = Create a clearly structured and comprehensible continuous text from the given BPMN that is understandable for an uninformed reader. The text should be easy to read in the summary and contain all important content; if there are subdivided points, these are integrated into the text with suitable sentence beginnings in order to obtain a well-structured and easy-to-read text. Under no circumstances should the output contain sub-items or paragraphs, but should cover all processes in one piece!
+P2T.exception.fail.fetch.models = Modelle konnten nicht abgerufen werden:
+P2T.exception.fetch.models = Modelle abrufen
+P2T.fetchmodels.button = GPT-Modelle abrufen
#*************
! Text 2 Process
#*************
@@ -487,6 +501,7 @@ T2P.openT2P.text = Text zu Prozess
T2P.tooltip = Petrinetz erzeugen
T2P.Error.ArcWeights.title = Petrinetz-Erzeugung fehlgeschlagen
T2P.Error.ArcWeights.message = Das Netz besitzt Kantengewichte.\nKantengewichte werden bei der Prozessgenerierung nicht unterst\u00FCtzt..
+
#*************
! Forms
#*************
@@ -808,6 +823,21 @@ Configuration.P2T.Label.Use = NLP Tools aktivieren
Configuration.P2T.Settings.Panel.Title = Process2Text Servereinstellungen
Configuration.T2P.Settings.Panel.Title = Text2Process Servereinstellungen
Configuration.P2T.Title = NLP Tools
+Configuration.GPT.apikey.Title = API Schl\u00FCssel
+Configuration.GPT.prompt.Title = Prompt
+Configuration.GPT.show.again.Title = Erneut anzeigen
+Configuration.GPT.standard.Title = Auf Standard zur\u00FCcksetzen
+Configuration.GPT.connection.Title = Verbindung pr\u00FCfen
+Configuration.GPT.settings.Title = GPT-Einstellungen
+Configuration.GPT.model.Title = GPT-Model
+Configuration.GPT.tool.tip.text.Title = Test
+Configuration.GPT.connection.successful.Title = GPT-Verbindung erfolgreich. Antwort-Code:
+Configuration.GPT.connection.failed.Title = GPT-Verbindung fehlgeschlagen. Antwort-Code:
+Configuration.GPT.connection.test.Title = Verbindung pr\u00FCfen
+Configuration.GPT.connection.test.failed.Title = GPT-Verbindungstest fehlgeschlagen:
+
+
+
Configuration.T2P.Dialog.Restart.Title = Neustart
Configuration.T2P.Label.ServerHost = Server Host
Configuration.T2P.Label.ServerPort = Port
@@ -830,6 +860,7 @@ Configuration.YAWL.Panel.Export.ExplicitPlaces = *.yawl Dat
Configuration.YAWL.Panel.Export.ExplicitPlaces.ToolTip = Alle Stellen im Petrinetz werden zu Conditions in YAWL exportiert
Configuration.YAWL.Panel.Export.Groups = *.ybkp Dateien mit Gruppen exportieren
Configuration.YAWL.Panel.Export.Groups.ToolTip = Alle Gruppen im Ressourcen Editor werden zu OrgGroups in YAWL exportiert
+
#*************
! Exit-Config
#*************
diff --git a/WoPeD-Installer/pom.xml b/WoPeD-Installer/pom.xml
index 98c449518..b32d704c5 100644
--- a/WoPeD-Installer/pom.xml
+++ b/WoPeD-Installer/pom.xml
@@ -35,6 +35,7 @@
org.apache.maven.plugins
maven-antrun-plugin
+ 1.8
com.akathist.maven.plugins.launch4j
@@ -107,7 +108,7 @@
-
com.akathist.maven.plugins.launch4j
@@ -327,7 +328,7 @@
-
+
diff --git a/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/P2TSideBar.java b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/P2TSideBar.java
index fc606da44..71bd46e02 100644
--- a/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/P2TSideBar.java
+++ b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/P2TSideBar.java
@@ -16,6 +16,8 @@
import javax.swing.event.HyperlinkListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.BadLocationException;
+
+import org.woped.core.config.ConfigurationManager;
import org.woped.core.controller.IEditor;
import org.woped.core.model.ModelElementContainer;
import org.woped.core.utilities.LoggerManager;
@@ -29,14 +31,13 @@
/** The sidebar to be used for displaying of the natural text-presentation (Process2Text). */
public class P2TSideBar extends JPanel implements ActionListener {
- private IEditor editor;
+ private final IEditor editor;
private JEditorPane textpane = null;
private Process2Text naturalTextParser = null;
private JButton buttonLoad = null;
private JButton buttonExport = null;
private JLabel labelLoading = null;
- private WebServiceThread webService = null;
- private boolean threadInProgress = false;
+ private boolean threadInProgress = false;
private boolean firstTimeDisplayed = false;
/**
@@ -227,7 +228,7 @@ public void actionPerformed(ActionEvent e) {
// If we already have a text/process description, ask for overwrite
// confirmation.
- if (naturalTextParser != null && naturalTextParser.getXmlText().length() > 0) {
+ if (naturalTextParser != null && !naturalTextParser.getXmlText().isEmpty()) {
if (JOptionPane.showConfirmDialog(
null,
Messages.getString("Paraphrasing.Load.Question.Content"),
@@ -253,7 +254,7 @@ public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.buttonExport) {
boolean fileTypeOk = false;
- if (this.textpane.getText().length() > 0) {
+ if (!this.textpane.getText().isEmpty()) {
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setFileFilter(
new FileFilter() {
@@ -320,7 +321,7 @@ public String getDescription() {
private void getText() {
clean();
- // Ensure their are no arc weights
+ // Ensure there are no arc weights
if (editor.getModelProcessor().usesArcWeights()) {
this.textpane.setText(Messages.getString("P2T.Error.ArcWeights.title"));
showErrorMessage("P2T.Error.ArcWeights");
@@ -347,21 +348,41 @@ private void getText() {
this.textpane.setText(Messages.getString("P2T.SoundError"));
return;
}
-
- this.textpane.setText(Messages.getString("P2T.loading"));
- this.showLoadingAnimation(true);
- webService = new WebServiceThread(this);
- webService.start();
- while (!webService.getIsFinished()) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e1) {
- // ignore
+ //New LLM
+ WebServiceThreadLLM webService = null;
+ if(ConfigurationManager.getConfiguration().getGptUseNew()){
+ this.textpane.setText(Messages.getString("P2T.loading"));
+ this.showLoadingAnimation(true);
+ webService = new WebServiceThreadLLM(this);
+ webService.start();
+ while (!webService.getIsFinished()) {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e1) {
+ // ignore
+ }
}
+ this.textpane.setText("");
+
+ if (naturalTextParser != null) this.textpane.setText(webService.getText());
}
- this.textpane.setText("");
- if (naturalTextParser != null) this.textpane.setText(naturalTextParser.getHtmlText());
+ if(!ConfigurationManager.getConfiguration().getGptUseNew()){
+ this.textpane.setText(Messages.getString("P2T.loading"));
+ this.showLoadingAnimation(true);
+ WebServiceThread webServiceOld = new WebServiceThread(this);
+ webServiceOld.start();
+ while (!webServiceOld.getIsFinished()) {
+ try{
+ Thread.sleep(500);
+ }catch (InterruptedException e1){
+ //ignore?
+ }
+ this.textpane.setText("");
+
+ if (naturalTextParser != null) this.textpane.setText(webServiceOld.getText());
+ }
+ }
setThreadInProgress(false);
webService = null;
diff --git a/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/Process2Text.java b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/Process2Text.java
index d637b65f3..04b6de338 100644
--- a/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/Process2Text.java
+++ b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/Process2Text.java
@@ -40,7 +40,7 @@ public String[] getText(String id) {
}
}
- return temptexts.toArray(new String[temptexts.size()]);
+ return temptexts.toArray(new String[0]);
}
private void parseXmlToHtml() {
diff --git a/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/WebServiceThread.java b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/WebServiceThread.java
index b18fd55a2..f1d4b71ab 100644
--- a/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/WebServiceThread.java
+++ b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/WebServiceThread.java
@@ -3,79 +3,97 @@
import java.io.ByteArrayOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
+
import org.woped.core.config.ConfigurationManager;
import org.woped.core.controller.IEditor;
import org.woped.gui.translations.Messages;
public class WebServiceThread extends Thread {
- private P2TSideBar paraphrasingPanel;
- private String[][] result = null;
- private boolean isFinished;
- private HttpRequest request;
- private HttpResponse response;
-
- public WebServiceThread(P2TSideBar paraphrasingPanel) {
- this.paraphrasingPanel = paraphrasingPanel;
- isFinished = false;
- }
-
- public boolean getIsFinished() {
- return isFinished;
- }
-
- public void run() {
- IEditor editor = paraphrasingPanel.getEditor();
- paraphrasingPanel.showLoadingAnimation(true);
- String url =
- "http://"
- + ConfigurationManager.getConfiguration().getProcess2TextServerHost()
- + ":"
- + ConfigurationManager.getConfiguration().getProcess2TextServerPort()
- + ConfigurationManager.getConfiguration().getProcess2TextServerURI()
- + "/generateText";
-
- String[] arg = {url, "P2T"};
- try {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- new PNMLExport().saveToStream(editor, stream);
- String text = stream.toString();
- String output;
- request = new HttpRequest(url, text);
- response = request.getResponse();
- output = response.getBody();
- output = output.replaceAll("\\s*\n\\s*", "");
- isFinished = true;
- paraphrasingPanel.setNaturalTextParser(new Process2Text(output));
- } finally {
+ private P2TSideBar paraphrasingPanel;
+ private boolean isFinished;
+ private HttpRequest request;
+ private HttpResponse response;
+ private String text;
+
+
+ public WebServiceThread(P2TSideBar paraphrasingPanel) {
+ this.paraphrasingPanel = paraphrasingPanel;
+ isFinished = false;
}
- ;
-
- switch (response.responseCode) {
- case HttpServletResponse.SC_NO_CONTENT:
- case HttpServletResponse.SC_REQUEST_TIMEOUT:
- case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
- JOptionPane.showMessageDialog(
- null,
- Messages.getString("Paraphrasing.Webservice.Error.TryAgain", arg),
- Messages.getString("Paraphrasing.Webservice.Error.Title"),
- JOptionPane.INFORMATION_MESSAGE);
- break;
- case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
- case HttpServletResponse.SC_NOT_FOUND:
- case HttpServletResponse.SC_METHOD_NOT_ALLOWED:
- case -1:
- JOptionPane.showMessageDialog(
- null,
- Messages.getString("Paraphrasing.Webservice.Error.Contact", arg)
- + "\n"
- + Messages.getString("Paraphrasing.Webservice.Settings"),
- Messages.getString("Paraphrasing.Webservice.Error.Title"),
- JOptionPane.INFORMATION_MESSAGE);
+
+ public boolean getIsFinished() {
+ return isFinished;
}
- paraphrasingPanel.showLoadingAnimation(false);
- paraphrasingPanel.enableButtons(true);
- paraphrasingPanel.setThreadInProgress(false);
- }
+
+ public void run() {
+ IEditor editor = paraphrasingPanel.getEditor();
+ paraphrasingPanel.showLoadingAnimation(true);
+
+ String url = "http://localhost:8080/p2t/generateText";
+
+ /*String url =
+ "http://"
+ + ConfigurationManager.getConfiguration().getProcess2TextServerHost()
+ + ":"
+ + ConfigurationManager.getConfiguration().getProcess2TextServerPort()
+ + ConfigurationManager.getConfiguration().getProcess2TextServerURI()
+ + "/generateText";*/
+
+
+
+ String[] arg = {url, "P2T"};
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ new PNMLExport().saveToStream(editor, stream);
+ String text = stream.toString();
+ String output;
+ request = new HttpRequest(url, text);
+ response = request.getResponse();
+ output = response.getBody();
+ output = output.replaceAll("\\s*\n\\s*", "");
+ setText(output);
+ isFinished = true;
+ paraphrasingPanel.setNaturalTextParser(new Process2Text(output));
+
+
+ switch (response.responseCode) {
+ case HttpServletResponse.SC_NO_CONTENT:
+ case HttpServletResponse.SC_REQUEST_TIMEOUT:
+ case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
+ JOptionPane.showMessageDialog(
+ null,
+ Messages.getString("Paraphrasing.Webservice.Error.TryAgain", arg),
+ Messages.getString("Paraphrasing.Webservice.Error.Title"),
+ JOptionPane.INFORMATION_MESSAGE);
+ break;
+ case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
+ case HttpServletResponse.SC_NOT_FOUND:
+ case HttpServletResponse.SC_METHOD_NOT_ALLOWED:
+ case -1:
+ JOptionPane.showMessageDialog(
+ null,
+ Messages.getString("Paraphrasing.Webservice.Error.Contact", arg)
+ + "\n"
+ + Messages.getString("Paraphrasing.Webservice.Settings"),
+ Messages.getString("Paraphrasing.Webservice.Error.Title"),
+ JOptionPane.INFORMATION_MESSAGE);
+ }
+
+ paraphrasingPanel.showLoadingAnimation(false);
+ paraphrasingPanel.enableButtons(true);
+ paraphrasingPanel.setThreadInProgress(false);
+ }
+
+ // Setter- und Getter for the result of the algorithm
+
+ public String getText() {
+ return text;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+
+
}
diff --git a/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/WebServiceThreadLLM.java b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/WebServiceThreadLLM.java
new file mode 100644
index 000000000..f4a44b3b7
--- /dev/null
+++ b/WoPeD-QualAnalysis/src/main/java/org/woped/qualanalysis/p2t/WebServiceThreadLLM.java
@@ -0,0 +1,146 @@
+package org.woped.qualanalysis.p2t;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Scanner;
+import javax.servlet.http.HttpServletResponse;
+import javax.swing.JOptionPane;
+
+import org.woped.core.config.ConfigurationManager;
+import org.woped.core.controller.IEditor;
+import org.woped.gui.translations.Messages;
+
+public class WebServiceThreadLLM extends Thread {
+
+ private P2TSideBar paraphrasingPanel;
+ private boolean isFinished;
+ private String apiKey;
+ private String prompt;
+ private String gptModel;
+ private String text;
+
+ public WebServiceThreadLLM(P2TSideBar paraphrasingPanel) {
+ this.paraphrasingPanel = paraphrasingPanel;
+ isFinished = false;
+ }
+
+ public boolean getIsFinished() {
+ return isFinished;
+ }
+
+ public void run() {
+ apiKey = ConfigurationManager.getConfiguration().getGptApiKey();
+ prompt = ConfigurationManager.getConfiguration().getGptPrompt();
+ gptModel = ConfigurationManager.getConfiguration().getGptModel();
+
+ // LoggerManager.info(Constants.EDITOR_LOGGER,"Started Fetching GPT Models");
+
+ IEditor editor = paraphrasingPanel.getEditor();
+ paraphrasingPanel.showLoadingAnimation(true);
+
+ String url = "http://localhost:8080/p2t/generateTextLLM";
+
+ // This URL parameter is prepared for the go-live of the LLM-based Process2Text service
+ /*String url =
+ "http://"
+ + ConfigurationManager.getConfiguration().getProcess2TextServerHost()
+ + ":"
+ + ConfigurationManager.getConfiguration().getProcess2TextServerPort()
+ + ConfigurationManager.getConfiguration().getProcess2TextServerURI()
+ + "/generateTextLLM";*/
+
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ new PNMLExport().saveToStream(editor, stream);
+ String text = stream.toString();
+ String output;
+
+ try {
+ // Encode URL parameters
+ String encodedApiKey = URLEncoder.encode(apiKey, StandardCharsets.UTF_8);
+ String encodedPrompt = URLEncoder.encode(prompt, StandardCharsets.UTF_8);
+ String encodedGptModel = URLEncoder.encode(gptModel, StandardCharsets.UTF_8);
+
+ // Construct URL with parameters
+ String urlWithParams = String.format("%s?apiKey=%s&prompt=%s&gptModel=%s",
+ url, encodedApiKey, encodedPrompt, encodedGptModel);
+ URL urlObj = new URL(urlWithParams);
+
+ // Establish connection
+ HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+ conn.setDoOutput(true);
+ conn.setRequestMethod("POST");
+ conn.setRequestProperty("Content-Type", "text/plain");
+
+ // Send request body
+ try (OutputStream os = conn.getOutputStream()) {
+ byte[] input = text.getBytes(StandardCharsets.UTF_8);
+ os.write(input, 0, input.length);
+ }
+
+ // Read response
+ int responseCode = conn.getResponseCode();
+ if (responseCode == HttpURLConnection.HTTP_OK) {
+ try (Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8)) {
+ output = scanner.useDelimiter("\\A").next();
+ output = output.replaceAll("\\s*\n\\s*", "");
+ paraphrasingPanel.setNaturalTextParser(new Process2Text(output));
+ setText(output);
+ }
+ } else {
+ output = "Request failed. Response Code: " + responseCode;
+ }
+
+ // Fehlerbehandlung basierend auf Response Code
+
+ switch (responseCode) {
+ case HttpServletResponse.SC_NO_CONTENT:
+ case HttpServletResponse.SC_REQUEST_TIMEOUT:
+ case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
+ JOptionPane.showMessageDialog(
+ null,
+ Messages.getString("Paraphrasing.Webservice.Error.TryAgain"),
+ Messages.getString("Paraphrasing.Webservice.Error.Title"),
+ JOptionPane.INFORMATION_MESSAGE);
+ break;
+ case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
+ case HttpServletResponse.SC_NOT_FOUND:
+ case HttpServletResponse.SC_METHOD_NOT_ALLOWED:
+ case -1:
+ JOptionPane.showMessageDialog(
+ null,
+ Messages.getString("Paraphrasing.Webservice.Error.Contact")
+ + "\n"
+ + Messages.getString("Paraphrasing.Webservice.Settings"),
+ Messages.getString("Paraphrasing.Webservice.Error.Title"),
+ JOptionPane.INFORMATION_MESSAGE);
+ break;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ JOptionPane.showMessageDialog(
+ null,
+ "Error processing request: " + e.getMessage(),
+ "Error",
+ JOptionPane.ERROR_MESSAGE);
+ } finally {
+ isFinished = true;
+ paraphrasingPanel.showLoadingAnimation(false);
+ paraphrasingPanel.enableButtons(true);
+ paraphrasingPanel.setThreadInProgress(false);
+ }
+ }
+
+ // Setter- und Getter für das Ergebnis des LLM
+
+ public void setText(String output) {
+ this.text = output;
+ }
+
+ public String getText() {
+ return this.text;
+ }
+}
diff --git a/WoPeD-Starter/pom.xml b/WoPeD-Starter/pom.xml
index d4b8021cd..7ce97a099 100644
--- a/WoPeD-Starter/pom.xml
+++ b/WoPeD-Starter/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
@@ -37,6 +37,7 @@
maven-antrun-plugin
+ 1.8
sh.tak.appbundler
diff --git a/WoPeD-Starter/src/main/java/org/woped/starter/MainFrame.java b/WoPeD-Starter/src/main/java/org/woped/starter/MainFrame.java
index 5268c2b57..c3154020d 100644
--- a/WoPeD-Starter/src/main/java/org/woped/starter/MainFrame.java
+++ b/WoPeD-Starter/src/main/java/org/woped/starter/MainFrame.java
@@ -1196,6 +1196,7 @@ private JRibbonBand getP2TBand() {
return p2tBand;
}
+
private JRibbonBand getWindowsBand() {
if (windowsBand == null) {
diff --git a/WoPeD-Starter/src/main/java/org/woped/starter/controller/vep/GUIViewEventProcessor.java b/WoPeD-Starter/src/main/java/org/woped/starter/controller/vep/GUIViewEventProcessor.java
index 263bcdca6..5c873d271 100644
--- a/WoPeD-Starter/src/main/java/org/woped/starter/controller/vep/GUIViewEventProcessor.java
+++ b/WoPeD-Starter/src/main/java/org/woped/starter/controller/vep/GUIViewEventProcessor.java
@@ -30,6 +30,7 @@
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
+
import org.woped.core.config.ConfigurationManager;
import org.woped.core.controller.AbstractEventProcessor;
import org.woped.core.controller.AbstractViewEvent;
@@ -41,11 +42,14 @@
import org.woped.core.model.petrinet.SubProcessModel;
import org.woped.core.utilities.FileFilterImpl;
import org.woped.core.utilities.LoggerManager;
+import org.woped.editor.action.WoPeDAction;
+import org.woped.editor.controller.ActionFactory;
import org.woped.editor.controller.VisualController;
import org.woped.editor.controller.vc.EditorVC;
import org.woped.editor.controller.vc.SubprocessEditorVC;
import org.woped.editor.help.HelpBrowser;
import org.woped.editor.help.action.LaunchDefaultBrowserAction;
+import org.woped.file.p2t.P2TUI;
import org.woped.file.t2p.T2PUI;
import org.woped.gui.translations.Messages;
import org.woped.qualanalysis.service.IQualanalysisService;
@@ -60,360 +64,386 @@
* @author Simon Landes
*/
public class GUIViewEventProcessor extends AbstractEventProcessor {
- public GUIViewEventProcessor(DefaultApplicationMediator mediator) {
- super(mediator);
- }
-
- public void processViewEvent(AbstractViewEvent event) {
- IEditor editor;
- if (event.getSource() instanceof EditorVC) {
- editor = (EditorVC) event.getSource();
- } else {
- editor = getMediator().getUi().getEditorFocus();
+ public GUIViewEventProcessor(DefaultApplicationMediator mediator) {
+ super(mediator);
}
- switch (event.getOrder()) {
- case AbstractViewEvent.T2P:
- T2PUI t2p;
- if (getMediator().getUi() != null
- && getMediator().getUi().getComponent() instanceof JFrame) {
- t2p = new T2PUI((JFrame) getMediator().getUi(), getMediator());
- } else {
- t2p = new T2PUI(getMediator());
- }
- t2p.setVisible(true);
- break;
- case AbstractViewEvent.NEW:
- getMediator().createEditor(true);
- break;
- case AbstractViewEvent.OPEN_SUBPROCESS:
+
+ public void processViewEvent(AbstractViewEvent event) {
+ IEditor editor;
if (event.getSource() instanceof EditorVC) {
- editor = (EditorVC) event.getSource();
+ editor = (EditorVC) event.getSource();
} else {
- editor = getMediator().getUi().getEditorFocus();
+ editor = getMediator().getUi().getEditorFocus();
}
- Object cell = editor.getGraph().getSelectionCell();
- if (cell instanceof GroupModel) {
-
- cell = ((GroupModel) cell).getMainElement();
- if (cell instanceof SubProcessModel) {
- SubProcessModel model = (SubProcessModel) cell;
-
- IEditor subEditor = getMediator().createSubprocessEditor(true, editor, model);
- // rotate of sub process like main process
- if (editor.isRotateSelected() != model.getDirection()) {
- subEditor.rotateLayout();
- model.setDirection(editor.isRotateSelected());
- }
- }
- }
- break;
+ switch (event.getOrder()) {
+ case AbstractViewEvent.T2P:
+ T2PUI t2p;
+ if (getMediator().getUi() != null
+ && getMediator().getUi().getComponent() instanceof JFrame) {
+ t2p = new T2PUI((JFrame) getMediator().getUi(), getMediator());
+ } else {
+ t2p = new T2PUI(getMediator());
+ }
+ t2p.setVisible(true);
+ break;
+ case AbstractViewEvent.P2T:
+ P2TUI p2t;
+ if (getMediator().getUi() != null
+ && getMediator().getUi().getComponent() instanceof JFrame) {
+ {
+ p2t = new P2TUI((JFrame) getMediator().getUi(), getMediator());
+ }
+ } else {
+ p2t = new P2TUI(getMediator());
+ }
+ if (ConfigurationManager.getConfiguration().getGptShowAgain()) {
+ p2t.setVisible(true);
+ }
+ if (!ConfigurationManager.getConfiguration().getGptShowAgain()) {
+ if (ConfigurationManager.getConfiguration().getGptUseNew()) {
+ WoPeDAction action = ActionFactory.getStaticAction(ActionFactory.ACTIONID_P2T_OLD);
+ action.actionPerformed(
+ new ViewEvent(this, AbstractViewEvent.VIEWEVENTTYPE_GUI, AbstractViewEvent.P2T, null));
+ }
+ if (!ConfigurationManager.getConfiguration().getGptUseNew()) {
+ WoPeDAction action = ActionFactory.getStaticAction(ActionFactory.ACTIONID_P2T_OLD);
+ action.actionPerformed(
+ new ViewEvent(this, AbstractViewEvent.VIEWEVENTTYPE_GUI, AbstractViewEvent.P2T, null));
+ }
+ }
+ break;
+ case AbstractViewEvent.NEW:
+ getMediator().createEditor(true);
+ break;
+ case AbstractViewEvent.OPEN_SUBPROCESS:
+ if (event.getSource() instanceof EditorVC) {
+ editor = (EditorVC) event.getSource();
+ } else {
+ editor = getMediator().getUi().getEditorFocus();
+ }
+ Object cell = editor.getGraph().getSelectionCell();
+ if (cell instanceof GroupModel) {
- case AbstractViewEvent.SELECT_EDITOR:
- selectEditor(editor);
- break;
+ cell = ((GroupModel) cell).getMainElement();
+ if (cell instanceof SubProcessModel) {
+ SubProcessModel model = (SubProcessModel) cell;
- case AbstractViewEvent.INCONIFY_EDITOR:
- getMediator().getUi().hideEditor(editor);
- VisualController.getInstance()
- .propertyChange(new PropertyChangeEvent(this, "InternalFrameCount", null, editor));
- break;
- case AbstractViewEvent.CLOSE:
- closeEditor(editor);
- break;
- case AbstractViewEvent.ABOUT:
- AboutUI about;
- if (getMediator().getUi() != null
- && getMediator().getUi().getComponent() instanceof JFrame) {
- about = new AboutUI((JFrame) getMediator().getUi());
- } else {
- about = new AboutUI();
- }
- about.setVisible(true);
- break;
-
- case AbstractViewEvent.BUGREPORT:
- BugReportUI bugReport;
- if (getMediator().getUi() != null
- && getMediator().getUi().getComponent() instanceof JFrame) {
- bugReport = new BugReportUI((JFrame) getMediator().getUi());
- } else {
- bugReport = new BugReportUI();
- }
- bugReport.setVisible(true);
- break;
-
- case AbstractViewEvent.HELP:
- try {
- showHelpPage((String) event.getData());
- } catch (Exception e) {
- LoggerManager.error(
- Constants.GUI_LOGGER,
- "Cannot find HTML manual files in " + event.getData() + "." + e.getMessage());
- JOptionPane.showMessageDialog(
- getMediator().getUi().getComponent(),
- Messages.getString("Help.Message.HTMLManualFileNotFound") + " in " + event.getData(),
- Messages.getString("Help.Message.notFound"),
- JOptionPane.ERROR_MESSAGE);
- }
- break;
- case AbstractViewEvent.HELP_CONTENTS:
- try {
- showHelpContents();
- } catch (Exception e) {
- LoggerManager.error(
- Constants.GUI_LOGGER, "Cannot find HTML contents file. " + e.getMessage());
- JOptionPane.showMessageDialog(
- getMediator().getUi().getComponent(),
- Messages.getString("Help.Message.HTMLManualFileNotFound"),
- Messages.getString("Help.Message.notFound"),
- JOptionPane.ERROR_MESSAGE);
+ IEditor subEditor = getMediator().createSubprocessEditor(true, editor, model);
+ // rotate of sub process like main process
+ if (editor.isRotateSelected() != model.getDirection()) {
+ subEditor.rotateLayout();
+ model.setDirection(editor.isRotateSelected());
+ }
+ }
+ }
+ break;
+
+ case AbstractViewEvent.SELECT_EDITOR:
+ selectEditor(editor);
+ break;
+
+ case AbstractViewEvent.INCONIFY_EDITOR:
+ getMediator().getUi().hideEditor(editor);
+ VisualController.getInstance()
+ .propertyChange(new PropertyChangeEvent(this, "InternalFrameCount", null, editor));
+ break;
+ case AbstractViewEvent.CLOSE:
+ closeEditor(editor);
+ break;
+ case AbstractViewEvent.ABOUT:
+ AboutUI about;
+ if (getMediator().getUi() != null
+ && getMediator().getUi().getComponent() instanceof JFrame) {
+ about = new AboutUI((JFrame) getMediator().getUi());
+ } else {
+ about = new AboutUI();
+ }
+ about.setVisible(true);
+ break;
+
+ case AbstractViewEvent.BUGREPORT:
+ BugReportUI bugReport;
+ if (getMediator().getUi() != null
+ && getMediator().getUi().getComponent() instanceof JFrame) {
+ bugReport = new BugReportUI((JFrame) getMediator().getUi());
+ } else {
+ bugReport = new BugReportUI();
+ }
+ bugReport.setVisible(true);
+ break;
+
+ case AbstractViewEvent.HELP:
+ try {
+ showHelpPage((String) event.getData());
+ } catch (Exception e) {
+ LoggerManager.error(
+ Constants.GUI_LOGGER,
+ "Cannot find HTML manual files in " + event.getData() + "." + e.getMessage());
+ JOptionPane.showMessageDialog(
+ getMediator().getUi().getComponent(),
+ Messages.getString("Help.Message.HTMLManualFileNotFound") + " in " + event.getData(),
+ Messages.getString("Help.Message.notFound"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ break;
+ case AbstractViewEvent.HELP_CONTENTS:
+ try {
+ showHelpContents();
+ } catch (Exception e) {
+ LoggerManager.error(
+ Constants.GUI_LOGGER, "Cannot find HTML contents file. " + e.getMessage());
+ JOptionPane.showMessageDialog(
+ getMediator().getUi().getComponent(),
+ Messages.getString("Help.Message.HTMLManualFileNotFound"),
+ Messages.getString("Help.Message.notFound"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ break;
+
+ case AbstractViewEvent.UPDATE:
+ break;
+ case AbstractViewEvent.EXIT:
+ quit();
+ break;
+ case AbstractViewEvent.ZOOMED:
+ break;
+ case AbstractViewEvent.FACEBOOK:
+ new LaunchDefaultBrowserAction(Messages.getString("Community.Facebook.link"), null)
+ .displayURL();
+ break;
+ case AbstractViewEvent.TWITTER:
+ new LaunchDefaultBrowserAction(Messages.getString("Community.Twitter.link"), null)
+ .displayURL();
+ break;
+ case AbstractViewEvent.GOOGLEPLUS:
+ //noinspection SpellCheckingInspection
+ new LaunchDefaultBrowserAction(Messages.getString("Community.Googleplus.link"), null)
+ .displayURL();
+ break;
+ case AbstractViewEvent.COMMUNITY:
+ new LaunchDefaultBrowserAction(Messages.getString("Community.Community.link"), null)
+ .displayURL();
+ break;
+ case AbstractViewEvent.REGISTER:
+ new RegistrationUI((JFrame) getMediator().getUi(), false);
+ break;
}
- break;
-
- case AbstractViewEvent.UPDATE:
- break;
- case AbstractViewEvent.EXIT:
- quit();
- break;
- case AbstractViewEvent.ZOOMED:
- break;
- case AbstractViewEvent.FACEBOOK:
- new LaunchDefaultBrowserAction(Messages.getString("Community.Facebook.link"), null)
- .displayURL();
- break;
- case AbstractViewEvent.TWITTER:
- new LaunchDefaultBrowserAction(Messages.getString("Community.Twitter.link"), null)
- .displayURL();
- break;
- case AbstractViewEvent.GOOGLEPLUS:
- //noinspection SpellCheckingInspection
- new LaunchDefaultBrowserAction(Messages.getString("Community.Googleplus.link"), null)
- .displayURL();
- break;
- case AbstractViewEvent.COMMUNITY:
- new LaunchDefaultBrowserAction(Messages.getString("Community.Community.link"), null)
- .displayURL();
- break;
- case AbstractViewEvent.REGISTER:
- new RegistrationUI((JFrame) getMediator().getUi(), false);
- break;
- }
- }
-
- private void quit() {
- Vector editorList = new Vector<>(getMediator().getUi().getAllEditors());
- boolean canceled = false;
- for (IEditor editor : editorList) {
- processViewEvent(
- new ViewEvent(editor, AbstractViewEvent.VIEWEVENTTYPE_GUI, AbstractViewEvent.CLOSE));
- if (getMediator().getUi().getAllEditors().contains(editor)) {
- canceled = true;
- break;
- }
- }
- if (!canceled) {
- // If window is maximized don't store the current size, since that
- // would lead to strange results when later leaving the maximised state
- // such as too large windows and negative positions
- ConfigurationManager.getConfiguration()
- .setMaximizeWindow(getMediator().getUi().isMaximized());
- if (!getMediator().getUi().isMaximized()) {
- ConfigurationManager.getConfiguration().setWindowX(getMediator().getUi().getX());
- ConfigurationManager.getConfiguration().setWindowY(getMediator().getUi().getY());
- ConfigurationManager.getConfiguration().setWindowSize(getMediator().getUi().getSize());
- }
- ConfigurationManager.getConfiguration().saveConfig();
- try {
- LoggerManager.info(Constants.GUI_LOGGER, "EXIT WoPeD");
- System.exit(0);
- } catch (AccessControlException ace) {
- getMediator().getUi().setVisible(false);
- }
- } else {
- LoggerManager.debug(Constants.GUI_LOGGER, "User has canceled quit-operation.");
- }
- }
-
- private void selectEditor(IEditor editor) {
- ((EditorVC) editor).getEditorPanel().getContainer().setVisible(true);
- if (((EditorVC) editor).getEditorPanel().getContainer() instanceof JInternalFrame) {
- try {
- ((JInternalFrame) ((EditorVC) editor).getEditorPanel().getContainer()).setIcon(false);
- } catch (PropertyVetoException e) {
- //noinspection SpellCheckingInspection
- LoggerManager.warn(Constants.GUI_LOGGER, "Could not deiconify the editor");
- }
}
- VisualController.getInstance()
- .propertyChange(new PropertyChangeEvent(this, "FrameSelection", null, editor));
- // notify the editor aware vc
- for (Object o : getMediator().getEditorAwareVCs()) {
- ((IEditorAware) o).selectEditor(editor);
- }
- }
-
- /**
- * Close the Editor... will start the the save procedure if necessary.
- *
- * @param editor the editor to close
- * @return returns if editor could be close or not.
- */
- private boolean closeEditor(IEditor editor) {
- boolean closeEditor = false;
- if (editor instanceof EditorVC) {
- EditorVC editorVC = (EditorVC) editor;
- if ((editor instanceof SubprocessEditorVC) && !editorVC.isTokenGameEnabled()) {
-
- @SuppressWarnings("SpellCheckingInspection")
- IQualanalysisService qualanService =
- QualAnalysisServiceFactory.createNewQualAnalysisService(editor);
-
- String inputID = ((SubprocessEditorVC) editor).getSubprocessInput().getId();
- String outputID = editor.getId();
-
- // Try to get the first source place of the model as well as the
- // first sink place
- // Note that there is a chance neither a source nor a sink actually exist
- // so we need to check whether the iterator is valid!!
- String ainputID = null;
- String aoutputID = null;
- Iterator i = qualanService.getSinkPlaces().iterator();
- if (i.hasNext()) {
- ainputID = i.next().getId();
+
+ private void quit() {
+ Vector editorList = new Vector<>(getMediator().getUi().getAllEditors());
+ boolean canceled = false;
+ for (IEditor editor : editorList) {
+ processViewEvent(
+ new ViewEvent(editor, AbstractViewEvent.VIEWEVENTTYPE_GUI, AbstractViewEvent.CLOSE));
+ if (getMediator().getUi().getAllEditors().contains(editor)) {
+ canceled = true;
+ break;
+ }
}
- i = qualanService.getSourcePlaces().iterator();
- if (i.hasNext()) aoutputID = i.next().getId();
-
- if (qualanService.getNotStronglyConnectedNodes().size() > 0
- || qualanService.getSinkPlaces().size() > 1
- || qualanService.getSourcePlaces().size() > 1
- || inputID.equals(ainputID)
- || outputID.equals(aoutputID)) {
- String errorMessage =
- Messages.getString(
- "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Start");
-
- if (qualanService.getNotStronglyConnectedNodes().size() > 0) {
- errorMessage +=
- Messages.getString(
- "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.StronglyConnected");
- }
- if (qualanService.getSourcePlaces().size() > 1) {
- errorMessage +=
- Messages.getString(
- "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Source");
- } else {
- if (inputID.equals(ainputID)) {
- errorMessage +=
- Messages.getString(
- "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Input");
+ if (!canceled) {
+ // If window is maximized don't store the current size, since that
+ // would lead to strange results when later leaving the maximised state
+ // such as too large windows and negative positions
+ ConfigurationManager.getConfiguration()
+ .setMaximizeWindow(getMediator().getUi().isMaximized());
+ if (!getMediator().getUi().isMaximized()) {
+ ConfigurationManager.getConfiguration().setWindowX(getMediator().getUi().getX());
+ ConfigurationManager.getConfiguration().setWindowY(getMediator().getUi().getY());
+ ConfigurationManager.getConfiguration().setWindowSize(getMediator().getUi().getSize());
}
- }
-
- if (qualanService.getSinkPlaces().size() > 1) {
- errorMessage +=
- Messages.getString(
- "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Sink");
- } else {
- if (outputID.equals(aoutputID)) {
- errorMessage +=
- Messages.getString(
- "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Output");
+ ConfigurationManager.getConfiguration().saveConfig();
+ try {
+ LoggerManager.info(Constants.GUI_LOGGER, "EXIT WoPeD");
+ System.exit(0);
+ } catch (AccessControlException ace) {
+ getMediator().getUi().setVisible(false);
}
- }
-
- errorMessage +=
- Messages.getString(
- "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.End");
-
- String textMessages[] = {
- Messages.getString("Dialog.Yes"), Messages.getString("Dialog.No")
- };
-
- int value =
- JOptionPane.showOptionDialog(
- editorVC.getEditorPanel(),
- errorMessage,
- Messages.getString("Action.CloseSubProcessEditor.StructuralAnalysisResult.Title"),
- JOptionPane.YES_NO_OPTION,
- JOptionPane.WARNING_MESSAGE,
- null,
- textMessages,
- textMessages[0]);
-
- if (value == JOptionPane.YES_OPTION) {
- closeEditor = true;
- }
-
} else {
- closeEditor = true;
+ LoggerManager.debug(Constants.GUI_LOGGER, "User has canceled quit-operation.");
+ }
+ }
+
+ private void selectEditor(IEditor editor) {
+ ((EditorVC) editor).getEditorPanel().getContainer().setVisible(true);
+ if (((EditorVC) editor).getEditorPanel().getContainer() instanceof JInternalFrame) {
+ try {
+ ((JInternalFrame) ((EditorVC) editor).getEditorPanel().getContainer()).setIcon(false);
+ } catch (PropertyVetoException e) {
+ //noinspection SpellCheckingInspection
+ LoggerManager.warn(Constants.GUI_LOGGER, "Could not deiconify the editor");
+ }
+ }
+ VisualController.getInstance()
+ .propertyChange(new PropertyChangeEvent(this, "FrameSelection", null, editor));
+ // notify the editor aware vc
+ for (Object o : getMediator().getEditorAwareVCs()) {
+ ((IEditorAware) o).selectEditor(editor);
}
- } else if (editorVC.isSubprocessEditor() && editorVC.isTokenGameEnabled()) {
- closeEditor = true;
- } else {
- if (!editorVC.isSaved()) {
- // Check sample net
- if (editorVC.getDefaultFileType() != FileFilterImpl.SAMPLEFilter) {
- String args[] = {editorVC.getName()};
-
- String textMessages[] = {
- Messages.getString("Dialog.Yes"),
- Messages.getString("Dialog.No"),
- Messages.getString("Dialog.Cancel")
- };
-
- int value =
- JOptionPane.showOptionDialog(
- editorVC.getEditorPanel(),
- Messages.getStringReplaced("Action.Confirm.File.Save.Text", args),
- Messages.getString("Action.Confirm.File.Save.Title"),
- JOptionPane.YES_NO_CANCEL_OPTION,
- JOptionPane.ERROR_MESSAGE,
- null,
- textMessages,
- textMessages[0]);
-
- if (value == (JOptionPane.YES_OPTION)) {
- // try to save
- getMediator()
- .processViewEvent(
- new ViewEvent(
- editor, AbstractViewEvent.VIEWEVENTTYPE_FILE, AbstractViewEvent.SAVE));
- closeEditor = editorVC.isSaved();
- } else if (value == JOptionPane.NO_OPTION) {
- closeEditor = true;
- } else if (value == JOptionPane.CANCEL_OPTION) {
- closeEditor = false;
+ }
+
+ /**
+ * Close the Editor... will start the the save procedure if necessary.
+ *
+ * @param editor the editor to close
+ * @return returns if editor could be close or not.
+ */
+ private boolean closeEditor(IEditor editor) {
+ boolean closeEditor = false;
+ if (editor instanceof EditorVC) {
+ EditorVC editorVC = (EditorVC) editor;
+ if ((editor instanceof SubprocessEditorVC) && !editorVC.isTokenGameEnabled()) {
+
+ @SuppressWarnings("SpellCheckingInspection")
+ IQualanalysisService qualanService =
+ QualAnalysisServiceFactory.createNewQualAnalysisService(editor);
+
+ String inputID = ((SubprocessEditorVC) editor).getSubprocessInput().getId();
+ String outputID = editor.getId();
+
+ // Try to get the first source place of the model as well as the
+ // first sink place
+ // Note that there is a chance neither a source nor a sink actually exist
+ // so we need to check whether the iterator is valid!!
+ String ainputID = null;
+ String aoutputID = null;
+ Iterator i = qualanService.getSinkPlaces().iterator();
+ if (i.hasNext()) {
+ ainputID = i.next().getId();
+ }
+ i = qualanService.getSourcePlaces().iterator();
+ if (i.hasNext()) aoutputID = i.next().getId();
+
+ if (qualanService.getNotStronglyConnectedNodes().size() > 0
+ || qualanService.getSinkPlaces().size() > 1
+ || qualanService.getSourcePlaces().size() > 1
+ || inputID.equals(ainputID)
+ || outputID.equals(aoutputID)) {
+ String errorMessage =
+ Messages.getString(
+ "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Start");
+
+ if (qualanService.getNotStronglyConnectedNodes().size() > 0) {
+ errorMessage +=
+ Messages.getString(
+ "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.StronglyConnected");
+ }
+ if (qualanService.getSourcePlaces().size() > 1) {
+ errorMessage +=
+ Messages.getString(
+ "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Source");
+ } else {
+ if (inputID.equals(ainputID)) {
+ errorMessage +=
+ Messages.getString(
+ "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Input");
+ }
+ }
+
+ if (qualanService.getSinkPlaces().size() > 1) {
+ errorMessage +=
+ Messages.getString(
+ "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Sink");
+ } else {
+ if (outputID.equals(aoutputID)) {
+ errorMessage +=
+ Messages.getString(
+ "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.Output");
+ }
+ }
+
+ errorMessage +=
+ Messages.getString(
+ "Action.CloseSubProcessEditor.StructuralAnalysisResult.Message.End");
+
+ String textMessages[] = {
+ Messages.getString("Dialog.Yes"), Messages.getString("Dialog.No")
+ };
+
+ int value =
+ JOptionPane.showOptionDialog(
+ editorVC.getEditorPanel(),
+ errorMessage,
+ Messages.getString("Action.CloseSubProcessEditor.StructuralAnalysisResult.Title"),
+ JOptionPane.YES_NO_OPTION,
+ JOptionPane.WARNING_MESSAGE,
+ null,
+ textMessages,
+ textMessages[0]);
+
+ if (value == JOptionPane.YES_OPTION) {
+ closeEditor = true;
+ }
+
+ } else {
+ closeEditor = true;
+ }
+ } else if (editorVC.isSubprocessEditor() && editorVC.isTokenGameEnabled()) {
+ closeEditor = true;
+ } else {
+ if (!editorVC.isSaved()) {
+ // Check sample net
+ if (editorVC.getDefaultFileType() != FileFilterImpl.SAMPLEFilter) {
+ String args[] = {editorVC.getName()};
+
+ String textMessages[] = {
+ Messages.getString("Dialog.Yes"),
+ Messages.getString("Dialog.No"),
+ Messages.getString("Dialog.Cancel")
+ };
+
+ int value =
+ JOptionPane.showOptionDialog(
+ editorVC.getEditorPanel(),
+ Messages.getStringReplaced("Action.Confirm.File.Save.Text", args),
+ Messages.getString("Action.Confirm.File.Save.Title"),
+ JOptionPane.YES_NO_CANCEL_OPTION,
+ JOptionPane.ERROR_MESSAGE,
+ null,
+ textMessages,
+ textMessages[0]);
+
+ if (value == (JOptionPane.YES_OPTION)) {
+ // try to save
+ getMediator()
+ .processViewEvent(
+ new ViewEvent(
+ editor, AbstractViewEvent.VIEWEVENTTYPE_FILE, AbstractViewEvent.SAVE));
+ closeEditor = editorVC.isSaved();
+ } else if (value == JOptionPane.NO_OPTION) {
+ closeEditor = true;
+ } else if (value == JOptionPane.CANCEL_OPTION) {
+ closeEditor = false;
+ }
+
+ } else {
+ closeEditor = true;
+ }
+ } else {
+ closeEditor = true;
+ }
}
+ }
- } else {
- closeEditor = true;
- }
- } else {
- closeEditor = true;
+ if (closeEditor) {
+ getMediator().removeViewController(editor);
+ // notify the editor aware vc
+ for (Object o : getMediator().getEditorAwareVCs()) {
+ ((IEditorAware) o).removeEditor(editor);
+ }
+ VisualController.getInstance()
+ .propertyChange(new PropertyChangeEvent(this, "InternalFrameCount", null, editor));
}
- }
+ return closeEditor;
+ }
+
+ private void showHelpPage(String fileName) throws Exception {
+ HelpBrowser br = HelpBrowser.getInstance();
+ br.showURL(fileName);
}
- if (closeEditor) {
- getMediator().removeViewController(editor);
- // notify the editor aware vc
- for (Object o : getMediator().getEditorAwareVCs()) {
- ((IEditorAware) o).removeEditor(editor);
- }
- VisualController.getInstance()
- .propertyChange(new PropertyChangeEvent(this, "InternalFrameCount", null, editor));
+ private void showHelpContents() throws Exception {
+ HelpBrowser br = HelpBrowser.getInstance();
+ br.showURL(Messages.getString("Help.File.Contents"));
}
- return closeEditor;
- }
-
- private void showHelpPage(String fileName) throws Exception {
- HelpBrowser br = HelpBrowser.getInstance();
- br.showURL(fileName);
- }
-
- private void showHelpContents() throws Exception {
- HelpBrowser br = HelpBrowser.getInstance();
- br.showURL(Messages.getString("Help.File.Contents"));
- }
}