diff --git a/WoPeD-BeanConfiguration/src/main/java/org/woped/beanconfiguration/configuration.xsd b/WoPeD-BeanConfiguration/src/main/java/org/woped/beanconfiguration/configuration.xsd index 69d3d29b1..8e6b0de4d 100644 --- a/WoPeD-BeanConfiguration/src/main/java/org/woped/beanconfiguration/configuration.xsd +++ b/WoPeD-BeanConfiguration/src/main/java/org/woped/beanconfiguration/configuration.xsd @@ -3,17 +3,18 @@ - - - - - - - - - - - + + + + + + + + + + + + @@ -101,22 +102,22 @@ - + - - - - - - - - - - + + + + + + + + + + @@ -136,6 +137,17 @@ + + + + + + + + + + + @@ -191,20 +203,20 @@ - - - - - - + + + + + + - - - - + + + + diff --git a/WoPeD-CommonLibs/pom.xml b/WoPeD-CommonLibs/pom.xml index 863931064..f234d7d5f 100644 --- a/WoPeD-CommonLibs/pom.xml +++ b/WoPeD-CommonLibs/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 @@ -21,6 +21,13 @@ + + de.dhbw.woped + jgraph + 5.10.2 + system + ${project.basedir}/lib/jgraph-5.10.2.jar + de.dhbw.woped jgraph diff --git a/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDGeneralConfiguration.java b/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDGeneralConfiguration.java index be4155f94..b8011d14f 100644 --- a/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDGeneralConfiguration.java +++ b/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDGeneralConfiguration.java @@ -78,6 +78,9 @@ public boolean initConfig() { if (getConfDocument().getConfiguration().getMetrics() == null) getConfDocument().getConfiguration().addNewMetrics(); + if(getConfDocument().getConfiguration().getGpt() == null) + getConfDocument().getConfiguration().addNewGpt(); + // Check if metrics configuration should be loaded // and react accordingly if (getConfDocument().getConfiguration().getMetrics().getUseMetrics()) { @@ -1475,6 +1478,64 @@ public String getText2ProcessServerURI() { return getConfDocument().getConfiguration().getT2P().getT2PServerURI(); } else return ConfigurationManager.getStandardConfiguration().getText2ProcessServerURI(); } + @Override + public String getGptApiKey() { + if(getConfDocument().getConfiguration().getGpt().isSetGptApiKey()){ + return getConfDocument().getConfiguration().getGpt().getGptApiKey(); + }else return ConfigurationManager.getStandardConfiguration().getGptApiKey(); + } + + @Override + public void setGptApiKey(String apiKey) { + getConfDocument().getConfiguration().getGpt().setGptApiKey(apiKey); + } + + public String getGptModel(){ + if(getConfDocument().getConfiguration().getGpt().isSetGptModel()){ + return getConfDocument().getConfiguration().getGpt().getGptModel(); + } else return ConfigurationManager.getStandardConfiguration().getGptModel(); + } + + public void setGptModel(String model){ + getConfDocument().getConfiguration().getGpt().setGptModel(model); + } + + @Override + public boolean getGptShowAgain() { + if(getConfDocument().getConfiguration().getGpt().isSetGptShowAgain()){ + return getConfDocument().getConfiguration().getGpt().getGptShowAgain(); + }else return ConfigurationManager.getStandardConfiguration().getGptShowAgain(); + } + + @Override + public void setGptShowAgain(boolean showAgain) { + getConfDocument().getConfiguration().getGpt().setGptShowAgain(showAgain); + } + + @Override + public String getGptPrompt() { + if(getConfDocument().getConfiguration().getGpt().isSetGptPrompt()){ + return getConfDocument().getConfiguration().getGpt().getGptPrompt(); + }else return ConfigurationManager.getStandardConfiguration().getGptPrompt(); + } + + @Override + public void setGptPrompt(String prompt) { + getConfDocument().getConfiguration().getGpt().setGptPrompt(prompt); + } + + @Override + public void setGptUseNew(boolean useNew){ + getConfDocument().getConfiguration().getGpt().setGptUseNew(useNew); + } + + @Override + public boolean getGptUseNew(){ + if(getConfDocument().getConfiguration().getGpt().getGptUseNew()){ + return getConfDocument().getConfiguration().getGpt().getGptUseNew(); + } else return ConfigurationManager.getStandardConfiguration().getGptUseNew(); + } + @Override public void setText2ProcessServerURI(String uri) { @@ -1605,4 +1666,6 @@ public void setYAWLExportGroups(boolean exportGroups) { .getExporting() .setYawlExportGroups(exportGroups); } + + } diff --git a/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDconfig.xml b/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDconfig.xml index 2665ed121..6f6b836ba 100644 --- a/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDconfig.xml +++ b/WoPeD-Configuration/src/main/java/org/woped/config/general/WoPeDconfig.xml @@ -116,4 +116,10 @@ 8081 /t2p + + test + test + true + + diff --git a/WoPeD-Core/src/main/java/org/woped/core/config/ConfigurationManager.java b/WoPeD-Core/src/main/java/org/woped/core/config/ConfigurationManager.java index 90091d32a..d32a84e2d 100644 --- a/WoPeD-Core/src/main/java/org/woped/core/config/ConfigurationManager.java +++ b/WoPeD-Core/src/main/java/org/woped/core/config/ConfigurationManager.java @@ -33,4 +33,5 @@ public static boolean hasNonStaticMetricsConfiguration() { if (metricsConfiguration != null) return true; else return false; } + } diff --git a/WoPeD-Core/src/main/java/org/woped/core/config/DefaultStaticConfiguration.java b/WoPeD-Core/src/main/java/org/woped/core/config/DefaultStaticConfiguration.java index 88bb24c59..132147e78 100644 --- a/WoPeD-Core/src/main/java/org/woped/core/config/DefaultStaticConfiguration.java +++ b/WoPeD-Core/src/main/java/org/woped/core/config/DefaultStaticConfiguration.java @@ -12,7 +12,7 @@ /** * Class that provides fallback configuration settings for the general WoPeD configuration part * - * @author Philip Allgaier + * @autor Philip Allgaier */ @SuppressWarnings("JavadocReference") public class DefaultStaticConfiguration implements IGeneralConfiguration { @@ -190,6 +190,32 @@ public class DefaultStaticConfiguration implements IGeneralConfiguration { private boolean yawlExportGroups = false; + // GPT settings + private String gptApiKey = ""; + private boolean gptShowAgain = true; + private String gptPrompt = "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!"; + private boolean gptUseNew = false; + private String gptModel = null; + + public boolean isGptUseNew() { + return gptUseNew; + } + + public void setGptUseNew(boolean gptUseNew) { + this.gptUseNew = gptUseNew; + } + public boolean getGptUseNew(){ + return gptUseNew; + } + + public void setGptModel(String gptModel) { + this.gptModel = gptModel; + } + + public String getGptModel() { + return gptModel; + } + public DefaultStaticConfiguration() { initConfig(); } @@ -919,29 +945,29 @@ public ApromoreServer[] getApromoreServers() { @Override public void addApromoreServer( - int ID, - String name, - String url, - int port, - String path, - String user, - String pwd, - boolean useProxy, - String proxyUrl, - int proxyPort) {} + int ID, + String name, + String url, + int port, + String path, + String user, + String pwd, + boolean useProxy, + String proxyUrl, + int proxyPort) {} @Override public void changeApromoreServerSettings( - int ID, - String name, - String url, - int port, - String path, - String user, - String pwd, - boolean useProxy, - String proxyUrl, - int proxyPort) {} + int ID, + String name, + String url, + int port, + String path, + String user, + String pwd, + boolean useProxy, + String proxyUrl, + int proxyPort) {} @Override public void removeApromoreServer(int index) {} @@ -1083,4 +1109,35 @@ public boolean isYAWLExportGroups() { public void setYAWLExportGroups(boolean exportGroups) { this.yawlExportGroups = exportGroups; } + + // GPT settings + @Override + public String getGptApiKey() { + return gptApiKey; + } + + @Override + public void setGptApiKey(String apiKey) { + this.gptApiKey = apiKey; + } + + @Override + public boolean getGptShowAgain() { + return gptShowAgain; + } + + @Override + public void setGptShowAgain(boolean showAgain) { + this.gptShowAgain = showAgain; + } + + @Override + public String getGptPrompt() { + return gptPrompt; + } + + @Override + public void setGptPrompt(String prompt) { + this.gptPrompt = prompt; + } } diff --git a/WoPeD-Core/src/main/java/org/woped/core/config/IGeneralConfiguration.java b/WoPeD-Core/src/main/java/org/woped/core/config/IGeneralConfiguration.java index 122d25dd7..b0821c8b6 100644 --- a/WoPeD-Core/src/main/java/org/woped/core/config/IGeneralConfiguration.java +++ b/WoPeD-Core/src/main/java/org/woped/core/config/IGeneralConfiguration.java @@ -478,28 +478,28 @@ public interface IGeneralConfiguration extends IConfiguration { public ApromoreServer[] getApromoreServers(); public void addApromoreServer( - int ID, - String name, - String url, - int port, - String path, - String user, - String pwd, - boolean useProxy, - String proxyUrl, - int proxyPort); + int ID, + String name, + String url, + int port, + String path, + String user, + String pwd, + boolean useProxy, + String proxyUrl, + int proxyPort); public void changeApromoreServerSettings( - int ID, - String name, - String url, - int port, - String path, - String user, - String pwd, - boolean useProxy, - String proxyUrl, - int proxyPort); + int ID, + String name, + String url, + int port, + String path, + String user, + String pwd, + boolean useProxy, + String proxyUrl, + int proxyPort); public void removeApromoreServer(int index); @@ -560,4 +560,25 @@ public void changeApromoreServerSettings( public boolean isYAWLExportGroups(); public void setYAWLExportGroups(boolean exportGroups); + + // GPT Settings + public String getGptApiKey(); + + public void setGptApiKey(String apiKey); + + public boolean getGptShowAgain(); + + public void setGptShowAgain(boolean showAgain); + + public String getGptPrompt(); + + public void setGptPrompt(String prompt); + + public void setGptUseNew(boolean useNew); + + public boolean getGptUseNew(); + + public void setGptModel(String model); + + public String getGptModel(); } diff --git a/WoPeD-Editor/pom.xml b/WoPeD-Editor/pom.xml index 9f6d682ee..bc244741e 100644 --- a/WoPeD-Editor/pom.xml +++ b/WoPeD-Editor/pom.xml @@ -26,6 +26,11 @@ jcalendar 1.3.2 + + com.googlecode.json-simple + json-simple + 1.1.1 + de.dhbw.woped WoPeD-CommonLibs diff --git a/WoPeD-Editor/src/main/java/org/woped/editor/controller/ActionFactory.java b/WoPeD-Editor/src/main/java/org/woped/editor/controller/ActionFactory.java index 47332f50e..7d01a5683 100644 --- a/WoPeD-Editor/src/main/java/org/woped/editor/controller/ActionFactory.java +++ b/WoPeD-Editor/src/main/java/org/woped/editor/controller/ActionFactory.java @@ -62,6 +62,9 @@ public class ActionFactory { public static final String ACTIONID_UPDATENETS = "Action.UpdateNets"; public static final String ACTIONID_P2T = "ToolBar.P2T"; + + public static final String ACTIONID_P2T_NEW = "Ausführen.Neu"; + public static final String ACTIONID_P2T_OLD = "Ausführen"; public static final String ACTIONID_T2P = "ToolBar.T2P"; public static final String ACTIONID_DRAWMODE_PLACE = "ToolBar.DrawPlace"; @@ -643,7 +646,7 @@ public static HashMap createStaticActions(ApplicationMediat STATIC_ACTION_MAP.put( ACTIONID_P2T, new WoPeDAction( - am, AbstractViewEvent.VIEWEVENTTYPE_EDIT, AbstractViewEvent.P2T, null, ACTIONID_P2T)); + am, AbstractViewEvent.VIEWEVENTTYPE_GUI, AbstractViewEvent.P2T, null, ACTIONID_P2T)); VisualController.getInstance() .addElement( STATIC_ACTION_MAP.get(ACTIONID_P2T), @@ -651,6 +654,29 @@ public static HashMap createStaticActions(ApplicationMediat VisualController.WITH_EDITOR, VisualController.P2T); + STATIC_ACTION_MAP.put( + ACTIONID_P2T_OLD, + new WoPeDAction( + am, AbstractViewEvent.VIEWEVENTTYPE_EDIT, AbstractViewEvent.P2T, null, ACTIONID_P2T_OLD)); + VisualController.getInstance() + .addElement( + STATIC_ACTION_MAP.get(ACTIONID_P2T_OLD), + VisualController.WITH_EDITOR, + VisualController.WITH_EDITOR, + VisualController.P2T); + + STATIC_ACTION_MAP.put( + ACTIONID_P2T_NEW, + new WoPeDAction( + am, AbstractViewEvent.VIEWEVENTTYPE_EDIT, AbstractViewEvent.P2T, null, ACTIONID_P2T_NEW)); + VisualController.getInstance() + .addElement( + STATIC_ACTION_MAP.get(ACTIONID_P2T_NEW), + VisualController.WITH_EDITOR, + VisualController.WITH_EDITOR, + VisualController.P2T); + + STATIC_ACTION_MAP.put( ACTIONID_T2P, new WoPeDAction( diff --git a/WoPeD-Editor/src/main/java/org/woped/editor/gui/config/ConfNLPToolsPanel.java b/WoPeD-Editor/src/main/java/org/woped/editor/gui/config/ConfNLPToolsPanel.java index bc47190fa..6626a6d2d 100644 --- a/WoPeD-Editor/src/main/java/org/woped/editor/gui/config/ConfNLPToolsPanel.java +++ b/WoPeD-Editor/src/main/java/org/woped/editor/gui/config/ConfNLPToolsPanel.java @@ -1,638 +1,758 @@ -/* - * - * Copyright (C) 2004-2005, see @author in JavaDoc for the author - * - * This library 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 2.1 of the License, or (at your option) any later version. - * - * This library 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 this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * - * For contact information please visit http://woped.dhbw-karlsruhe.de - * - */ package org.woped.editor.gui.config; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; +import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; -import java.net.MalformedURLException; +import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; -import javax.swing.BorderFactory; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTextField; +import java.util.List; +import javax.swing.*; + +import org.json.simple.parser.ParseException; import org.woped.core.config.ConfigurationManager; +import org.woped.editor.tools.ApiHelper; import org.woped.gui.lookAndFeel.WopedButton; import org.woped.gui.translations.Messages; -/** - * @author Simon Landes
- *
- * The ConfLanguagePanel is the AbstractConfPanel for the - * configuration of the language.
- * Created on: 26.11.2004 Last Change on: 14.11.2005 - */ -@SuppressWarnings("serial") public class ConfNLPToolsPanel extends AbstractConfPanel { - private JCheckBox useBox = null; - private JPanel enabledPanel = null; - private JPanel settingsPanel = null; - private JPanel settingsPanel_T2P = null; - - private JTextField serverURLText = null; - private JLabel serverURLLabel = null; - private JLabel serverPortLabel = null; - private JTextField serverPortText = null; - private JTextField managerPathText = null; - private JLabel managerPathLabel = null; - private WopedButton testButton = null; - private WopedButton defaultButton = null; - private JTextField serverURLText_T2P = null; - private JLabel serverURLLabel_T2P = null; - private JLabel serverPortLabel_T2P = null; - private JTextField serverPortText_T2P = null; - private JTextField managerPathText_T2P = null; - private JLabel managerPathLabel_T2P = null; - private WopedButton testButton_T2P = null; - private WopedButton defaultButton_T2P = null; - - /** Constructor for ConfToolsPanel. */ - public ConfNLPToolsPanel(String name) { - super(name); - initialize(); - } - - /** - * @see AbstractConfPanel#applyConfiguration() - */ - public boolean applyConfiguration() { - boolean newsetting = useBox.isSelected(); - boolean oldsetting = ConfigurationManager.getConfiguration().getProcess2TextUse(); - - if (newsetting != oldsetting) { - ConfigurationManager.getConfiguration().setProcess2TextUse(newsetting); - JOptionPane.showMessageDialog( - this, - Messages.getString("Configuration.P2T.Dialog.Restart.Message"), - Messages.getString("Configuration.P2T.Dialog.Restart.Title"), - JOptionPane.INFORMATION_MESSAGE); - } - ConfigurationManager.getConfiguration().setProcess2TextServerHost(getServerURLText().getText()); - ConfigurationManager.getConfiguration() - .setProcess2TextServerURI(getManagerPathText().getText()); - if (getServerPortText().getText().equals("")) { - ConfigurationManager.getConfiguration().setProcess2TextServerPort(0); - } else - ConfigurationManager.getConfiguration() - .setProcess2TextServerPort(Integer.parseInt(getServerPortText().getText())); - ConfigurationManager.getConfiguration().setProcess2TextUse(useBox.isSelected()); - - ConfigurationManager.getConfiguration() - .setText2ProcessServerHost(getServerURLText_T2P().getText()); - - ConfigurationManager.getConfiguration() - .setText2ProcessServerURI(getManagerPathText_T2P().getText()); - - if (getServerPortText_T2P().getText().equals("")) { - ConfigurationManager.getConfiguration().setText2ProcessServerPort(0); - } else - ConfigurationManager.getConfiguration() - .setText2ProcessServerPort(Integer.parseInt(getServerPortText_T2P().getText())); - - return true; - } - - /** - * @see AbstractConfPanel#readConfiguration() - */ - public void readConfiguration() { - - getServerURLText().setText(ConfigurationManager.getConfiguration().getProcess2TextServerHost()); - getManagerPathText() - .setText(ConfigurationManager.getConfiguration().getProcess2TextServerURI()); - getServerPortText() - .setText("" + ConfigurationManager.getConfiguration().getProcess2TextServerPort()); - getUseBox().setSelected(ConfigurationManager.getConfiguration().getProcess2TextUse()); - - getServerURLText_T2P() - .setText(ConfigurationManager.getConfiguration().getText2ProcessServerHost()); - getManagerPathText_T2P() - .setText(ConfigurationManager.getConfiguration().getText2ProcessServerURI()); - - getServerPortText_T2P() - .setText("" + ConfigurationManager.getConfiguration().getText2ProcessServerPort()); - } - - private void initialize() { - JPanel contentPanel = new JPanel(); - contentPanel.setLayout(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.NORTH; - c.fill = GridBagConstraints.HORIZONTAL; - - c.weightx = 1; - c.gridx = 0; - c.gridy = 0; - contentPanel.add(getEnabledPanel(), c); - - c.weightx = 1; - c.gridx = 0; - c.gridy = 1; - contentPanel.add(getSettingsPanel(), c); - - c.weightx = 1; - c.gridx = 0; - c.gridy = 3; - contentPanel.add(getSettingsPanel_T2P(), c); - - // dummy - c.fill = GridBagConstraints.VERTICAL; - c.weighty = 1; - c.gridy = 4; - contentPanel.add(new JPanel(), c); - - setMainPanel(contentPanel); - } - - // ################## GUI COMPONENTS #################### */ - - private JTextField getServerURLText() { - if (serverURLText == null) { - serverURLText = new JTextField(); - serverURLText.setColumns(40); - serverURLText.setEnabled(true); - serverURLText.setToolTipText( - "" + Messages.getString("Configuration.P2T.Label.ServerHost") + ""); - } - return serverURLText; - } - - private JTextField getServerURLText_T2P() { - if (serverURLText_T2P == null) { - serverURLText_T2P = new JTextField(); - serverURLText_T2P.setColumns(40); - serverURLText_T2P.setEnabled(true); - serverURLText_T2P.setToolTipText( - "" + Messages.getString("Configuration.T2P.Label.ServerHost") + ""); - } - return serverURLText_T2P; - } - - private JPanel getEnabledPanel() { - if (enabledPanel == null) { - enabledPanel = new JPanel(); - enabledPanel.setLayout(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.WEST; - - enabledPanel.setBorder( - BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder( - Messages.getTitle("Configuration.P2T.Enabled.Panel")), - BorderFactory.createEmptyBorder(10, 10, 10, 10))); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 0; - enabledPanel.add(getUseBox(), c); - } - return enabledPanel; - } - - private JPanel getSettingsPanel() { - if (settingsPanel == null) { - settingsPanel = new JPanel(); - settingsPanel.setLayout(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.WEST; - - settingsPanel.setBorder( - BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder( - Messages.getString("Configuration.P2T.Settings.Panel.Title")), - BorderFactory.createEmptyBorder(10, 10, 10, 10))); - c.weightx = 1; - c.gridx = 0; - c.gridy = 0; - settingsPanel.add(getServerURLLabel(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 0; - c.gridwidth = 2; - settingsPanel.add(getServerURLText(), c); - - c.weightx = 1; - c.gridx = 0; - c.gridy = 1; - c.gridwidth = 1; - settingsPanel.add(getServerPortLabel(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 1; - settingsPanel.add(getServerPortText(), c); - - c.weightx = 1; - c.gridx = 2; - c.gridy = 1; - settingsPanel.add(getTestButton(), c); - - c.weightx = 1; - c.gridx = 0; - c.gridy = 2; - settingsPanel.add(getManagerPathLabel(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 2; - c.gridwidth = 2; - settingsPanel.add(getManagerPathText(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 4; - settingsPanel.add(getDefaultButton(), c); - } - - settingsPanel.setVisible(getUseBox().isSelected()); - return settingsPanel; - } - - private JPanel getSettingsPanel_T2P() { - if (settingsPanel_T2P == null) { - settingsPanel_T2P = new JPanel(); - settingsPanel_T2P.setLayout(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.WEST; - - settingsPanel_T2P.setBorder( - BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder( - Messages.getString("Configuration.T2P.Settings.Panel.Title")), - BorderFactory.createEmptyBorder(10, 10, 10, 10))); - c.weightx = 1; - c.gridx = 0; - c.gridy = 0; - settingsPanel_T2P.add(getServerURLLabel_T2P(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 0; - c.gridwidth = 2; - settingsPanel_T2P.add(getServerURLText_T2P(), c); - - c.weightx = 1; - c.gridx = 0; - c.gridy = 1; - c.gridwidth = 1; - settingsPanel_T2P.add(getServerPortLabel_T2P(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 1; - settingsPanel_T2P.add(getServerPortText_T2P(), c); - - c.weightx = 1; - c.gridx = 2; - c.gridy = 1; - settingsPanel_T2P.add(getTestButton_T2P(), c); - - c.weightx = 1; - c.gridx = 0; - c.gridy = 2; - settingsPanel_T2P.add(getManagerPathLabel_T2P(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 2; - c.gridwidth = 2; - settingsPanel_T2P.add(getManagerPathText_T2P(), c); - - c.weightx = 1; - c.gridx = 1; - c.gridy = 4; - settingsPanel_T2P.add(getDefaultButton_T2P(), c); - } - - settingsPanel_T2P.setVisible(getUseBox_T2P().isSelected()); - return settingsPanel_T2P; - } - - class CheckboxListener implements ItemListener { - - public void itemStateChanged(ItemEvent ie) { - JCheckBox jcb = (JCheckBox) ie.getSource(); - if (jcb == useBox) { - getSettingsPanel().setVisible(jcb.isSelected()); - getSettingsPanel_T2P().setVisible(jcb.isSelected()); - } - } - } - - private JLabel getServerURLLabel() { - if (serverURLLabel == null) { - serverURLLabel = - new JLabel( - "" + Messages.getString("Configuration.P2T.Label.ServerHost") + ""); - serverURLLabel.setHorizontalAlignment(JLabel.RIGHT); - } - return serverURLLabel; - } - - private JLabel getServerURLLabel_T2P() { - if (serverURLLabel_T2P == null) { - serverURLLabel_T2P = - new JLabel( - "" + Messages.getString("Configuration.T2P.Label.ServerHost") + ""); - serverURLLabel_T2P.setHorizontalAlignment(JLabel.RIGHT); - } - return serverURLLabel_T2P; - } - - private JLabel getServerPortLabel() { - if (serverPortLabel == null) { - serverPortLabel = - new JLabel( - "" + Messages.getString("Configuration.P2T.Label.ServerPort") + ""); - serverPortLabel.setHorizontalAlignment(JLabel.RIGHT); - } - return serverPortLabel; - } - - private JLabel getServerPortLabel_T2P() { - if (serverPortLabel_T2P == null) { - serverPortLabel_T2P = - new JLabel( - "" + Messages.getString("Configuration.T2P.Label.ServerPort") + ""); - serverPortLabel_T2P.setHorizontalAlignment(JLabel.RIGHT); - } - return serverPortLabel_T2P; - } - - private JTextField getServerPortText() { - if (serverPortText == null) { - serverPortText = new JTextField(); - serverPortText.setColumns(4); - serverPortText.setEnabled(true); - serverPortText.setToolTipText( - "" + Messages.getString("Configuration.P2T.Label.ServerPort") + ""); - } - return serverPortText; - } - - private JTextField getServerPortText_T2P() { - if (serverPortText_T2P == null) { - serverPortText_T2P = new JTextField(); - serverPortText_T2P.setColumns(4); - serverPortText_T2P.setEnabled(true); - serverPortText_T2P.setToolTipText( - "" + Messages.getString("Configuration.T2P.Label.ServerPort") + ""); - } - return serverPortText_T2P; - } - - private JCheckBox getUseBox() { - if (useBox == null) { - useBox = new JCheckBox(Messages.getString("Configuration.P2T.Label.Use")); - useBox.setEnabled(true); - useBox.setToolTipText( - "" + Messages.getString("Configuration.P2T.Label.Use") + ""); - CheckboxListener cbl = new CheckboxListener(); - useBox.addItemListener(cbl); - } - - return useBox; - } - - private JCheckBox getUseBox_T2P() { - if (useBox == null) { - useBox = new JCheckBox(Messages.getString("Configuration.P2T.Label.Use")); - useBox.setEnabled(true); - useBox.setToolTipText( - "" + Messages.getString("Configuration.T2P.Label.Use") + ""); - CheckboxListener cbl = new CheckboxListener(); - useBox.addItemListener(cbl); - } - - return useBox; - } - - private JLabel getManagerPathLabel() { - if (managerPathLabel == null) { - managerPathLabel = - new JLabel( - "" + Messages.getString("Configuration.P2T.Label.ServerURI") + ""); - managerPathLabel.setHorizontalAlignment(JLabel.RIGHT); - } - return managerPathLabel; - } - - private JLabel getManagerPathLabel_T2P() { - if (managerPathLabel_T2P == null) { - managerPathLabel_T2P = - new JLabel( - "" + Messages.getString("Configuration.T2P.Label.ServerURI") + ""); - managerPathLabel_T2P.setHorizontalAlignment(JLabel.RIGHT); - } - return managerPathLabel_T2P; - } - - private JTextField getManagerPathText() { - if (managerPathText == null) { - managerPathText = new JTextField(); - managerPathText.setColumns(40); - managerPathText.setEnabled(true); - managerPathText.setToolTipText( - "" + Messages.getString("Configuration.P2T.Label.ServerURI") + ""); - } - return managerPathText; - } - - private JTextField getManagerPathText_T2P() { - if (managerPathText_T2P == null) { - managerPathText_T2P = new JTextField(); - managerPathText_T2P.setColumns(40); - managerPathText_T2P.setEnabled(true); - managerPathText_T2P.setToolTipText( - "" + Messages.getString("Configuration.T2P.Label.ServerURI") + ""); - } - return managerPathText_T2P; - } - - private WopedButton getTestButton() { - if (testButton == null) { - testButton = new WopedButton(); - testButton.setText(Messages.getTitle("Button.TestConnection")); - testButton.setIcon(Messages.getImageIcon("Button.TestConnection")); - testButton.setMnemonic(Messages.getMnemonic("Button.TestConnection")); - testButton.setPreferredSize(new Dimension(160, 25)); - testButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - testProcess2TextConnection(); + private JCheckBox useBox = null; + private JPanel enabledPanel = null; + private JPanel settingsPanel = null; + private JPanel settingsPanel_T2P = null; + private JPanel settingsPanel_GPT = null; + + private JTextField serverURLText = null; + private JLabel serverURLLabel = null; + private JLabel serverPortLabel = null; + private JTextField serverPortText = null; + private JTextField managerPathText = null; + private JLabel managerPathLabel = null; + private WopedButton testButton = null; + private WopedButton defaultButton = null; + private JTextField serverURLText_T2P = null; + private JLabel serverURLLabel_T2P = null; + private JLabel serverPortLabel_T2P = null; + private JTextField serverPortText_T2P = null; + private JTextField managerPathText_T2P = null; + private JLabel managerPathLabel_T2P = null; + private WopedButton testButton_T2P = null; + private WopedButton defaultButton_T2P = null; + + // Components for additionalPanel + private JTextField apiKeyText = null; + private JCheckBox showAgainBox = null; + private WopedButton resetButton = null; + private JTextArea promptText = null; + private WopedButton fetchGPTModelsButton = null; + private WopedButton checkConnectionButton = null; + private JComboBox modelComboBox = new JComboBox(); + + public ConfNLPToolsPanel(String name) { + super(name); + initialize(); + } + + public boolean applyConfiguration() { + boolean newsetting = useBox.isSelected(); + boolean oldsetting = ConfigurationManager.getConfiguration().getProcess2TextUse(); + + if (newsetting != oldsetting) { + ConfigurationManager.getConfiguration().setProcess2TextUse(newsetting); + JOptionPane.showMessageDialog( + this, + Messages.getString("Configuration.P2T.Dialog.Restart.Message"), + Messages.getString("Configuration.P2T.Dialog.Restart.Title"), + JOptionPane.INFORMATION_MESSAGE); + } + ConfigurationManager.getConfiguration().setProcess2TextServerHost(getServerURLText().getText()); + ConfigurationManager.getConfiguration().setProcess2TextServerURI(getManagerPathText().getText()); + if (getServerPortText().getText().isEmpty()) { + ConfigurationManager.getConfiguration().setProcess2TextServerPort(0); + } else { + ConfigurationManager.getConfiguration() + .setProcess2TextServerPort(Integer.parseInt(getServerPortText().getText())); + } + ConfigurationManager.getConfiguration().setProcess2TextUse(useBox.isSelected()); + + ConfigurationManager.getConfiguration().setText2ProcessServerHost(getServerURLText_T2P().getText()); + + ConfigurationManager.getConfiguration().setText2ProcessServerURI(getManagerPathText_T2P().getText()); + + if (getServerPortText_T2P().getText().isEmpty()) { + ConfigurationManager.getConfiguration().setText2ProcessServerPort(0); + } else { + ConfigurationManager.getConfiguration() + .setText2ProcessServerPort(Integer.parseInt(getServerPortText_T2P().getText())); + } + ConfigurationManager.getConfiguration().setGptApiKey(getApiKeyText().getText()); + ConfigurationManager.getConfiguration().setGptShowAgain(true); + ConfigurationManager.getConfiguration().setGptPrompt(getPromptText().getText()); + ConfigurationManager.getConfiguration().setGptModel(modelComboBox.getSelectedItem().toString()); + + return true; + } + + public void readConfiguration() { + getServerURLText().setText(ConfigurationManager.getConfiguration().getProcess2TextServerHost()); + getManagerPathText().setText(ConfigurationManager.getConfiguration().getProcess2TextServerURI()); + getServerPortText().setText("" + ConfigurationManager.getConfiguration().getProcess2TextServerPort()); + getUseBox().setSelected(ConfigurationManager.getConfiguration().getProcess2TextUse()); + + getServerURLText_T2P().setText(ConfigurationManager.getConfiguration().getText2ProcessServerHost()); + getManagerPathText_T2P().setText(ConfigurationManager.getConfiguration().getText2ProcessServerURI()); + getServerPortText_T2P().setText("" + ConfigurationManager.getConfiguration().getText2ProcessServerPort()); + getApiKeyText().setText(ConfigurationManager.getConfiguration().getGptApiKey()); + getShowAgainBox().setSelected(ConfigurationManager.getConfiguration().getGptShowAgain()); + getPromptText().setText(ConfigurationManager.getConfiguration().getGptPrompt()); + } + + private void initialize() { + JPanel contentPanel = new JPanel(); + contentPanel.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.anchor = GridBagConstraints.NORTH; + c.fill = GridBagConstraints.HORIZONTAL; + c.insets = new Insets(2, 0, 2, 0); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 0; + contentPanel.add(getEnabledPanel(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 1; + contentPanel.add(getSettingsPanel(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 2; + contentPanel.add(getSettingsPanel_T2P(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 3; + contentPanel.add(getGPTPanel(), c); + + c.fill = GridBagConstraints.VERTICAL; + c.weighty = 1; + c.gridy = 4; + contentPanel.add(new JPanel(), c); + + setMainPanel(contentPanel); + + } + + private JTextField getServerURLText() { + if (serverURLText == null) { + serverURLText = new JTextField(); + serverURLText.setColumns(40); + serverURLText.setEnabled(true); + serverURLText.setToolTipText("" + Messages.getString("Configuration.P2T.Label.ServerHost") + ""); + } + return serverURLText; + } + + private JTextField getServerURLText_T2P() { + if (serverURLText_T2P == null) { + serverURLText_T2P = new JTextField(); + serverURLText_T2P.setColumns(40); + serverURLText_T2P.setEnabled(true); + serverURLText_T2P.setToolTipText("" + Messages.getString("Configuration.T2P.Label.ServerHost") + ""); + } + return serverURLText_T2P; + } + + private JPanel getEnabledPanel() { + if (enabledPanel == null) { + enabledPanel = new JPanel(); + enabledPanel.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.anchor = GridBagConstraints.WEST; + c.insets = new Insets(2, 0, 2, 0); + + enabledPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(Messages.getTitle("Configuration.P2T.Enabled.Panel")), BorderFactory.createEmptyBorder(10, 10, 10, 10))); + + c.weightx = 1; + c.gridx = 0; // Move further left + c.gridy = 0; + enabledPanel.add(getUseBox(), c); + } + return enabledPanel; + } + + private JPanel getSettingsPanel() { + if (settingsPanel == null) { + settingsPanel = new JPanel(); + settingsPanel.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.anchor = GridBagConstraints.WEST; + c.insets = new Insets(2, 0, 2, 0); + + settingsPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(Messages.getString("Configuration.P2T.Settings.Panel.Title")), BorderFactory.createEmptyBorder(10, 10, 10, 10))); + c.weightx = 1; + c.gridx = 0; + c.gridy = 0; + settingsPanel.add(getServerURLLabel(), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 0; + c.gridwidth = 2; + settingsPanel.add(getServerURLText(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 1; + c.gridwidth = 1; + settingsPanel.add(getServerPortLabel(), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 1; + settingsPanel.add(getServerPortText(), c); + + c.weightx = 1; + c.gridx = 2; + c.gridy = 1; + settingsPanel.add(getTestButton(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 2; + settingsPanel.add(getManagerPathLabel(), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 2; + c.gridwidth = 2; + settingsPanel.add(getManagerPathText(), c); + + c.weightx = 1; + c.gridx = 3; + c.gridy = 1; + settingsPanel.add(getDefaultButton(), c); + } + + settingsPanel.setVisible(getUseBox().isSelected()); + return settingsPanel; + } + + private JPanel getSettingsPanel_T2P() { + if (settingsPanel_T2P == null) { + settingsPanel_T2P = new JPanel(); + settingsPanel_T2P.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.anchor = GridBagConstraints.WEST; + c.insets = new Insets(2, 0, 2, 0); + + settingsPanel_T2P.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(Messages.getString("Configuration.T2P.Settings.Panel.Title")), BorderFactory.createEmptyBorder(10, 10, 10, 10))); + c.weightx = 1; + c.gridx = 0; + c.gridy = 0; + settingsPanel_T2P.add(getServerURLLabel_T2P(), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 0; + c.gridwidth = 2; + settingsPanel_T2P.add(getServerURLText_T2P(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 1; + c.gridwidth = 1; + settingsPanel_T2P.add(getServerPortLabel_T2P(), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 1; + settingsPanel_T2P.add(getServerPortText_T2P(), c); + + c.weightx = 1; + c.gridx = 2; + c.gridy = 1; + settingsPanel_T2P.add(getTestButton_T2P(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 2; + settingsPanel_T2P.add(getManagerPathLabel_T2P(), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 2; + c.gridwidth = 2; + settingsPanel_T2P.add(getManagerPathText_T2P(), c); + + c.weightx = 1; + c.gridx = 3; + c.gridy = 1; + settingsPanel_T2P.add(getDefaultButton_T2P(), c); + } + + settingsPanel_T2P.setVisible(getUseBox_T2P().isSelected()); + return settingsPanel_T2P; + } + + private JPanel getGPTPanel() { + if (settingsPanel_GPT == null) { + settingsPanel_GPT = new JPanel(); + settingsPanel_GPT.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.anchor = GridBagConstraints.WEST; + c.insets = new Insets(2, 0, 2, 0); + + settingsPanel_GPT.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(Messages.getString("Configuration.GPT.settings.Title")), BorderFactory.createEmptyBorder(10, 10, 10, 10))); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 0; + settingsPanel_GPT.add(new JLabel(Messages.getString("Configuration.GPT.apikey.Title")), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 0; + settingsPanel_GPT.add(getApiKeyText(), c); + + c.weightx = 1; + c.gridx = 0; + c.gridy = 1; + settingsPanel_GPT.add(new JLabel(Messages.getString("Configuration.GPT.prompt.Title")), c); + + c.weightx = 1; + c.gridx = 1; + c.gridy = 1; + c.gridwidth = 2; + settingsPanel_GPT.add(getPromptTextScrollPane(), c); + + // Add the new row with the label and combo box + c.weightx = 0; + c.gridx = 0; + c.gridy = 2; + settingsPanel_GPT.add(new JLabel(Messages.getString("Configuration.GPT.model.Title")), c); + + // Adjust the constraints for the combo box + c.weightx = 1; + c.gridx = 1; + c.gridy = 2; + c.gridwidth = 1; + c.insets = new Insets(2, 0, 2, 12); // Add padding to the right of the combo box + c.fill = GridBagConstraints.HORIZONTAL; + settingsPanel_GPT.add(getModelComboBox(), c); + + // Adjust the constraints for the fetchModels button + c.weightx = 0; + c.gridx = 2; + c.gridy = 2; + c.insets = new Insets(2, 0, 2, 10); + settingsPanel_GPT.add(getFetchGPTModelsButton(), c); + + // Adjust the constraints for the show again checkbox + c.weightx = 1; + c.gridx = 0; + c.gridy = 3; + c.insets = new Insets(2, 0, 2, 0); + settingsPanel_GPT.add(getShowAgainBox(), c); + + // Adjust the constraints for the reset button + c.weightx = 1; + c.gridx = 2; + c.gridy = 3; + c.insets = new Insets(2, 0, 2, 10); // Add padding to the right of the checkbox + settingsPanel_GPT.add(getResetButton(), c); + + // Adjust the constraints for the check connection button + c.weightx = 1; + c.gridx = 1; + c.gridy = 3; + c.insets = new Insets(2, 0, 2, 12); // Reset insets for the button + settingsPanel_GPT.add(getCheckConnectionButton(), c); + } + + settingsPanel_GPT.setVisible(getUseBox().isSelected()); + for (int i = 0; i < modelComboBox.getItemCount(); i++){ + if (modelComboBox.getItemAt(i).equals(ConfigurationManager.getConfiguration().getGptModel())){ + modelComboBox.setSelectedIndex(i); + break; + } + } + return settingsPanel_GPT; + } + + private JScrollPane getPromptTextScrollPane() { + JScrollPane scrollPane = new JScrollPane(getPromptText()); + scrollPane.setPreferredSize(new Dimension(getApiKeyText().getPreferredSize().width, 100)); + return scrollPane; + } + + private JTextField getApiKeyText() { + if (apiKeyText == null) { + apiKeyText = new JTextField(); + apiKeyText.setColumns(40); + apiKeyText.setEnabled(true); + } + return apiKeyText; + } + + private JTextArea getPromptText() { + if (promptText == null) { + promptText = new JTextArea(); + promptText.setColumns(40); + promptText.setRows(5); + promptText.setLineWrap(true); + promptText.setWrapStyleWord(true); + promptText.setEnabled(true); + promptText.setText("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!"); + } + return promptText; + } + + private JCheckBox getShowAgainBox() { + if (showAgainBox == null) { + showAgainBox = new JCheckBox(Messages.getString("Configuration.GPT.show.again.Title")); + showAgainBox.setEnabled(true); + showAgainBox.setToolTipText(Messages.getString("Configuration.GPT.tool.tip.text.Title")); + } + return showAgainBox; + } + + private WopedButton getResetButton() { + if (resetButton == null) { + resetButton = new WopedButton(); + resetButton.setText(Messages.getString("Configuration.GPT.standard.Title")); + resetButton.setPreferredSize(new Dimension(200, 25)); + resetButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setDefaultValuesGPT(); + } + }); + } + return resetButton; + } + + private WopedButton getFetchGPTModelsButton(){ + if (fetchGPTModelsButton == null){ + fetchGPTModelsButton = new WopedButton(); + fetchGPTModelsButton.setText(Messages.getString("P2T.fetchmodels.button")); + fetchGPTModelsButton.setPreferredSize(new Dimension(200, 25)); + fetchGPTModelsButton.addActionListener(e -> fetchAndFillModels()); + } + return fetchGPTModelsButton; + } + + private WopedButton getCheckConnectionButton() { + if (checkConnectionButton == null) { + checkConnectionButton = new WopedButton(); + checkConnectionButton.setText(Messages.getString("Configuration.GPT.connection.Title")); + checkConnectionButton.setIcon(Messages.getImageIcon("Button.TestConnection")); + checkConnectionButton.setMnemonic(Messages.getMnemonic("Button.TestConnection")); + checkConnectionButton.setPreferredSize(new Dimension(170, 25)); + checkConnectionButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + testGPTConnection(); + } + }); + } + return checkConnectionButton; + } + + private void testGPTConnection() { + String apiKey = apiKeyText.getText(); + String urlString = "https://api.openai.com/v1/engines"; + + try { + URL url = new URL(urlString); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setRequestProperty("Authorization", "Bearer " + apiKey); + connection.connect(); + + int responseCode = connection.getResponseCode(); + String message; + + if (responseCode == 200) { + message = Messages.getString("Configuration.GPT.connection.successful.Title") + responseCode; + } else { + message = Messages.getString("Configuration.GPT.connection.failed.Title") + responseCode; + } + + JOptionPane.showMessageDialog( + this.getGPTPanel(), + message, + Messages.getString("Configuration.GPT.connection.test.Title"), + JOptionPane.INFORMATION_MESSAGE); + + } catch (IOException e) { + JOptionPane.showMessageDialog( + this.getGPTPanel(), + Messages.getString("Configuration.GPT.connection.test.failed.Title") + e.getMessage(), + Messages.getString("Configuration.GPT.connection.test.Title"), + JOptionPane.ERROR_MESSAGE); + } + } + + private void setDefaultValuesGPT() { + getApiKeyText().setText(ConfigurationManager.getStandardConfiguration().getGptApiKey()); + getShowAgainBox().setSelected(ConfigurationManager.getStandardConfiguration().getGptShowAgain()); + getPromptText().setText(ConfigurationManager.getStandardConfiguration().getGptPrompt()); + } + + private JComboBox getModelComboBox() { + if (modelComboBox == null) { + modelComboBox = new JComboBox<>(); + modelComboBox.setEnabled(true); + modelComboBox.setToolTipText("Select a model"); + } + return modelComboBox; + } + + private JCheckBox getUseBox() { + if (useBox == null) { + useBox = new JCheckBox(Messages.getString("Configuration.P2T.Label.Use")); + useBox.setEnabled(true); + useBox.setToolTipText("" + Messages.getString("Configuration.P2T.Label.Use") + ""); + CheckboxListener cbl = new CheckboxListener(); + useBox.addItemListener(cbl); + } + + return useBox; + } + + private JCheckBox getUseBox_T2P() { + if (useBox == null) { + useBox = new JCheckBox(Messages.getString("Configuration.P2T.Label.Use")); + useBox.setEnabled(true); + useBox.setToolTipText("" + Messages.getString("Configuration.T2P.Label.Use") + ""); + CheckboxListener cbl = new CheckboxListener(); + useBox.addItemListener(cbl); + } + + return useBox; + } + + private JLabel getManagerPathLabel() { + if (managerPathLabel == null) { + managerPathLabel = new JLabel("" + Messages.getString("Configuration.P2T.Label.ServerURI") + ""); + managerPathLabel.setHorizontalAlignment(JLabel.RIGHT); + } + return managerPathLabel; + } + + private JLabel getManagerPathLabel_T2P() { + if (managerPathLabel_T2P == null) { + managerPathLabel_T2P = new JLabel("" + Messages.getString("Configuration.T2P.Label.ServerURI") + ""); + managerPathLabel_T2P.setHorizontalAlignment(JLabel.RIGHT); + } + return managerPathLabel_T2P; + } + + private JTextField getManagerPathText() { + if (managerPathText == null) { + managerPathText = new JTextField(); + managerPathText.setColumns(40); + managerPathText.setEnabled(true); + managerPathText.setToolTipText("" + Messages.getString("Configuration.P2T.Label.ServerURI") + ""); + } + return managerPathText; + } + + private JTextField getManagerPathText_T2P() { + if (managerPathText_T2P == null) { + managerPathText_T2P = new JTextField(); + managerPathText_T2P.setColumns(40); + managerPathText_T2P.setEnabled(true); + managerPathText_T2P.setToolTipText("" + Messages.getString("Configuration.T2P.Label.ServerURI") + ""); + } + return managerPathText_T2P; + } + + private WopedButton getTestButton() { + if (testButton == null) { + testButton = new WopedButton(); + testButton.setText(Messages.getTitle("Button.TestConnection")); + testButton.setIcon(Messages.getImageIcon("Button.TestConnection")); + testButton.setMnemonic(Messages.getMnemonic("Button.TestConnection")); + testButton.setPreferredSize(new Dimension(160, 25)); + testButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + testProcess2TextConnection(); + } + }); + } + + return testButton; + } + + private WopedButton getTestButton_T2P() { + if (testButton_T2P == null) { + testButton_T2P = new WopedButton(); + testButton_T2P.setText(Messages.getTitle("Button.TestConnection")); + testButton_T2P.setIcon(Messages.getImageIcon("Button.TestConnection")); + testButton_T2P.setMnemonic(Messages.getMnemonic("Button.TestConnection")); + testButton_T2P.setPreferredSize(new Dimension(160, 25)); + testButton_T2P.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + testText2ProcessConnection(); + } + }); + } + + return testButton_T2P; + } + + private WopedButton getDefaultButton() { + if (defaultButton == null) { + defaultButton = new WopedButton(); + defaultButton.setText(Messages.getTitle("Button.SetToDefault")); + defaultButton.setPreferredSize(new Dimension(200, 25)); + defaultButton.addActionListener(e -> setDefaultValues()); + } + return defaultButton; + } + + private WopedButton getDefaultButton_T2P() { + if (defaultButton_T2P == null) { + defaultButton_T2P = new WopedButton(); + defaultButton_T2P.setText(Messages.getTitle("Button.SetToDefault")); + defaultButton_T2P.setPreferredSize(new Dimension(200, 25)); + defaultButton_T2P.addActionListener(e -> setDefaultValues_T2P()); + } + return defaultButton_T2P; + } + + private void testProcess2TextConnection() { + URL url = null; + String connection = "http://" + getServerURLText().getText() + ":" + getServerPortText().getText() + getManagerPathText().getText(); + String[] arg = {connection, ""}; + + try { + url = new URL(connection); + URLConnection urlConnection = url.openConnection(); + + if (urlConnection.getContent() != null) { + arg[1] = "P2T"; + JOptionPane.showMessageDialog(this.getSettingsPanel(), Messages.getString("Paraphrasing.Webservice.Success.Message", arg), Messages.getString("Paraphrasing.Webservice.Success.Title"), JOptionPane.INFORMATION_MESSAGE); } - }); - } - - return testButton; - } - - private WopedButton getTestButton_T2P() { - if (testButton_T2P == null) { - testButton_T2P = new WopedButton(); - testButton_T2P.setText(Messages.getTitle("Button.TestConnection")); - testButton_T2P.setIcon(Messages.getImageIcon("Button.TestConnection")); - testButton_T2P.setMnemonic(Messages.getMnemonic("Button.TestConnection")); - testButton_T2P.setPreferredSize(new Dimension(160, 25)); - testButton_T2P.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - testText2ProcessConnection(); + } catch (IOException ex) { + JOptionPane.showMessageDialog(this.getSettingsPanel(), Messages.getString("Paraphrasing.Webservice.Error.WebserviceException.Message", arg), Messages.getString("Paraphrasing.Webservice.Error.Title"), JOptionPane.ERROR_MESSAGE); + } + } + + private void testText2ProcessConnection() { + URL url; + String connection = "http://" + getServerURLText_T2P().getText() + ":" + getServerPortText_T2P().getText() + getManagerPathText_T2P().getText(); + String[] arg = {connection, ""}; + + try { + url = new URL(connection); + URLConnection urlConnection = url.openConnection(); + if (urlConnection.getContent() != null) { + arg[1] = "T2P"; + JOptionPane.showMessageDialog(this.getSettingsPanel_T2P(), Messages.getString("Paraphrasing.Webservice.Success.Message", arg), Messages.getString("Paraphrasing.Webservice.Success.Title"), JOptionPane.INFORMATION_MESSAGE); } - }); + } catch (IOException ex) { + JOptionPane.showMessageDialog(this.getSettingsPanel_T2P(), Messages.getString("Paraphrasing.Webservice.Error.WebserviceException.Message", arg), Messages.getString("Paraphrasing.Webservice.Error.Title"), JOptionPane.ERROR_MESSAGE); + } + } + + private void setDefaultValues() { + getServerURLText().setText(ConfigurationManager.getStandardConfiguration().getProcess2TextServerHost()); + getManagerPathText().setText(ConfigurationManager.getStandardConfiguration().getProcess2TextServerURI()); + getServerPortText().setText("" + ConfigurationManager.getStandardConfiguration().getProcess2TextServerPort()); } - return testButton_T2P; - } + private void setDefaultValues_T2P() { + getServerURLText_T2P().setText(ConfigurationManager.getStandardConfiguration().getText2ProcessServerHost()); + getManagerPathText_T2P().setText(ConfigurationManager.getStandardConfiguration().getText2ProcessServerURI()); + getServerPortText_T2P().setText("" + ConfigurationManager.getStandardConfiguration().getText2ProcessServerPort()); + } - private WopedButton getDefaultButton() { - if (defaultButton == null) { - defaultButton = new WopedButton(); - defaultButton.setText(Messages.getTitle("Button.SetToDefault")); - defaultButton.setPreferredSize(new Dimension(200, 25)); - defaultButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - setDefaultValues(); + class CheckboxListener implements ItemListener { + public void itemStateChanged(ItemEvent ie) { + JCheckBox jcb = (JCheckBox) ie.getSource(); + if (jcb == useBox) { + getSettingsPanel().setVisible(jcb.isSelected()); + getSettingsPanel_T2P().setVisible(jcb.isSelected()); + getGPTPanel().setVisible(jcb.isSelected()); } - }); - } - return defaultButton; - } - - private WopedButton getDefaultButton_T2P() { - if (defaultButton_T2P == null) { - defaultButton_T2P = new WopedButton(); - defaultButton_T2P.setText(Messages.getTitle("Button.SetToDefault")); - defaultButton_T2P.setPreferredSize(new Dimension(200, 25)); - defaultButton_T2P.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - setDefaultValues_T2P(); + } + } + + private JLabel getServerURLLabel() { + if (serverURLLabel == null) { + serverURLLabel = new JLabel("" + Messages.getString("Configuration.P2T.Label.ServerHost") + ""); + serverURLLabel.setHorizontalAlignment(JLabel.RIGHT); + } + return serverURLLabel; + } + + private JLabel getServerURLLabel_T2P() { + if (serverURLLabel_T2P == null) { + serverURLLabel_T2P = new JLabel("" + Messages.getString("Configuration.T2P.Label.ServerHost") + ""); + serverURLLabel_T2P.setHorizontalAlignment(JLabel.RIGHT); + } + return serverURLLabel_T2P; + } + + private JLabel getServerPortLabel() { + if (serverPortLabel == null) { + serverPortLabel = new JLabel("" + Messages.getString("Configuration.P2T.Label.ServerPort") + ""); + serverPortLabel.setHorizontalAlignment(JLabel.RIGHT); + } + return serverPortLabel; + } + + private JLabel getServerPortLabel_T2P() { + if (serverPortLabel_T2P == null) { + serverPortLabel_T2P = new JLabel("" + Messages.getString("Configuration.T2P.Label.ServerPort") + ""); + serverPortLabel_T2P.setHorizontalAlignment(JLabel.RIGHT); + } + return serverPortLabel_T2P; + } + + private JTextField getServerPortText() { + if (serverPortText == null) { + serverPortText = new JTextField(); + serverPortText.setColumns(4); + serverPortText.setEnabled(true); + serverPortText.setToolTipText("" + Messages.getString("Configuration.P2T.Label.ServerPort") + ""); + } + return serverPortText; + } + + private JTextField getServerPortText_T2P() { + if (serverPortText_T2P == null) { + serverPortText_T2P = new JTextField(); + serverPortText_T2P.setColumns(4); + serverPortText_T2P.setEnabled(true); + serverPortText_T2P.setToolTipText("" + Messages.getString("Configuration.T2P.Label.ServerPort") + ""); + } + return serverPortText_T2P; + } + private void fetchAndFillModels() { + new Thread(() -> { + try { + List models = ApiHelper.fetchModels(apiKeyText.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); + }); } - }); - } - return defaultButton_T2P; - } - - private void testProcess2TextConnection() { - URL url = null; - String connection = - "http://" - + getServerURLText().getText() - + ":" - + getServerPortText().getText() - + getManagerPathText().getText(); - String arg[] = {connection, ""}; - - try { - url = new URL(connection); - URLConnection urlConnection = url.openConnection(); - - if (urlConnection.getContent() != null) { - arg[1] = "P2T"; - JOptionPane.showMessageDialog( - this.getSettingsPanel(), - Messages.getString("Paraphrasing.Webservice.Success.Message", arg), - Messages.getString("Paraphrasing.Webservice.Success.Title"), - JOptionPane.INFORMATION_MESSAGE); - } - } catch (MalformedURLException mue) { - JOptionPane.showMessageDialog( - this.getSettingsPanel(), - Messages.getString("Paraphrasing.Webservice.Error.WebserviceException.Message", arg), - Messages.getString("Paraphrasing.Webservice.Error.Title"), - JOptionPane.ERROR_MESSAGE); - } catch (IOException ex) { - JOptionPane.showMessageDialog( - this.getSettingsPanel(), - Messages.getString("Paraphrasing.Webservice.Error.WebserviceException.Message", arg), - Messages.getString("Paraphrasing.Webservice.Error.Title"), - JOptionPane.ERROR_MESSAGE); - } - } - - private void testText2ProcessConnection() { - URL url = null; - String connection = - "http://" - + getServerURLText_T2P().getText() - + ":" - + getServerPortText_T2P().getText() - + getManagerPathText_T2P().getText() - + ""; - String arg[] = {connection, ""}; - - try { - url = new URL(connection); - URLConnection urlConnection = url.openConnection(); - if (urlConnection.getContent() != null) { - arg[1] = "T2P"; - JOptionPane.showMessageDialog( - this.getSettingsPanel_T2P(), - Messages.getString("Paraphrasing.Webservice.Success.Message", arg), - Messages.getString("Paraphrasing.Webservice.Success.Title"), - JOptionPane.INFORMATION_MESSAGE); - } - } catch (MalformedURLException mue) { - JOptionPane.showMessageDialog( - this.getSettingsPanel_T2P(), - Messages.getString("Paraphrasing.Webservice.Error.WebserviceException.Message", arg), - Messages.getString("Paraphrasing.Webservice.Error.Title"), - JOptionPane.ERROR_MESSAGE); - } catch (IOException ex) { - JOptionPane.showMessageDialog( - this.getSettingsPanel_T2P(), - Messages.getString("Paraphrasing.Webservice.Error.WebserviceException.Message", arg), - Messages.getString("Paraphrasing.Webservice.Error.Title"), - JOptionPane.ERROR_MESSAGE); - } - } - - private void setDefaultValues() { - getServerURLText() - .setText(ConfigurationManager.getStandardConfiguration().getProcess2TextServerHost()); - getManagerPathText() - .setText(ConfigurationManager.getStandardConfiguration().getProcess2TextServerURI()); - getServerPortText() - .setText("" + ConfigurationManager.getStandardConfiguration().getProcess2TextServerPort()); - } - - private void setDefaultValues_T2P() { - getServerURLText_T2P() - .setText(ConfigurationManager.getStandardConfiguration().getText2ProcessServerHost()); - getManagerPathText_T2P() - .setText(ConfigurationManager.getStandardConfiguration().getText2ProcessServerURI()); - getServerPortText_T2P() - .setText("" + ConfigurationManager.getStandardConfiguration().getText2ProcessServerPort()); - } + }).start(); + } + } diff --git a/WoPeD-Editor/src/main/java/org/woped/editor/tools/ApiHelper.java b/WoPeD-Editor/src/main/java/org/woped/editor/tools/ApiHelper.java new file mode 100644 index 000000000..d7f80663f --- /dev/null +++ b/WoPeD-Editor/src/main/java/org/woped/editor/tools/ApiHelper.java @@ -0,0 +1,54 @@ +package org.woped.editor.tools; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.json.simple.JSONArray; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.woped.core.utilities.LoggerManager; +import org.woped.editor.Constants; + +public class ApiHelper { + + public static List fetchModels(String apiKey) throws IOException, ParseException { + LoggerManager.info(Constants.EDITOR_LOGGER,"Started Fetching GPT Models"); + + String urlString = "http://localhost:8080/p2t/gptModels?apiKey=" + apiKey; + List models = new ArrayList<>(); + + URL url = new URL(urlString); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int responseCode = connection.getResponseCode(); + if (responseCode == 200) { + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String inputLine; + StringBuilder content = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + JSONParser parser = new JSONParser(); + JSONArray modelsArray = (JSONArray) parser.parse(content.toString()); + for (Object model : modelsArray) { + models.add(model.toString()); + } + + LoggerManager.info(Constants.EDITOR_LOGGER,"Finished Fetching GPT Models"); + } else { + LoggerManager.error(Constants.EDITOR_LOGGER, "Failed to Fetch GPT Models"); + throw new IOException("Failed to fetch models. Response Code: " + responseCode + "\n" + + "Please check your API Key"); + } + return models; + } +} diff --git a/WoPeD-FileInterface/pom.xml b/WoPeD-FileInterface/pom.xml index 3e0f5ee45..afd2e28c2 100644 --- a/WoPeD-FileInterface/pom.xml +++ b/WoPeD-FileInterface/pom.xml @@ -114,6 +114,65 @@ WoPeD-QualAnalysis ${project.version}
+ + com.googlecode.json-simple + json-simple + 1.1.1 + compile + + + junit + junit + 4.13.2 + test + + + org.jsoup + jsoup + 1.10.2 + + + org.junit.jupiter + junit-jupiter-engine + 5.7.0 + test + + + org.junit.jupiter + junit-jupiter + 5.7.0 + test + + + org.mockito + mockito-core + 5.7.0 + test + + + org.mockito + mockito-inline + 5.2.0 + test + + + org.projectlombok + lombok + 1.18.30 + provided + + + org.mockito + mockito-core + 5.7.0 + test + + + org.mockito + mockito-junit-jupiter + 5.12.0 + test +
diff --git a/WoPeD-FileInterface/src/main/java/org/woped/file/p2t/P2TUI.java b/WoPeD-FileInterface/src/main/java/org/woped/file/p2t/P2TUI.java new file mode 100644 index 000000000..d74def14d --- /dev/null +++ b/WoPeD-FileInterface/src/main/java/org/woped/file/p2t/P2TUI.java @@ -0,0 +1,435 @@ +package org.woped.file.p2t; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.HeadlessException; +import java.awt.Insets; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import javax.swing.*; + +import org.json.simple.parser.ParseException; +import org.woped.core.config.ConfigurationManager; +import org.woped.core.controller.AbstractApplicationMediator; +import org.woped.core.controller.AbstractViewEvent; +import org.woped.core.controller.ViewEvent; +import org.woped.core.utilities.LoggerManager; +import org.woped.editor.Constants; +import org.woped.editor.action.WoPeDAction; +import org.woped.editor.controller.ActionFactory; +import org.woped.editor.tools.ApiHelper; +import org.woped.gui.translations.Messages; + +/** + * P2TUI + *

+ * The P2TUI class is a dialog to select the P2T service. + */ +public class P2TUI extends JDialog { + + private JDialog loadDialog; + private JTextField apiKeyField; + private JTextArea promptField; + private JCheckBox enablePromptCheckBox; + private JCheckBox showAgainCheckBox; + private JRadioButton newRadioButton = null; + private JRadioButton oldRadioButton = null; + JComboBox 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")); - } }