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

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

Introduction

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

Prototype

Closure

Source Link

Usage

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

/**
 * @param args//  w ww .j  av  a 2  s .c o m
 */
public static void main(String[] args) {
    mainImpl(args, null, new Closure<UpdateCheckContext>() {
        @Override
        public void execute(UpdateCheckContext context) {
            try {
                String url = context.getBaseUrl();
                if (!Check.isEmpty(url)) {
                    UpdateCheckRequest request = new UpdateCheckRequest(context.getWindow(),
                            KdxConstants.VERSION_CODE, KdxConstants.VERSION, true, url);

                    new UpdateDialog(request, context, KdxConstants.getVersionInfo()).setVisible(true);
                }
            } catch (IllegalStateException ignore) {

            }
        }
    });
}

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

public static void main(String[] args) {

    String host = null;/*  w w w.  ja  v a 2 s.  com*/
    int port = DalServerUtil.DEFAULT_DAL_SERVER_PORT;

    int inactiveMins = DalServerUtil.DEFAULT_MAX_INACTIVE_MINUTES;

    File docRoot = null;

    String serviceName = null;

    for (int i = 0; i < args.length; ++i) {
        String argi = args[i];
        if (argi.startsWith("-")) {
            if ("--".equals(argi)) {
                break;
            }

            if ("-version".equals(argi)) {
                System.out.println(DAL_SERVER_VERSION);
                System.exit(0);
            }

            if ("-help".equals(argi)) {
                giveHelpThenExit(0);
            }

            if ("-docroot".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                docRoot = new File(args[i]);
            } else if ("-sqllog".equals(argi)) {
                SqlUtil.logger = Logger.getLogger(SqlUtil.class.getName());
            } else if ("-expire".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }

                try {
                    inactiveMins = Integer.parseInt(args[i], 10);
                    if (inactiveMins <= 0) {
                        fatal("invalid minutes: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid minutes: " + args[i]);
                }
            } else if ("-localhost".equals(argi)) {
                host = "localhost";
            } else if ("-port".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                try {
                    port = Integer.parseInt(args[i], 10);
                    if (port < 0 || port > 65535) {
                        fatal("invalid port number: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid port number: " + args[i]);
                }
            } else {
                fatal("invalid option: " + argi);
            }
        } else {
            if (serviceName != null) {
                fatal("multiple serviceNames not supported: " + argi);
            }
            serviceName = argi;
        }
    }

    final DalServerPreferences preferences = new DalServerPreferences(
            Preferences.userNodeForPackage(DalServer.class));

    if (docRoot == null) {
        docRoot = preferences.getWebRoot(new File(System.getProperty("user.dir"), "www"));
    }

    DalServer server = null;

    if (serviceName != null && docRoot.isDirectory()) {
        try {
            DalDatabase db = createDalDatabase(serviceName, preferences);
            if (db.isInitialiseRequired()) {
                Closure<String> progress = new Closure<String>() {
                    @Override
                    public void execute(String msg) {
                        System.out.println("Database Initialisation: " + msg);
                    }
                };
                db.initialise(progress);
            }
            server = create(preferences, host, port, docRoot, db);
        } catch (NoServiceException e) {
            throw new RuntimeException(e);
        } catch (DalDbException e) {
            throw new RuntimeException(e);
        }
    }

    Image serverIconImage = null;
    InputStream imageIs = DalServer.class.getResourceAsStream("dalserver-24.png");
    if (imageIs != null) {
        try {
            serverIconImage = ImageIO.read(imageIs);

            if (Util.isMacOS()) {
                try {
                    MacApplication macapp = new MacApplication(null);
                    macapp.setDockIconImage(serverIconImage);
                } catch (MacApplicationException e) {
                    System.err.println(e.getMessage());
                }
            }

        } catch (IOException ignore) {
        }
    }

    if (server != null) {
        server.setMaxInactiveMinutes(inactiveMins);
    } else {
        AskServerParams asker = new AskServerParams(serverIconImage, null, "DAL Server Start", docRoot,
                preferences);
        GuiUtil.centreOnScreen(asker);
        asker.setVisible(true);

        if (asker.cancelled) {
            System.exit(0);
        }

        host = asker.dalServerHostName;
        port = asker.dalServerPort;
        inactiveMins = asker.maxInactiveMinutes;

        server = create(preferences, host, port, asker.wwwRoot, asker.dalDatabase);
        // server.setUseSimpleDatabase(asker.useSimpleDatabase);
    }

    final DalServer f_server = server;
    final File f_wwwRoot = docRoot;
    final Image f_serverIconImage = serverIconImage;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            DalServerFactory factory = new DalServerFactory() {
                @Override
                public DalServer create(String hostName, int port, File wwwRoot, DalDatabase dalDatabase) {
                    return DalServer.create(preferences, hostName, port, wwwRoot, dalDatabase);
                }
            };
            ServerGui gui = new ServerGui(f_serverIconImage, f_server, factory, f_wwwRoot, preferences);
            gui.setVisible(true);
        }
    });

}

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

@Override
public void createUserInterface(BackgroundRunner backgroundRunner, CurationParams params,
        Consumer<Either<InitError, TrialDataEditorResult>> onComplete) {
    BackgroundTask<CurationData, Void> task = new BackgroundTask<CurationData, Void>("Collecting Trial Data...",
            false) {//from  w ww.  j a va 2  s. c om

        @Override
        public void onTaskComplete(CurationData cd) {

            PlotIdentSummary pis = cd.getTrial().getPlotIdentSummary();

            if (pis == null) {
                onComplete.accept(Either.left(InitError.NO_PLOTIDENT_SUMMARY));
                return;
            }

            if (!pis.hasXandY() && pis.plotIdentRange.isEmpty()) {
                onComplete.accept(Either.left(InitError.NO_ID_X_OR_Y));
                return;
            }

            if (PlotIdentOption.NO_X_Y_OR_PLOT_ID == cd.getTrial().getPlotIdentOption()) {
                onComplete.accept(Either.left(InitError.NO_IDENT_SPECIFIED));
                return;
            }

            try {
                TrialDataEditor editor = TrialDataEditor.createTrialDataEditor(params.offlineData, cd,
                        params.windowOpener, params.messageLogger);

                TrialDataEditorResult result = new TrialDataEditorResult();
                result.curationData = cd;
                result.frame = params.windowOpener.addDesktopObject(editor);
                result.onFrameClosed = new Closure<Void>() {
                    @Override
                    public void execute(Void arg0) {
                        editor.pushDownAllGraphAndPlotFrames();
                    }
                };

                onComplete.accept(Either.right(result));
            } catch (IOException e) {
                onComplete.accept(Either.left(InitError.error(e)));
            }
        }

        @Override
        public void onException(Throwable error) {
            onComplete.accept(Either.left(InitError.error(error)));
        }

        @Override
        public void onCancel(CancellationException ce) {
            onComplete.accept(Either.left(InitError.error(ce)));
        }

        @Override
        public CurationData generateResult(Closure<Void> arg0) throws Exception {
            CurationData curationData = CurationData.create(params.trial, CurationData.FULL_DETAILS,
                    params.offlineData.getKdxploreDatabase());

            return curationData;
        }
    };

    backgroundRunner.runBackgroundTask(task);
}

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

/**
 * We only have to change the editedSamples into "suppressed" samples.
 * @param option/*from w w w . j a va 2 s .  c  om*/
 * @param editedSamples
 */
public void setSuppressionSimple(SuppressOption option, List<KdxSample> editedSamples,
        List<CurationCellValue> ccvList, JComponent parent) {
    if (editedSamples.size() > 0) {
        switch (option) {
        case ACCEPT:
            List<KdxSample> notYetIncluded = new ArrayList<>();
            for (KdxSample sample : editedSamples) {
                if (sample.isSuppressed()) {
                    notYetIncluded.add(sample);
                }
            }

            if (notYetIncluded.isEmpty()) {
                MsgBox.info(parent == null ? curationContext.getDialogOwnerWindow() : parent,
                        Vocab.MSG_ALL_VALUES_ALREADY_ACCEPTED(), Vocab.ACTION_ACCEPT_TRAIT_VALUES());
            } else {
                // Some of them were NOT already included
                Closure<List<EditedSampleInfo>> registerSamplesClosure = new Closure<List<EditedSampleInfo>>() {
                    @Override
                    public void execute(List<EditedSampleInfo> infoList) {
                        registerAcceptedSamples(infoList);
                    }
                };
                curationCellEditor.acceptOrSuppressEditedSamples(ccvList, NOT_SUPPRESSED,
                        registerSamplesClosure);
            }
            break;

        case REJECT:
            List<KdxSample> notYetRejected = new ArrayList<>();
            for (KdxSample sample : editedSamples) {
                if (!sample.isSuppressed()) {
                    notYetRejected.add(sample);
                }
            }

            if (notYetRejected.isEmpty()) {
                MsgBox.info(parent == null ? curationContext.getDialogOwnerWindow() : parent,
                        Vocab.MSG_ALL_VALUES_ALREADY_SUPPRESSED(), Vocab.ACTION_SUPPRESS_TRAIT_VALUES());
            } else {
                Window owner = parent == null ? curationContext.getDialogOwnerWindow()
                        : GuiUtil.getOwnerWindow(parent);
                ExcludeReasonDialog dlg = new ExclusionDialog.ExcludeReasonDialog(owner);
                dlg.setVisible(true);

                String reason = dlg.reason;
                if (reason != null) {
                    Closure<List<EditedSampleInfo>> registerSamplesClosure = new Closure<List<EditedSampleInfo>>() {
                        @Override
                        public void execute(List<EditedSampleInfo> infoList) {
                            //                        for (EditedSampleInfo info : infoList) {
                            //                           curationTableModel.setEditedSampleValue(
                            //                                 info.modelRow, info.modelColumn, info.ccid,
                            //                                 info.newEditedSample);
                            //                        }
                            registerRejectedSamples(infoList, reason);
                        }
                    };
                    curationCellEditor.acceptOrSuppressEditedSamples(ccvList, reason, registerSamplesClosure);
                }
            }
            break;
        }
    }
}

From source file:com.diversityarrays.kdxplore.data.kdx.CurationDataCollector.java

public CurationDataCollector(KdxploreDatabase kdxdb, Trial trial, boolean fullDetails)
        throws IOException, KdxploreConfigException {
    this.trial = trial;

    int trialId = trial.getTrialId();
    this.deviceIdentifiers = kdxdb.getDeviceIdentifiers();

    deviceIdentifierById.clear();/*w w  w.j a va2  s.  co m*/
    for (DeviceIdentifier d : deviceIdentifiers) {
        deviceIdentifierById.put(d.getDeviceIdentifierId(), d);
    }

    //        ProgressUpdater progressUpdater;
    //        kdxdb.getKDXploreKSmartDatabase().collectPlotsFor(trial, 
    //                SampleGroupChoice.ANY_SAMPLE_GROUP, 
    //                KDSmartDatabase.WithPlotAttributesOption.WITH_PLOT_ATTRIBUTES,
    //                KDSmartDatabase.WithTraitOption.ALL_WITH_TRAITS,
    //                progressUpdater);
    //        
    //        this.plots = kdxdb.getPlots(trial, SampleGroupChoice.ANY_SAMPLE_GROUP,
    //                KDSmartDatabase.WithPlotAttributesOption.WITH_PLOT_ATTRIBUTES);

    Closure<Pair<WhyMissing, MediaFileRecord>> reportMissing = new Closure<Pair<WhyMissing, MediaFileRecord>>() {
        @Override
        public void execute(Pair<WhyMissing, MediaFileRecord> arg0) {
            // TODO Auto-generated method stub

        }
    };
    Map<Integer, Plot> plotById = DatabaseUtil.collectPlotsIncludingMediaFiles(
            kdxdb.getKDXploreKSmartDatabase(), trialId, "CurationDataCollector",
            SampleGroupChoice.ANY_SAMPLE_GROUP, reportMissing);
    this.plots = new ArrayList<>(plotById.values());

    this.countByTagLabel = Collections.unmodifiableMap(plots.stream()
            .flatMap(plot -> plot.getTagsBySampleGroup().entrySet().stream())
            .flatMap(e -> e.getValue().stream())
            .collect(Collectors.groupingBy(Tag::getLabel, Collectors.reducing(0, e -> 1, Integer::sum))));

    collectPlotPositionIdentifiers(plots);

    trialAttributes = kdxdb.getTrialAttributes(trialId);

    KDSmartDatabase kdsdb = kdxdb.getKDXploreKSmartDatabase();

    plotAttributes = kdsdb.getAllPlotAttributesForTrial(trialId);
    traitInstances = kdsdb.getTraitInstances(trialId, KDSmartDatabase.WithTraitOption.ALL_WITH_TRAITS);

    //        tagById.clear();
    //        for (Tag tag : kdsdb.getAllTags()) {
    //            tagById.put(tag.getTagId(), tag);
    //        }

    //        collectTagPlotUsage(trialId, kdsdb);

    //        collectMediaFileRecords(trialId, kdsdb);

    loadSampleGroups(kdxdb, trialId, fullDetails);
}

From source file:com.diversityarrays.kdxplore.editing.EntityPropertiesTable.java

@Override
public boolean editCellAt(int row, int column, EventObject e) {
    if (e instanceof MouseEvent) {
        MouseEvent me = (MouseEvent) e;
        if (SwingUtilities.isLeftMouseButton(me) && 2 != me.getClickCount()) {
            return false;
        }//from   w  ww . j  a v  a  2s  .  c  om
        me.consume();
    }

    @SuppressWarnings("unchecked")
    EntityPropertiesTableModel<T> eptm = (EntityPropertiesTableModel<T>) getModel();
    if (!eptm.isCellEditable(row, column)) {
        return false;
    }

    if (handleEditCellAt(eptm, row, column)) {
        return false;
    }

    PropertyDescriptor pd = eptm.getPropertyDescriptor(row);
    if (pd == null) {
        return super.editCellAt(row, column);
    }

    Class<?> propertyClass = pd.getPropertyType();

    if (propertyChangeConfirmer != null && !propertyChangeConfirmer.isChangeAllowed(pd)) {
        return false;
    }

    if (java.util.Date.class.isAssignableFrom(propertyClass)) {
        try {
            java.util.Date dateValue = (Date) pd.getReadMethod().invoke(eptm.getEntity());

            if (propertyChangeConfirmer != null) {
                propertyChangeConfirmer.setValueBeforeChange(dateValue);
            }

            Closure<Date> onComplete = new Closure<Date>() {
                @Override
                public void execute(Date result) {
                    if (result != null) {
                        if (propertyChangeConfirmer == null
                                || propertyChangeConfirmer.valueChangeCanCommit(pd, result)) {
                            getModel().setValueAt(result, row, column);
                        }
                    }
                }
            };

            String title = pd.getDisplayName();
            DatePickerDialog datePicker = new DatePickerDialog(GuiUtil.getOwnerWindow(this), title, onComplete);
            datePicker.setDate(dateValue);
            datePicker.setVisible(true);

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
            e1.printStackTrace();
        }
        return false;
    }
    // else if (Enum.class.isAssignableFrom(propertyClass)) {
    // }

    Log.d(TAG, "editCellAt(" + row + "," + column + ") No Editor override provided for "
            + propertyClass.getName());
    return super.editCellAt(row, column, e);
}

From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java

protected SortedSet<File> ensureFoldersExistence(File appBase, NamedExtendedPlaceholderResolver propsResolver,
        ExtendedPlaceholderResolver sourcesResolver) {
    final SortedSet<File> createdFiles = verifyFolderProperty(ConfigUtils.GITCLOUD_BASE_PROP, appBase,
            ExtendedSetUtils.<File>sortedSet(ExtendedFileUtils.BY_ABSOLUTE_PATH_COMPARATOR));
    final String appBasePrefix = appBase.getAbsolutePath();
    final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(
            SystemPropertyUtils.PLACEHOLDER_PREFIX, SystemPropertyUtils.PLACEHOLDER_SUFFIX,
            SystemPropertyUtils.VALUE_SEPARATOR, true);
    final ExtendedPlaceholderResolver resolver = new AggregatedExtendedPlaceholderResolver(propsResolver,
            sourcesResolver);//from  www  . j  a  v  a  2s . c  o m
    ExtendedPlaceholderResolverUtils.forAllEntriesDo(propsResolver, new Closure<Map.Entry<String, String>>() {
        @Override
        @SuppressWarnings("synthetic-access")
        public void execute(Entry<String, String> e) {
            String propName = e.getKey(), propValue = e.getValue();
            if (StringUtils.isEmpty(propName) || (!propName.endsWith(".dir"))
                    || StringUtils.isEmpty(propValue)) {
                return;
            }

            String resolvedValue = helper.replacePlaceholders(propValue, resolver);
            if (ExtendedCharSequenceUtils.getSafeLength(resolvedValue) < appBasePrefix.length()) {
                return;
            }

            String pathValue = resolvedValue.replace('/', File.separatorChar); // just in case using '/'
            if (logger.isDebugEnabled()) {
                logger.debug("ensureFoldersExistence(" + propName + "): " + pathValue);
            }

            if (pathValue.startsWith(appBasePrefix)) {
                verifyFolderProperty(propName, new File(pathValue), createdFiles);
            }
        }
    });
    return createdFiles;
}

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

public void doComplexSuppression(SuppressionData suppressionData, JComponent parent) {
    if (!suppressionData.editedSamples.isEmpty() && suppressionData.nonEditedSamples.isEmpty()) {
        // All the samples to be suppressed or approved are editedSamples.
        setSuppressionSimple(suppressionData.suppressOption, suppressionData.editedSamples,
                suppressionData.curationCellValues, parent);
    } else {//from www . ja v  a2 s.com
        List<CurationCellValue> values = suppressionData.curationCellValues;

        if (values.isEmpty()) {
            String msg;
            String title;
            if (suppressionData.suppressOption == SuppressOption.REJECT) {
                msg = Vocab.MSG_NO_VALID_SAMPLES_SELECTED_TO_SUPPRESS();
                title = Vocab.ACTION_SUPPRESS_TRAIT_VALUES();
            } else {
                msg = Vocab.MSG_NO_VALID_SAMPLES_SELECTED_TO_SET();
                title = Vocab.ACTION_ACCEPT_TRAIT_VALUES();
            }
            MsgBox.warn(parent == null ? curationContext.getDialogOwnerWindow() : parent, msg, title);
        } else {

            // TODO the "edited" samples for both of these should be the "visible" i.e. most recent
            // from both. We can change the "which data" selection to be:
            //    Visible (most recent)
            //    DeviceName     noting that if only one devices data is available then we just use it.
            //    DeviceName     and possibly don't even bother showing the list. So we just want the reason.
            //    ...

            // TODO: instead of sampleGetter.getEditedSamples(), make the exclusionDialog call return them

            Window owner = parent == null ? curationContext.getDialogOwnerWindow()
                    : GuiUtil.getOwnerWindow(parent);

            Pair<SampleSource, ValueForUnscored> pair;
            switch (suppressionData.suppressOption) {
            case ACCEPT:

                pair = ExclusionDialog.confirmIncludeUnCuratedSamples(owner, curationCellEditor,
                        suppressionData.askAboutValueForUnscored, values);

                if (pair != null) {
                    SampleSource selectedSampleSource = pair.first;
                    ValueForUnscored valueForUnscored = pair.second;

                    Closure<List<EditedSampleInfo>> registerSamplesClosure = new Closure<List<EditedSampleInfo>>() {
                        @Override
                        public void execute(List<EditedSampleInfo> infoList) {
                            //                        for (EditedSampleInfo info : infoList) {
                            //                           info.newEditedSample.setTraitValue(valueToUse);
                            //                        }

                            registerAcceptedSamples(infoList);
                        }
                    };
                    curationCellEditor.acceptOrSuppressValueIgnoringParameters(valueForUnscored,
                            selectedSampleSource, values, NOT_SUPPRESSED, registerSamplesClosure);

                    //                  addSuppressChangeable(newEditedSamples, null);
                }
                break;

            case REJECT:
                ExcludeUncuratedSampleReason dlg = new ExclusionDialog.ExcludeUncuratedSampleReason(owner,
                        curationCellEditor, suppressionData.askAboutValueForUnscored, values);
                dlg.setVisible(true);

                if (dlg.sampleSource != null) {
                    String reason = dlg.excludeReason;
                    Closure<List<EditedSampleInfo>> closure = new Closure<List<EditedSampleInfo>>() {
                        @Override
                        public void execute(List<EditedSampleInfo> infoList) {
                            //                              for (EditedSampleInfo info : infoList) {
                            ////                                    info.newEditedSample.setSuppressedReason(reason);
                            //                                  curationTableModel.setEditedSampleValue(
                            //                                          info.modelRow, info.modelColumn, info.ccid,
                            //                                          info.newEditedSample);
                            //                              }
                            registerRejectedSamples(infoList, reason);
                        }
                    };

                    curationCellEditor.acceptOrSuppressValueIgnoringParameters(dlg.valueForUnscored,
                            dlg.sampleSource, values, reason, closure);
                }

                break;
            }
        }
    }
}

From source file:com.diversityarrays.update.UpdateDialog.java

private void checkForUpdates(PrintStream ps) {

    StringBuilder sb = new StringBuilder(updateCheckRequest.updateBaseUrl);
    sb.append(updateCheckRequest.versionCode);
    if (RunMode.getRunMode().isDeveloper()) {
        sb.append("-dev"); //$NON-NLS-1$
    }/*from ww  w  .jav  a2  s.  co m*/
    sb.append(".json"); //$NON-NLS-1$

    final String updateUrl;
    updateUrl = sb.toString();
    // updateUrl = "NONEXISTENT"; // Uncomment to check error

    final ProgressMonitor progressMonitor = new ProgressMonitor(updateCheckRequest.owner,
            Msg.PROGRESS_CHECKING(), null, 0, 0);

    worker = new SwingWorker<String, Void>() {

        @Override
        protected String doInBackground() throws Exception {

            // Thread.sleep(3000); // Uncomment to check delay

            BufferedReader reader = null;
            StringBuffer buffer = new StringBuffer();

            try {
                URL url = new URL(updateUrl);
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1) {
                    if (progressMonitor.isCanceled()) {
                        cancel(true);
                        return null;
                    }
                    buffer.append(chars, 0, read);
                }
            } catch (IOException e) {
                System.err.println("checkForUpdates: " + e.getMessage()); //$NON-NLS-1$
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

            return buffer.toString();
        }

        @Override
        protected void done() {
            try {
                String json = get();
                Gson gson = new Gson();
                setKDXploreUpdate(gson.fromJson(json, KDXploreUpdate.class));
            } catch (CancellationException ignore) {
            } catch (InterruptedException ignore) {
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();

                if (cause instanceof UnknownHostException) {
                    String site = extractSite(updateUrl);
                    ps.println(Msg.ERRMSG_UNABLE_TO_CONTACT_UPDATE_SITE(site));
                } else {
                    cause.printStackTrace(ps);
                }

                if (cause instanceof FileNotFoundException) {
                    FileNotFoundException fnf = (FileNotFoundException) cause;
                    if (updateUrl.equals(fnf.getMessage())) {
                        // Well maybe someone forgot to create the file on
                        // the server!
                        System.err.println("Maybe someone forgot to create the file!"); //$NON-NLS-1$
                        System.err.println(fnf.getMessage());

                        setKDXploreUpdate(new KDXploreUpdate(Msg.ERRMSG_PROBLEMS_CONTACTING_UPDATE_SERVER_1()));
                        return;
                    }
                }

                String msg = Msg.HTML_PROBLEMS_CONTACTING_UPDATE_2(StringUtil.htmlEscape(updateUrl),
                        cause.getClass().getSimpleName(), StringUtil.htmlEscape(cause.getMessage()));
                kdxploreUpdate = new KDXploreUpdate(msg);

                kdxploreUpdate.unknownHost = (cause instanceof UnknownHostException);
                return;
            }
        }

        private String extractSite(final String updateUrl) {
            String site = null;
            int spos = updateUrl.indexOf("://");
            if (spos > 0) {
                int epos = updateUrl.indexOf('/', spos + 1);
                if (epos > 0) {
                    site = updateUrl.substring(0, epos);
                }
            }
            if (site == null) {
                site = updateUrl;
            }
            return site;
        }
    };

    Closure<JDialog> onComplete = new Closure<JDialog>() {
        @Override
        public void execute(JDialog d) {
            if (!processReadUrlResult(updateUrl)) {
                d.dispose();
            } else {
                d.setVisible(true);
            }
        }
    };

    SwingWorkerCompletionWaiter waiter = new SwingWorkerCompletionWaiter(this, onComplete);
    worker.addPropertyChangeListener(waiter);

    worker.execute();
}

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

/**
 * //from  ww  w .  j  a  va  2s .  c  o m
 * @param databaseFolder
 * @param databaseServer
 * @param databasePort
 * @param wwwRoot
 * @param host
 * @param serviceName
 * @param prefs
 * @param errors
 * @throws IllegalArgumentException if no provider or unable to create
 * @return
 * @throws NoServiceException 
 */
private static DalDatabase createDalDatabase(String dalDbServiceName, DalServerPreferences prefs)
        throws NoServiceException {
    DalDbProviderService provider = null;
    for (Iterator<DalDbProviderService> iter = ServiceRegistry.lookupProviders(DalDbProviderService.class); iter
            .hasNext();) {
        provider = iter.next();
        if (dalDbServiceName.equals(provider.getProviderName())) {
            break;
        }
    }

    if (provider == null) {
        throw new NoServiceException("No provider for " + dalDbServiceName);
    }

    Set<Parameter<?>> required = provider.getParametersRequired();
    Map<Parameter<?>, Throwable> errors = new LinkedHashMap<Parameter<?>, Throwable>();
    Map<Parameter<?>, ParameterValue<?>> savedSettings = prefs.loadSavedSettings(provider, required, errors);

    if (!errors.isEmpty()) {
        StringBuilder sb = new StringBuilder("Parameter errors:");
        for (Parameter<?> p : errors.keySet()) {
            sb.append("\n  ").append(p.name).append(errors.get(p).getMessage());
        }
        throw new NoServiceException(sb.toString());
    }

    Set<ParameterValue<?>> parameterValues = new LinkedHashSet<ParameterValue<?>>();
    for (Parameter<?> p : required) {
        ParameterValue<?> v = savedSettings.get(p);
        if (v != null) {
            parameterValues.add(v);
        }
    }

    try {
        Closure<String> progress = new Closure<String>() {
            @Override
            public void execute(String msg) {
                System.out.println(msg);
            }
        };
        return provider.createDatabase(parameterValues, progress, false);

    } catch (DalDbException e) {
        throw new NoServiceException("provider " + provider.getProviderName() + " couldn't create DalDatabase",
                e);
    }
}