Example usage for org.apache.commons.collections15 Closure execute

List of usage examples for org.apache.commons.collections15 Closure execute

Introduction

In this page you can find the example usage for org.apache.commons.collections15 Closure execute.

Prototype

public void execute(T input);

Source Link

Document

Performs an action on the specified input object.

Usage

From source file:com.diversityarrays.dal.db.bms.BmsConnectionInfo.java

@SuppressWarnings("unchecked")
BmsConnectionInfo(JdbcConnectionParameters local, JdbcConnectionParameters central, Closure<String> progress)
        throws DalDbException {

    if (progress == null) {
        progress = ClosureUtils.nopClosure();
    }/*from w  ww .  jav  a 2 s. c  o  m*/

    this.localParams = local;
    this.centralParams = central;

    List<SQLException> errors = new ArrayList<SQLException>();
    try {
        if (localParams != null) {
            progress.execute("Connecting to " + localParams.connectionUrl);
            localConnection = createLocalConnection();
        }

        progress.execute("Connecting to " + centralParams.connectionUrl);
        centralConnection = createCentralConnection();

        int totalGids = 0;
        for (Connection c : Arrays.asList(centralConnection, localConnection)) {
            if (c != null) {
                Integer count = SqlUtil.getSingleInteger(c, "SELECT COUNT(*) FROM GERMPLSM");
                if (count != null) {
                    totalGids += count;
                }
            }
        }
        progress.execute("Total of " + totalGids + " GERMPLSM records in database");

        collectUserTypes(progress);

        collectFldnoForGenus(progress);

        if (fldNoForGenus == null) {
            StringBuilder sb = new StringBuilder("Missing FLDNO values for:");
            sb.append("\n").append(genusFromSpecies ? SPECIES_NAME_CONSTRAINT : TAXONOMY_CONSTRAINT);
            throw new DalDbException(sb.toString());
        }

        genusStore = new GenusStore(centralConnection, fldNoForGenus, progress);
        // TODO Determine if need to populate from local database as well

    } catch (SQLException e) {
        errors.add(e);
    } finally {
        if (!errors.isEmpty()) {
            closeConnections();
        }
    }

    if (!errors.isEmpty()) {
        // Just the first one!
        throw new DalDbException(errors.get(0));
    }
}

From source file:com.diversityarrays.dal.server.TestFiltering.java

public void testExpressions(boolean shouldPass, String[] expressions, Closure<Filtering> check,
        String... expectedColumnNames) {
    for (String expr : expressions) {
        Filtering f = new Filtering(expr);
        if (shouldPass) {
            if (f.error != null) {
                fail(expr + ": " + f.error);
            }/*from ww  w.  j  a  v  a  2 s.  co m*/
            Collection<String> coll = new ArrayList<String>(f.columnNames);

            for (String expectedColumnName : expectedColumnNames) {
                if (!coll.remove(expectedColumnName)) {
                    fail(expr + ": Missing expected columnName '" + expectedColumnName + "'");
                }
            }

            if (!coll.isEmpty()) {
                fail(expr + ": Missing unexpected columnNames: " + join(",", coll));
            }
            if (check != null) {
                check.execute(f);
            }
        } else {
            if (f.error == null) {
                fail(expr + ": VALID but should not be!");
            }
        }
    }
}

From source file:com.diversityarrays.dal.db.kddart.KddartDalDatabase.java

public KddartDalDatabase(Closure<String> progress, boolean test, URI uri, String username, String password,
        Boolean autoSwitchGroup) throws DalDbException {
    super("KDDart-DAL@" + uri.toString());

    this.dalUrl = uri.toString();
    this.dalUsername = username;
    this.dalPassword = password;
    this.autoSwitchGroupOnLogin = autoSwitchGroup == null ? false : autoSwitchGroup.booleanValue();

    entityClassByName.put("genus", Genus.class);
    entityClassByName.put("genotype", Genotype.class);

    if (test) {// w  w w . jav a  2s. c  o  m
        DALClient client = new DefaultDALClient(dalUrl);
        try {
            progress.execute("Attempting login to " + dalUrl);
            client.login(username, password);
        } catch (DalException e) {
            throw new DalDbException(e);
        } catch (IOException e) {
            throw new DalDbException(e);
        } finally {
            client.logout();
        }
    }
}

From source file:com.diversityarrays.kdxplore.trials.TrialSelectionSearchOptionsPanel.java

private void initialiseLookups(final DALClient client) {

    lookupsInitialised = InitState.INITIALISING;

    // Returns the Set of LookupTables which were loaded
    // (if user cancelled then we don't get them all)
    // TODO make this fact visible !
    BackgroundTask<Set<LookupTable<?>>, Chunk<?>> task = new BackgroundTask<Set<LookupTable<?>>, Chunk<?>>(
            "Loading Lookups...", false) {

        @Override//from  www  . j a v a  2s . co  m
        public boolean onTaskStart() {
            // Do this otherwise when we twist it open after loading nothing happens!
            // TODO figure out why and fix it.
            treeTable.collapseAll();
            return true;
        }

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override
        public Set<LookupTable<?>> generateResult(final Closure<Chunk<?>> publishPartial) throws Exception {
            Set<LookupTable<?>> processed = new HashSet<LookupTable<?>>();

            for (LookupTable lt : lookupTables) {
                LookupTableNode node = lookupTableRootNodeByTable.get(lt);
                node.clear();

                // This is the callback from getLookupRecords()
                Transformer<Chunk<?>, Boolean> consumer = new Transformer<Chunk<?>, Boolean>() {
                    @Override
                    public Boolean transform(Chunk<?> chunk) {
                        publishPartial.execute(chunk);
                        return !cancelRequested;
                    }
                };

                if (!lt.getLookupRecords(client, CHUNK_SIZE, consumer)) {
                    break;
                }

                processed.add(lt);
            }
            lookupsInitialised = InitState.DONE;

            return processed;
        }

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override
        public void processPartial(List<Chunk<?>> chunks) {
            for (Chunk chunk : chunks) {
                LookupTable<?> lt = chunk.lookupTable;
                LookupTableNode node = lookupTableRootNodeByTable.get(lt);
                node.addRecords(chunk.payload);
            }
        }

        @SuppressWarnings("rawtypes")
        @Override
        public void onTaskComplete(Set<LookupTable<?>> processed) {
            for (LookupTable lt : lookupTableRootNodeByTable.keySet()) {
                LookupTableNode node = lookupTableRootNodeByTable.get(lt);
                node.establishLoadState(processed.contains(lt));
            }
            //            treeTable.repaint();
            treeTable.expandAll();

            GuiUtil.initialiseTableColumnWidths(treeTable);

            fireLookupsLoaded();
            //            TrialSelectionSearchOptionsPanel.this.firePropertyChange(PROP_LOOKUPS_LOADED, false, true);
        }

        @Override
        public void onException(Throwable cause) {
            cause.printStackTrace();
            MsgBox.error(TrialSelectionSearchOptionsPanel.this, cause, "Failed to load Lookup Tables");
        }

        @Override
        public void onCancel(CancellationException e) {
            throw new RuntimeException(e); // should never happen
        }

        @Override
        public void onInterrupt(InterruptedException e) {
            lookupsInitialised = InitState.INCOMPLETE;
            MsgBox.error(TrialSelectionSearchOptionsPanel.this, "You chose to cancel the load operation",
                    "Lookup Tables may be incomplete");
        }

    };

    backgroundRunner.runBackgroundTask(task);
}

From source file:com.diversityarrays.kdxplore.curate.CurationCellEditorImpl.java

@Override
public void acceptOrSuppressEditedSamples(List<CurationCellValue> ccvList, String reasonForSuppression,
        Closure<List<EditedSampleInfo>> register) {
    boolean suppressing = reasonForSuppression != null;

    List<EditedSampleInfo> infoList = new ArrayList<>();

    final SampleType sampleType = sampleEntryPanel.getSelectedSampleType();

    for (CurationCellValue ccv : ccvList) {

        String traitValue = null;
        java.util.Date when = null;

        // If editedSample alreadyExists then don't change it
        KdxSample editedSample = ccv.getEditedSample();
        if (editedSample != null) {
            if (suppressing == editedSample.isSuppressed()) {
                // doing the same thing as the sample's suppression state so NO need to change
                continue;
            }//  w w  w.j  a  va  2  s. c  om
            // If we get here we are changing it
            traitValue = editedSample.getTraitValue();
            when = editedSample.getMeasureDateTime();

            // It shouldn't be null but let's just protect
            KdxSample newEditedSample = curationData.createEditedSampleMeasurement(ccv, traitValue, when,
                    sampleType, reasonForSuppression);

            infoList.add(new EditedSampleInfo(ccv.getCurationCellId(), editedSample, newEditedSample));
        }
    } // each ccv

    if (!infoList.isEmpty()) {
        register.execute(infoList);
    }

    refreshFieldLayoutView.execute(null);
    this.repaint();
}

From source file:com.diversityarrays.kdxplore.trials.TrialOverviewPanel.java

public TrialOverviewPanel(String title, OfflineData offdata, TrialExplorerManager manager,
        FileListTransferHandler flth, MessagePrinter mp, final Closure<List<Trial>> onTrialSelected) {
    super(new BorderLayout());

    offlineData = offdata;//from  w  w  w  .ja v a2  s.co m
    KdxploreDatabase kdxdb = offlineData.getKdxploreDatabase();
    if (kdxdb != null) {
        kdxdb.addEntityChangeListener(trialChangeListener);
        kdxdb.addEntityChangeListener(traitChangeListener);
    }

    this.messagePrinter = mp;

    TableTransferHandler tth = TableTransferHandler.initialiseForCopySelectAll(trialsTable, true);
    trialsTable.setTransferHandler(new ChainingTransferHandler(flth, tth));
    trialsTable.setAutoCreateRowSorter(true);

    trialsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                List<Trial> selectedTrials = getSelectedTrials();
                if (selectedTrials.size() == 1) {
                    trialTraitsTableModel.setSelectedTrial(selectedTrials.get(0));
                } else {
                    trialTraitsTableModel.setSelectedTrial(null);
                }
                onTrialSelected.execute(selectedTrials);
            }
        }
    });
    trialsTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
                fireEditCommand(e);
            }
        }
    });

    GuiUtil.setVisibleRowCount(trialsTable, MAX_INITIAL_VISIBLE_TRIAL_ROWS);

    offlineData.addOfflineDataChangeListener(offlineDataChangeListener);

    trialTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            updateRefreshAction();
        }
    });
    trialTraitsTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            updateAddTraitAction();
            updateRemoveTraitAction();
            updateScoringOrderAction();
        }
    });
    trialTraitsTable.addMouseListener(new MouseAdapter() {

        List<Trait> selectedTraits;
        JPopupMenu popupMenu;
        Action showTraitsAction = new AbstractAction("Select in Trait Explorer") {
            @Override
            public void actionPerformed(ActionEvent e) {
                manager.showTraitsInTraitExplorer(selectedTraits);
            }
        };

        @Override
        public void mouseClicked(MouseEvent e) {

            if (SwingUtilities.isLeftMouseButton(e) && 2 == e.getClickCount()) {
                // Start editing the Trait
                e.consume();
                int vrow = trialTraitsTable.rowAtPoint(e.getPoint());
                if (vrow >= 0) {
                    int mrow = trialTraitsTable.convertRowIndexToModel(vrow);
                    if (mrow >= 0) {
                        Trait trait = trialTraitsTableModel.getTraitAt(mrow);
                        if (trait != null) {
                            traitExplorer.startEditing(trait);
                            ;
                        }
                    }
                }
            } else if (SwingUtilities.isRightMouseButton(e) && 1 == e.getClickCount()) {
                // Select the traits in the traitExplorer
                e.consume();
                List<Integer> modelRows = GuiUtil.getSelectedModelRows(trialTraitsTable);
                if (!modelRows.isEmpty()) {
                    selectedTraits = modelRows.stream().map(trialTraitsTableModel::getTraitAt)
                            .collect(Collectors.toList());

                    if (popupMenu == null) {
                        popupMenu = new JPopupMenu();
                        popupMenu.add(showTraitsAction);
                    }
                    Point pt = e.getPoint();
                    popupMenu.show(trialTraitsTable, pt.x, pt.y);
                }
            }
        }
    });
    trialTraitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                updateRemoveTraitAction();
            }
        }
    });
    updateAddTraitAction();
    updateRemoveTraitAction();
    updateScoringOrderAction();
    updateRefreshAction();

    KDClientUtils.initAction(ImageId.REFRESH_24, refreshTrialTraitsAction, "Refresh");
    KDClientUtils.initAction(ImageId.MINUS_GOLD_24, removeTraitAction, "Remove selected Traits");
    KDClientUtils.initAction(ImageId.PLUS_BLUE_24, addTraitAction, "Add Traits to Trial");
    KDClientUtils.initAction(ImageId.TRAIT_ORDER_24, setScoringOrderAction, "Define Trait Scoring Order");

    Box buttons = Box.createHorizontalBox();

    buttons.add(new JButton(setScoringOrderAction));
    buttons.add(Box.createHorizontalGlue());
    buttons.add(new JButton(addTraitAction));
    buttons.add(new JButton(removeTraitAction));
    buttons.add(Box.createHorizontalStrut(10));
    buttons.add(refreshTrialTraitsButton);

    JPanel traitsPanel = new JPanel(new BorderLayout());
    traitsPanel.add(GuiUtil.createLabelSeparator("Uses Traits", buttons), BorderLayout.NORTH);
    traitsPanel.add(new PromptScrollPane(trialTraitsTable,
            "If the (single) selected Trial has Traits they will appear here"), BorderLayout.CENTER);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(trialsTable), traitsPanel);
    splitPane.setResizeWeight(0.5);

    add(splitPane, BorderLayout.CENTER);
}

From source file:com.diversityarrays.kdxplore.vistool.VisToolbarFactory.java

static public VisToolToolBar create(final String title, final JComponent comp, final Closure<File> snapshotter,
        final VisToolDataProvider visToolDataProvider, boolean floatable, final String[] imageSuffixes) {
    Window window = GuiUtil.getOwnerWindow(comp);

    boolean anyButtons = false;

    final JCheckBox keepOnTop;

    if (window == null) {
        keepOnTop = null;/*from   w  ww .  jav  a  2s. co  m*/
    } else {
        anyButtons = true;
        keepOnTop = new JCheckBox(Msg.OPTION_KEEP_ON_TOP(), true);

        keepOnTop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                window.setAlwaysOnTop(keepOnTop.isSelected());
            }
        });
        window.setAlwaysOnTop(keepOnTop.isSelected());

        //         buttons.add(keepOnTop);

        final PropertyChangeListener alwaysOnTopListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                keepOnTop.setSelected(window.isAlwaysOnTop());
            }
        };
        window.addPropertyChangeListener(PROPERTY_ALWAYS_ON_TOP, alwaysOnTopListener);

        window.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                window.removeWindowListener(this);
                window.removePropertyChangeListener(PROPERTY_ALWAYS_ON_TOP, alwaysOnTopListener);
            }
        });
    }

    final JButton cameraButton;
    if (snapshotter == null) {
        cameraButton = null;
    } else {
        Action cameraAction = new AbstractAction(Msg.ACTION_SNAPSHOT()) {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (chooser == null) {
                    chooser = new JFileChooser();
                    chooser.setFileFilter(new FileFilter() {
                        @Override
                        public boolean accept(File f) {
                            if (!f.isFile()) {
                                return true;
                            }
                            String loname = f.getName().toLowerCase();
                            for (String sfx : imageSuffixes) {
                                if (loname.endsWith(sfx)) {
                                    return true;
                                }
                            }
                            return false;
                        }

                        @Override
                        public String getDescription() {
                            return Msg.DESC_IMAGE_FILE();
                        }
                    });
                    chooser.setMultiSelectionEnabled(false);
                    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                }

                if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(comp)) {
                    File file = chooser.getSelectedFile();
                    snapshotter.execute(file);
                }
            }
        };

        ImageIcon icon = loadIcon("camera-24.png"); //$NON-NLS-1$
        if (icon != null) {
            cameraAction.putValue(Action.SMALL_ICON, icon);
            cameraAction.putValue(Action.NAME, null);
        }

        anyButtons = true;
        cameraButton = new JButton(cameraAction);
    }

    final JButton refreshButton;
    if (visToolDataProvider == null) {
        refreshButton = null;
    } else {
        anyButtons = true;

        refreshButton = new JButton(Msg.ACTION_REFRESH());

        ImageIcon icon = loadIcon("refresh-24.png"); //$NON-NLS-1$
        if (icon != null) {
            refreshButton.setIcon(icon);
            // don't remove the name
        }

        refreshButton.setForeground(Color.RED);
        refreshButton.setEnabled(false);

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (visToolDataProvider.refreshData()) {
                    refreshButton.setEnabled(false);
                }
            }
        });

        visToolDataProvider.addVisToolDataChangedListener(new VisToolDataChangedListener() {
            @Override
            public void visToolDataChanged(Object source) {
                refreshButton.setEnabled(true);
            }
        });
    }

    VisToolToolBar toolBar = null;

    if (anyButtons) {
        toolBar = new VisToolToolBar(keepOnTop, cameraButton, refreshButton);
        toolBar.setFloatable(floatable);
    }
    return toolBar;

}

From source file:com.diversityarrays.kdxplore.trials.TrialExplorerPanel.java

/**
 * Called because the user changed the client's URL by logging in to a
 * different database.//from www . j a  va 2 s .  c o m
 * 
 * @param why
 * @param client
 * @param onLoadComplete
 */
private void loadDatabaseDataFromKddart(final String prefix, UrlChangeConfirmation confirmation,
        final DALClient client, final Closure<DALClient> onLoadComplete) {
    String why = prefix + confirmation.reason;

    String dbfilename = KdxploreDatabase.LOCAL_DATABASE_URL;
    switch (confirmation) {
    case NEW_DATABASE:
        dbfilename = KdxploreDatabase.LOCAL_DATABASE_URL;
        break;
    case CHANGE_APPROVED:
    case NO_CHANGE_SAME_URL:
        dbfilename = DatabaseDataUtils.normaliseUrlForFilename(client.getBaseUrl());
        break;
    case CHANGE_DENIED:
        throw new IllegalStateException("loadDatabaseDataFromKddart with " + confirmation);
    }

    final File dbdataDirectory = new File(userDataFolder, dbfilename);

    Closure<Throwable> onFailure = new Closure<Throwable>() {
        @Override
        public void execute(Throwable t) {
            messagePrinter.println("Problem loading database from: " + dbdataDirectory.getPath());
            messagePrinter.println(t.getMessage());

            MsgBox.error(TrialExplorerPanel.this, t, why);
            onLoadComplete.execute(null);
        }
    };

    Closure<DALClient> onSuccess = new Closure<DALClient>() {
        @Override
        public void execute(DALClient dalClient) {
            onLoadComplete.execute(dalClient);
        }
    };

    offlineData.loadDatabaseDataFromKddart("Loading Reference Data from KDDart", driverType, dbdataDirectory,
            client, messageLogger, backgroundRunner, onFailure, onSuccess);
}

From source file:com.diversityarrays.kdxplore.curate.CurationCellEditorImpl.java

/**
 * /* w  w  w. ja v a 2  s  . c  o m*/
 * @param selectedDeviceName
 * @param ccvList
 * @param reasonForSuppression
 * @param register
 */
@Override
public void acceptOrSuppressValueIgnoringParameters(ValueForUnscored valueForUnscored, SampleSource source,
        List<CurationCellValue> ccvList, String reasonForSuppression,
        Closure<List<EditedSampleInfo>> register) {
    List<EditedSampleInfo> infoList = new ArrayList<>();

    final SampleType sampleType = sampleEntryPanel.getSelectedSampleType();

    final java.util.Date now = new java.util.Date();

    for (CurationCellValue ccv : ccvList) {
        // If editedSample alreadyExists then don't change it
        KdxSample editedSample = ccv.getEditedSample();
        if (editedSample != null) {
            continue;
        }

        String traitValue = null;
        java.util.Date when = null;

        KdxSample sampleToUse = null;
        if (source.equals(SampleSource.MOST_RECENT)) {
            sampleToUse = ccv.getLatestRawSample();
        } else if (source == SampleSource.DATABASE) {
            sampleToUse = ccv.getDatabaseSample();
        } else if (source == SampleSource.CURATED) {
            sampleToUse = ccv.getEditedSample();
            //         } else if (source == SampleSource.SCORING) {
            //            //TODO - Check on whether SampleSource.SCORING is still relevant
            //             sampleToUse = null;
        } else {
            //TODO - TODO - TODO This does currently not support multiple different samples for the same plot
            // from the same device. It only grabs the first one it finds.
            sampleToUse = sampleEntryPanel.findSampleForDevice(ccv, source.sampleGroupId);
        }

        boolean applyValueForUnscored;
        if (sampleToUse != null && sampleToUse.hasBeenScored()) {
            traitValue = sampleToUse.getTraitValue();

            switch (TraitValue.classify(traitValue)) {
            case MISSING:
            case NA:
            case SET:
                when = sampleToUse.getMeasureDateTime();
                applyValueForUnscored = false;
                break;

            case UNSET:
            default:
                applyValueForUnscored = true;
                traitValue = null;
                when = null;
                break;
            }
        } else {
            applyValueForUnscored = true;
        }

        boolean doSample = true;
        if (applyValueForUnscored) {
            switch (valueForUnscored) {
            case DONT_USE:
                doSample = false;
                break;
            case MISSING:
                traitValue = TraitValue.VALUE_MISSING;
                when = now;
                break;
            case NA:
                traitValue = TraitValue.VALUE_NA;
                when = now;
                break;
            default:
                throw new RuntimeException("Unhandled ValueForUnscored: " + valueForUnscored); //$NON-NLS-1$
            }
        }

        if (doSample) {
            KdxSample newEditedSample = curationData.createEditedSampleMeasurement(ccv, traitValue, when,
                    sampleType, reasonForSuppression);

            infoList.add(new EditedSampleInfo(ccv.getCurationCellId(), editedSample, newEditedSample));
            ccv.setEditedSample(newEditedSample); // ignore boolean result
        }
    } // each ccv

    if (!infoList.isEmpty()) {
        register.execute(infoList);
    }

    refreshFieldLayoutView.execute(null);
    this.repaint();
}

From source file:com.diversityarrays.kdxplore.KDXplore.java

public static void mainImpl(String[] args, Closure<KDXploreFrame> onCreateCallback,
        final Closure<UpdateCheckContext> updateChecker) {
    Locale defaultLocale = Locale.getDefault();
    System.out.println("Locale=" + defaultLocale); //$NON-NLS-1$

    // System.setProperty("apple.laf.useScreenMenuBar", "true");
    // //$NON-NLS-1$ //$NON-NLS-2$

    // Initialise the appFolder

    KdxplorePreferences prefs = KdxplorePreferences.getInstance();
    applyUIdefaultPreferences(prefs);//from  w ww . j  av a2s  .  c  o  m

    String kdxploreName = KDXPLORE_APP_NAME;
    ApplicationFolder defaultAppFolder = ApplicationFolders.getApplicationFolder(kdxploreName);
    String[] newArgs = CommandArgs.parseRunModeOption(defaultAppFolder, args);

    String baseNameForDistrib = kdxploreName.toLowerCase();
    if (RunMode.DEMO == RunMode.getRunMode()) {
        kdxploreName = kdxploreName + "Demo"; //$NON-NLS-1$
    }
    final ApplicationFolder appFolder = ApplicationFolders.getApplicationFolder(kdxploreName);
    CommandArgs commandArgs = new CommandArgs(appFolder, KdxConstants.VERSION, KdxConstants.VERSION_CODE,
            newArgs);

    org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(ClassPathExtender.class);

    if (commandArgs.baseDir == null) {
        File userDir = new File(System.getProperty("user.dir")); //$NON-NLS-1$

        File distribDir;
        if ("kdxos_main".equals(userDir.getName())) {
            // In Eclipse project this is where we store it
            distribDir = new File(userDir.getParentFile(), baseNameForDistrib);
        } else {
            distribDir = new File(userDir, baseNameForDistrib);
        }

        System.out.println("userDir=" + userDir); //$NON-NLS-1$
        System.out.println("distribDir=" + distribDir); //$NON-NLS-1$

        commandArgs.baseDir = distribDir.isDirectory() ? distribDir : userDir;
    }

    if (!commandArgs.baseDir.isDirectory()) {
        GuiUtil.errorMessage(null, "baseDir is not a directory: " + commandArgs.baseDir); //$NON-NLS-1$
        System.exit(1);
    }

    File libDir = new File(commandArgs.baseDir, "lib"); //$NON-NLS-1$
    File[] libFiles = libDir.listFiles();
    if (libFiles == null) {
        MsgBox.error(null, Msg.MSG_APP_START_DIRECTORY(kdxploreName, commandArgs.baseDir),
                Msg.ERRTITLE_MISSING_LIBRARY_FILES() + ": " + libDir.getPath());
        System.exit(1);
    } else if (libFiles.length < REQD_LIB_COUNT) {
        MsgBox.error(null, Msg.MSG_APP_START_DIRECTORY(kdxploreName, commandArgs.baseDir),
                Msg.ERRTITLE_MISSING_LIBRARY_FILES() + ": " + libFiles.length);
        System.exit(1);
    }

    // = = = = = = = = = = = = = = = = = = =
    // = = = = = = = = = = = = = = = = = = =
    // = = = = = = = CLASSPATH = = = = = = =
    ClassPathExtender.VERBOSE = !commandArgs.quiet; // RunMode.getRunMode().isDeveloper();
    String libs_sb = "lib,plugins,kdxlibs,../runlibs"; //$NON-NLS-1$

    boolean[] seenPdfbox = new boolean[1];
    Consumer<File> jarChecker = new Consumer<File>() {
        @Override
        public void accept(File f) {
            if (f.getName().startsWith("pdfbox")) {
                seenPdfbox[0] = true;
            }
        }
    };
    ClassPathExtender.appendToClassPath(commandArgs.baseDir, libs_sb, jarChecker, log);
    if (seenPdfbox[0]) {
        System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");
    }

    // = = = = = = = = = = = = = = = = = = =
    // = = = = = = = = = = = = = = = = = = =
    // = = = = = = = = = = = = = = = = = = =

    doStaticInitChecks(commandArgs.quiet);
    if (commandArgs.runInitChecks) {
        System.out.println("Init checks OK"); //$NON-NLS-1$
        System.exit(0);
    }

    establishLogger(appFolder);

    @SuppressWarnings("unused")
    String configName = commandArgs.establishKdxConfig();

    Long versionSubinfo = null;
    if (commandArgs.errmsg == null) {
        if (!KdxploreConfig.getInstance().isEternal()) {
            commandArgs.expiryChecks(KdxConstants.VERSION);
            versionSubinfo = KdxConstants.getVersionSubinfo();
            if (versionSubinfo == Long.MAX_VALUE) {
                versionSubinfo = null;
            }
        }
    }

    String baseTitle = appFolder.getApplicationName() + " v" + KdxConstants.VERSION; //$NON-NLS-1$

    String expiresIn = ""; //$NON-NLS-1$
    if (versionSubinfo != null) {
        if ((0 < versionSubinfo && versionSubinfo < 14) || RunMode.getRunMode().isDeveloper()) {
            expiresIn = " " + Msg.KDX_EXPIRES_IN_N_DAYS(versionSubinfo.intValue()); //$NON-NLS-1$
        }
    }
    if (commandArgs.errmsg != null) {
        JOptionPane.showMessageDialog(null, commandArgs.errmsg, baseTitle + expiresIn,
                JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    final String kdxploreTitle = buildKdxploreTitle(baseTitle, expiresIn,
            commandArgs.kdxConfigService.getConfigName());

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            // TODO allow user to change "base font size"
            String uiMultiplier = null;
            try {
                String propertyName = CommandArgs.UI_MULTIPLIER_PROPERTY_NAME;
                uiMultiplier = System.getProperty(propertyName);
                if (uiMultiplier != null) {
                    try {
                        float multiplier = Float.parseFloat(uiMultiplier);
                        setUIfontSize(multiplier);
                    } catch (NumberFormatException e) {
                        System.err.println(String.format("?invalid value for %s: %s", //$NON-NLS-1$
                                propertyName, uiMultiplier));
                    }
                }
            } catch (SecurityException e) {
                System.err.println(String.format("Ignoring: %s %s", //$NON-NLS-1$
                        e.getClass().getSimpleName(), e.getMessage()));
            }

            GuiUtil.initLookAndFeel();

            try {
                KDXploreFrame frame = new KDXploreFrame(appFolder, kdxploreTitle, KdxConstants.VERSION_CODE,
                        KdxConstants.VERSION, updateChecker);
                frame.setVisible(true);
                if (onCreateCallback != null) {
                    onCreateCallback.execute(frame);
                }
            } catch (IOException e) {
                MsgBox.error(null, e, Msg.ERRTITLE_UNABLE_TO_START_KDXPLORE(KDXPLORE_APP_NAME));
            }

        }
    });
}