Search in sources :

Example 11 with Profile

use of jmri.profile.Profile in project JMRI by JMRI.

the class JmriConfigurationManager method load.

@Override
public boolean load(URL file, boolean registerDeferred) throws JmriException {
    log.debug("loading {} ...", file);
    try {
        if (file == null || //NOI18N
        (new File(file.toURI())).getName().equals("ProfileConfig.xml") || (new File(file.toURI())).getName().equals(Profile.CONFIG)) {
            Profile profile = ProfileManager.getDefault().getActiveProfile();
            List<PreferencesManager> providers = new ArrayList<>(InstanceManager.getList(PreferencesManager.class));
            providers.stream().forEach((provider) -> {
                this.initializeProvider(provider, profile);
            });
            if (!this.initializationExceptions.isEmpty()) {
                if (!GraphicsEnvironment.isHeadless()) {
                    ArrayList<String> errors = new ArrayList<>();
                    this.initialized.forEach((provider) -> {
                        List<Exception> exceptions = provider.getInitializationExceptions(profile);
                        if (!exceptions.isEmpty()) {
                            exceptions.forEach((exception) -> {
                                errors.add(exception.getLocalizedMessage());
                            });
                        } else if (this.initializationExceptions.get(provider) != null) {
                            errors.add(this.initializationExceptions.get(provider).getLocalizedMessage());
                        }
                    });
                    Object list;
                    if (errors.size() == 1) {
                        list = errors.get(0);
                    } else {
                        list = new JList<>(errors.toArray(new String[errors.size()]));
                    }
                    JOptionPane.showMessageDialog(null, new Object[] { (list instanceof JList) ? Bundle.getMessage("InitExMessageListHeader") : null, list, // Add a visual break between list of errors and notes // NOI18N
                    "<html><br></html>", // NOI18N
                    Bundle.getMessage("InitExMessageLogs"), // NOI18N
                    Bundle.getMessage("InitExMessagePrefs") }, // NOI18N
                    Bundle.getMessage("InitExMessageTitle", Application.getApplicationName()), JOptionPane.ERROR_MESSAGE);
                    (new TabbedPreferencesAction()).actionPerformed();
                }
            }
            if (file != null && (new File(file.toURI())).getName().equals("ProfileConfig.xml")) {
                // NOI18N
                log.debug("Loading legacy configuration...");
                return this.legacy.load(file, registerDeferred);
            }
            return this.initializationExceptions.isEmpty();
        }
    } catch (URISyntaxException ex) {
        log.error("Unable to get File for {}", file);
        throw new JmriException(ex.getMessage(), ex);
    }
    return this.legacy.load(file, registerDeferred);
// return true; // always return true once legacy support is dropped
}
Also used : TabbedPreferencesAction(apps.gui3.TabbedPreferencesAction) ArrayList(java.util.ArrayList) JmriException(jmri.JmriException) URISyntaxException(java.net.URISyntaxException) PreferencesManager(jmri.spi.PreferencesManager) Profile(jmri.profile.Profile) URISyntaxException(java.net.URISyntaxException) InitializationException(jmri.util.prefs.InitializationException) JmriException(jmri.JmriException) File(java.io.File) XmlFile(jmri.jmrit.XmlFile) JList(javax.swing.JList)

Example 12 with Profile

use of jmri.profile.Profile in project JMRI by JMRI.

the class ReportContext method getReport.

/**
     * Provide a report of the current JMRI context
     *
     * @param reportNetworkInfo true if network connection and zeroconf service
     *                          information to be included
     * @return current JMRI context
     */
public String getReport(boolean reportNetworkInfo) {
    addString("JMRI Version: " + jmri.Version.name() + "   ");
    addString("JMRI configuration file name: " + System.getProperty("org.jmri.apps.Apps.configFilename") + "   ");
    if (jmri.util.JmriJFrame.getFrameList().get(0) != null) {
        addString("JMRI main window name: " + jmri.util.JmriJFrame.getFrameList().get(0).getTitle() + "   ");
    }
    addString("JMRI Application: " + jmri.Application.getApplicationName() + "   ");
    ConnectionConfig[] connList = InstanceManager.getDefault(ConnectionConfigManager.class).getConnections();
    if (connList != null) {
        for (int x = 0; x < connList.length; x++) {
            ConnectionConfig conn = connList[x];
            addString("Connection " + x + ": " + conn.getManufacturer() + " connected via " + conn.name() + " on " + conn.getInfo() + " Disabled " + conn.getDisabled() + "   ");
        }
    }
    addString("Available Communication Ports:");
    addCommunicationPortInfo();
    Profile profile = ProfileManager.getDefault().getActiveProfile();
    addString("Active profile: " + profile.getName() + "   ");
    addString("Profile location: " + profile.getPath().getPath() + "   ");
    addString("Profile ID: " + profile.getId() + "   ");
    String prefs = FileUtil.getUserFilesPath();
    addString("Preferences directory: " + prefs + "   ");
    String prog = System.getProperty("user.dir");
    addString("Program directory: " + prog + "   ");
    String roster = jmri.jmrit.roster.Roster.getDefault().getRosterIndexPath();
    addString("Roster index location: " + roster + "   ");
    File panel = jmri.configurexml.LoadXmlUserAction.getCurrentFile();
    addString("Current panel file: " + (panel == null ? "[none]" : panel.getPath()) + "   ");
    //String operations = jmri.jmrit.operations.setup.OperationsSetupXml.getFileLocation();
    //addString("Operations files location: "+operations+"  ");
    jmri.jmrit.audio.AudioFactory af = jmri.InstanceManager.getDefault(jmri.AudioManager.class).getActiveAudioFactory();
    String audio = af != null ? af.toString() : "[not initialised]";
    addString("Audio factory type: " + audio + "   ");
    addProperty("java.version");
    addProperty("java.vendor");
    addProperty("java.home");
    addProperty("java.vm.version");
    addProperty("java.vm.vendor");
    addProperty("java.vm.name");
    addProperty("java.specification.version");
    addProperty("java.specification.vendor");
    addProperty("java.specification.name");
    addProperty("java.class.version");
    addProperty("java.class.path");
    addProperty("java.library.path");
    addProperty("java.compiler");
    addProperty("java.ext.dirs");
    addProperty("file.encoding");
    addProperty("os.name");
    addProperty("os.arch");
    addProperty("os.version");
    addProperty("python.home");
    addProperty("python.path");
    addProperty("python.cachedir");
    addProperty("python.cachedir.skip");
    addProperty("python.startup");
    addProperty("user.name");
    addProperty("user.home");
    addProperty("user.dir");
    addProperty("user.country");
    addProperty("user.language");
    addProperty("user.timezone");
    addProperty("jmri.log.path");
    addString("FileSystemView#getDefaultDirectory(): " + javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory().getPath());
    addString("FileSystemView#getHomeDirectory(): " + javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory().getPath());
    addString("Default JFileChooser(): " + (new javax.swing.JFileChooser()).getCurrentDirectory().getPath());
    addScreenSize();
    if (reportNetworkInfo) {
        addNetworkInfo();
    }
    return report;
}
Also used : Profile(jmri.profile.Profile) ConnectionConfigManager(jmri.jmrix.ConnectionConfigManager) File(java.io.File) ConnectionConfig(jmri.jmrix.ConnectionConfig)

Example 13 with Profile

use of jmri.profile.Profile in project JMRI by JMRI.

the class ReportPanel method sendButtonActionPerformed.

@SuppressWarnings("unchecked")
public void sendButtonActionPerformed(java.awt.event.ActionEvent e) {
    try {
        sendButton.setEnabled(false);
        log.debug("initial checks");
        InternetAddress email = new InternetAddress(emailField.getText());
        email.validate();
        log.debug("start send");
        //NO18N
        String charSet = "UTF-8";
        //NOI18N
        String requestURL = "http://jmri.org/problem-report.php";
        MultipartMessage msg = new MultipartMessage(requestURL, charSet);
        // add reporter email address
        log.debug("start creating message");
        msg.addFormField("reporter", emailField.getText());
        // add if to Cc sender
        msg.addFormField("sendcopy", checkCopy.isSelected() ? "yes" : "no");
        // add problem summary
        msg.addFormField("summary", summaryField.getText());
        // build detailed error report (include context if selected)
        String report = descField.getText() + "\r\n";
        if (checkContext.isSelected()) {
            //NOI18N
            report += "=========================================================\r\n";
            report += (new ReportContext()).getReport(checkNetwork.isSelected() && checkNetwork.isEnabled());
        }
        msg.addFormField("problem", report);
        log.debug("start adding attachments");
        // add panel file if OK
        if (checkPanel.isSelected()) {
            log.debug("prepare panel attachment");
            // Check that some startup panel files have been loaded
            for (PerformFileModel m : InstanceManager.getDefault(StartupActionsManager.class).getActions(PerformFileModel.class)) {
                String fn = m.getFileName();
                File f = new File(fn);
                log.debug("add startup panel file: {}", f);
                msg.addFilePart("logfileupload[]", f);
            }
            // Check that a manual panel file has been loaded
            File file = jmri.configurexml.LoadXmlUserAction.getCurrentFile();
            if (file != null) {
                log.debug("add manual panel file: {}", file.getPath());
                msg.addFilePart("logfileupload[]", jmri.configurexml.LoadXmlUserAction.getCurrentFile());
            } else {
                // No panel file loaded
                log.warn("No manual panel file loaded - not sending");
            }
        }
        // add profile files if OK
        if (checkProfile.isSelected()) {
            log.debug("prepare profile attachment");
            // Check that a profile has been loaded
            Profile profile = ProfileManager.getDefault().getActiveProfile();
            File file = profile.getPath();
            if (file != null) {
                log.debug("add profile: {}", file.getPath());
                // Now zip-up contents of profile
                // Create temp file that will be deleted when Java quits
                File temp = File.createTempFile("profile", ".zip");
                temp.deleteOnExit();
                FileOutputStream out = new FileOutputStream(temp);
                ZipOutputStream zip = new ZipOutputStream(out);
                addDirectory(zip, file);
                zip.close();
                out.close();
                msg.addFilePart("logfileupload[]", temp);
            } else {
                // No profile loaded
                log.warn("No profile loaded - not sending");
            }
        }
        // add the log if OK
        if (checkLog.isSelected()) {
            log.debug("prepare log attachments");
            // search for an appender that stores a file
            for (java.util.Enumeration<org.apache.log4j.Appender> en = org.apache.log4j.Logger.getRootLogger().getAllAppenders(); en.hasMoreElements(); ) {
                // does this have a file?
                org.apache.log4j.Appender a = en.nextElement();
                // see if it's one of the ones we know
                if (log.isDebugEnabled()) {
                    log.debug("check appender {}", a);
                }
                try {
                    org.apache.log4j.FileAppender f = (org.apache.log4j.FileAppender) a;
                    log.debug("find file: {}", f.getFile());
                    msg.addFilePart("logfileupload[]", new File(f.getFile()), "application/octet-stream");
                } catch (ClassCastException ex) {
                }
            }
        }
        log.debug("done adding attachments");
        // finalise and get server response (if any)
        log.debug("posting report...");
        List<String> response = msg.finish();
        log.debug("send complete");
        log.debug("server response:");
        boolean checkResponse = false;
        for (String line : response) {
            log.debug("               :{}", line);
            if (line.contains("<p>Message successfully sent!</p>")) {
                checkResponse = true;
            }
        }
        if (checkResponse) {
            JOptionPane.showMessageDialog(null, rb.getString("InfoMessage"), rb.getString("InfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            // close containing Frame
            getTopLevelAncestor().setVisible(false);
        } else {
            // TODO add Bundle to folder and use ErrorTitle key in NamedBeanBundle props
            JOptionPane.showMessageDialog(null, rb.getString("ErrMessage"), rb.getString("ErrTitle"), JOptionPane.ERROR_MESSAGE);
            sendButton.setEnabled(true);
        }
    } catch (IOException ex) {
        log.error("Error when attempting to send report: " + ex);
        sendButton.setEnabled(true);
    } catch (AddressException ex) {
        log.error("Invalid email address: " + ex);
        // TODO add Bundle to folder and use ErrorTitle key in NamedBeanBundle props
        JOptionPane.showMessageDialog(null, rb.getString("ErrAddress"), rb.getString("ErrTitle"), JOptionPane.ERROR_MESSAGE);
        sendButton.setEnabled(true);
    }
}
Also used : MultipartMessage(jmri.util.MultipartMessage) InternetAddress(javax.mail.internet.InternetAddress) StartupActionsManager(apps.StartupActionsManager) IOException(java.io.IOException) Profile(jmri.profile.Profile) PerformFileModel(apps.PerformFileModel) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) AddressException(javax.mail.internet.AddressException) File(java.io.File)

Example 14 with Profile

use of jmri.profile.Profile in project JMRI by JMRI.

the class ConnectionConfigManagerTest method testInitialize_EmptyProfile.

/**
     * Test of initialize method, of class ConnectionConfigManager.
     *
     * @throws java.io.IOException if untested condition (most likely inability
     *                             to write to temp space) fails
     */
@Test
public void testInitialize_EmptyProfile() throws IOException {
    String id = Long.toString((new Date()).getTime());
    Profile profile = new Profile(this.getClass().getSimpleName(), id, new File(this.workspace.toFile(), id));
    ConnectionConfigManager instance = new ConnectionConfigManager();
    try {
        instance.initialize(profile);
    } catch (InitializationException ex) {
        Assert.fail(ex.getMessage());
    }
}
Also used : InitializationException(jmri.util.prefs.InitializationException) File(java.io.File) Date(java.util.Date) Profile(jmri.profile.Profile) Test(org.junit.Test)

Example 15 with Profile

use of jmri.profile.Profile in project JMRI by JMRI.

the class AbstractPreferencesManager method requiresNoInitializedWithExceptions.

/**
     * Require that instances of the specified classes have initialized
     * correctly. This method should only be called from within
     * {@link #initialize(jmri.profile.Profile)}, generally immediately after
     * the PreferencesManager verifies that it is not already initialized. If
     * this method is within a try-catch block, the exception it generates
     * should be re-thrown by initialize(profile).
     *
     * @param profile the profile against which the manager is being initialized
     * @param classes the manager classes for which all calling
     *                {@link #isInitialized(jmri.profile.Profile)} must return
     *                true against all instances of
     * @param message the localized message to display if an
     *                InitializationExcpetion is thrown
     * @throws InitializationException  if any instance of any class in classes
     *                                  returns false on isIntialized(profile)
     * @throws IllegalArgumentException if any member of classes is not also in
     *                                  the set of classes returned by
     *                                  {@link #getRequires()}
     */
protected void requiresNoInitializedWithExceptions(@Nonnull Profile profile, @Nonnull Set<Class<? extends PreferencesManager>> classes, @Nonnull String message) throws InitializationException {
    classes.stream().filter((clazz) -> (!this.getRequires().contains(clazz))).forEach((clazz) -> {
        throw new IllegalArgumentException("Class " + clazz.getClass().getName() + " not marked as required by " + this.getClass().getName());
    });
    for (Class<? extends PreferencesManager> clazz : classes) {
        for (PreferencesManager instance : InstanceManager.getList(clazz)) {
            if (instance.isInitializedWithExceptions(profile)) {
                InitializationException exception = new InitializationException("Refusing to initialize", message);
                this.addInitializationException(profile, exception);
                this.setInitialized(profile, true);
                throw exception;
            }
        }
    }
}
Also used : HashSet(java.util.HashSet) InstanceManager(jmri.InstanceManager) List(java.util.List) ConnectionConfigManager(jmri.jmrix.ConnectionConfigManager) PreferencesManager(jmri.spi.PreferencesManager) Bean(jmri.beans.Bean) Profile(jmri.profile.Profile) Set(java.util.Set) HashMap(java.util.HashMap) Nonnull(javax.annotation.Nonnull) ArrayList(java.util.ArrayList) PreferencesManager(jmri.spi.PreferencesManager)

Aggregations

Profile (jmri.profile.Profile)23 File (java.io.File)14 Date (java.util.Date)7 ArrayList (java.util.ArrayList)6 InitializationException (jmri.util.prefs.InitializationException)6 HashMap (java.util.HashMap)5 List (java.util.List)5 Set (java.util.Set)5 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 IOException (java.io.IOException)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 PropertyChangeEvent (java.beans.PropertyChangeEvent)3 HashSet (java.util.HashSet)3 Locale (java.util.Locale)3 Map (java.util.Map)3 ServiceLoader (java.util.ServiceLoader)3 ProfileUtils (jmri.profile.ProfileUtils)3 AbstractPreferencesManager (jmri.util.prefs.AbstractPreferencesManager)3 Test (org.junit.Test)3