List of usage examples for java.lang NumberFormatException NumberFormatException
public NumberFormatException()
NumberFormatException
with no detail message. From source file:org.monome.pages.MIDIKeyboardPage.java
/** * sets the scales to those entered in the gui *///from w ww. j a va 2 s . c om public void setScales(String s[]) { scaleStr[0].replace(0, 20, s[0]); scaleStr[1].replace(0, 20, s[1]); scaleStr[2].replace(0, 20, s[2]); scaleStr[3].replace(0, 20, s[3]); scaleStr[4].replace(0, 20, s[4]); scaleStr[5].replace(0, 20, s[5]); for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { try { if (this.scaleStr[i].length() < 13) throw new NumberFormatException(); scales[i][j] = Integer.parseInt(this.scaleStr[i].substring(j * 2, j * 2 + 1)); if (j < 5 && this.scaleStr[i].charAt(j * 2 + 1) != ',') throw new NumberFormatException(); } catch (java.lang.NumberFormatException nfe) { JOptionPane.showMessageDialog(this.monome, "Scale input must be formatted \"#,#,#,#,#,#,#\".", "Input Error!", 1); return; } } } }
From source file:edu.usc.scrc.PriorityPruner.CommandLineOptions.java
/** * Parses a String-argument to a double value and makes sure it's valid. * /*from ww w . j av a2 s. c om*/ * @param option * name of the Option to that the argument belongs * @param argument * String that will be parsed * @param min * minimum value allowed for this parameter * @param max * maximum value allowed for this parameter * @return a double value * @throws NumberFormatException * if invalid String-argument were provided * @throws PriorityPrunerException * if invalid String-argument were provided */ private double getDoubleArgument(String option, String argument, double min, double max) throws PriorityPrunerException { try { Double doubleValue = Double.parseDouble(argument); if (doubleValue >= min && doubleValue <= max) { return doubleValue; } else { // exception get thrown either if parsing is impossible or // values are out of range throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new PriorityPrunerException("\"" + argument + "\" is not a valid input for option \r\n" + option + "\r\n, please specify an decimal value between " + min + " and " + max + ".\r\nFor more information type \"-h\"."); } }
From source file:dhbw.ka.mwi.businesshorizon2.ui.process.parameter.ParameterPresenter.java
/** * Methode die sich nach der Auswahl der Wahrscheinlichkeit fuer eine * positive Fremdkapitalentwicklung kuemmert. Konkret wird aus dem String * des Eingabefelds der Double-Wert gezogen und geprueft ob der Wert * zwischen 0 und 100 liegt. Vor der Uebergabe wird der uebergebene an das * Project-Objekt wird der Wert noch durch 100 geteilt, da die Rechenlogig * mit einem Wert zwischen 0 und 1 arbeitet. Falls nicht wird eine ClassCastException * geworfen, die eine Fehlermeldung auf der Benutzeroberflaecher angezeigt * und ein ComponentError generiert.// w w w. j a v a 2s. c o m * * @author Christian Scherer * @param borrowedCapitalProbabilityOfRiseString * Wahrscheinlichkeit fuer eine positive Fremdkapitalentwicklung * fuer die RandomWalk Methode */ public void borrowedCapitalProbabilityOfRiseChosen(String borrowedCapitalProbabilityOfRiseString) { logger.debug("Anwender-Eingabe zu Wahrscheinlichkeit f\u00fcr steigende Fremdkapitalentwicklung"); try { borrowedCapitalProbabilityOfRise = Double.parseDouble(borrowedCapitalProbabilityOfRiseString); if (borrowedCapitalProbabilityOfRise >= 0 && borrowedCapitalProbabilityOfRise <= 100) { borrowedCapitalProbabilityOfRiseValid = true; getView().setComponentError(false, "borrowedCapitalProbabilityOfRise", ""); this.projectProxy.getSelectedProject() .setBorrowedCapitalProbabilityOfRise((this.borrowedCapitalProbabilityOfRise / 100)); logger.debug( "Wahrscheinlichkeit f\u00fcr steigende Fremdkapitalentwicklung in das Projekt-Objekten gesetzt"); } else { throw new NumberFormatException(); } } catch (NumberFormatException nfe) { borrowedCapitalProbabilityOfRiseValid = false; getView().setComponentError(true, "borrowedCapitalProbabilityOfRise", errorMessageBorrowedCapitalProbabilityOfRise); getView().showErrorMessage(errorMessageBorrowedCapitalProbabilityOfRise); logger.debug( "Keine gueltige Eingabe in Feld 'Wahrscheinlichkeit f\u00fcr steigende Fremdkapitalentwicklung"); } eventBus.fireEvent(new ValidateContentStateEvent()); }
From source file:jp.terasoluna.fw.web.struts.form.FieldChecksExTest05.java
/** * testValidateByteLength05()/* w w w . ja v a 2 s . c o m*/ * <br><br> * * (?n) * <br> * _?FF * <br><br> * l?F(?) bean:String:"abc0#"<br> * (?) va:not null<br> * (?) field:not null<br> * var:byteLength="A"<br> * Msg("message","message")<br> * (?) errors:not null<br> * (vf)<br> * (?) validator:not null<br> * (?) request:not null<br> * * <br> * l?F(l) boolean:true<br> * (?) ?O:?Ox?FG?[<br> * ?bZ?[W?F<br> * "byteLength is not numeric(integer)."<br> * O?FNumberFormatException<br> * (?) errors:not null<br> * (vf)<br> * * <br> * fieldbyteLengthl?l?A * truemF?B * <br> * * @throws Exception ?\bh?O */ public void testValidateByteLength05() throws Exception { //eXgf?[^? // ++++ beanIuWFNg ++++ String bean = "abc0#"; // ++++ ??IuWFNg ValidatorAction va = new ValidatorAction(); va.setName("message"); // ++++ ?tB?[h? Field field = new Field(); Var var = new Var(); var.setName("byteLength"); var.setValue("A"); field.addVar(var); // ?bZ?[W? Msg msg = new Msg(); msg.setKey("message"); msg.setName("message"); msg.setResource(false); field.addMsg(msg); // G?[? ActionMessages errors = new ActionMessages(); // [HTTPNGXg MockHttpServletRequest request = new MockHttpServletRequest(); // ValidatorResourcesCX^X ValidatorResources validatorResources = new ValidatorResources(); // ValidatorCX^X Validator validator = new Validator(validatorResources); // eXg?s boolean result = FieldChecksEx.validateByteLength(bean, va, field, errors, validator, request); // eXgmF // truep?B assertTrue(result); // G?[??B assertTrue(errors.isEmpty()); // ??O`FbN assertTrue(LogUTUtil.checkError("byteLength is not numeric(integer).", new NumberFormatException())); }
From source file:jp.terasoluna.fw.web.struts.form.FieldChecksExTest08.java
/** * testValidateByteRange14()/*from ww w. j a va 2 s.c o m*/ * <br><br> * * (??n) * <br> * _?FF * <br><br> * l?F(?) bean:String:"aaaaaa"<br> * (?) va:not null<br> * (?) field:not null<br> * var:minByte=""<br> * var:maxByte="abc"<br> * encoding=""<br> * Msg("message","message")<br> * (?) errors:not null<br> * ActionMessage("testMessage")<br> * (?) validator:not null<br> * (?) request:not null<br> * * <br> * l?F(l) boolean:true<br> * (?) ?O:?Ox?FG?[<br> * ?bZ?[W?F""<br> * O?FNumberFormatException<br> * (?) errors:not null<br> * (vf)<br> * * <br> * fieldminByte?AmaxByte?l?A * ?A0?AInteger.MAX_VALUEvZ?s?AG?[?O * ?omF?B * <br> * * @throws Exception ?\bh?O */ public void testValidateByteRange14() throws Exception { //eXgf?[^? // ++++ beanIuWFNg ++++ String bean = "aaaaaa"; // ++++ ??IuWFNg ValidatorAction va = new ValidatorAction(); va.setName("message"); // ++++ ?tB?[h? Field field = new Field(); Var var = new Var(); var.setName("maxByte"); var.setValue("abc"); field.addVar(var); var = new Var(); var.setName("minByte"); var.setValue(""); field.addVar(var); var = new Var(); var.setName("encoding"); var.setValue(""); field.addVar(var); // ?bZ?[W? Msg msg = new Msg(); msg.setKey("message"); msg.setName("message"); msg.setResource(false); field.addMsg(msg); // G?[? ActionMessages errors = new ActionMessages(); // [HTTPNGXg MockHttpServletRequest request = new MockHttpServletRequest(); // ValidatorResourcesCX^X ValidatorResources validatorResources = new ValidatorResources(); // ValidatorCX^X Validator validator = new Validator(validatorResources); // eXg?s boolean result = FieldChecksEx.validateByteRange(bean, va, field, errors, validator, request); // eXgmF // truep?B assertTrue(result); // G?[??B assertTrue(errors.isEmpty()); // G?[?O`FbN assertTrue(LogUTUtil.checkError("", new NumberFormatException())); }
From source file:name.mjw.cytospade.fcsFile.java
/** * getCompensatedEventList ---/*w w w . ja v a 2 s.c o m*/ * <p> * Returns the event list compensated by the SPILL matrix. * <p> * * @return array of double arrays containing the events. */ public double[][] getCompensatedEventList() { double[][] events = this.getEventList(); if (events.length != this.getNumChannels()) return events; // Unable to extract the underlying events // Convert the SPILL string to a compensation matrix String compString = this.getSpillString(); if (compString == null) return events; // No compensation, just return the events // Split the compensation string into its values // // The basic structure for SPILL* is: // $SPILLOVER/n,string1,string2,...,f1,f2,f3,f4,.../ String[] compValues = compString.split(","); String[] compNames = null; String[] compData = null; int compDataStart = 0; int n = 0; try { // Try to parse the number of acquisition parameters n = Integer.parseInt(compValues[0]); if (n <= 0 || n > this.parameters) throw new NumberFormatException(); } catch (NumberFormatException nfe) { CyLogger.getLogger().error("Failed to parse parameter count in spill string", nfe); return events; } compNames = Arrays.copyOfRange(compValues, 1, n + 1); // Match names in spill string to columns in parameter lists compDataStart = Arrays.asList(this.channelShortname).indexOf(compNames[0]); if (compDataStart < 0) { CyLogger.getLogger().error("Failed to match channel " + compNames[0] + " to parameter in file"); return events; // Failure match spill string names to channels } for (int i = 0; i < n; i++) { if (!compNames[i].equals(this.channelShortname[compDataStart + i])) { CyLogger.getLogger().error("Spill channel are not continguous parameters in file"); return events; // Spill string columns not in order } } // Extract actual compensation data compData = Arrays.copyOfRange(compValues, n + 1, compValues.length); if (compData.length != (n * n)) return events; /** * Populate the compensation matrix --- The values are stored in * row-major order, i.e., the elements in the first row appear * first. */ double[][] matrix = new double[n][n]; // Loop through the array of compensation values for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { try { matrix[i][j] = Double.parseDouble(compData[i * n + j]); } catch (NumberFormatException nfe) { // Set default value If a NumberFormatException occurred matrix[i][j] = 0.0d; } } } // Compute the inverse of the compensation data and then apply // to data matrix (which is column major). Specifically compute // transpose(inverse(<SPILL MATRIX>)) * data RealMatrix comp = (new LUDecompositionImpl(new Array2DRowRealMatrix(matrix))).getSolver().getInverse(); RealMatrix data = new BlockRealMatrix(events); data.setSubMatrix( // Update compensated portion of data matrix comp.transpose() .multiply(data.getSubMatrix(compDataStart, compDataStart + n - 1, 0, this.getEventCount() - 1)) .getData(), compDataStart, 0); return data.getData(); }
From source file:gephi.spade.panel.fcsFile.java
/** * getCompensatedEventList ---//from w ww.j a va 2s . c om * <p> * Returns the event list compensated by the SPILL matrix. * <p> * * @return array of double arrays containing the events. */ public double[][] getCompensatedEventList() { double[][] events = this.getEventList(); if (events.length != this.getNumChannels()) return events; // Unable to extract the underlying events // Convert the SPILL string to a compensation matrix String compString = this.getSpillString(); if (compString == null) return events; // No compensation, just return the events // Split the compensation string into its values // // The basic structure for SPILL* is: // $SPILLOVER/n,string1,string2,...,f1,f2,f3,f4,.../ String[] compValues = compString.split(","); String[] compNames = null; String[] compData = null; int compDataStart = 0; int n = 0; try { // Try to parse the number of acquisition parameters n = Integer.parseInt(compValues[0]); if (n <= 0 || n > this.parameters) throw new NumberFormatException(); } catch (NumberFormatException nfe) { //CyLogger.getLogger().error("Failed to parse parameter count in spill string",nfe); return events; } compNames = Arrays.copyOfRange(compValues, 1, n + 1); // Match names in spill string to columns in parameter lists compDataStart = Arrays.asList(this.channelShortname).indexOf(compNames[0]); if (compDataStart < 0) { //CyLogger.getLogger().error("Failed to match channel "+compNames[0]+" to parameter in file"); return events; // Failure match spill string names to channels } for (int i = 0; i < n; i++) { if (!compNames[i].equals(this.channelShortname[compDataStart + i])) { //CyLogger.getLogger().error("Spill channel are not continguous parameters in file"); return events; // Spill string columns not in order } } // Extract actual compensation data compData = Arrays.copyOfRange(compValues, n + 1, compValues.length); if (compData.length != (n * n)) return events; /** * Populate the compensation matrix --- The values are stored in * row-major order, i.e., the elements in the first row appear * first. */ double[][] matrix = new double[n][n]; // Loop through the array of compensation values for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { try { matrix[i][j] = Double.parseDouble(compData[i * n + j]); } catch (NumberFormatException nfe) { // Set default value If a NumberFormatException occurred matrix[i][j] = 0.0d; } } } // Compute the inverse of the compensation data and then apply // to data matrix (which is column major). Specifically compute // transpose(inverse(<SPILL MATRIX>)) * data RealMatrix comp = (new LUDecompositionImpl(new Array2DRowRealMatrix(matrix))).getSolver().getInverse(); RealMatrix data = new BlockRealMatrix(events); data.setSubMatrix( // Update compensated portion of data matrix comp.transpose() .multiply(data.getSubMatrix(compDataStart, compDataStart + n - 1, 0, this.getEventCount() - 1)) .getData(), compDataStart, 0); return data.getData(); }
From source file:jp.terasoluna.fw.web.struts.form.FieldChecksExTest08.java
/** * testValidateByteRange15()/*from w ww. j ava 2s . com*/ * <br><br> * * (??n) * <br> * _?FF * <br><br> * l?F(?) bean:String:"bbbbb"<br> * (?) va:not null<br> * (?) field:not null<br> * var:minByte="def"<br> * var:maxByte=""<br> * encoding=""<br> * Msg("message","message")<br> * (?) errors:not null<br> * ActionMessage("testMessage")<br> * (?) validator:not null<br> * (?) request:not null<br> * * <br> * l?F(l) boolean:true<br> * (?) ?O:?Ox?FG?[<br> * ?bZ?[W?F""<br> * O?FNumberFormatException<br> * (?) errors:not null<br> * (vf)<br> * * <br> * fieldminByte?l?AmaxByte?A * ?A0?AInteger.MAX_VALUEvZ?s?AG?[?O * ?omF?B * <br> * * @throws Exception ?\bh?O */ public void testValidateByteRange15() throws Exception { //eXgf?[^? // ++++ beanIuWFNg ++++ String bean = "bbbbb"; // ++++ ??IuWFNg ValidatorAction va = new ValidatorAction(); va.setName("message"); // ++++ ?tB?[h? Field field = new Field(); Var var = new Var(); var.setName("maxByte"); var.setValue(""); field.addVar(var); var = new Var(); var.setName("minByte"); var.setValue("def"); field.addVar(var); var = new Var(); var.setName("encoding"); var.setValue(""); field.addVar(var); // ?bZ?[W? Msg msg = new Msg(); msg.setKey("message"); msg.setName("message"); msg.setResource(false); field.addMsg(msg); // G?[? ActionMessages errors = new ActionMessages(); // [HTTPNGXg MockHttpServletRequest request = new MockHttpServletRequest(); // ValidatorResourcesCX^X ValidatorResources validatorResources = new ValidatorResources(); // ValidatorCX^X Validator validator = new Validator(validatorResources); // eXg?s boolean result = FieldChecksEx.validateByteRange(bean, va, field, errors, validator, request); // eXgmF // truep?B assertTrue(result); // G?[??B assertTrue(errors.isEmpty()); // G?[?O`FbN assertTrue(LogUTUtil.checkError("", new NumberFormatException())); }
From source file:org.pentaho.reporting.engine.classic.core.modules.gui.base.PreviewPane.java
protected float parseRelativeFloat(final String value) { if (value == null) { throw new NumberFormatException(); }//from w ww . jav a 2s. c om final String tvalue = value.trim(); if (tvalue.length() > 0 && tvalue.charAt(tvalue.length() - 1) == '%') { //$NON-NLS-1$ final String number = tvalue.substring(0, tvalue.length() - 1); //$NON-NLS-1$ return Float.parseFloat(number) * -1.0f; } else { return Float.parseFloat(tvalue); } }
From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_link.java
private List<JComponent> getExtraOptions(final int row, final Object itemId) { List<JComponent> options = new LinkedList<JComponent>(); final List<Link> rowVisibleLinks = getVisibleElementsInTable(); final NetPlan netPlan = callback.getDesign(); if (itemId != null) { final long linkId = (long) itemId; JMenuItem lengthToEuclidean_thisLink = new JMenuItem("Set link length to node-pair Euclidean distance"); lengthToEuclidean_thisLink.addActionListener(new ActionListener() { @Override/* w w w . ja v a 2 s . c o m*/ public void actionPerformed(ActionEvent e) { Link link = netPlan.getLinkFromId(linkId); Node originNode = link.getOriginNode(); Node destinationNode = link.getDestinationNode(); double euclideanDistance = netPlan.getNodePairEuclideanDistance(originNode, destinationNode); link.setLengthInKm(euclideanDistance); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(lengthToEuclidean_thisLink); JMenuItem lengthToHaversine_allNodes = new JMenuItem( "Set link length to node-pair Haversine distance (longitude-latitude) in km"); lengthToHaversine_allNodes.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Link link = netPlan.getLinkFromId(linkId); Node originNode = link.getOriginNode(); Node destinationNode = link.getDestinationNode(); double haversineDistanceInKm = netPlan.getNodePairHaversineDistanceInKm(originNode, destinationNode); link.setLengthInKm(haversineDistanceInKm); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(lengthToHaversine_allNodes); JMenuItem scaleLinkLength_thisLink = new JMenuItem("Scale link length"); scaleLinkLength_thisLink.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double scaleFactor; while (true) { String str = JOptionPane.showInputDialog(null, "(Multiplicative) Scale factor", "Scale link length", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { scaleFactor = Double.parseDouble(str); if (scaleFactor < 0) throw new RuntimeException(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog( "Non-valid scale value. Please, introduce a non-negative number", "Error setting scale factor"); } } netPlan.getLinkFromId(linkId) .setLengthInKm(netPlan.getLinkFromId(linkId).getLengthInKm() * scaleFactor); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(scaleLinkLength_thisLink); if (netPlan.isMultilayer()) { Link link = netPlan.getLinkFromId(linkId); if (link.getCoupledDemand() != null) { JMenuItem decoupleLinkItem = new JMenuItem("Decouple link (if coupled to unicast demand)"); decoupleLinkItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { netPlan.getLinkFromId(linkId).getCoupledDemand().decouple(); model.setValueAt("", row, 20); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(decoupleLinkItem); } else { JMenuItem createLowerLayerDemandFromLinkItem = new JMenuItem( "Create lower layer demand from link"); createLowerLayerDemandFromLinkItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Collection<Long> layerIds = netPlan.getNetworkLayerIds(); final JComboBox layerSelector = new WiderJComboBox(); for (long layerId : layerIds) { if (layerId == netPlan.getNetworkLayerDefault().getId()) continue; final String layerName = netPlan.getNetworkLayerFromId(layerId).getName(); String layerLabel = "Layer " + layerId; if (!layerName.isEmpty()) layerLabel += " (" + layerName + ")"; layerSelector.addItem(StringLabeller.of(layerId, layerLabel)); } layerSelector.setSelectedIndex(0); JPanel pane = new JPanel(); pane.add(new JLabel("Select layer: ")); pane.add(layerSelector); while (true) { int result = JOptionPane.showConfirmDialog(null, pane, "Please select the lower layer to create the demand", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) return; try { long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem()) .getObject(); Link link = netPlan.getLinkFromId(linkId); netPlan.addDemand(link.getOriginNode(), link.getDestinationNode(), link.getCapacity(), link.getAttributes(), netPlan.getNetworkLayerFromId(layerId)); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error creating lower layer demand from link"); } } } }); options.add(createLowerLayerDemandFromLinkItem); JMenuItem coupleLinkToDemand = new JMenuItem("Couple link to lower layer demand"); coupleLinkToDemand.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Collection<Long> layerIds = netPlan.getNetworkLayerIds(); final JComboBox layerSelector = new WiderJComboBox(); final JComboBox demandSelector = new WiderJComboBox(); for (long layerId : layerIds) { if (layerId == netPlan.getNetworkLayerDefault().getId()) continue; final String layerName = netPlan.getNetworkLayerFromId(layerId).getName(); String layerLabel = "Layer " + layerId; if (!layerName.isEmpty()) layerLabel += " (" + layerName + ")"; layerSelector.addItem(StringLabeller.of(layerId, layerLabel)); } layerSelector.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (layerSelector.getSelectedIndex() >= 0) { long selectedLayerId = (Long) ((StringLabeller) layerSelector .getSelectedItem()).getObject(); demandSelector.removeAllItems(); for (Demand demand : netPlan .getDemands(netPlan.getNetworkLayerFromId(selectedLayerId))) { if (demand.isCoupled()) continue; long ingressNodeId = demand.getIngressNode().getId(); long egressNodeId = demand.getEgressNode().getId(); String ingressNodeName = demand.getIngressNode().getName(); String egressNodeName = demand.getEgressNode().getName(); demandSelector.addItem(StringLabeller.unmodifiableOf(demand.getId(), "d" + demand.getId() + " [n" + ingressNodeId + " (" + ingressNodeName + ") -> n" + egressNodeId + " (" + egressNodeName + ")]")); } } if (demandSelector.getItemCount() == 0) { demandSelector.setEnabled(false); } else { demandSelector.setSelectedIndex(0); demandSelector.setEnabled(true); } } }); layerSelector.setSelectedIndex(-1); layerSelector.setSelectedIndex(0); JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]")); pane.add(new JLabel("Select layer: ")); pane.add(layerSelector, "growx, wrap"); pane.add(new JLabel("Select demand: ")); pane.add(demandSelector, "growx, wrap"); while (true) { int result = JOptionPane.showConfirmDialog(null, pane, "Please select the lower layer demand", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) return; try { long demandId; try { demandId = (long) ((StringLabeller) demandSelector.getSelectedItem()) .getObject(); } catch (Throwable ex) { throw new RuntimeException("No demand was selected"); } netPlan.getDemandFromId(demandId) .coupleToUpperLayerLink(netPlan.getLinkFromId(linkId)); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error coupling lower layer demand to link"); } } } }); options.add(coupleLinkToDemand); } } } if (rowVisibleLinks.size() > 1) { if (!options.isEmpty()) options.add(new JPopupMenu.Separator()); JMenuItem caFixValue = new JMenuItem("Set capacity to all"); caFixValue.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double u_e; while (true) { String str = JOptionPane.showInputDialog(null, "Capacity value", "Set capacity to all table links", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { u_e = Double.parseDouble(str); if (u_e < 0) throw new NumberFormatException(); break; } catch (NumberFormatException ex) { ErrorHandling.showErrorDialog( "Non-valid capacity value. Please, introduce a non-negative number", "Error setting capacity value"); } } try { for (Link link : rowVisibleLinks) link.setCapacity(u_e); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set capacity to all links"); } } }); options.add(caFixValue); JMenuItem caFixValueUtilization = new JMenuItem("Set capacity to match a given utilization"); caFixValueUtilization.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double utilization; while (true) { String str = JOptionPane.showInputDialog(null, "Link utilization value", "Set capacity to all table links to match a given utilization", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { utilization = Double.parseDouble(str); if (utilization <= 0) throw new NumberFormatException(); break; } catch (NumberFormatException ex) { ErrorHandling.showErrorDialog( "Non-valid link utilization value. Please, introduce a strictly positive number", "Error setting link utilization value"); } } try { for (Link link : rowVisibleLinks) link.setCapacity(link.getOccupiedCapacity() / utilization); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set capacity to all links according to a given link utilization"); } } }); options.add(caFixValueUtilization); JMenuItem lengthToAll = new JMenuItem("Set link length to all"); lengthToAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double l_e; while (true) { String str = JOptionPane.showInputDialog(null, "Link length value (in km)", "Set link length to all table links", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { l_e = Double.parseDouble(str); if (l_e < 0) throw new RuntimeException(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog( "Non-valid link length value. Please, introduce a non-negative number", "Error setting link length"); } } NetPlan netPlan = callback.getDesign(); try { for (Link link : rowVisibleLinks) link.setLengthInKm(l_e); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set link length to all links"); } } }); options.add(lengthToAll); JMenuItem lengthToEuclidean_allLinks = new JMenuItem( "Set all table link lengths to node-pair Euclidean distance"); lengthToEuclidean_allLinks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { for (Link link : rowVisibleLinks) link.setLengthInKm(netPlan.getNodePairEuclideanDistance(link.getOriginNode(), link.getDestinationNode())); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set link length value to all links"); } } }); options.add(lengthToEuclidean_allLinks); JMenuItem lengthToHaversine_allLinks = new JMenuItem( "Set all table link lengths to node-pair Haversine distance (longitude-latitude) in km"); lengthToHaversine_allLinks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { NetPlan netPlan = callback.getDesign(); try { for (Link link : rowVisibleLinks) { link.setLengthInKm(netPlan.getNodePairHaversineDistanceInKm(link.getOriginNode(), link.getDestinationNode())); } callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set link length value to all links"); } } }); options.add(lengthToHaversine_allLinks); JMenuItem scaleLinkLength_allLinks = new JMenuItem("Scale all table link lengths"); scaleLinkLength_allLinks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double scaleFactor; while (true) { String str = JOptionPane.showInputDialog(null, "(Multiplicative) Scale factor", "Scale (all) link length", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { scaleFactor = Double.parseDouble(str); if (scaleFactor < 0) throw new RuntimeException(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog( "Non-valid scale value. Please, introduce a non-negative number", "Error setting scale factor"); } } NetPlan netPlan = callback.getDesign(); try { for (Link link : rowVisibleLinks) link.setLengthInKm(link.getLengthInKm() * scaleFactor); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to scale link length"); } } }); options.add(scaleLinkLength_allLinks); if (netPlan.isMultilayer()) { final Set<Link> coupledLinks = rowVisibleLinks.stream().filter(e -> e.isCoupled()) .collect(Collectors.toSet()); if (!coupledLinks.isEmpty()) { JMenuItem decoupleAllLinksItem = new JMenuItem("Decouple all table links"); decoupleAllLinksItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (Link link : coupledLinks) if (link.getCoupledDemand() == null) link.getCoupledMulticastDemand().decouple(); else link.getCoupledDemand().decouple(); int numRows = model.getRowCount(); for (int i = 0; i < numRows; i++) model.setValueAt("", i, 20); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(decoupleAllLinksItem); } if (coupledLinks.size() < rowVisibleLinks.size()) { JMenuItem createLowerLayerDemandsFromLinksItem = new JMenuItem( "Create lower layer unicast demands from uncoupled links"); createLowerLayerDemandsFromLinksItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JComboBox layerSelector = new WiderJComboBox(); for (NetworkLayer layer : netPlan.getNetworkLayers()) { if (layer.getId() == netPlan.getNetworkLayerDefault().getId()) continue; final String layerName = layer.getName(); String layerLabel = "Layer " + layer.getId(); if (!layerName.isEmpty()) layerLabel += " (" + layerName + ")"; layerSelector.addItem(StringLabeller.of(layer.getId(), layerLabel)); } layerSelector.setSelectedIndex(0); JPanel pane = new JPanel(); pane.add(new JLabel("Select layer: ")); pane.add(layerSelector); while (true) { int result = JOptionPane.showConfirmDialog(null, pane, "Please select the lower layer to create demands", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) return; try { long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem()) .getObject(); NetworkLayer layer = netPlan.getNetworkLayerFromId(layerId); for (Link link : rowVisibleLinks) if (!link.isCoupled()) link.coupleToNewDemandCreated(layer); callback.getVisualizationState() .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error creating lower layer demands"); } } } }); options.add(createLowerLayerDemandsFromLinksItem); } } } return options; }