Example usage for java.beans PropertyChangeEvent getNewValue

List of usage examples for java.beans PropertyChangeEvent getNewValue

Introduction

In this page you can find the example usage for java.beans PropertyChangeEvent getNewValue.

Prototype

public Object getNewValue() 

Source Link

Document

Gets the new value for the property, expressed as an Object.

Usage

From source file:biz.wolschon.fileformats.gnucash.jwsdpimpl.GnucashAccountWritingImpl.java

/**
 * same as getBalance(new Date()).<br/>
 * ignores transactions after the current date+time<br/>
 * This implementation caches the result.<br/>
 * We assume that time does never move backwards
 * @see #getBalance(Date)/*from  w w  w  .  j  a  v  a2 s .co m*/
 */
@Override
public FixedPointNumber getBalance() {

    if (myBalanceCached != null) {
        return myBalanceCached;
    }

    Collection<GnucashTransactionSplit> after = new LinkedList<GnucashTransactionSplit>();
    FixedPointNumber balance = getBalance(new Date(), after);

    if (after.isEmpty()) {
        myBalanceCached = balance;

        // add a listener to keep the cache up to date
        if (myBalanceCachedInvalidtor != null) {
            myBalanceCachedInvalidtor = new PropertyChangeListener() {
                private final Collection<GnucashTransactionSplit> splitsWeAreAddedTo = new HashSet<GnucashTransactionSplit>();

                public void propertyChange(final PropertyChangeEvent evt) {
                    myBalanceCached = null;

                    // we don't handle the case of removing an account
                    // because that happenes seldomly enough

                    if (evt.getPropertyName().equals("account")
                            && evt.getSource() instanceof GnucashWritableTransactionSplit) {
                        GnucashWritableTransactionSplit splitw = (GnucashWritableTransactionSplit) evt
                                .getSource();
                        if (splitw.getAccount() != GnucashAccountWritingImpl.this) {
                            splitw.removePropertyChangeListener("account", this);
                            splitw.removePropertyChangeListener("quantity", this);
                            splitw.getTransaction().removePropertyChangeListener("datePosted", this);
                            splitsWeAreAddedTo.remove(splitw);

                        }

                    }
                    if (evt.getPropertyName().equals("transactionSplits")) {
                        Collection<GnucashTransactionSplit> splits = (Collection<GnucashTransactionSplit>) evt
                                .getNewValue();
                        for (GnucashTransactionSplit split : splits) {
                            if (!(split instanceof GnucashWritableTransactionSplit)
                                    || splitsWeAreAddedTo.contains(split)) {
                                continue;
                            }
                            GnucashWritableTransactionSplit splitw = (GnucashWritableTransactionSplit) split;
                            splitw.addPropertyChangeListener("account", this);
                            splitw.addPropertyChangeListener("quantity", this);
                            splitw.getTransaction().addPropertyChangeListener("datePosted", this);
                            splitsWeAreAddedTo.add(splitw);
                        }
                    }
                }
            };
            addPropertyChangeListener("currencyID", myBalanceCachedInvalidtor);
            addPropertyChangeListener("currencyNameSpace", myBalanceCachedInvalidtor);
            addPropertyChangeListener("transactionSplits", myBalanceCachedInvalidtor);
        }
    }

    return balance;
}

From source file:pcgui.SetupParametersPanel.java

private void runModel() {

    //retrieve master configuration
    ArrayList<ArrayList<Object>> mod = model.getData();
    //create a new list and check for dependencies
    ArrayList<Symbol> list = new ArrayList<Symbol>();
    //independent variable list
    ArrayList<Symbol> ivList = new ArrayList<Symbol>();
    //step variable list
    ArrayList<Symbol> stepList = new ArrayList<Symbol>();
    //dependent list
    ArrayList<Symbol> depList = new ArrayList<Symbol>();
    //output tracking
    ArrayList<Symbol> trackedSymbols = new ArrayList<Symbol>();
    Symbol tempSym = null;//from  www  .  j  av a2s . co m
    //step variable counter to be used for making combinations
    int stepVarCount = 0;
    long stepCombinations = 1;
    TextParser textParser = new TextParser();
    compileSuccess = true;
    for (ArrayList<Object> rowData : mod) {
        tempSym = paramList.get(mod.indexOf(rowData));
        if ("Manual".equals((String) rowData.get(2))) {
            System.out.println("Found Customized Symbol : " + rowData.get(0));
            System.out.println("Value : " + rowData.get(3) + ": type=" + rowData.get(3).getClass());

            tempSym.mode = "Manual";
            String data = (String) rowData.get(3);

            //checking dependent variables
            if (data != null && !data.isEmpty()) {
                //dependent
                if (hashTable.containsKey(data)) {
                    tempSym.setDependent(true);
                    depList.add(tempSym);
                } else {
                    //independents
                    tempSym.setDependent(false);
                    tempSym.set(data);
                    ivList.add(tempSym);
                }
            }
        } else if ("External".equals((String) rowData.get(2))) {
            System.out.println("Found External Symbol : " + rowData.get(0));
            System.out.println("External : " + rowData.get(3) + ": type=" + rowData.get(3).getClass());

            if (!(((String) rowData.get(4)).isEmpty())) {

                tempSym.externalFile = (String) rowData.get(4);
                tempSym.set(tempSym.externalFile);
                tempSym.mode = "External";
                if (tempSym.externalFile.endsWith(".xls") || tempSym.externalFile.endsWith(".xlsx")) {

                    if (tempSym.excelFileRange.isEmpty()) {
                        // TODO show an error dialog
                        System.err.println("Error user missed excel range arguments");
                        JOptionPane.showMessageDialog(new JFrame(), "Error user missed excel range arguments");
                        return;
                    } else {
                        tempSym.excelFileRange = (String) rowData.get(5);
                        //'[Daten_10$B'+(i)+':B'+(5+n)+']'
                        //user has to add quote before the 1st + and after the last +
                        //the data file used should be inside Models/Data folder
                        tempSym.set("Models//Data//" + tempSym.externalFile + "::" + tempSym.excelFileRange);

                    }
                } else {
                    //for non excel files
                    tempSym.set("Models//Data//" + tempSym.externalFile);

                }
            } else {
                System.err.println("Error user missed excel file");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter external file for variable : " + tempSym.name);
                return;
            }
            ivList.add(tempSym);
            list.add(tempSym);
        } else if ("Randomized".equals((String) rowData.get(2))) {
            System.out.println("Found Randomized Symbol : " + rowData.get(0));
            System.out.println("Value : " + rowData.get(6));

            boolean isValid = textParser.validate((String) rowData.get(6));
            if (isValid) {

                //saving the array declaration parameters
                if (((String) rowData.get(1)).trim().startsWith("array")) {
                    System.out.println("Found randomized array : " + tempSym.name);
                    //found an array
                    tempSym.isArray = true;
                    List<String> arrayParams = parseArrayParam((String) rowData.get(1));
                    tempSym.arrayParams = arrayParams;
                    System.out.println("Param list : ");
                    for (Object obj : tempSym.arrayParams) {
                        //check if any of the param is symbol
                        if (hashTable.containsKey((String) obj)) {
                            tempSym.isDependentDimension = true;
                            depList.add(tempSym);
                            break;
                        }
                        System.out.println((String) obj);
                    }
                    //add to independent variable list if none of the dimension is based on variable
                    if (!tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }

                }
                Distribution dist = textParser.getDistribution((String) rowData.get(6));
                if ("Step".equalsIgnoreCase(dist.getDistribution())) {
                    System.err.println("Error: User entered step distribution in Randomized variable");
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Please enter random distribution only" + " for variable : " + tempSym.name);
                    return;
                }
                tempSym.setDistribution(dist);
                tempSym.mode = "Randomized";
                //check dependent variables
                List<String> distParamList = dist.getParamList();
                for (String param : distParamList) {
                    //TODO: if .contains work on Symbol
                    if (hashTable.containsKey(param) && !depList.contains(tempSym)) {
                        tempSym.setDependent(true);
                        depList.add(tempSym);
                        break;
                    }
                }
                //generate apache distribution object for independent vars
                if (!tempSym.isDependent()) {
                    Object apacheDist = generateDistribution(tempSym);
                    tempSym.setApacheDist(apacheDist);
                    if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) {
                        stepVarCount++;
                        StepDistribution stepDist = (StepDistribution) apacheDist;
                        stepCombinations *= stepDist.getStepCount();

                        tempSym.isStepDist = true;
                        tempSym.setStepDist(stepDist);
                        stepList.add(tempSym);
                    } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }
                }
                list.add(tempSym);
            } else {
                System.err.println("Error: User entered unknown distribution for randomized variable");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter random distribution only" + " for variable : " + tempSym.name);
                return;
            }
        } else if ("Step".equals((String) rowData.get(2))) {
            System.out.println("Found Step Symbol : " + rowData.get(0));
            System.out.println("Value : " + rowData.get(6));
            Distribution dist = textParser.getStepDistribution((String) rowData.get(6));
            if (dist == null || !"Step".equalsIgnoreCase(dist.getDistribution())) {
                System.err.println("Error: User entered unknown distribution for step variable");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter random distribution only" + " for variable : " + tempSym.name);
                return;
            }

            boolean isValid = textParser.validateStepDist((String) rowData.get(6));
            if (isValid) {

                //saving the array declaration parameters
                if (((String) rowData.get(1)).trim().startsWith("array")) {
                    //TODO: if this can work for step arrays
                    System.out.println("Found step array : " + tempSym.name);
                    //found an array
                    tempSym.isArray = true;
                    List<String> arrayParams = parseArrayParam((String) rowData.get(1));
                    tempSym.arrayParams = arrayParams;
                    System.out.println("Param list : ");
                    for (Object obj : tempSym.arrayParams) {
                        //check if any of the param is symbol
                        if (hashTable.containsKey((String) obj)) {
                            tempSym.isDependentDimension = true;
                            depList.add(tempSym);
                            break;
                        }
                        System.out.println((String) obj);
                    }
                    //add to independent variable list if none of the dimension is based on variable
                    if (!tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }

                }
                tempSym.setDistribution(dist);
                tempSym.mode = "Randomized";
                //check dependent variables
                List<String> distParamList = dist.getParamList();
                for (String param : distParamList) {
                    if (hashTable.containsKey(param) && !depList.contains(tempSym)) {
                        tempSym.setDependent(true);
                        depList.add(tempSym);
                        break;
                    }
                }
                //generate apache distribution object for independent vars
                if (!tempSym.isDependent()) {
                    Object apacheDist = generateDistribution(tempSym);
                    tempSym.setApacheDist(apacheDist);
                    //dual safe check
                    if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) {
                        stepVarCount++;
                        StepDistribution stepDist = (StepDistribution) apacheDist;
                        stepCombinations *= stepDist.getStepCount();

                        tempSym.isStepDist = true;
                        tempSym.setStepDist(stepDist);
                        stepList.add(tempSym);
                    } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }
                }
                list.add(tempSym);
            } else {
                System.err.println("Error: User entered unknown distribution for randomized variable");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter random distribution only" + " for variable : " + tempSym.name);
                return;
            }
        }
        //add symbol to trackedSymbol list for output tracking
        if (tempSym != null && rowData.get(7) != null && (boolean) rowData.get(7)) {
            trackedSymbols.add(tempSym);
        }

    }

    System.out.println("Total step distribution variables =" + stepVarCount);
    System.out.println("Total step combinations =" + stepCombinations);
    System.out.println("====STEP VARIABLES====");
    for (Symbol sym : stepList) {
        System.out.println(sym.name);
    }

    //resolve dependencies and generate random distributions object
    //list for an instance of execution

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    for (int i = 0; i < stepList.size(); i++) {
        map.put(stepList.get(i).name, getSteppingCount(stepList, i));
        System.out.println(stepList.get(i).name + " has stepping count =" + map.get(stepList.get(i).name));
    }
    int repeatitions = 0;
    try {
        repeatitions = Integer.parseInt(repeatCount.getText());
    } catch (NumberFormatException e) {
        System.err.println("Invalid repeat count");
        JOptionPane.showMessageDialog(new JFrame(), "Please enter integer value for repeat count");
        return;
    }
    //generate instances

    showProgressBar();

    final long totalIterations = repeatitions * stepCombinations;
    final long repeatitionsFinal = repeatitions;
    final long combinations = stepCombinations;

    SwingWorker<Void, Void> executionTask = new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {

            long itNum = 1;
            int itCount = 1;

            System.out.println("Total iterations: " + totalIterations);
            // TODO Auto-generated method stub
            for (int c = 1; c <= repeatitionsFinal; c++) {
                for (int i = 1; i <= combinations; i++) {

                    setProgress((int) (itNum * 100 / totalIterations));
                    //step variables first
                    for (Symbol sym : stepList) {
                        if (map.get(sym.name) == 1 || i % map.get(sym.name) - 1 == 0 || i == 1) {
                            sym.set(sym.getStepDist().sample());
                            hashTable.put(sym.name, sym);
                        }
                        //System.out.println(sym.name+" = "+sym.get());

                    }
                    //independent randomized variables
                    for (Symbol sym : ivList) {
                        if (sym.mode.equals("Randomized")) {
                            Object distObj = sym.getApacheDist();
                            switch (sym.getApacheDist().getClass().getSimpleName()) {
                            case "UniformIntegerDistribution":

                                //case "GeometricDistribution" :

                                //   case "BinomialDistribution"://not implemented yet
                                IntegerDistribution intDist = (IntegerDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateIndependentArray(sym, intDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }

                                break;

                            case "LogisticDistribution":

                            case "UniformRealDistribution":

                            case "ExponentialDistribution":

                            case "GammaDistribution":

                            case "NormalDistribution":
                                RealDistribution realDist = (RealDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateIndependentArray(sym, realDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }

                                break;

                            default:

                                System.err.println("Unknown distribution");
                                JOptionPane.showMessageDialog(new JFrame(),
                                        "Error occurred : Unknown distribution");
                                return null;
                            }

                        }
                        //System.out.println(sym.name+" = "+sym.get());
                        //other types of independent variable already have values
                    }

                    for (Symbol sym : depList) {

                        if (sym.mode != null && "Manual".equals(sym.mode)) {
                            //value depends on some other value
                            String ref = (String) sym.get();
                            Object val = (Object) hashTable.get(ref);
                            sym.set(val);
                            hashTable.put(sym.name, sym);

                        } else if (sym.mode != null && "Randomized".equals(sym.mode)) {

                            Object distObj = null;
                            //when a random distribution depends on another variable
                            Distribution dist = sym.getDistribution();
                            StringBuilder sb = new StringBuilder();
                            sb.append(dist.getDistribution());
                            sb.append("(");
                            for (String s : dist.getParamList()) {
                                //replacing a dependency by actual value of that variable
                                if (hashTable.containsKey(s)) {
                                    Symbol val = (Symbol) hashTable.get(s);
                                    sb.append((String) val.get());
                                } else {
                                    //this param is a number itself
                                    sb.append(s);
                                }
                                sb.append(",");
                            }
                            //check if param list length = 0
                            if (dist.getParamList() != null && dist.getParamList().size() >= 1) {
                                sb.deleteCharAt(sb.length() - 1);
                            }
                            sb.append(")");
                            if (sym.typeString != null && sym.typeString.contains("integer")) {
                                try {
                                    distObj = textParser.parseText(sb.toString(), TextParser.INTEGER);

                                    sym.setApacheDist(distObj);
                                } catch (Exception e) {
                                    System.err.println(
                                            "Exception occured when trying to get Random distribution for variable"
                                                    + sym.name + "\n" + e.getMessage());
                                    e.printStackTrace();
                                    JOptionPane.showMessageDialog(new JFrame(),
                                            "Error occurred : " + e.getMessage());
                                    return null;
                                }
                            } else {
                                try {
                                    distObj = textParser.parseText(sb.toString(), TextParser.REAL);
                                    sym.setApacheDist(distObj);
                                } catch (Exception e) {
                                    System.err.println(
                                            "Exception occured when trying to get Random distribution for variable"
                                                    + sym.name + "\n" + e.getMessage());
                                    e.printStackTrace();
                                    JOptionPane.showMessageDialog(new JFrame(),
                                            "Error occurred : " + e.getMessage());
                                    return null;
                                }
                            }
                            //generation of actual apache distribution objects

                            switch (distObj.getClass().getSimpleName()) {
                            case "UniformIntegerDistribution":

                                //case "GeometricDistribution" :

                                //case "BinomialDistribution":
                                IntegerDistribution intDist = (IntegerDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateDependentArray(sym, intDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }
                                break;

                            case "LogisticDistribution":

                            case "UniformRealDistribution":

                            case "ExponentialDistribution":

                            case "GammaDistribution":

                            case "NormalDistribution":
                                RealDistribution realDist = (RealDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateDependentArray(sym, realDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }
                                break;

                            default:

                                System.err.println("Unknown distribution");
                                JOptionPane.showMessageDialog(new JFrame(),
                                        "Error occurred : Unknown distribution");
                            }
                        }

                        //System.out.println(sym.name+" = "+sym.get());

                    }
                    ArrayList<Symbol> instanceList = new ArrayList<Symbol>();
                    instanceList.addAll(stepList);
                    instanceList.addAll(ivList);
                    instanceList.addAll(depList);
                    System.out.println("=======ITERATION " + itCount++ + "=======");
                    System.out.println("=======instanceList.size =" + instanceList.size() + " =======");
                    for (Symbol sym : instanceList) {
                        System.out.println(sym.name + " = " + sym.get());
                    }
                    //runModel here
                    try {

                        //TODO anshul: pass output variables to be written to excel
                        System.out.println("Tracked output symbols");
                        for (Symbol sym : trackedSymbols) {
                            System.out.println(sym.name);
                        }
                        HashMap<String, OutputParams> l = parser.changeModel(instanceList, trackedSymbols,
                                itNum);

                        if (l == null) {
                            compileSuccess = false;
                            break;
                        }
                    } catch (/*XPRMCompileException | */XPRMLicenseError | IOException e) {
                        e.printStackTrace();
                        JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage());
                        compileSuccess = false;
                        break;
                    }
                    itNum++;
                }
            }
            this.notifyAll();
            done();
            return null;
        }

        @Override
        protected void done() {

            super.done();
            //check if compilation was successful
            if (compileSuccess) {
                ModelSaver.saveModelResult();
                visPanel.setTrackedVariables(trackedSymbols);
                mapVisPanel.setTrackedVariables(trackedSymbols);
                JOptionPane.showMessageDialog(new JFrame("Success"),
                        "Model execution completed.\nOutput written to excel file : " + outputFile);

            } else {
                //Error popup should have been shown by ModelParser
                System.err.println("There was an error while running the model.");
                return;
            }
            if (progressFrame != null) {
                progressFrame.dispose();
            }
        }

    };

    executionTask.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                if (pbar != null)
                    pbar.setValue(progress);
                if (taskOutput != null)
                    taskOutput.append(String.format("Completed %d%% of task.\n", executionTask.getProgress()));
            }
        }
    });
    executionTask.execute();

}

From source file:com.microsoft.live.LiveConnectClient.java

/**
 * Constructs a new {@code LiveConnectClient} instance and initializes it.
 *
 * @param session that will be used to authenticate calls over to the Live Connect REST API.
 * @throws NullPointerException if session is null or if session.getAccessToken() is null.
 * @throws IllegalArgumentException if session.getAccessToken() is empty.
 *///  www  .  ja va2  s .co  m
public LiveConnectClient(LiveConnectSession session) {
    LiveConnectUtils.assertNotNull(session, ParamNames.SESSION);

    String accessToken = session.getAccessToken();
    LiveConnectUtils.assertNotNullOrEmpty(accessToken, ParamNames.ACCESS_TOKEN);

    this.session = session;
    this.sessionState = SessionState.LOGGED_IN;

    // set a listener for the accessToken. If it is set to null, then the session was logged
    // out.
    this.session.addPropertyChangeListener("accessToken", new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent event) {
            String newValue = (String) event.getNewValue();

            if (TextUtils.isEmpty(newValue)) {
                LiveConnectClient.this.sessionState = SessionState.LOGGED_OUT;
            } else {
                LiveConnectClient.this.sessionState = SessionState.LOGGED_IN;
            }
        }
    });

    this.httpClient = getHttpClient();
}

From source file:org.yccheok.jstock.gui.Utils.java

public static FileEx promptSavePortfolioCSVAndExcelJFileChooser(final String suggestedFileName) {
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    final JFileChooser chooser = new JFileChooser(jStockOptions.getLastFileIODirectory());
    final FileNameExtensionFilter csvFilter = new FileNameExtensionFilter("CSV Documents (*.csv)", "csv");
    final FileNameExtensionFilter xlsFilter = new FileNameExtensionFilter("Microsoft Excel (*.xls)", "xls");
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.addChoosableFileFilter(csvFilter);
    chooser.addChoosableFileFilter(xlsFilter);

    final org.yccheok.jstock.gui.file.PortfolioSelectionJPanel portfolioSelectionJPanel = new org.yccheok.jstock.gui.file.PortfolioSelectionJPanel();
    chooser.setAccessory(portfolioSelectionJPanel);
    chooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() {

        @Override// w  w w.  java2s . co m
        public void propertyChange(PropertyChangeEvent evt) {
            final boolean flag = ((FileNameExtensionFilter) evt.getNewValue()).equals(csvFilter);
            portfolioSelectionJPanel.setEnabled(flag);
            chooser.setSelectedFile(chooser.getFileFilter().getDescription().equals(csvFilter.getDescription())
                    ? new File(portfolioSelectionJPanel.getSuggestedFileName())
                    : new File(suggestedFileName));
        }

    });
    portfolioSelectionJPanel.addJRadioButtonsActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            chooser.setSelectedFile(new File(portfolioSelectionJPanel.getSuggestedFileName()));
        }

    });
    final java.util.Map<String, FileNameExtensionFilter> map = new HashMap<String, FileNameExtensionFilter>();
    map.put(csvFilter.getDescription(), csvFilter);
    map.put(xlsFilter.getDescription(), xlsFilter);

    final FileNameExtensionFilter filter = map.get(jStockOptions.getLastSavedFileNameExtensionDescription());
    if (filter != null) {
        chooser.setFileFilter(filter);
    }

    // Only enable portfolioSelectionJPanel, if CSV is being selected.
    portfolioSelectionJPanel
            .setEnabled(chooser.getFileFilter().getDescription().equals(csvFilter.getDescription()));
    chooser.setSelectedFile(chooser.getFileFilter().getDescription().equals(csvFilter.getDescription())
            ? new File(portfolioSelectionJPanel.getSuggestedFileName())
            : new File(suggestedFileName));

    while (true) {
        final int returnVal = chooser.showSaveDialog(JStock.instance());
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return null;
        }

        File file = chooser.getSelectedFile();
        if (file == null) {
            return null;
        }

        // Ensure the saved file is in correct extension. If user provide correct
        // file extension explicitly, leave it as is. If not, mutate the filename.
        final String extension = Utils.getFileExtension(file);
        if (extension.equals("csv") == false && extension.equals("xls") == false) {
            if (chooser.getFileFilter().getDescription().equals(csvFilter.getDescription())) {
                file = new File(file.getAbsolutePath() + ".csv");
            } else if (chooser.getFileFilter().getDescription().equals(xlsFilter.getDescription())) {
                file = new File(file.getAbsolutePath() + ".xls");
            } else {
                // Impossible.
                return null;
            }
        }

        if (file.exists()) {
            final String output = MessageFormat
                    .format(MessagesBundle.getString("question_message_replace_old_template"), file.getName());

            final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                    MessagesBundle.getString("question_title_replace_old"),
                    javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
            if (result != javax.swing.JOptionPane.YES_OPTION) {
                continue;
            }
        }

        final String parent = chooser.getSelectedFile().getParent();
        if (parent != null) {
            jStockOptions.setLastFileIODirectory(parent);
        }

        if (Utils.getFileExtension(file).equals("csv")) {
            jStockOptions.setLastFileNameExtensionDescription(csvFilter.getDescription());
        } else if (Utils.getFileExtension(file).equals("xls")) {
            jStockOptions.setLastFileNameExtensionDescription(xlsFilter.getDescription());
        } else {
            // Impossible.
            return null;
        }

        return new FileEx(file, portfolioSelectionJPanel.getType());
    }
}

From source file:uk.ac.diamond.scisoft.analysis.rcp.inspector.InspectionTab.java

@Override
public void setParameters(ILazyDataset data, List<AxisSelection> datasetAxisList,
        List<PlotAxisProperty> plotAxisList) {
    if (axesListener != null && daxes != null) {
        for (AxisSelection a : daxes) {
            a.removePropertyChangeListener(axesListener);
        }//  w  ww. j  a  v  a  2  s. c  o m
    }
    super.setParameters(data, datasetAxisList, plotAxisList);
    if (daxes != null) {
        if (axesListener == null) {
            axesListener = new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    repopulateCombos(evt.getOldValue().toString(), evt.getNewValue().toString());
                }
            };
        }
        for (AxisSelection a : daxes) {
            a.addPropertyChangeListener(axesListener);
        }
    }

    if (combos != null)
        populateCombos();
}

From source file:org.isatools.isacreator.spreadsheet.Spreadsheet.java

public void propertyChange(PropertyChangeEvent event) {
    if (event.getPropertyName().equals(JOptionPane.VALUE_PROPERTY)) {
        int lastOptionAnswer = Integer.valueOf(event.getNewValue().toString());
        parentFrame.hideSheet();/*w ww.j a v  a  2s  .  c  o  m*/

        if ((currentState == DELETING_COLUMN) && (lastOptionAnswer == JOptionPane.YES_OPTION)) {

            spreadsheetFunctions.removeColumn();
            curColDelete = -1;
            currentState = DEFAULT_STATE;
        }

        if ((currentState == DELETING_ROW) && (lastOptionAnswer == JOptionPane.YES_OPTION)) {
            spreadsheetFunctions.removeRows();
            rowsToDelete = null;
            currentState = DEFAULT_STATE;
        }

        currentState = DEFAULT_STATE;
        curColDelete = -1;
        rowsToDelete = null;
    }
}

From source file:fr.ritaly.dungeonmaster.champion.Champion.java

@Override
public void propertyChange(PropertyChangeEvent event) {
    if (event.getSource() != stats) {
        // On ignore cet vnement
        return;//from   w  w  w . j a v a  2 s .com
    }

    if (Stats.PROPERTY_HEALTH.equals(event.getPropertyName())) {
        final int oldHealth = ((Integer) event.getOldValue()).intValue();
        final int newHealth = ((Integer) event.getNewValue()).intValue();

        if ((oldHealth > 0) && (newHealth == 0)) {
            // Le hros vient de mourir
            if (log.isDebugEnabled()) {
                log.debug(name + " is dying ...");
            }

            kill();
        } else if ((oldHealth == 0) && (newHealth > 0)) {
            if (log.isInfoEnabled()) {
                // Le hros vient de ressusciter
                log.info(name + " has been resurrected ...");
            }

            // Inutile de le rintgrer au groupe, il y est dj !
        }
    }
}

From source file:org.sleuthkit.autopsy.imagegallery.ImageGalleryController.java

/**
 * invoked by {@link OnStart} to make sure that the ImageGallery listeners
 * get setup as early as possible, and do other setup stuff.
 *//* w  w w .  ja va  2  s .co  m*/
void onStart() {
    Platform.setImplicitExit(false);
    LOGGER.info("setting up ImageGallery listeners");
    //TODO can we do anything usefull in an InjestJobEventListener?
    //IngestManager.getInstance().addIngestJobEventListener((PropertyChangeEvent evt) -> {});
    IngestManager.getInstance().addIngestModuleEventListener((PropertyChangeEvent evt) -> {
        switch (IngestManager.IngestModuleEvent.valueOf(evt.getPropertyName())) {
        case CONTENT_CHANGED:
            //TODO: do we need to do anything here?  -jm
        case DATA_ADDED:
            /* we could listen to DATA events and progressivly
             * update files, and get data from DataSource ingest
             * modules, but given that most modules don't post new
             * artifacts in the events and we would have to query for
             * them, without knowing which are the new ones, we just
             * ignore these events for now. The relevant data should all
             * be captured by file done event, anyways -jm */
            break;
        case FILE_DONE:
            /**
             * getOldValue has fileID getNewValue has
             * {@link Abstractfile}
             */
            AbstractFile file = (AbstractFile) evt.getNewValue();
            if (isListeningEnabled()) {
                if (ImageGalleryModule.isSupportedAndNotKnown(file)) {
                    //this file should be included and we don't already know about it from hash sets (NSRL)
                    queueDBWorkerTask(new UpdateFileTask(file));
                } else if (ImageGalleryModule.getAllSupportedExtensions().contains(file.getNameExtension())) {
                    //doing this check results in fewer tasks queued up, and faster completion of db update
                    //this file would have gotten scooped up in initial grab, but actually we don't need it
                    queueDBWorkerTask(new RemoveFileTask(file));
                }
            } else { //TODO: keep track of what we missed for later
                setStale(true);
            }
            break;
        }
    });
    Case.addPropertyChangeListener((PropertyChangeEvent evt) -> {
        switch (Case.Events.valueOf(evt.getPropertyName())) {
        case CURRENT_CASE:
            Case newCase = (Case) evt.getNewValue();
            if (newCase != null) { // case has been opened
                setCase(newCase); //connect db, groupmanager, start worker thread
            } else { // case is closing
                //close window, reset everything
                SwingUtilities.invokeLater(ImageGalleryTopComponent::closeTopComponent);
                reset();
            }
            break;
        case DATA_SOURCE_ADDED:
            //copy all file data to drawable databse
            Content newDataSource = (Content) evt.getNewValue();
            if (isListeningEnabled()) {
                queueDBWorkerTask(new PrePopulateDataSourceFiles(newDataSource));
            } else {//TODO: keep track of what we missed for later
                setStale(true);
            }
            break;
        }
    });
}

From source file:com.ti.sensortag.gui.services.ServicesActivity.java

/**
 * This class listens to changes in the model of sensor values.
 * *//*from   w  ww  .j av  a 2 s. c om*/

@Override
public void propertyChange(final PropertyChangeEvent event) {
    final String property = event.getPropertyName();

    runOnUiThread(new Runnable() {
        public void run() {
            try {
                /*if (property.equals(PROPERTY_ACCELEROMETER)) {
                  // A change in accelerometer data has occured.
                  Point3D newValue = (Point3D) event.getNewValue();
                  String xaxis = decimal.format(newValue.x);
                  String yaxis = decimal.format(newValue.y);
                  String zaxis = decimal.format(newValue.z);
                        
                  String acl = "X: " + decimal.format(newValue.x) + "g" + "\nY: " + decimal.format(newValue.y) + "g" + "\nZ: " + decimal.format(newValue.z) + "g";
                          
                  ((TextView) findViewById(R.id.accelerometerTxt)).setText(acl);
                          
                }
                } else */if (property.equals(PROPERTY_AMBIENT_TEMPERATURE)) {
                    double newAmbientValue = (Double) event.getNewValue();

                    final int img;
                    TextView textView = (TextView) findViewById(R.id.ambientTemperatureTxt);
                    String formattedText = "Touch Not Detected";

                    if (newAmbientValue == 11.00) {
                        formattedText = "Touch Detected";
                        //img = touch;

                    } else {

                        //img = notouch;
                    }

                    //((ImageView) findViewById(R.id.touch)).setImageResource(img);

                    textView.setText(formattedText);
                } /*ARVelse*/

                else if (property.equals(PROPERTY_IR_TEMPERATURE)) {
                    double newIRValue = (Double) event.getNewValue();
                    //  float newIRValue_1 = (Float) event.getNewValue();
                    TextView textView = (TextView) findViewById(R.id.ir_temperature);
                    String value = decimal.format(newIRValue);
                    String formattedText = value + DEGREE_SYM;
                    wakelockk.acquire();
                    textView.setText(formattedText);
                    tempwriteintoafile(value);
                    analyze(Float.valueOf(value), patient); // Added by Nihesh for analysis of incoming readings.

                    //ARV
                    /*try {
                    java.util.Date date = new java.util.Date();
                    Timestamp chk = new Timestamp(date.getTime());
                    long timemilli =  System.currentTimeMillis();
                    String abc = String.valueOf(timemilli);//chk.toString();
                    String separator = System.getProperty("line.separator");
                            
                    File ext = Environment.getExternalStorageDirectory();
                    File myFile = new File(ext, "mysdfile_7.txt");
                    if(myFile.exists()){
                       try {
                          FileOutputStream fOut = new FileOutputStream(myFile,true);
                           OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                           myOutWriter.append(abc);
                           myOutWriter.append("   ");
                           myOutWriter.append(formattedText_1);
                           myOutWriter.append(separator);
                           myOutWriter.flush();
                           myOutWriter.close();
                           fOut.close();
                       } catch (Exception e) {
                          // TODO: handle exception
                       }
                    }
                    else{
                       myFile.createNewFile();
                    }
                            
                    //   File myFile = new File("/sdcard/mysdfile.txt");
                    //   myFile.createNewFile();
                    //   FileOutputStream fOut = new FileOutputStream(myFile);
                    //ARV            OutputStreamWriter myOutWriter = 
                    //ARV                              new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_APPEND));//fOut
                    //   myOutWriter.append(txtData.getText());
                    //ARV            myOutWriter.write(abc);
                    //ARV            myOutWriter.append(separator);
                    //ARV            myOutWriter.flush();
                    //ARV            myOutWriter.close();
                    //      fOut.close();
                    Toast.makeText(getBaseContext(),
                          "Done writing SD 'mysdfile.txt'",
                          Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(),
                          Toast.LENGTH_SHORT).show();
                    } //ARV
                            
                    */

                } //endif

                /* else if (property.equals(PROPERTY_HUMIDITY)) {
                  double newHumidity = (Double) event.getNewValue();
                // ARV        TextView textView = (TextView) findViewById(R.id.humidityTxt);
                  String formattedText = decimal.format(newHumidity) + "%rH";
                //ARV         textView.setText(formattedText);
                } else if (property.equals(PROPERTY_MAGNETOMETER)) {
                  Point3D newValue = (Point3D) event.getNewValue();
                        
                  String msg = "X: " + decimal.format(newValue.x) + "uT" + "\nY: " + decimal.format(newValue.y) + "uT" + "\nZ: " + decimal.format(newValue.z) + "uT";
                        
                //ARV         ((TextView) findViewById(R.id.magnetometerTxt)).setText(msg);
                } else if (property.equals(PROPERTY_GYROSCOPE)) {
                  Point3D newValue = (Point3D) event.getNewValue();
                        
                  String msg = "X: " + decimal.format(newValue.x) + "deg/s" + "\nY: " + decimal.format(newValue.y) + "deg/s" + "\nZ: " + decimal.format(newValue.z)
                      + "deg/s";
                        
                //ARV          ((TextView) findViewById(R.id.gyroscopeTxt)).setText(msg);
                } else if (property.equals(Measurements.PROPERTY_BAROMETER)) {
                  Double newValue = (Double) event.getNewValue();
                        
                  String msg = new DecimalFormat("+0.0;-0.0").format(newValue / 100) + " hPa";
                        
                //ARV           ((TextView) findViewById(R.id.barometerTxt)).setText(msg);
                } else if (property.equals(PROPERTY_SIMPLE_KEYS)) {
                  SimpleKeysStatus newValue = (SimpleKeysStatus) event.getNewValue();
                        
                  final int img;
                  switch (newValue) {
                  case OFF_OFF:
                    img = buttonsoffoff;
                    break;
                  case OFF_ON:
                    img = buttonsoffon;
                    break;
                  case ON_OFF:
                    img = buttonsonoff;
                    break;
                  case ON_ON:
                    img = buttonsonon;
                    break;
                  default:
                    throw new UnsupportedOperationException();
                  }
                        
                  ((ImageView) findViewById(R.id.buttons)).setImageResource(img);
                }*/ else if (property.equals(LOST_DEVICE_ + CONNECTED)) {
                    // A device has been disconnected
                    // We notify the user with a toast

                    int duration = Toast.LENGTH_SHORT;
                    String text = "Lost connection";

                    Toast.makeText(ServicesActivity.this, text, duration).show();
                    finish();
                } else if (property.equals(NEW_DEVICE_ + CONNECTED)) {
                    // A device has been disconnected
                    // We notify the user with a toast

                    int duration = Toast.LENGTH_SHORT;
                    String text = "Established connection";

                    Toast.makeText(ServicesActivity.this, text, duration).show();
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
                // Could be that the ServicesFragment is no longer visible
                // But we still receive property change events.
                // referring to the views with findViewById will then return a null.
            }
        }
    });
}

From source file:org.rdv.viz.image.ImageViz.java

private void initFilmstripPanel() {
    filmstripPanel = new FilmstripPanel();
    filmstripPanel.setBackground(Color.black);
    filmstripPanel.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent pce) {
            String propertyName = pce.getPropertyName();
            if (propertyName.equals(FilmstripPanel.MAXIMUM_IMAGES_PROPERTY)) {
                if (filmstripPanel.getMaximumImages() != FilmstripPanel.MAXIMUM_IMAGES_DEFAULT) {
                    properties.setProperty(DATA_PANEL_PROPERTY_MAXIMUM_FILMSTRIP_IMAGES,
                            pce.getNewValue().toString());
                } else {
                    properties.remove(DATA_PANEL_PROPERTY_MAXIMUM_FILMSTRIP_IMAGES);
                }/*from  w ww  .  j  a  v  a  2 s.c  om*/
                updateMaximumFilmstripImagesRadioButtons();
            }
        }
    });

    filmstripPanel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
                setFilmstripMode(false);
            }
        }
    });
}