/*
* Provides a GUI for editing settings
*/
package GUI;
import java.awt.Toolkit;
import java.io.File;
import java.net.URL;
import java.util.Enumeration;
import javax.swing.UIManager;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.FormSubmitEvent;
import javax.swing.text.html.HTMLEditorKit;
import utils.Settings;
import definitions.is;
import net.htmlparser.jericho.*;
import script.log;
/**
*
* @author Nuno Brito, 16th of April 2013 in Darmstadt, Germany.
*/
// 2013-APR-26 psc :
// do not write "_SubmitButton"
// collect "Plugins" values;
public class SettingsGUI extends javax.swing.JFrame {
private final String plugins = "$Plugins";
private final String components = "$Components";
private final String files = "$Files";
private final String submitBtn = "$SubmitButton";
/**
* Creates new form SettingsGUI
*/
public SettingsGUI() {
// adopt the default user interface menus and buttons
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
// get the window icon working
URL imgURL = this.getClass().getResource("reboot.png");
setIconImage(Toolkit.getDefaultToolkit().getImage(imgURL));
initComponents();
}
/**
* 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("settings");
setBackground(new java.awt.Color(255, 255, 255));
jTextPane1.setEditable(false);
jTextPane1.setBorder(null);
jTextPane1.setContentType("text/html"); // NOI18N
jTextPane1.setMargin(new java.awt.Insets(10, 10, 10, 10));
jScrollPane1.setViewportView(jTextPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SettingsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SettingsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SettingsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SettingsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new SettingsGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration//GEN-END:variables
/**
* Part that intercepts the event triggered when the user submits an HTML
* form
*/
void doFormInterception() {
// add the URL interception
HTMLEditorKit kit = (HTMLEditorKit) jTextPane1.getEditorKit();
kit.setAutoFormSubmission(false);
jTextPane1.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e instanceof FormSubmitEvent) {
processFormSubmit(((FormSubmitEvent) e).getData());
}
}
});
}
/**
* Show the settings for specific item
*/
public void showItem(String webpage) {
// start the action when submitting the form
doFormInterception();
// are there settings available?
File configFile = null;
if ((configFile.exists()) && (configFile.isFile())) {
Settings config = new Settings(configFile, "");
// instantiate our HTML manipulating class
net.htmlparser.jericho.Source source =
new net.htmlparser.jericho.Source(webpage);
// get all the data available right now on the form
FormFields formFields = source.getFormFields();
//formFields.clearValues();
// go throught all the saved values
Enumeration e = config.getAllKeys();
FormField fld;
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
if (!key.equals("")) {
String value = config.read(key);
if (!key.startsWith("$")) {
// change them as necessary
formFields.addValue(key, value);
} else {
if (key.equals(plugins)) {
fld = formFields.get(plugins);
} else if (key.equals(components)) {
fld = formFields.get(components);
} else if (key.equals(files)) {
fld = formFields.get(files);
} else { // should be submitBtn
return;
}
fld.clearValues();
String[] plugs = value.split("\\|");
for (int i = 0; i < plugs.length; i++) {
fld.addValue(plugs[i]);
}
}
}
}
// save the output
OutputDocument outputDocument = new OutputDocument(source);
outputDocument.replace(formFields); // adds all segments necessary to effect changes
webpage = outputDocument.toString();
}
// do our stuff now, add the HTML on the screen
this.jTextPane1.setText(webpage);
// place the cursor on the first line for end user see top of page
this.jTextPane1.setCaretPosition(0);
this.setVisible(true);
}
/**
* Starts processing the form that was submitted by user, on this method we
* will decompose each of the parameters and write them for future use
*/
void processFormSubmit(String text) {
String pluginList = "";
String componentList = "";
String filesList = "";
String[] params = text.split("&");
boolean hasPlugins = false;
boolean hasFiles = false;
boolean hasComponents = false;
// Create our settings file
Settings formSettings = new Settings(null,
"Settings for " + "");
for (String param : params) {
String[] pair = param.split("=");
String value = "";
String key = "";
if (pair.length > 1) {
try {
key = java.net.URLDecoder.decode(pair[0], "UTF-8");
value = java.net.URLDecoder.decode(pair[1], "UTF-8");
//value = pair[1];
} catch (Exception e) {
log.write(is.ERROR,
"Failed to save settings for %1", "");
return;
}
} else if (pair.length == 1) {
try {
key = java.net.URLDecoder.decode(pair[0], "UTF-8");
//value = pair[1];
} catch (Exception e) {
log.write(is.ERROR,
"Failed to save settings for %1", "");
return;
}
}
if (key.startsWith("$")) {
if (key.equalsIgnoreCase(plugins)) {
hasPlugins = true;
if (!pluginList.equals("")) {
pluginList = pluginList.concat("|");
}
pluginList = pluginList.concat(value);
} else if (key.equalsIgnoreCase(files)) {
hasFiles = true;
if (!filesList.equals("")) {
filesList = filesList.concat("|");
}
filesList = filesList.concat(value);
} else if (key.equalsIgnoreCase(components)) {
hasComponents = true;
if (!componentList.equals("")) {
componentList = componentList.concat("|");
}
componentList = componentList.concat(value);
} // Do nothing with $SubmitButton
} else {
if (!key.startsWith("!")) {
formSettings.write(key, value.trim());
}
}
}
if (hasPlugins) {
formSettings.write(plugins, pluginList);
} else {
formSettings.delete(plugins);
}
if (hasFiles) {
formSettings.write(files, filesList);
} else {
formSettings.delete(files);
}
if (hasComponents) {
formSettings.write(components, componentList);
} else {
formSettings.delete(components);
}
log.write(is.COMPLETED,
"Settings for %1 were saved", "");
// hide and destroy this frame, no longer needed
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
}
}