Skip to content

Commit

Permalink
Code Gardening for PluginConfigure Fixes #367
Browse files Browse the repository at this point in the history
  • Loading branch information
Maksim Bezsaznyj authored and mcicolella committed Oct 14, 2017
1 parent 1f9854e commit 7469017
Showing 1 changed file with 71 additions and 93 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,35 +17,31 @@
* Freedomotic; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/

package com.freedomotic.jfrontend;

import com.freedomotic.api.API;
import com.freedomotic.api.Client;
import com.freedomotic.api.Plugin;
import com.freedomotic.app.Freedomotic;
import com.freedomotic.plugins.ClientStorage;
import com.freedomotic.plugins.PluginsManager;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.stream.Collectors;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* This class is the gui to edit the plugins.
* @author Enrico Nicoletti
*/
@SuppressWarnings("squid:S1948") //We are not planning to serialize UI components
public class PluginConfigure extends javax.swing.JFrame {

private ClientStorage clients;
Expand All @@ -67,101 +63,87 @@ public PluginConfigure(API api) {
initComponents();
populatePluginsList();
//add listener to category selection changes
cmbPlugin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Plugin item = (Plugin) cmbPlugin.getSelectedItem();
btnDefault.setEnabled(false);
getConfiguration(item);
}
cmbPlugin.addActionListener(e -> {
btnDefault.setEnabled(false);
getConfiguration((Plugin) cmbPlugin.getSelectedItem());
});

try {
cmbPlugin.setSelectedIndex(0);
} catch (Exception e) {
Freedomotic.getStackTraceInfo(e);
}

setPreferredSize(new Dimension(650, 550));
pack();
setVisible(true);
}

/**
* set the configurtion for the plugin.
* @param api the api to set to the plugin.
* @param showClient to set selected plugin
* Populates the list of all plugins from the API.
*/
public PluginConfigure(API api, Client showClient) {
this(api);
if (showClient instanceof Plugin) {
cmbPlugin.setSelectedItem((Plugin) showClient);
}
}

private void populatePluginsList() {
cmbPlugin.removeAllItems();

for (Client client : api.getClients("plugin")) {
if (client instanceof Plugin) {
Plugin plugin = (Plugin) client;
cmbPlugin.addItem(plugin);
}
api.getClients("plugin").stream()
.filter(it -> it instanceof Plugin)
.forEach(cmbPlugin::addItem);

if (cmbPlugin.getItemCount() > 0) {
cmbPlugin.setSelectedIndex(0);
}
}

/**
* Loads the configuration for selected plugin for modification. Also caches the current
* configuration in a `predefined` map to restore later if needed.
* @param item - plugin for which configuration needs to be modified.
*/
private void getConfiguration(Plugin item) {
txtArea.setContentType("text/xml");

String config = readConfiguration(item.getFile()).trim();
String config = readConfiguration(item);
//add old config to predefined to be restored in a later step
predefined.put(item, config);
btnDefault.setEnabled(true);
txtArea.setText(config);
}

private String readConfiguration(File file) {
StringBuilder buff = new StringBuilder();

try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);) {

// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
buff.append(dis.readLine()).append("\n");
}
} catch (FileNotFoundException e) {
Freedomotic.getStackTraceInfo(e);
/**
* Convenient method for reading the configuration of given plugin.
* @param plugin - plugin for which to load the configuration
* @return String representation of full configuration
*/
private String readConfiguration(Plugin plugin) {
File file = plugin.getFile();
try {
return FileUtils.readFileToString(file, (Charset) null).trim();
} catch (IOException e) {
Freedomotic.getStackTraceInfo(e);
LOG.error("Failed to read configuration from file '"+file.getAbsolutePath()+"'", e);
return "";
}
return buff.toString();
}

private void saveConfiguration(File file, String text)
/**
* Persists the given configuration for the given plugin.
*
* @param plugin - plugin for which to store the new configuration
* @param newConfig - string representation of new configuration to store
* @throws IOException thrown in case access to file system fails
*/
private void saveConfiguration(Plugin plugin, String newConfig)
throws IOException {
// Create file
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
out.write(text);
//Close the streams
out.close();
fstream.close();
FileUtils.write(plugin.getFile(), newConfig, (Charset) null);
}

private void rollbackConfiguration() {
Plugin item = (Plugin) cmbPlugin.getSelectedItem();
txtArea.setText(predefined.get(item));
/** Loads the original configuration of given plugin.
*
* @param plugin - plugin for which to restore configuration
*/
private void rollbackConfiguration(Plugin plugin) {
txtArea.setText(predefined.get(plugin));
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "Convert2Lambda"})
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

Expand Down Expand Up @@ -254,25 +236,24 @@ private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed

Plugin item = (Plugin) cmbPlugin.getSelectedItem();
String name = item.getName();
Plugin plugin = (Plugin) cmbPlugin.getSelectedItem();
String name = plugin.getName();

try {
saveConfiguration(item.getFile(),
txtArea.getText());
saveConfiguration(plugin, txtArea.getText());
//stopping and unloading the plugin
clients.remove(item);
clients.remove(plugin);
//reload it with the new configuration
System.out.println(item.getFile().getParentFile().toString());
pluginsManager.loadSingleBoundle(item.getFile().getParentFile());
File configDir = plugin.getFile().getParentFile();
LOG.trace("Reloading plugin '{}' with configuration '{}'", name, configDir);
pluginsManager.loadSingleBoundle(configDir);

//if not loaded sucessfully reset to old configuration
if (clients.get(name) == null) {
//reset to old working config and reload plugin
rollbackConfiguration();
saveConfiguration(item.getFile(),
txtArea.getText());
pluginsManager.loadSingleBoundle(item.getFile().getParentFile());
rollbackConfiguration(plugin);
saveConfiguration(plugin, txtArea.getText());
pluginsManager.loadSingleBoundle(configDir);
clients.get(name).start();
JOptionPane.showMessageDialog(this,
api.getI18n().msg("warn_reset_old_config"));
Expand All @@ -281,32 +262,29 @@ private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FI
this.dispose();
}
} catch (Exception ex) {
LOG.error(Freedomotic.getStackTraceInfo(ex));
LOG.error("Failed to save configuration for plugin '"+name+"'", ex);
}
}//GEN-LAST:event_btnSaveActionPerformed

private void btnDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDefaultActionPerformed
rollbackConfiguration();
Plugin plugin = (Plugin) cmbPlugin.getSelectedItem();
rollbackConfiguration(plugin);
}//GEN-LAST:event_btnDefaultActionPerformed

private void uninstallButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uninstallButtonActionPerformed

Plugin item = (Plugin) cmbPlugin.getSelectedItem();

StringBuilder uninstallCandidates = new StringBuilder();
File boundleRootFolder = item.getFile().getParentFile();
for (Client client : clients.getClients()) {
if (client instanceof Plugin) {
Plugin plugin = (Plugin) client;
//if this plugin is in the same plugin boundle of the one
//the user is trying to uninstall
if (plugin.getFile().getParentFile().equals(boundleRootFolder)) {
uninstallCandidates.append("'" + plugin.getName() + "' ");
}
}
}
String uninstallCandidates =
clients.getClients().stream()
.filter(client -> client instanceof Plugin)
.map(plugin -> (Plugin) plugin)
.filter(plugin -> plugin.getFile().getParentFile().equals(boundleRootFolder))
.map(plugin -> "'" + plugin.getName() + "'")
.collect(Collectors.joining(" "));

String localizedMessage
= api.getI18n().msg("confirm_plugin_delete", new Object[]{uninstallCandidates.toString()});
= api.getI18n().msg("confirm_plugin_delete", new Object[]{uninstallCandidates});

int result = JOptionPane.showConfirmDialog(null,
new JLabel(localizedMessage),
Expand Down

0 comments on commit 7469017

Please sign in to comment.