diff --git a/vcell-client/src/main/java/cbit/vcell/client/desktop/VCDocumentDecorator.java b/vcell-client/src/main/java/cbit/vcell/client/desktop/VCDocumentDecorator.java index 0ac1e85afa..ba0cf22302 100644 --- a/vcell-client/src/main/java/cbit/vcell/client/desktop/VCDocumentDecorator.java +++ b/vcell-client/src/main/java/cbit/vcell/client/desktop/VCDocumentDecorator.java @@ -9,11 +9,8 @@ import java.util.Objects; import java.util.Set; -import org.vcell.util.BeanUtils; -import org.vcell.util.Issue; +import org.vcell.util.*; import org.vcell.util.Issue.IssueCategory; -import org.vcell.util.IssueContext; -import org.vcell.util.ProgrammingException; import org.vcell.util.document.VCDocument; import cbit.vcell.biomodel.BioModel; @@ -277,7 +274,7 @@ void setSolverDescription(SolverDescription sd) { @Override public void activateView(SelectionManager selectionManager) { - SimulationContext sc = BeanUtils.downcast(SimulationContext.class, simulation.getSimulationOwner()); + SimulationContext sc = CastingUtils.downcast(SimulationContext.class, simulation.getSimulationOwner()); Window activated = null; if (sc != null ) { ActiveView av = new ActiveView(sc, DocumentEditorTreeFolderClass.SIMULATIONS_NODE, ActiveViewID.simulations); diff --git a/vcell-client/src/main/java/cbit/vcell/client/desktop/biomodel/IssueTableModel.java b/vcell-client/src/main/java/cbit/vcell/client/desktop/biomodel/IssueTableModel.java index f9c12e3950..05ba8b8c6d 100644 --- a/vcell-client/src/main/java/cbit/vcell/client/desktop/biomodel/IssueTableModel.java +++ b/vcell-client/src/main/java/cbit/vcell/client/desktop/biomodel/IssueTableModel.java @@ -18,13 +18,10 @@ import org.vcell.model.rbm.MolecularComponent; import org.vcell.model.rbm.MolecularType; import org.vcell.model.rbm.SpeciesPattern; -import org.vcell.util.BeanUtils; -import org.vcell.util.Issue; +import org.vcell.util.*; import org.vcell.util.Issue.IssueCategory; import org.vcell.util.Issue.IssueOrigin; import org.vcell.util.Issue.Severity; -import org.vcell.util.ObjectNotFoundException; -import org.vcell.util.VCAssert; import org.vcell.util.document.VCDocument; import org.vcell.util.gui.GuiUtils; import org.vcell.util.gui.ScrollTable; @@ -210,7 +207,7 @@ private String getSourceObjectPathDescription(VCDocument vcDocument, Issue issue VCAssert.assertValid(issue); Object source = issue.getSource(); { - IssueOrigin io = BeanUtils.downcast(IssueOrigin.class, source); + IssueOrigin io = CastingUtils.downcast(IssueOrigin.class, source); if (io != null) { return io.getDescription(); } @@ -358,7 +355,7 @@ private String getSourceObjectDescription(VCDocument vcDocument, Issue issue) { if (vcDocument instanceof BioModel){ Object object = issue.getSource(); { - DecoratedIssueSource dis = BeanUtils.downcast(DecoratedIssueSource.class, object); + DecoratedIssueSource dis = CastingUtils.downcast(DecoratedIssueSource.class, object); if (dis != null) { return dis.getSourcePath(); } diff --git a/vcell-client/src/main/java/cbit/vcell/client/desktop/simulation/SimulationListTableModel.java b/vcell-client/src/main/java/cbit/vcell/client/desktop/simulation/SimulationListTableModel.java index e327165fcb..ced325702b 100644 --- a/vcell-client/src/main/java/cbit/vcell/client/desktop/simulation/SimulationListTableModel.java +++ b/vcell-client/src/main/java/cbit/vcell/client/desktop/simulation/SimulationListTableModel.java @@ -214,12 +214,6 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { } } - -/** - * Insert the method's description here. - * Creation date: (5/10/2004 6:32:09 PM) - * @param newSimContext cbit.vcell.mapping.SimulationContext - */ public void setSimulationWorkspace(SimulationWorkspace newSimulationWorkspace) { SimulationWorkspace oldValue = this.simulationWorkspace; simulationWorkspace = newSimulationWorkspace; @@ -282,7 +276,7 @@ public void setValueAt(Object aValue, int rowIndex, int columnIndex) { suggestedInterval = timeStep; bValid = false; } else { - if (!BeanUtils.isIntegerMultiple(outputTime, timeStep)) { + if (BeanUtils.isNotAnIntegerMultiple(outputTime, timeStep)) { double n = outputTime/timeStep; int intn = (int)Math.round(n); suggestedInterval = (intn * timeStep); diff --git a/vcell-client/src/main/java/cbit/vcell/client/task/ClientTaskDispatcher.java b/vcell-client/src/main/java/cbit/vcell/client/task/ClientTaskDispatcher.java index 1fcbcbd972..d1bdcf7bbb 100644 --- a/vcell-client/src/main/java/cbit/vcell/client/task/ClientTaskDispatcher.java +++ b/vcell-client/src/main/java/cbit/vcell/client/task/ClientTaskDispatcher.java @@ -438,7 +438,7 @@ public void finished() { } if (lg.isInfoEnabled()) { Object obj = hash.get(STACK_TRACE_ARRAY); - StackTraceElement ste[] = BeanUtils.downcast(StackTraceElement[].class, obj); + StackTraceElement ste[] = CastingUtils.downcast(StackTraceElement[].class, obj); if (ste != null) { String stackTraceString = StringUtils.join(ste,'\n'); lg.info(stackTraceString,(Throwable)hash.get(TASK_ABORTED_BY_ERROR)); @@ -641,7 +641,7 @@ private static void runTask(AsynchClientTask currentTask, Hashtable T findOwnerOfType(Class clzz,Component swingParent) { final Logger lg = LGHolder.LG; - T t = BeanUtils.downcast(clzz, swingParent); + T t = CastingUtils.downcast(clzz, swingParent); if (t != null) { return t; } diff --git a/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java b/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java index 2d13fcd7cf..7b908975eb 100644 --- a/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java +++ b/vcell-client/src/main/java/org/vcell/util/gui/DialogUtils.java @@ -300,10 +300,10 @@ public static Dimension getScreenSize( ) { private static void setInternalNotCancelEnabled(final JOptionPane jop,final boolean bEnabled, boolean bClickOK) { VCAssert.assertTrue(!bClickOK || bEnabled, "bEnabled must be true if bClickOK is true"); for(Component topLevel : jop.getComponents() ) { - Container cntr = BeanUtils.downcast(Container.class, topLevel); + Container cntr = CastingUtils.downcast(Container.class, topLevel); if (cntr != null) { for (Component cmpt : cntr.getComponents()) { - JButton btn = BeanUtils.downcast(JButton.class, cmpt); + JButton btn = CastingUtils.downcast(JButton.class, cmpt); if (btn != null && !btn.getText().equalsIgnoreCase(getCancelText())) { btn.setEnabled(bEnabled); if(bEnabled && bClickOK) { @@ -757,7 +757,7 @@ public static void showErrorDialog(final Component requester, final String messa dialog.setVisible(true); if (goingToEmail ) { Object ro = pane.getValue( ); - Integer reply = BeanUtils.downcast(Integer.class, ro); + Integer reply = CastingUtils.downcast(Integer.class, ro); boolean userSaidYes = reply != null ? reply == JOptionPane.YES_OPTION : false; if (userSaidYes) { Throwable throwableToSend = exception; diff --git a/vcell-client/src/main/java/org/vcell/util/gui/GuiUtils.java b/vcell-client/src/main/java/org/vcell/util/gui/GuiUtils.java index 3692a22a84..f149451584 100644 --- a/vcell-client/src/main/java/org/vcell/util/gui/GuiUtils.java +++ b/vcell-client/src/main/java/org/vcell/util/gui/GuiUtils.java @@ -33,7 +33,7 @@ import javax.swing.tree.TreePath; import org.apache.commons.lang3.StringUtils; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.ISize; import cbit.vcell.desktop.BioModelNode; @@ -219,7 +219,7 @@ private static void prefSize(StringBuilder destination, int level, Component cmp Dimension dim = cmpnt.getPreferredSize(); destination.append(StringUtils.repeat(' ', level) + ExecutionTrace.justClassName(cmpnt) + " prefers " + dim); destination.append('\n'); - Container container = BeanUtils.downcast(Container.class, cmpnt); + Container container = CastingUtils.downcast(Container.class, cmpnt); if (container != null) { for ( Component c : container.getComponents()) { prefSize(destination, level + 1, c); @@ -246,11 +246,11 @@ public static String getPreferredSizes(Component container) { public static String describe(Window w) { if (w != null) { String className = ExecutionTrace.justClassName(w) + " "; - Frame f = BeanUtils.downcast(Frame.class, w); + Frame f = CastingUtils.downcast(Frame.class, w); if (f != null) { return className + f.getTitle(); } - Dialog d = BeanUtils.downcast(Dialog.class, w); + Dialog d = CastingUtils.downcast(Dialog.class, w); if (d != null) { return className + d.getTitle(); } diff --git a/vcell-client/src/main/java/org/vcell/util/gui/IndefiniteProgressDialog.java b/vcell-client/src/main/java/org/vcell/util/gui/IndefiniteProgressDialog.java index 0a48f94696..93d1ca1682 100644 --- a/vcell-client/src/main/java/org/vcell/util/gui/IndefiniteProgressDialog.java +++ b/vcell-client/src/main/java/org/vcell/util/gui/IndefiniteProgressDialog.java @@ -28,7 +28,7 @@ import javax.swing.Timer; import org.vcell.client.logicalwindow.LWContainerHandle; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; @SuppressWarnings("serial") @@ -219,7 +219,7 @@ public void actionPerformed(ActionEvent arg0) { private boolean isModelDialogPresent( ) { for (Window w: Window.getWindows()) { if (w.isShowing()) { - Dialog d = BeanUtils.downcast(Dialog.class, w); + Dialog d = CastingUtils.downcast(Dialog.class, w); if (d != null && d != IndefiniteProgressDialog.this) { switch (d.getModalityType()) { case MODELESS: diff --git a/vcell-client/src/main/java/org/vcell/util/gui/LinearDefiniteProgressDialog.java b/vcell-client/src/main/java/org/vcell/util/gui/LinearDefiniteProgressDialog.java index 44f7dd85a8..15d69d907f 100644 --- a/vcell-client/src/main/java/org/vcell/util/gui/LinearDefiniteProgressDialog.java +++ b/vcell-client/src/main/java/org/vcell/util/gui/LinearDefiniteProgressDialog.java @@ -26,7 +26,7 @@ import javax.swing.Timer; import org.vcell.client.logicalwindow.LWContainerHandle; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; @SuppressWarnings("serial") @@ -251,7 +251,7 @@ public void actionPerformed(ActionEvent arg0) { private boolean isModelDialogPresent( ) { for (Window w: Window.getWindows()) { if (w.isShowing()) { - Dialog d = BeanUtils.downcast(Dialog.class, w); + Dialog d = CastingUtils.downcast(Dialog.class, w); if (d != null && d != LinearDefiniteProgressDialog.this) { switch (d.getModalityType()) { case MODELESS: diff --git a/vcell-client/src/test/java/org/vcell/client/logicalwindow/TestPanel.java b/vcell-client/src/test/java/org/vcell/client/logicalwindow/TestPanel.java index f38189418c..c7d2b5d273 100644 --- a/vcell-client/src/test/java/org/vcell/client/logicalwindow/TestPanel.java +++ b/vcell-client/src/test/java/org/vcell/client/logicalwindow/TestPanel.java @@ -7,7 +7,7 @@ import javax.swing.JOptionPane; import javax.swing.JPanel; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.gui.DialogUtils; @SuppressWarnings("serial") @@ -95,7 +95,7 @@ private void optionPaneDialogs( ) { // int r = JOptionPane.showConfirmDialog(this, "What say ye?","A question", JOptionPane.YES_NO_OPTION); Object v = jop.getValue(); System.out.println(v); - Integer rval = BeanUtils.downcast(Integer.class, v); + Integer rval = CastingUtils.downcast(Integer.class, v); if (rval != null) { int r = rval; switch (r) { diff --git a/vcell-core/src/main/java/cbit/vcell/export/server/ASCIIExporter.java b/vcell-core/src/main/java/cbit/vcell/export/server/ASCIIExporter.java index 5161afc912..f099a0e65a 100644 --- a/vcell-core/src/main/java/cbit/vcell/export/server/ASCIIExporter.java +++ b/vcell-core/src/main/java/cbit/vcell/export/server/ASCIIExporter.java @@ -25,11 +25,7 @@ import org.apache.logging.log4j.Logger; import org.vcell.solver.smoldyn.SmoldynVCellMapper; import org.vcell.solver.smoldyn.SmoldynVCellMapper.SmoldynKeyword; -import org.vcell.util.BeanUtils; -import org.vcell.util.Coordinate; -import org.vcell.util.DataAccessException; -import org.vcell.util.NumberUtils; -import org.vcell.util.VCAssert; +import org.vcell.util.*; import org.vcell.util.document.TSJobResultsNoStats; import org.vcell.util.document.TimeSeriesJobSpec; import org.vcell.util.document.User; @@ -1248,7 +1244,7 @@ private FileDataContainerID getSlice(SliceHelper sliceHelper, CartesianMesh mesh public CollectionmakeASCIIData(OutputContext outputContext,JobRequest jobRequest, User user, DataServerImpl dataServerImpl, ExportSpecs exportSpecs,FileDataContainerManager fileDataContainerManager) throws DataAccessException, IOException { FormatSpecificSpecs formatSpecs = exportSpecs.getFormatSpecificSpecs( ); - ASCIISpecs asciiSpecs = BeanUtils.downcast(ASCIISpecs.class, formatSpecs); + ASCIISpecs asciiSpecs = CastingUtils.downcast(ASCIISpecs.class, formatSpecs); if (asciiSpecs != null) { switch (asciiSpecs.getDataType()) { case PDE_VARIABLE_DATA: diff --git a/vcell-core/src/main/java/cbit/vcell/export/server/PDEOffscreenRenderer.java b/vcell-core/src/main/java/cbit/vcell/export/server/PDEOffscreenRenderer.java index c37878211c..0ab828ee03 100644 --- a/vcell-core/src/main/java/cbit/vcell/export/server/PDEOffscreenRenderer.java +++ b/vcell-core/src/main/java/cbit/vcell/export/server/PDEOffscreenRenderer.java @@ -54,111 +54,139 @@ public class PDEOffscreenRenderer { private int normalAxis = 0; private BitSet domainValid; - -/** - * Insert the method's description here. - * Creation date: (10/26/00 4:49:39 PM) - */ -private int[] getCurveColors(Hashtable curvesAndMembraneIndexes, Curve curve,MeshDisplayAdapter meshDisplayAdapter) { + /** + * Insert the method's description here. + * Creation date: (10/26/00 4:49:39 PM) + */ + private int[] getCurveColors(Hashtable curvesAndMembraneIndexes, Curve curve,MeshDisplayAdapter meshDisplayAdapter) { - int[] membraneIndexes = (int[]) curvesAndMembraneIndexes.get(curve); - double[] membraneValues = meshDisplayAdapter.getDataValuesForMembraneIndexes(membraneIndexes,getServerPDEDataContext().getDataValues(),getServerPDEDataContext().getDataIdentifier().getVariableType()); - int notInDomainColor = getDisplayAdapterService().getSpecialColors()[DisplayAdapterService.NOT_IN_DOMAIN_COLOR_OFFSET]; - if(membraneValues != null){ - int[] valueColors = new int[membraneValues.length]; - for (int i = 0; i < membraneValues.length; i += 1) { - int valueColor = getDisplayAdapterService().getColorFromValue(membraneValues[i]); - valueColors[i] = (domainValid!=null?(domainValid.get(membraneIndexes[i])?valueColor:notInDomainColor):valueColor); + int[] membraneIndexes = curvesAndMembraneIndexes.get(curve); + double[] membraneValues = meshDisplayAdapter.getDataValuesForMembraneIndexes(membraneIndexes,getServerPDEDataContext().getDataValues(),getServerPDEDataContext().getDataIdentifier().getVariableType()); + int notInDomainColor = getDisplayAdapterService().getSpecialColors()[DisplayAdapterService.NOT_IN_DOMAIN_COLOR_OFFSET]; + if(membraneValues != null){ + int[] valueColors = new int[membraneValues.length]; + for (int i = 0; i < membraneValues.length; i += 1) { + int valueColor = getDisplayAdapterService().getColorFromValue(membraneValues[i]); + valueColors[i] = (domainValid!=null?(domainValid.get(membraneIndexes[i])?valueColor:notInDomainColor):valueColor); + } + return valueColors; } - return valueColors; + return null; + } + /** + * Insert the method's description here. + * Creation date: (3/2/2001 1:37:01 AM) + * @return cbit.image.DisplayAdapterService + */ + private cbit.image.DisplayAdapterService getDisplayAdapterService() { + return displayAdapterService; } - return null; -} -/** - * Insert the method's description here. - * Creation date: (3/2/2001 1:37:01 AM) - * @return cbit.image.DisplayAdapterService - */ -private cbit.image.DisplayAdapterService getDisplayAdapterService() { - return displayAdapterService; -} -/** - * Insert the method's description here. - * Creation date: (3/2/2001 1:47:07 AM) - * @return int - */ -private int getNormalAxis() { - return normalAxis; -} + /** + * Insert the method's description here. + * Creation date: (3/2/2001 1:47:07 AM) + * @return int + */ + private int getNormalAxis() { + return normalAxis; + } -private BufferedImage getScaledRGBVolume(CartesianMesh mesh,int meshMode,int imageScale,boolean bBackground){ - Dimension dim = FormatSpecificSpecs.getMeshDimensionUnscaled(getNormalAxis(),getServerPDEDataContext().getCartesianMesh()); - int width = (int)dim.getWidth(); - int height = (int)dim.getHeight(); - double[] volumeData = new double[width*height]; - if(!bBackground){ - //if(bNeedsDefaultScaling){setDefaultScaling();} - double notInDomainValue = getDisplayAdapterService().getValueDomain().getMin()-1.0; - double values[] = getServerPDEDataContext().getDataValues(); - int dataIndices[] = getServerPDEDataContext().getCartesianMesh().getVolumeSliceIndices(getNormalAxis(),getSlice()); - for (int i = 0; i < dataIndices.length; i++) { - double value = values[dataIndices[i]]; - if (domainValid!=null){ - if (domainValid.get(dataIndices[i]) || domainValid.isEmpty()){ - volumeData[i] = value; + private BufferedImage getScaledRGBVolume(CartesianMesh mesh,int meshMode,int imageScale,boolean bBackground){ + Dimension dim = FormatSpecificSpecs.getMeshDimensionUnscaled(getNormalAxis(),getServerPDEDataContext().getCartesianMesh()); + int width = (int)dim.getWidth(); + int height = (int)dim.getHeight(); + double[] volumeData = new double[width*height]; + if(!bBackground){ + //if(bNeedsDefaultScaling){setDefaultScaling();} + double notInDomainValue = getDisplayAdapterService().getValueDomain().getMin()-1.0; + double values[] = getServerPDEDataContext().getDataValues(); + int dataIndices[] = getServerPDEDataContext().getCartesianMesh().getVolumeSliceIndices(getNormalAxis(),getSlice()); + for (int i = 0; i < dataIndices.length; i++) { + double value = values[dataIndices[i]]; + if (domainValid!=null){ + if (domainValid.get(dataIndices[i]) || domainValid.isEmpty()){ + volumeData[i] = value; + }else{ + volumeData[i] = notInDomainValue; + } }else{ - volumeData[i] = notInDomainValue; + volumeData[i] = value; } - }else{ - volumeData[i] = value; } } + + SourceDataInfo sourceDataInfo = + new SourceDataInfo(SourceDataInfo.RAW_VALUE_TYPE, + volumeData, + mesh.getExtent(), mesh.getOrigin(), + new Range(0,1), + 0, width, 1, + height, width, + 1, 0); + ImagePaneModel imagePaneModel = new ImagePaneModel(); + imagePaneModel.setSourceData(sourceDataInfo); + imagePaneModel.setBackgroundColor(Color.black); + imagePaneModel.setDisplayAdapterService(getDisplayAdapterService()); + // getDisplayAdapterService().setActiveScaleRange(new Range(0,1)); + imagePaneModel.setMode(meshMode); + imagePaneModel.setZoom(imageScale); + imagePaneModel.setViewport(new Rectangle(imagePaneModel.getScaledLength(width),imagePaneModel.getScaledLength(height))); + imagePaneModel.updateViewPortImage(); + if(bBackground){ + int[] internalBuffer = ((DataBufferInt)(imagePaneModel.getViewPortImage().getRaster().getDataBuffer())).getData(); + Arrays.fill(internalBuffer, getDisplayAdapterService().getSpecialColors()[DisplayAdapterService.NULL_COLOR_OFFSET]); + } + + BufferedImage bufferedImage = imagePaneModel.getViewPortImage(); + imagePaneModel.setDisplayAdapterService(null); + return bufferedImage; + } - - SourceDataInfo sourceDataInfo = - new SourceDataInfo(SourceDataInfo.RAW_VALUE_TYPE, - volumeData, - mesh.getExtent(), mesh.getOrigin(), - new Range(0,1), - 0, width, 1, - height, width, - 1, 0); - ImagePaneModel imagePaneModel = new ImagePaneModel(); - imagePaneModel.setSourceData(sourceDataInfo); - imagePaneModel.setBackgroundColor(Color.black); - imagePaneModel.setDisplayAdapterService(getDisplayAdapterService()); -// getDisplayAdapterService().setActiveScaleRange(new Range(0,1)); - imagePaneModel.setMode(meshMode); - imagePaneModel.setZoom(imageScale); - imagePaneModel.setViewport(new Rectangle(imagePaneModel.getScaledLength(width),imagePaneModel.getScaledLength(height))); - imagePaneModel.updateViewPortImage(); - if(bBackground){ - int[] internalBuffer = ((DataBufferInt)(imagePaneModel.getViewPortImage().getRaster().getDataBuffer())).getData(); - Arrays.fill(internalBuffer, getDisplayAdapterService().getSpecialColors()[DisplayAdapterService.NULL_COLOR_OFFSET]); - } - - BufferedImage bufferedImage = imagePaneModel.getViewPortImage(); - imagePaneModel.setDisplayAdapterService(null); - return bufferedImage; - -} -/** - * Insert the method's description here. - * Creation date: (3/1/2001 11:54:44 PM) - * @return int[] - */ -public int[] getPixelsRGB(int imageScale,int membrScale,int meshMode,int volVarMembrOutlineThickness) { - if (getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.VOLUME) || - getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.POSTPROCESSING)) { - CartesianMesh mesh = getServerPDEDataContext().getCartesianMesh(); - MeshDisplayAdapter meshDisplayAdapter = new MeshDisplayAdapter(mesh); - BufferedImage bufferedImage = getScaledRGBVolume(mesh,meshMode,imageScale,false); - // - // apply curve renderer - // - if (!getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.POSTPROCESSING) && volVarMembrOutlineThickness > 0){ + /** + * Insert the method's description here. + * Creation date: (3/1/2001 11:54:44 PM) + * @return int[] + */ + public int[] getPixelsRGB(int imageScale,int membrScale,int meshMode,int volVarMembrOutlineThickness) { + if (getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.VOLUME) || + getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.POSTPROCESSING)) { + CartesianMesh mesh = getServerPDEDataContext().getCartesianMesh(); + MeshDisplayAdapter meshDisplayAdapter = new MeshDisplayAdapter(mesh); + BufferedImage bufferedImage = getScaledRGBVolume(mesh,meshMode,imageScale,false); + // + // apply curve renderer + // + if (!getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.POSTPROCESSING) && volVarMembrOutlineThickness > 0){ + cbit.vcell.geometry.CurveRenderer curveRenderer = + new cbit.vcell.geometry.CurveRenderer(getDisplayAdapterService()); + curveRenderer.setNormalAxis(getNormalAxis()); + + org.vcell.util.Origin origin = mesh.getOrigin(); + org.vcell.util.Extent extent = mesh.getExtent(); + curveRenderer.setWorldOrigin(new org.vcell.util.Coordinate(origin.getX(),origin.getY(),origin.getZ())); + Coordinate pixeldelta = getPixelDelta(extent, mesh, meshMode,imageScale); + curveRenderer.setWorldDelta(new org.vcell.util.Coordinate(pixeldelta.getX(),pixeldelta.getY(),pixeldelta.getZ())); + Hashtable curvesAndMembraneIndexes = meshDisplayAdapter.getCurvesAndMembraneIndexes(getNormalAxis(),getSlice()); + if (curvesAndMembraneIndexes!=null){ + for (Curve curve : Collections.list(curvesAndMembraneIndexes.keys())) { + curveRenderer.addCurve(curve); + curveRenderer.renderPropertySegmentColors(curve, null/*getCurveColors(curvesAndMembraneIndexes,curves[i],meshDisplayAdapter)*/); + curveRenderer.renderPropertyLineWidthMultiplier(curve, volVarMembrOutlineThickness); + } + Graphics2D g = (Graphics2D)bufferedImage.getGraphics(); + curveRenderer.setAntialias(false);//must be false or could get more than 256 colors + curveRenderer.draw(g); + } + } + return ((DataBufferInt)bufferedImage.getData().getDataBuffer()).getData(); + } else if (getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.MEMBRANE)) { + CartesianMesh mesh = getServerPDEDataContext().getCartesianMesh(); + MeshDisplayAdapter meshDisplayAdapter = new MeshDisplayAdapter(mesh); + BufferedImage bufferedImage = getScaledRGBVolume(mesh,meshMode,imageScale,true); + // + // apply curve renderer + // cbit.vcell.geometry.CurveRenderer curveRenderer = new cbit.vcell.geometry.CurveRenderer(getDisplayAdapterService()); curveRenderer.setNormalAxis(getNormalAxis()); @@ -166,118 +194,101 @@ public int[] getPixelsRGB(int imageScale,int membrScale,int meshMode,int volVarM org.vcell.util.Origin origin = mesh.getOrigin(); org.vcell.util.Extent extent = mesh.getExtent(); curveRenderer.setWorldOrigin(new org.vcell.util.Coordinate(origin.getX(),origin.getY(),origin.getZ())); - Coordinate pixeldelta = getPixelDelta(extent, mesh, meshMode,imageScale); + Coordinate pixeldelta = getPixelDelta(extent, mesh,meshMode, imageScale); curveRenderer.setWorldDelta(new org.vcell.util.Coordinate(pixeldelta.getX(),pixeldelta.getY(),pixeldelta.getZ())); Hashtable curvesAndMembraneIndexes = meshDisplayAdapter.getCurvesAndMembraneIndexes(getNormalAxis(),getSlice()); if (curvesAndMembraneIndexes!=null){ - for (Curve curve : Collections.list(curvesAndMembraneIndexes.keys())) { - curveRenderer.addCurve(curve); - curveRenderer.renderPropertySegmentColors(curve, null/*getCurveColors(curvesAndMembraneIndexes,curves[i],meshDisplayAdapter)*/); - curveRenderer.renderPropertyLineWidthMultiplier(curve, volVarMembrOutlineThickness); - } + for (Curve curve : Collections.list(curvesAndMembraneIndexes.keys())) { + curveRenderer.addCurve(curve); + curveRenderer.renderPropertySegmentColors(curve, getCurveColors(curvesAndMembraneIndexes, curve, meshDisplayAdapter)); + curveRenderer.renderPropertyLineWidthMultiplier(curve, membrScale); + } Graphics2D g = (Graphics2D)bufferedImage.getGraphics(); - curveRenderer.setAntialias(false);//must be false or could get more than 256 colors + curveRenderer.setAntialias(false); curveRenderer.draw(g); } + return ((DataBufferInt)bufferedImage.getData().getDataBuffer()).getData(); + } else { + throw new RuntimeException("unsupported VariableType "+getServerPDEDataContext().getDataIdentifier().getVariableType()); } - return ((DataBufferInt)bufferedImage.getData().getDataBuffer()).getData(); - } else if (getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.MEMBRANE)) { - CartesianMesh mesh = getServerPDEDataContext().getCartesianMesh(); - MeshDisplayAdapter meshDisplayAdapter = new MeshDisplayAdapter(mesh); - BufferedImage bufferedImage = getScaledRGBVolume(mesh,meshMode,imageScale,true); - // - // apply curve renderer - // - cbit.vcell.geometry.CurveRenderer curveRenderer = - new cbit.vcell.geometry.CurveRenderer(getDisplayAdapterService()); - curveRenderer.setNormalAxis(getNormalAxis()); + } + + private Coordinate getPixelDelta(Extent extent,CartesianMesh mesh,int meshMode,int imageScale){ + ImagePaneModel imagePaneModel = new ImagePaneModel(); + imagePaneModel.setMode(meshMode); + imagePaneModel.setZoom(imageScale); + double pixelScaleX = extent.getX()/imagePaneModel.getScaledLength(mesh.getSizeX()); + double pixelScaleY = extent.getY()/imagePaneModel.getScaledLength(mesh.getSizeY()); + double pixelScaleZ = extent.getZ()/imagePaneModel.getScaledLength(mesh.getSizeZ()); + return new Coordinate(pixelScaleX,pixelScaleY,pixelScaleZ); - org.vcell.util.Origin origin = mesh.getOrigin(); - org.vcell.util.Extent extent = mesh.getExtent(); - curveRenderer.setWorldOrigin(new org.vcell.util.Coordinate(origin.getX(),origin.getY(),origin.getZ())); - Coordinate pixeldelta = getPixelDelta(extent, mesh,meshMode, imageScale); - curveRenderer.setWorldDelta(new org.vcell.util.Coordinate(pixeldelta.getX(),pixeldelta.getY(),pixeldelta.getZ())); - Hashtable curvesAndMembraneIndexes = meshDisplayAdapter.getCurvesAndMembraneIndexes(getNormalAxis(),getSlice()); - if (curvesAndMembraneIndexes!=null){ - for (Curve curve : Collections.list(curvesAndMembraneIndexes.keys())) { - curveRenderer.addCurve(curve); - curveRenderer.renderPropertySegmentColors(curve, getCurveColors(curvesAndMembraneIndexes, curve, meshDisplayAdapter)); - curveRenderer.renderPropertyLineWidthMultiplier(curve, membrScale); - } - Graphics2D g = (Graphics2D)bufferedImage.getGraphics(); - curveRenderer.setAntialias(false); - curveRenderer.draw(g); - } - return ((DataBufferInt)bufferedImage.getData().getDataBuffer()).getData(); - } else { - throw new RuntimeException("unsupported VariableType "+getServerPDEDataContext().getDataIdentifier().getVariableType()); } -} + /** + * Insert the method's description here. + * Creation date: (3/2/2001 1:37:01 AM) + * @return cbit.vcell.simdata.ServerPDEDataContext + */ + private cbit.vcell.simdata.ServerPDEDataContext getServerPDEDataContext() { + return serverPDEDataContext; + } + /** + * Insert the method's description here. + * Creation date: (3/2/2001 1:47:07 AM) + * @return int + */ + private int getSlice() { + return slice; + } -private Coordinate getPixelDelta(Extent extent,CartesianMesh mesh,int meshMode,int imageScale){ - ImagePaneModel imagePaneModel = new ImagePaneModel(); - imagePaneModel.setMode(meshMode); - imagePaneModel.setZoom(imageScale); - double pixelScaleX = extent.getX()/imagePaneModel.getScaledLength(mesh.getSizeX()); - double pixelScaleY = extent.getY()/imagePaneModel.getScaledLength(mesh.getSizeY()); - double pixelScaleZ = extent.getZ()/imagePaneModel.getScaledLength(mesh.getSizeZ()); - return new Coordinate(pixelScaleX,pixelScaleY,pixelScaleZ); + /** + * Insert the method's description here. + * Creation date: (3/2/2001 1:47:07 AM) + * @param newNormalAxis int + */ + public void setNormalAxis(int newNormalAxis) { + normalAxis = newNormalAxis; + } + /** + * Insert the method's description here. + * Creation date: (3/2/2001 1:37:01 AM) + * @param newServerPDEDataContext cbit.vcell.simdata.ServerPDEDataContext + */ + private void setServerPDEDataContext(cbit.vcell.simdata.ServerPDEDataContext newServerPDEDataContext) { + serverPDEDataContext = newServerPDEDataContext; + } + /** + * Insert the method's description here. + * Creation date: (3/2/2001 1:47:07 AM) + * @param newSlice int + */ + public void setSlice(int newSlice) { + slice = newSlice; + } -} -/** - * Insert the method's description here. - * Creation date: (3/2/2001 1:37:01 AM) - * @return cbit.vcell.simdata.ServerPDEDataContext - */ -private cbit.vcell.simdata.ServerPDEDataContext getServerPDEDataContext() { - return serverPDEDataContext; -} -/** - * Insert the method's description here. - * Creation date: (3/2/2001 1:47:07 AM) - * @return int - */ -private int getSlice() { - return slice; -} + public void setVarAndTimeAndDisplay(String varName,double timepoint,DisplayPreferences displayPreferences) throws DataAccessException{ + getServerPDEDataContext().setVariableName(varName); + getServerPDEDataContext().setTimePoint(timepoint); + domainValid = (displayPreferences==null?null:(displayPreferences.getDomainValid()==null?null:displayPreferences.getDomainValid())); + Range valueDomain = PDEOffscreenRenderer.calculateValueDomain(getServerPDEDataContext().getDataValues(),domainValid); + ExportSpecs.setupDisplayAdapterService(displayPreferences,getDisplayAdapterService(),valueDomain); -/** - * Insert the method's description here. - * Creation date: (3/2/2001 1:47:07 AM) - * @param newNormalAxis int - */ -public void setNormalAxis(int newNormalAxis) { - normalAxis = newNormalAxis; -} -/** - * Insert the method's description here. - * Creation date: (3/2/2001 1:37:01 AM) - * @param newServerPDEDataContext cbit.vcell.simdata.ServerPDEDataContext - */ -private void setServerPDEDataContext(cbit.vcell.simdata.ServerPDEDataContext newServerPDEDataContext) { - serverPDEDataContext = newServerPDEDataContext; -} -/** - * Insert the method's description here. - * Creation date: (3/2/2001 1:47:07 AM) - * @param newSlice int - */ -public void setSlice(int newSlice) { - slice = newSlice; -} + } -public void setVarAndTimeAndDisplay(String varName,double timepoint,DisplayPreferences displayPreferences) throws DataAccessException{ - getServerPDEDataContext().setVariableName(varName); - getServerPDEDataContext().setTimePoint(timepoint); - domainValid = (displayPreferences==null?null:(displayPreferences.getDomainValid()==null?null:displayPreferences.getDomainValid())); - Range valueDomain = BeanUtils.calculateValueDomain(getServerPDEDataContext().getDataValues(),domainValid); - ExportSpecs.setupDisplayAdapterService(displayPreferences,getDisplayAdapterService(),valueDomain); - -} + public PDEOffscreenRenderer(OutputContext outputContext,User user, DataServerImpl dataServerImpl, VCDataIdentifier vcdID) throws Exception { + setServerPDEDataContext(new ServerPDEDataContext(outputContext,user, dataServerImpl, vcdID)); + getDisplayAdapterService().addColorModelForValues(DisplayAdapterService.createGrayColorModel(), DisplayAdapterService.createGraySpecialColors(), DisplayAdapterService.GRAY); + getDisplayAdapterService().addColorModelForValues(DisplayAdapterService.createBlueRedColorModel(), DisplayAdapterService.createBlueRedSpecialColors(), DisplayAdapterService.BLUERED); + } -public PDEOffscreenRenderer(OutputContext outputContext,User user, DataServerImpl dataServerImpl, VCDataIdentifier vcdID) throws Exception { - setServerPDEDataContext(new ServerPDEDataContext(outputContext,user, dataServerImpl, vcdID)); - getDisplayAdapterService().addColorModelForValues(DisplayAdapterService.createGrayColorModel(), DisplayAdapterService.createGraySpecialColors(), DisplayAdapterService.GRAY); - getDisplayAdapterService().addColorModelForValues(DisplayAdapterService.createBlueRedColorModel(), DisplayAdapterService.createBlueRedSpecialColors(), DisplayAdapterService.BLUERED); -} + private static Range calculateValueDomain(double[] values,BitSet domainValid){ + double min=Double.POSITIVE_INFINITY; + double max=Double.NEGATIVE_INFINITY; + for (int i = 0; i < values.length; i++) { + if((domainValid == null || domainValid.get(i) || domainValid.isEmpty()) && !Double.isNaN(values[i]) && !Double.isInfinite(values[i])){ + if(values[i] < min){min = values[i];} + if(values[i] > max){max = values[i];} + } + } + return new Range(min,max); + } } diff --git a/vcell-core/src/main/java/cbit/vcell/math/MathDescription.java b/vcell-core/src/main/java/cbit/vcell/math/MathDescription.java index 8b3ce3ea9b..52c403c289 100644 --- a/vcell-core/src/main/java/cbit/vcell/math/MathDescription.java +++ b/vcell-core/src/main/java/cbit/vcell/math/MathDescription.java @@ -3665,7 +3665,7 @@ public boolean hasSpeciesObservable() { @Override public boolean isMovingMembrane( ) { Predicate movingMembrane = s -> { - MembraneSubDomain m = BeanUtils.downcast(MembraneSubDomain.class, s); + MembraneSubDomain m = CastingUtils.downcast(MembraneSubDomain.class, s); return m != null && m.isMoving(); }; return subDomainList.stream().filter(movingMembrane).findAny().isPresent(); diff --git a/vcell-core/src/main/java/cbit/vcell/solver/SolverTaskDescription.java b/vcell-core/src/main/java/cbit/vcell/solver/SolverTaskDescription.java index 0cf7b63d53..6fad227e33 100644 --- a/vcell-core/src/main/java/cbit/vcell/solver/SolverTaskDescription.java +++ b/vcell-core/src/main/java/cbit/vcell/solver/SolverTaskDescription.java @@ -17,11 +17,7 @@ import org.apache.logging.log4j.Logger; import org.vcell.chombo.ChomboSolverSpec; import org.vcell.chombo.TimeInterval; -import org.vcell.util.BeanUtils; -import org.vcell.util.CommentStringTokenizer; -import org.vcell.util.Compare; -import org.vcell.util.DataAccessException; -import org.vcell.util.Matchable; +import org.vcell.util.*; import cbit.vcell.mapping.SimulationContext; import cbit.vcell.mapping.SimulationContext.Application; @@ -428,12 +424,6 @@ public Constant getSensitivityParameter() { return fieldSensitivityParameter; } - - /** - * Gets the endingTime property (double) value. - * @return The endingTime property value. - * @see #setEndingTime - */ public Simulation getSimulation() { return fieldSimulation; } @@ -894,7 +884,7 @@ public void readVCML(CommentStringTokenizer tokens) throws DataAccessException { } if (token.equalsIgnoreCase(VCML.UseSymbolicJacobian)) { token = tokens.nextToken(); - setUseSymbolicJacobian((new Boolean(token)).booleanValue()); + setUseSymbolicJacobian(Boolean.parseBoolean(token)); continue; } // JMW 01/25/2001 We have removed the maxTime property @@ -1136,7 +1126,7 @@ public void readVCML(CommentStringTokenizer tokens) throws DataAccessException { stopAtSpatiallyUniformErrorTolerance.readVCML(tokens); } else if (token.equalsIgnoreCase(VCML.RunParameterScanSerially)) { token = tokens.nextToken(); - setSerialParameterScan((new Boolean(token)).booleanValue()); + setSerialParameterScan(Boolean.parseBoolean(token)); } else if (token.equalsIgnoreCase(VCML.SmoldynSimulationOptions)) { setSmoldynSimulationOptions(new SmoldynSimulationOptions(tokens)); } else if (token.equalsIgnoreCase(VCML.SundialsSolverOptions)) { @@ -1152,10 +1142,10 @@ else if (token.equalsIgnoreCase(VCML.NUM_PROCESSORS)) else if (token.equalsIgnoreCase(VCML.TimeoutSimulationDisabled)) { token = tokens.nextToken(); - setTimeoutDisabled((new Boolean(token)).booleanValue()); + setTimeoutDisabled(Boolean.parseBoolean(token)); }else if (token.equalsIgnoreCase(VCML.BorderExtrapolationDisabled)){ token = tokens.nextToken(); - setBorderExtrapolationDisabled((new Boolean(token)).booleanValue()); + setBorderExtrapolationDisabled(Boolean.parseBoolean(token)); } else if (token.equalsIgnoreCase(VCML.MovingBoundarySolverOptions)) @@ -1255,13 +1245,6 @@ public void setSensitivityParameter(Constant sensitivityParameter) throws java.b } } - - /** - * Gets the endingTime property (double) value. - * @return The endingTime property value. - * @throws PropertyVetoException - * @see #setEndingTime - */ private void setSimulation(Simulation simulation) { if (getSimulation() != null) { getSimulation().removePropertyChangeListener(this); @@ -1301,12 +1284,6 @@ public void setSolverDescription(SolverDescription solverDescription) throws jav } } - - /** - * Insert the method's description here. - * Creation date: (12/6/2006 6:16:42 PM) - * @param newFieldStochOpt cbit.vcell.solver.StochSimOptions - */ public void setStochOpt(NonspatialStochSimOptions newStochOpt) { if (lg.isDebugEnabled()) { lg.debug("setStochOption " + Objects.hashCode(newStochOpt) + ' ' + Objects.toString(newStochOpt)); @@ -1319,11 +1296,6 @@ public void setStochOpt(NonspatialStochSimOptions newStochOpt) { } } - /** - * Insert the method's description here. - * Creation date: (12/6/2006 6:16:42 PM) - * @param newFieldStochOpt cbit.vcell.solver.StochSimOptions - */ public void setStochHybridOpt(NonspatialStochHybridOptions newStochHybridOpt) { if (lg.isDebugEnabled()) { lg.debug("setStochOption " + Objects.hashCode(newStochHybridOpt) + ' ' + Objects.toString(newStochHybridOpt)); @@ -1344,9 +1316,9 @@ public void setStochHybridOpt(NonspatialStochHybridOptions newStochHybridOpt) { public void setTaskType(int taskType) throws java.beans.PropertyVetoException { if (fieldTaskType != taskType) { int oldValue = fieldTaskType; - fireVetoableChange("taskType", new Integer(oldValue), new Integer(taskType)); + fireVetoableChange("taskType", oldValue, taskType); fieldTaskType = taskType; - firePropertyChange("taskType", new Integer(oldValue), new Integer(taskType)); + firePropertyChange("taskType", oldValue, taskType); } } @@ -1393,7 +1365,7 @@ public void setTimeStep(TimeStep timeStep) throws java.beans.PropertyVetoExcepti */ public void setDefaultTimeStep(TimeStep timeStep) throws java.beans.PropertyVetoException { TimeStep adjusted = timeStep; - UniformOutputTimeSpec uots = BeanUtils.downcast(UniformOutputTimeSpec.class, fieldOutputTimeSpec); + UniformOutputTimeSpec uots = CastingUtils.downcast(UniformOutputTimeSpec.class, fieldOutputTimeSpec); if (uots != null && timeStep.getDefaultTimeStep() > uots.getOutputTimeStep()) { adjusted = timeStep.withDefault(uots.getOutputTimeStep()); } @@ -1409,7 +1381,7 @@ public void setUseSymbolicJacobian(boolean useSymbolicJacobian) { if (useSymbolicJacobian != fieldUseSymbolicJacobian) { boolean oldValue = fieldUseSymbolicJacobian; fieldUseSymbolicJacobian = useSymbolicJacobian; - firePropertyChange(PROPERTY_USE_SYMBOLIC_JACOBIAN, new Boolean(oldValue), new Boolean(useSymbolicJacobian)); + firePropertyChange(PROPERTY_USE_SYMBOLIC_JACOBIAN, oldValue, useSymbolicJacobian); } } diff --git a/vcell-core/src/main/java/cbit/vcell/solvers/FVSolverStandalone.java b/vcell-core/src/main/java/cbit/vcell/solvers/FVSolverStandalone.java index 1680fe18a0..c1dc9739a9 100644 --- a/vcell-core/src/main/java/cbit/vcell/solvers/FVSolverStandalone.java +++ b/vcell-core/src/main/java/cbit/vcell/solvers/FVSolverStandalone.java @@ -9,7 +9,7 @@ */ package cbit.vcell.solvers; -import static org.vcell.util.BeanUtils.notNull; +import org.vcell.util.BeanUtils; import java.io.File; import java.io.FileWriter; @@ -82,366 +82,373 @@ public FVSolverStandalone (SimulationTask simTask, File userDir, boolean bMsging this(simTask, userDir, userDir, bMsging); } -public FVSolverStandalone (SimulationTask simTask, File userDir, File destinationDirectory, boolean bMsging) throws SolverException { - super(simTask, userDir, bMsging); - this.destinationDirectory = destinationDirectory; - if (! simTask.getSimulation().isSpatial()) { - throw new SolverException("Cannot use FVSolver on non-spatial simulation"); + public FVSolverStandalone (SimulationTask simTask, File userDir, File destinationDirectory, boolean bMsging) throws SolverException { + super(simTask, userDir, bMsging); + String nullMessageFormat = "`%s` value is unexpectedly null"; + SolverDescription sd = FVSolverStandalone.getSolverDescription(simTask, nullMessageFormat); + if (sd == null ) throw new NullPointerException(String.format(nullMessageFormat, SolverDescription.class.getName())); + + this.destinationDirectory = destinationDirectory; + this.simResampleInfoProvider = simTask.getSimulationJob().getVCDataIdentifier(); + this.baseName = new File(getBaseName()).getName(); + this.primaryCommand = null; + this.isChombo = sd.isChomboSolver(); + this.isPETSc = sd.isPETSc(); + + } + + private static SolverDescription getSolverDescription(SimulationTask simTask, String nullMessageFormat) throws SolverException { + if (simTask == null) throw new NullPointerException(String.format(nullMessageFormat, SimulationTask.class.getName())); + Simulation sim = simTask.getSimulation(); + if (sim == null) throw new NullPointerException(String.format(nullMessageFormat, Simulation.class.getName())); + if (!sim.isSpatial()) { + throw new SolverException("Cannot use FVSolver on non-spatial simulation"); + } + SolverTaskDescription solverTaskDescription = sim.getSolverTaskDescription(); + if (solverTaskDescription == null) throw new NullPointerException(String.format(nullMessageFormat, SolverTaskDescription.class.getName())); + return solverTaskDescription.getSolverDescription(); } - this.simResampleInfoProvider = (VCSimulationDataIdentifier)simTask.getSimulationJob().getVCDataIdentifier(); - baseName = new File(getBaseName()).getName(); - primaryCommand = null; - - notNull(SimulationTask.class,simTask); - Simulation s = notNull(Simulation.class,simTask.getSimulation()); - SolverTaskDescription sts = notNull(SolverTaskDescription.class, s.getSolverTaskDescription()); - SolverDescription sd = notNull(SolverDescription.class,sts.getSolverDescription()); - isChombo = sd.isChomboSolver(); - isPETSc = sd.isPETSc(); -} -@Override -public void setUnixMode() { - unixMode = true; -} + @Override + public void setUnixMode() { + unixMode = true; + } -/** - * no-op - */ -public void cleanup() { -} + /** + * no-op + */ + public void cleanup() { + } -/** - * Insert the method's description here. - * Creation date: (6/27/01 3:25:11 PM) - * @return cbit.vcell.solvers.ApplicationMessage - * @param message java.lang.String - */ -protected ApplicationMessage getApplicationMessage(String message) { - // - // "data:iteration:time" .... sent every time data written for FVSolver - // "progress:xx.x%" .... sent every 1% for FVSolver - // - // - if (message.startsWith(DATA_PREFIX)){ - double timepoint = Double.parseDouble(message.substring(message.lastIndexOf(SEPARATOR)+1)); - setCurrentTime(timepoint); - return new ApplicationMessage(ApplicationMessage.DATA_MESSAGE,getProgress(),timepoint,null,message); - }else if (message.startsWith(PROGRESS_PREFIX)){ - String progressString = message.substring(message.lastIndexOf(SEPARATOR)+1,message.indexOf("%")); - double progress = Double.parseDouble(progressString)/100.0; - double startTime = simTask.getSimulation().getSolverTaskDescription().getTimeBounds().getStartingTime(); - double endTime = simTask.getSimulation().getSolverTaskDescription().getTimeBounds().getEndingTime(); - setCurrentTime(startTime + (endTime-startTime)*progress); - return new ApplicationMessage(ApplicationMessage.PROGRESS_MESSAGE,progress,-1,null,message); - }else{ - throw new RuntimeException("unrecognized message"); + /** + * Insert the method's description here. + * Creation date: (6/27/01 3:25:11 PM) + * @return cbit.vcell.solvers.ApplicationMessage + * @param message java.lang.String + */ + protected ApplicationMessage getApplicationMessage(String message) { + // + // "data:iteration:time" .... sent every time data written for FVSolver + // "progress:xx.x%" .... sent every 1% for FVSolver + // + // + if (message.startsWith(DATA_PREFIX)){ + double timepoint = Double.parseDouble(message.substring(message.lastIndexOf(SEPARATOR)+1)); + setCurrentTime(timepoint); + return new ApplicationMessage(ApplicationMessage.DATA_MESSAGE,getProgress(),timepoint,null,message); + }else if (message.startsWith(PROGRESS_PREFIX)){ + String progressString = message.substring(message.lastIndexOf(SEPARATOR)+1,message.indexOf("%")); + double progress = Double.parseDouble(progressString)/100.0; + double startTime = simTask.getSimulation().getSolverTaskDescription().getTimeBounds().getStartingTime(); + double endTime = simTask.getSimulation().getSolverTaskDescription().getTimeBounds().getEndingTime(); + setCurrentTime(startTime + (endTime-startTime)*progress); + return new ApplicationMessage(ApplicationMessage.PROGRESS_MESSAGE,progress,-1,null,message); + }else{ + throw new RuntimeException("unrecognized message"); + } } -} -public Geometry getResampledGeometry() throws SolverException { - if (resampledGeometry == null) { - // clone and resample geometry - try { - resampledGeometry = (Geometry) BeanUtils.cloneSerializable(simTask.getSimulation().getMathDescription().getGeometry()); - GeometrySurfaceDescription geoSurfaceDesc = resampledGeometry.getGeometrySurfaceDescription(); - ISize newSize = simTask.getSimulation().getMeshSpecification().getSamplingSize(); - geoSurfaceDesc.setVolumeSampleSize(newSize); - geoSurfaceDesc.updateAll(); - } catch (Exception e) { - throw new SolverException(e.getMessage(), e); + public Geometry getResampledGeometry() throws SolverException { + if (resampledGeometry == null) { + // clone and resample geometry + try { + resampledGeometry = (Geometry) BeanUtils.cloneSerializable(simTask.getSimulation().getMathDescription().getGeometry()); + GeometrySurfaceDescription geoSurfaceDesc = resampledGeometry.getGeometrySurfaceDescription(); + ISize newSize = simTask.getSimulation().getMeshSpecification().getSamplingSize(); + geoSurfaceDesc.setVolumeSampleSize(newSize); + geoSurfaceDesc.updateAll(); + } catch (Exception e) { + throw new SolverException(e.getMessage(), e); + } } + return resampledGeometry; } - return resampledGeometry; -} - -protected void writeVCGAndResampleFieldData() throws SolverException { - fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_PROC_GEOM); - - try { - // write subdomains file - SubdomainInfo.write(new File(getSaveDirectory(), baseName + SimDataConstants.SUBDOMAINS_FILE_SUFFIX), simTask.getSimulation().getMathDescription()); - - PrintWriter pw = new PrintWriter(new FileWriter(new File(getSaveDirectory(), baseName+SimDataConstants.VCG_FILE_EXTENSION))); - GeometryFileWriter.write(pw, getResampledGeometry()); - pw.close(); - - FieldDataIdentifierSpec[] argFieldDataIDSpecs = simTask.getSimulationJob().getFieldDataIdentifierSpecs(); - if(argFieldDataIDSpecs != null && argFieldDataIDSpecs.length > 0){ - fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_RESAMPLE_FD); - - FieldFunctionArguments psfFieldFunc = null; - Variable var = simTask.getSimulationJob().getSimulationSymbolTable().getVariable(Simulation.PSF_FUNCTION_NAME); - if (var != null) { - FieldFunctionArguments[] ffas = FieldUtilities.getFieldFunctionArguments(var.getExpression()); - if (ffas == null || ffas.length == 0) { - throw new DataAccessException("Point Spread Function " + Simulation.PSF_FUNCTION_NAME + " can only be a single field function."); - } else { - Expression newexp; - try { - newexp = new Expression(ffas[0].infix()); - if (!var.getExpression().compareEqual(newexp)) { - throw new DataAccessException("Point Spread Function " + Simulation.PSF_FUNCTION_NAME + " can only be a single field function."); + + protected void writeVCGAndResampleFieldData() throws SolverException { + fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_PROC_GEOM); + + try { + // write subdomains file + SubdomainInfo.write(new File(getSaveDirectory(), baseName + SimDataConstants.SUBDOMAINS_FILE_SUFFIX), simTask.getSimulation().getMathDescription()); + + PrintWriter pw = new PrintWriter(new FileWriter(new File(getSaveDirectory(), baseName+SimDataConstants.VCG_FILE_EXTENSION))); + GeometryFileWriter.write(pw, getResampledGeometry()); + pw.close(); + + FieldDataIdentifierSpec[] argFieldDataIDSpecs = simTask.getSimulationJob().getFieldDataIdentifierSpecs(); + if(argFieldDataIDSpecs != null && argFieldDataIDSpecs.length > 0){ + fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_RESAMPLE_FD); + + FieldFunctionArguments psfFieldFunc = null; + Variable var = simTask.getSimulationJob().getSimulationSymbolTable().getVariable(Simulation.PSF_FUNCTION_NAME); + if (var != null) { + FieldFunctionArguments[] ffas = FieldUtilities.getFieldFunctionArguments(var.getExpression()); + if (ffas == null || ffas.length == 0) { + throw new DataAccessException("Point Spread Function " + Simulation.PSF_FUNCTION_NAME + " can only be a single field function."); + } else { + Expression newexp; + try { + newexp = new Expression(ffas[0].infix()); + if (!var.getExpression().compareEqual(newexp)) { + throw new DataAccessException("Point Spread Function " + Simulation.PSF_FUNCTION_NAME + " can only be a single field function."); + } + psfFieldFunc = ffas[0]; + } catch (ExpressionException e) { + throw new DataAccessException(e.getMessage(), e); } - psfFieldFunc = ffas[0]; - } catch (ExpressionException e) { - throw new DataAccessException(e.getMessage(), e); } } - } - - boolean bResample[] = new boolean[argFieldDataIDSpecs.length]; - Arrays.fill(bResample, true); - for (int i = 0; i < argFieldDataIDSpecs.length; i++) { - argFieldDataIDSpecs[i].getFieldFuncArgs().getTime().bindExpression(simTask.getSimulationJob().getSimulationSymbolTable()); - if (argFieldDataIDSpecs[i].getFieldFuncArgs().equals(psfFieldFunc)) { - bResample[i] = false; + + boolean bResample[] = new boolean[argFieldDataIDSpecs.length]; + Arrays.fill(bResample, true); + for (int i = 0; i < argFieldDataIDSpecs.length; i++) { + argFieldDataIDSpecs[i].getFieldFuncArgs().getTime().bindExpression(simTask.getSimulationJob().getSimulationSymbolTable()); + if (argFieldDataIDSpecs[i].getFieldFuncArgs().equals(psfFieldFunc)) { + bResample[i] = false; + } } + + int numMembraneElements = getResampledGeometry().getGeometrySurfaceDescription().getSurfaceCollection().getTotalPolygonCount(); + CartesianMesh simpleMesh = CartesianMesh.createSimpleCartesianMesh(getResampledGeometry().getOrigin(), + getResampledGeometry().getExtent(), + simTask.getSimulation().getMeshSpecification().getSamplingSize(), + getResampledGeometry().getGeometrySurfaceDescription().getRegionImage()); + String secondarySimDataDir = PropertyLoader.getProperty(PropertyLoader.secondarySimDataDirInternalProperty, null); + DataSetControllerImpl dsci = new DataSetControllerImpl(null, getSaveDirectory().getParentFile(), + secondarySimDataDir == null ? null : new File(secondarySimDataDir)); + dsci.writeFieldFunctionData(null,argFieldDataIDSpecs, bResample, simpleMesh, simResampleInfoProvider, + numMembraneElements, HESM_OVERWRITE_AND_CONTINUE); } - - int numMembraneElements = getResampledGeometry().getGeometrySurfaceDescription().getSurfaceCollection().getTotalPolygonCount(); - CartesianMesh simpleMesh = CartesianMesh.createSimpleCartesianMesh(getResampledGeometry().getOrigin(), - getResampledGeometry().getExtent(), - simTask.getSimulation().getMeshSpecification().getSamplingSize(), - getResampledGeometry().getGeometrySurfaceDescription().getRegionImage()); - String secondarySimDataDir = PropertyLoader.getProperty(PropertyLoader.secondarySimDataDirInternalProperty, null); - DataSetControllerImpl dsci = new DataSetControllerImpl(null, getSaveDirectory().getParentFile(), - secondarySimDataDir == null ? null : new File(secondarySimDataDir)); - dsci.writeFieldFunctionData(null,argFieldDataIDSpecs, bResample, simpleMesh, simResampleInfoProvider, - numMembraneElements, HESM_OVERWRITE_AND_CONTINUE); + } catch(Exception e){ + throw new SolverException(e.getMessage()); } - } catch(Exception e){ - throw new SolverException(e.getMessage()); } -} -// -// -///** -// * Insert the method's description here. -// * Creation date: (6/27/2001 2:33:03 PM) -// */ -//public void propertyChange(java.beans.PropertyChangeEvent event) { -// super.propertyChange(event); -// -// if (event.getSource() == getMathExecutable() && event.getPropertyName().equals("applicationMessage")) { -// String messageString = (String)event.getNewValue(); -// if (messageString==null || messageString.length()==0){ -// return; -// } -// ApplicationMessage appMessage = getApplicationMessage(messageString); -// if (appMessage!=null && appMessage.getMessageType() == ApplicationMessage.DATA_MESSAGE) { -// fireSolverPrinted(appMessage.getTimepoint()); -// } -// } -//} + // + // + ///** + // * Insert the method's description here. + // * Creation date: (6/27/2001 2:33:03 PM) + // */ + //public void propertyChange(java.beans.PropertyChangeEvent event) { + // super.propertyChange(event); + // + // if (event.getSource() == getMathExecutable() && event.getPropertyName().equals("applicationMessage")) { + // String messageString = (String)event.getNewValue(); + // if (messageString==null || messageString.length()==0){ + // return; + // } + // ApplicationMessage appMessage = getApplicationMessage(messageString); + // if (appMessage!=null && appMessage.getMessageType() == ApplicationMessage.DATA_MESSAGE) { + // fireSolverPrinted(appMessage.getTimepoint()); + // } + // } + //} -/** - * This method was created by a SmartGuide. - */ -protected void initialize() throws SolverException { - try { - Simulation sim = simTask.getSimulation(); - if (sim.isSerialParameterScan()) { - //write functions file for all the simulations in the scan - for (int scan = 0; scan < sim.getScanCount(); scan ++) { - SimulationJob simJob = new SimulationJob(sim, scan, simTask.getSimulationJob().getFieldDataIdentifierSpecs()); - // ** Dumping the functions of a simulation into a '.functions' file. - String basename = new File(getSaveDirectory(), simJob.getSimulationJobID()).getPath(); - String functionFileName = basename + FUNCTIONFILE_EXTENSION; - - Vector funcList = simJob.getSimulationSymbolTable().createAnnotatedFunctionsList(simTask.getSimulation().getMathDescription()); - //Try to save existing user defined functions - try{ - File existingFunctionFile = new File(functionFileName); - if (existingFunctionFile.exists()){ - Vector oldFuncList = FunctionFileGenerator.readFunctionsFile(existingFunctionFile, simTask.getSimulationJobID()); - for(AnnotatedFunction func : oldFuncList){ - if(func.isOldUserDefined()){ - funcList.add(func); + /** + * This method was created by a SmartGuide. + */ + protected void initialize() throws SolverException { + try { + Simulation sim = simTask.getSimulation(); + if (sim.isSerialParameterScan()) { + //write functions file for all the simulations in the scan + for (int scan = 0; scan < sim.getScanCount(); scan ++) { + SimulationJob simJob = new SimulationJob(sim, scan, simTask.getSimulationJob().getFieldDataIdentifierSpecs()); + // ** Dumping the functions of a simulation into a '.functions' file. + String basename = new File(getSaveDirectory(), simJob.getSimulationJobID()).getPath(); + String functionFileName = basename + FUNCTIONFILE_EXTENSION; + + Vector funcList = simJob.getSimulationSymbolTable().createAnnotatedFunctionsList(simTask.getSimulation().getMathDescription()); + //Try to save existing user defined functions + try{ + File existingFunctionFile = new File(functionFileName); + if (existingFunctionFile.exists()){ + Vector oldFuncList = FunctionFileGenerator.readFunctionsFile(existingFunctionFile, simTask.getSimulationJobID()); + for(AnnotatedFunction func : oldFuncList){ + if(func.isOldUserDefined()){ + funcList.add(func); + } } } + }catch(Exception e){ + lg.error(e.getMessage(), e); + //ignore + } + + //Try to save existing user defined functions + FunctionFileGenerator functionFileGenerator = new FunctionFileGenerator(functionFileName, funcList); + + try { + functionFileGenerator.generateFunctionFile(); + }catch (Exception e){ + throw new RuntimeException("Error creating .function file for "+functionFileGenerator.getBasefileName()+e.getMessage(), e); } - }catch(Exception e){ - lg.error(e.getMessage(), e); - //ignore - } - - //Try to save existing user defined functions - FunctionFileGenerator functionFileGenerator = new FunctionFileGenerator(functionFileName, funcList); - - try { - functionFileGenerator.generateFunctionFile(); - }catch (Exception e){ - throw new RuntimeException("Error creating .function file for "+functionFileGenerator.getBasefileName()+e.getMessage(), e); } + + } else { + writeFunctionsFile(); } - - } else { - writeFunctionsFile(); - } - - // not for Chombo solver - if (!isChombo) { - writeVCGAndResampleFieldData(); - } - - setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INIT)); - fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT); - - setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE)); - - File fvinputFile = new File(getInputFilename()); - PrintWriter pw = null; - try { - pw = new PrintWriter(new FileWriter(fvinputFile)); - new FiniteVolumeFileWriter(pw, simTask, getResampledGeometry(), getSaveDirectory(), destinationDirectory, bMessaging).write(); - } finally { - if (pw != null) { - pw.close(); + + // not for Chombo solver + if (!isChombo) { + writeVCGAndResampleFieldData(); } - } - } catch (Exception ex) { - throw new SolverException(ex.getMessage(), ex); - } -} + setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INIT)); + fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT); -/** - * @return full path of baseName + ".fvinput" - */ -private String getInputFilename() { - String ipf = new File(getSaveDirectory(),baseName + ".fvinput").getAbsolutePath(); - if (!unixMode) { - return ipf; - } - return ResourceUtil.forceUnixPath(ipf); -} + setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE)); -@Override -public MathExecutable getMathExecutable() { - if (isChombo) { - //throw new UnsupportedOperationException("Chombo does not support Quick Run"); - } - MathExecutable me = super.getMathExecutable(); - if (me != null) { - return me; - } - - if (primaryCommand == null) { - getCommands(); //sets primaryCommand as sideEffect + File fvinputFile = new File(getInputFilename()); + PrintWriter pw = null; + try { + pw = new PrintWriter(new FileWriter(fvinputFile)); + new FiniteVolumeFileWriter(pw, simTask, getResampledGeometry(), getSaveDirectory(), destinationDirectory, bMessaging).write(); + } finally { + if (pw != null) { + pw.close(); + } + } + } catch (Exception ex) { + throw new SolverException(ex.getMessage(), ex); + } } - assert(primaryCommand != null); - String[] carray = primaryCommand.getCommands().toArray(new String[0]); - File workingDir = getSaveDirectory(); - setMathExecutable(new MathExecutable(carray, workingDir)); - me= super.getMathExecutable(); - assert(me != null); - return me; -} -@Override -public Collection getCommands() { - if (isChombo) { - return getChomboCommands( ); - }else if (isPETSc) { - return getPETScCommands(); + /** + * @return full path of baseName + ".fvinput" + */ + private String getInputFilename() { + String ipf = new File(getSaveDirectory(),baseName + ".fvinput").getAbsolutePath(); + if (!unixMode) { + return ipf; + } + return ResourceUtil.forceUnixPath(ipf); } - return getFVCommands(); -} -private Collection getFVCommands() { - assert (!isChombo && !isPETSc); - Simulation simulation = getSimulationJob().getSimulation(); - final boolean isParallel = simulation.getSolverTaskDescription().isParallel(); - String executableName = null; - try { - executableName = SolverUtilities.getExes(SolverDescription.FiniteVolumeStandalone)[0].getAbsolutePath(); - }catch (IOException e){ - throw new RuntimeException("failed to get executable for solver "+SolverDescription.FiniteVolumeStandalone.getDisplayLabel()+": "+e.getMessage(),e); - } - if (isParallel) { - throw new UnsupportedOperationException(executableName + " does not support parallel"); - } - String inputFilename = getInputFilename(); - primaryCommand = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), true, false, executableName, inputFilename ); - return Arrays.asList(primaryCommand); -} + @Override + public MathExecutable getMathExecutable() { + if (isChombo) { + //throw new UnsupportedOperationException("Chombo does not support Quick Run"); + } + MathExecutable me = super.getMathExecutable(); + if (me != null) { + return me; + } -private Collection getPETScCommands() { - assert (!isChombo); - Simulation simulation = getSimulationJob().getSimulation(); - final boolean isParallel = simulation.getSolverTaskDescription().isParallel(); - String executableName = null; - try { - executableName = SolverUtilities.getExes(SolverDescription.VCellPetsc)[0].getAbsolutePath(); - }catch (IOException e){ - throw new RuntimeException("failed to get executable for solver "+SolverDescription.FiniteVolumeStandalone.getDisplayLabel()+": "+e.getMessage(),e); + if (primaryCommand == null) { + getCommands(); //sets primaryCommand as sideEffect + } + assert(primaryCommand != null); + String[] carray = primaryCommand.getCommands().toArray(new String[0]); + File workingDir = getSaveDirectory(); + setMathExecutable(new MathExecutable(carray, workingDir)); + me= super.getMathExecutable(); + assert(me != null); + return me; } - if (isParallel) { - throw new UnsupportedOperationException(executableName + " does not support parallel"); + + + @Override + public Collection getCommands() { + if (isChombo) { + return getChomboCommands( ); + }else if (isPETSc) { + return getPETScCommands(); + } + return getFVCommands(); } - String inputFilename = getInputFilename(); - primaryCommand = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), true, false, executableName, inputFilename ); - return Arrays.asList(primaryCommand); -} -private Collection getChomboCommands() { - assert (isChombo); - ArrayList commands = new ArrayList(2); - String inputFilename = getInputFilename(); - - String executableName = null; - Simulation simulation = getSimulationJob().getSimulation(); - SolverTaskDescription sTaskDesc = simulation.getSolverTaskDescription(); - final boolean isParallel = sTaskDesc.isParallel(); - int dimension = simulation.getMeshSpecification().getGeometry().getDimension(); - switch (dimension) { - case 2: + private Collection getFVCommands() { + assert (!isChombo && !isPETSc); + Simulation simulation = getSimulationJob().getSimulation(); + final boolean isParallel = simulation.getSolverTaskDescription().isParallel(); + String executableName = null; try { - executableName = SolverUtilities.getExes(SolverDescription.Chombo)[0].getAbsolutePath(); + executableName = SolverUtilities.getExes(SolverDescription.FiniteVolumeStandalone)[0].getAbsolutePath(); }catch (IOException e){ - throw new RuntimeException("failed to get executable for 2D solver "+SolverDescription.Chombo.getDisplayLabel()+": "+e.getMessage(),e); + throw new RuntimeException("failed to get executable for solver "+SolverDescription.FiniteVolumeStandalone.getDisplayLabel()+": "+e.getMessage(),e); + } + if (isParallel) { + throw new UnsupportedOperationException(executableName + " does not support parallel"); } - break; - case 3: + String inputFilename = getInputFilename(); + primaryCommand = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), true, false, executableName, inputFilename ); + return Arrays.asList(primaryCommand); + } + + private Collection getPETScCommands() { + assert (!isChombo); + Simulation simulation = getSimulationJob().getSimulation(); + final boolean isParallel = simulation.getSolverTaskDescription().isParallel(); + String executableName = null; try { - executableName = SolverUtilities.getExes(SolverDescription.Chombo)[1].getAbsolutePath(); + executableName = SolverUtilities.getExes(SolverDescription.VCellPetsc)[0].getAbsolutePath(); }catch (IOException e){ - throw new RuntimeException("failed to get executable for 3D solver "+SolverDescription.Chombo.getDisplayLabel()+": "+e.getMessage(),e); + throw new RuntimeException("failed to get executable for solver "+SolverDescription.FiniteVolumeStandalone.getDisplayLabel()+": "+e.getMessage(),e); } - break; - default: - throw new IllegalArgumentException("VCell Chombo solver does not support " + dimension + "problems"); - } - - if (isParallel) { - String parallelName = executableName + "parallel"; - ExecutableCommand solve = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), - true, true, parallelName, inputFilename ); - commands.add(solve); - ChomboSolverSpec css = sTaskDesc.getChomboSolverSpec(); - Objects.requireNonNull(css); - if (css.isSaveVCellOutput()) { - ExecutableCommand convertChomboData = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), - true, false,executableName, "-ccd", inputFilename ); - commands.add(convertChomboData); + if (isParallel) { + throw new UnsupportedOperationException(executableName + " does not support parallel"); } + String inputFilename = getInputFilename(); + primaryCommand = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), true, false, executableName, inputFilename ); + return Arrays.asList(primaryCommand); } - else { - ExecutableCommand ec = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), - true, false, executableName, inputFilename ); - commands.add(ec); - primaryCommand = ec; - } - - return commands; -} + private Collection getChomboCommands() { + assert (isChombo); + ArrayList commands = new ArrayList(2); + String inputFilename = getInputFilename(); + String executableName = null; + Simulation simulation = getSimulationJob().getSimulation(); + SolverTaskDescription sTaskDesc = simulation.getSolverTaskDescription(); + final boolean isParallel = sTaskDesc.isParallel(); + int dimension = simulation.getMeshSpecification().getGeometry().getDimension(); + switch (dimension) { + case 2: + try { + executableName = SolverUtilities.getExes(SolverDescription.Chombo)[0].getAbsolutePath(); + }catch (IOException e){ + throw new RuntimeException("failed to get executable for 2D solver "+SolverDescription.Chombo.getDisplayLabel()+": "+e.getMessage(),e); + } + break; + case 3: + try { + executableName = SolverUtilities.getExes(SolverDescription.Chombo)[1].getAbsolutePath(); + }catch (IOException e){ + throw new RuntimeException("failed to get executable for 3D solver "+SolverDescription.Chombo.getDisplayLabel()+": "+e.getMessage(),e); + } + break; + default: + throw new IllegalArgumentException("VCell Chombo solver does not support " + dimension + "problems"); + } + + if (isParallel) { + String parallelName = executableName + "parallel"; + ExecutableCommand solve = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), + true, true, parallelName, inputFilename ); + commands.add(solve); + ChomboSolverSpec css = sTaskDesc.getChomboSolverSpec(); + Objects.requireNonNull(css); + if (css.isSaveVCellOutput()) { + ExecutableCommand convertChomboData = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), + true, false,executableName, "-ccd", inputFilename ); + commands.add(convertChomboData); + } + } + else { + ExecutableCommand ec = new ExecutableCommand(new ExecutableCommand.LibraryPath(ResourceUtil.getLocalSolversDirectory().getAbsolutePath()), + true, false, executableName, inputFilename ); + commands.add(ec); + primaryCommand = ec; + } + + return commands; + } } diff --git a/vcell-core/src/main/java/cbit/vcell/solvers/MovingBoundaryFileWriter.java b/vcell-core/src/main/java/cbit/vcell/solvers/MovingBoundaryFileWriter.java index ec78eb77a4..48e7eadcb2 100644 --- a/vcell-core/src/main/java/cbit/vcell/solvers/MovingBoundaryFileWriter.java +++ b/vcell-core/src/main/java/cbit/vcell/solvers/MovingBoundaryFileWriter.java @@ -16,7 +16,7 @@ import org.jdom.Document; import org.jdom.Element; import org.vcell.movingboundary.MovingBoundarySolverSpec; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.ISize; import org.vcell.util.Matchable; @@ -124,7 +124,7 @@ private int subdomainsSanityCheck() { } continue; } - MembraneSubDomain msd = BeanUtils.downcast(MembraneSubDomain.class, sd); + MembraneSubDomain msd = CastingUtils.downcast(MembraneSubDomain.class, sd); if (msd != null) { if (theMembrane != null) { throw new IllegalArgumentException("only one membrane currently supported"); @@ -429,7 +429,6 @@ private void manageCompartment(Element e, SubDomain sd) { * set and annotate expression value; optionally include even if null. If ex is null and always == false, does nothing * @param dest element to set * @param ex to evaluate, could be null - * @param always if true, set element even if expression null * @throws ExpressionException * @throws MathException */ diff --git a/vcell-core/src/main/java/cbit/vcell/solvers/mb/MovingBoundaryReader.java b/vcell-core/src/main/java/cbit/vcell/solvers/mb/MovingBoundaryReader.java index 5c2681d214..55a8d8cf65 100644 --- a/vcell-core/src/main/java/cbit/vcell/solvers/mb/MovingBoundaryReader.java +++ b/vcell-core/src/main/java/cbit/vcell/solvers/mb/MovingBoundaryReader.java @@ -7,8 +7,8 @@ import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.vcell.util.BeanUtils; -import org.vcell.util.BeanUtils.CastInfo; +import org.vcell.util.CastingUtils.CastInfo; +import org.vcell.util.CastingUtils; import org.vcell.util.ProgrammingException; import org.vcell.util.VCAssert; @@ -384,7 +384,7 @@ private static T select(Class clzz, Vector v, String[] names,String pat } private static T safeCast(Class clzz, Object obj, String path) { - CastInfo ci = BeanUtils.attemptCast(clzz, obj); + CastInfo ci = CastingUtils.attemptCast(clzz, obj); if (ci.isGood()) { return ci.get(); } diff --git a/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5Path.java b/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5Path.java index bb8dbf5de7..0fd81ddaa6 100644 --- a/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5Path.java +++ b/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5Path.java @@ -7,7 +7,7 @@ import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.VCAssert; import ncsa.hdf.hdf5lib.exceptions.HDF5Exception; @@ -131,7 +131,7 @@ private static boolean lastIndex(int index, String[] steps) { private static Object walk(Object hobj, String[] steps, int index) throws Exception { final boolean isLastIndex = lastIndex(index,steps); final String finding = steps[index]; - Group g = BeanUtils.downcast(Group.class, hobj); + Group g = CastingUtils.downcast(Group.class, hobj); if (g != null) { List ml = g.getMemberList(); for (HObject sub : ml) { @@ -146,7 +146,7 @@ private static Object walk(Object hobj, String[] steps, int index) throws Except } } } - H5CompoundDS cds = BeanUtils.downcast(H5CompoundDS.class, hobj); + H5CompoundDS cds = CastingUtils.downcast(H5CompoundDS.class, hobj); if (cds != null) { cds.read(); String[] mn = cds.getMemberNames(); @@ -154,7 +154,7 @@ private static Object walk(Object hobj, String[] steps, int index) throws Except for (int i = 0; i < mn.length ; i++) { if (finding.equals(mn[i]) ) { Object c = cds.read(); - Vector vec = BeanUtils.downcast(Vector.class, c); + Vector vec = CastingUtils.downcast(Vector.class, c); if (vec != null) { VCAssert.assertTrue(i < vec.size( ), "Disconnect between H5CompoundDS.getMemberNames( ) and returned Vector"); Object child = vec.get(i); @@ -170,13 +170,13 @@ private static Object walk(Object hobj, String[] steps, int index) throws Except } if (isLastIndex) { - DataFormat df= BeanUtils.downcast(DataFormat.class, hobj); + DataFormat df= CastingUtils.downcast(DataFormat.class, hobj); if (df != null && df.hasAttribute()) { try { @SuppressWarnings("unchecked") List meta = df.getMetadata(); for (Object o : meta) { - Attribute a = BeanUtils.downcast(Attribute.class, o); + Attribute a = CastingUtils.downcast(Attribute.class, o); if (a != null) { if (finding.equals(a.getName())) { return a.getValue(); diff --git a/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5TypedPath.java b/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5TypedPath.java index d855c7bc3d..04e1279c0f 100644 --- a/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5TypedPath.java +++ b/vcell-core/src/main/java/cbit/vcell/solvers/mb/VH5TypedPath.java @@ -2,7 +2,7 @@ import java.util.Objects; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.VCAssert; import ncsa.hdf.object.Group; @@ -32,7 +32,7 @@ public VH5TypedPath(Group g, Class clzz, String... names) { Objects.requireNonNull(target); Class tclass = target.getClass(); if (!clzz.isAssignableFrom(tclass)){ - H5ScalarDS sds = BeanUtils.downcast(H5ScalarDS.class, target); + H5ScalarDS sds = CastingUtils.downcast(H5ScalarDS.class, target); if (sds != null) { convert(sds,clzz,names); return; diff --git a/vcell-core/src/main/java/org/vcell/movingboundary/MovingBoundarySolverSpec.java b/vcell-core/src/main/java/org/vcell/movingboundary/MovingBoundarySolverSpec.java index 8721c8d88d..e9ec4720ab 100644 --- a/vcell-core/src/main/java/org/vcell/movingboundary/MovingBoundarySolverSpec.java +++ b/vcell-core/src/main/java/org/vcell/movingboundary/MovingBoundarySolverSpec.java @@ -2,10 +2,7 @@ import java.io.Serializable; -import org.vcell.util.BeanUtils; -import org.vcell.util.CommentStringTokenizer; -import org.vcell.util.DataAccessException; -import org.vcell.util.Matchable; +import org.vcell.util.*; import cbit.vcell.math.VCML; @@ -43,7 +40,7 @@ public boolean compareEqual(Matchable object) { if (this == object) { return (true); } - MovingBoundarySolverSpec other = BeanUtils.downcast(MovingBoundarySolverSpec.class, object); + MovingBoundarySolverSpec other = CastingUtils.downcast(MovingBoundarySolverSpec.class, object); if (other == null) { return false; } diff --git a/vcell-core/src/main/java/org/vcell/sbml/KineticsAdapter.java b/vcell-core/src/main/java/org/vcell/sbml/KineticsAdapter.java index ca86141d5a..3170e90f0c 100644 --- a/vcell-core/src/main/java/org/vcell/sbml/KineticsAdapter.java +++ b/vcell-core/src/main/java/org/vcell/sbml/KineticsAdapter.java @@ -1,11 +1,10 @@ package org.vcell.sbml; -import org.vcell.util.BeanUtils; - import cbit.vcell.model.DistributedKinetics; import cbit.vcell.model.Kinetics; import cbit.vcell.model.LumpedKinetics; import cbit.vcell.parser.Expression; +import org.vcell.util.CastingUtils; /** * adapt {@link Kinetics} class hiearchy for SBML @@ -24,12 +23,12 @@ public abstract class KineticsAdapter { * @throws {@link NullPointerException} if k null */ public static KineticsAdapter create(Kinetics k) throws SbmlException { - DistributedKinetics dk = BeanUtils.downcast(DistributedKinetics.class,k); + DistributedKinetics dk = CastingUtils.downcast(DistributedKinetics.class,k); if (dk != null) { return new Distributed(dk); } - LumpedKinetics lk = BeanUtils.downcast(LumpedKinetics.class, k); + LumpedKinetics lk = CastingUtils.downcast(LumpedKinetics.class, k); if (lk != null) { return new Lumped(lk); } diff --git a/vcell-core/src/main/java/org/vcell/sbml/SBMLHelper.java b/vcell-core/src/main/java/org/vcell/sbml/SBMLHelper.java index 01314475f0..07b2fd9eff 100644 --- a/vcell-core/src/main/java/org/vcell/sbml/SBMLHelper.java +++ b/vcell-core/src/main/java/org/vcell/sbml/SBMLHelper.java @@ -3,7 +3,7 @@ import javax.xml.stream.XMLStreamException; import org.sbml.jsbml.SBase; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.VCAssert; import cbit.vcell.model.Model; @@ -135,7 +135,7 @@ private BoundaryKind(BoundaryConditionType boundaryConditionType, int sbmlCode) * @param name not null * @return desired structure or null */ - public static BeanUtils.CastInfo getTypedStructure(Class type,Model source, String name) { + public static CastingUtils.CastInfo getTypedStructure(Class type, Model source, String name) { VCAssert.assertValid(type); VCAssert.assertValid(source); VCAssert.assertValid(name); @@ -154,7 +154,7 @@ public static BeanUtils.CastInfo getTypedStructure(Clas } } } - return BeanUtils.attemptCast(type, strct); + return CastingUtils.attemptCast(type, strct); } } diff --git a/vcell-core/src/main/java/org/vcell/sbml/vcell/SBMLImporter.java b/vcell-core/src/main/java/org/vcell/sbml/vcell/SBMLImporter.java index 45635715a2..1ce02c0ad8 100644 --- a/vcell-core/src/main/java/org/vcell/sbml/vcell/SBMLImporter.java +++ b/vcell-core/src/main/java/org/vcell/sbml/vcell/SBMLImporter.java @@ -75,7 +75,7 @@ import org.vcell.sbml.SBMLUtils; import org.vcell.sbml.vcell.SBMLImportException.Category; import org.vcell.util.*; -import org.vcell.util.BeanUtils.CastInfo; +import org.vcell.util.CastingUtils.CastInfo; import org.vcell.util.Issue.IssueCategory; import org.vcell.util.document.BioModelChildSummary; @@ -3952,7 +3952,7 @@ private static void addGeometry(org.sbml.jsbml.Model sbmlModel, BioModel vcBioMo // set its expr using analyticVol's math. SubVolume vcSubvolume = vcGeometrySpec .getSubVolume(analyticVol.getDomainType()); - CastInfo ci = BeanUtils.attemptCast(AnalyticSubVolume.class, vcSubvolume); + CastInfo ci = CastingUtils.attemptCast(AnalyticSubVolume.class, vcSubvolume); if (!ci.isGood()) { throw new RuntimeException("analytic volume '" + analyticVol.getId() @@ -3982,7 +3982,7 @@ private static void addGeometry(org.sbml.jsbml.Model sbmlModel, BioModel vcBioMo readGeometrySamplingAnnotation(analyticGeometryDefinition, vcGsd); } - SampledFieldGeometry sfg = BeanUtils.downcast(SampledFieldGeometry.class, selectedGeometryDefinition); + SampledFieldGeometry sfg = CastingUtils.downcast(SampledFieldGeometry.class, selectedGeometryDefinition); if (sfg != null) { ListOf sampledVolumes = sfg.getListOfSampledVolumes(); @@ -4214,7 +4214,7 @@ private static void addGeometry(org.sbml.jsbml.Model sbmlModel, BioModel vcBioMo Structure struct = ci.get(); String domainType = compMapping.getDomainType(); GeometryClass geometryClass = vcGeometry.getGeometryClass(domainType); - Feature feat = BeanUtils.downcast(Feature.class,struct); + Feature feat = CastingUtils.downcast(Feature.class,struct); if (feat != null) { FeatureMapping featureMapping = new FeatureMapping(feat, vcBioModel.getSimulationContext(0), vcModelUnitSystem); featureMapping.setGeometryClass(geometryClass); diff --git a/vcell-core/src/main/java/org/vcell/sbml/vcell/VCReactionProxy.java b/vcell-core/src/main/java/org/vcell/sbml/vcell/VCReactionProxy.java index d5f0a899c6..f70bc6c1b0 100644 --- a/vcell-core/src/main/java/org/vcell/sbml/vcell/VCReactionProxy.java +++ b/vcell-core/src/main/java/org/vcell/sbml/vcell/VCReactionProxy.java @@ -4,7 +4,7 @@ import java.util.Map; import java.util.Map.Entry; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.ProgrammingException; import org.vcell.util.VCAssert; @@ -35,11 +35,11 @@ private VCReactionProxy() { } */ public static VCReactionProxy factory(ReactionStep reaction) { VCAssert.assertValid(reaction); - SimpleReaction sr = BeanUtils.downcast(SimpleReaction.class,reaction); + SimpleReaction sr = CastingUtils.downcast(SimpleReaction.class,reaction); if (sr != null) { return new Simple(sr); } - FluxReaction fr = BeanUtils.downcast(FluxReaction.class,reaction); + FluxReaction fr = CastingUtils.downcast(FluxReaction.class,reaction); if (fr != null) { return new Flux(fr); } diff --git a/vcell-core/src/main/java/org/vcell/solver/smoldyn/SmoldynFileWriter.java b/vcell-core/src/main/java/org/vcell/solver/smoldyn/SmoldynFileWriter.java index 206c22d2a6..133f341932 100644 --- a/vcell-core/src/main/java/org/vcell/solver/smoldyn/SmoldynFileWriter.java +++ b/vcell-core/src/main/java/org/vcell/solver/smoldyn/SmoldynFileWriter.java @@ -35,16 +35,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.vcell.solver.smoldyn.SmoldynVCellMapper.SmoldynKeyword; -import org.vcell.util.BeanUtils; -import org.vcell.util.ColorUtil; -import org.vcell.util.Coordinate; -import org.vcell.util.DataAccessException; -import org.vcell.util.Extent; -import org.vcell.util.Hex; -import org.vcell.util.ISize; -import org.vcell.util.Origin; -import org.vcell.util.ProgrammingException; -import org.vcell.util.VCAssert; +import org.vcell.util.*; import cbit.image.ImageException; import cbit.image.VCImage; @@ -284,7 +275,7 @@ private void init() throws SolverException { if (!bGraphicOpenGL) { writeMeshFile(); } - colors = ColorUtil.generateAutoColor(particleVariableList.size() + resampledGeometry.getGeometrySurfaceDescription().getSurfaceClasses().length, bg, new Integer(5)); + colors = ColorUtil.generateAutoColor(particleVariableList.size() + resampledGeometry.getGeometrySurfaceDescription().getSurfaceClasses().length, bg, 5); } @@ -343,12 +334,12 @@ private ArrayList getClosestTriangle( ) { private void setupMolecules() throws ExpressionException, MathException{ // write molecules for ( SubDomain sd : mathDesc.getSubDomainCollection()) { - MembraneSubDomain msd = BeanUtils.downcast(MembraneSubDomain.class, sd); + MembraneSubDomain msd = CastingUtils.downcast(MembraneSubDomain.class, sd); if (msd != null) { for (ParticleProperties particleProperties :msd.getParticleProperties() ) { ArrayList particleInitialConditions = particleProperties.getParticleInitialConditions(); for (ParticleInitialCondition pic : particleInitialConditions) { - ParticleInitialConditionCount picc = BeanUtils.downcast(ParticleInitialConditionCount.class, pic); + ParticleInitialConditionCount picc = CastingUtils.downcast(ParticleInitialConditionCount.class, pic); if (picc != null && !picc.isUniform()) { Variable var = particleProperties.getVariable(); try { diff --git a/vcell-core/src/test/java/cbit/vcell/solvers/mb/H5FileStructure.java b/vcell-core/src/test/java/cbit/vcell/solvers/mb/H5FileStructure.java index f2e6420d26..239eab3456 100644 --- a/vcell-core/src/test/java/cbit/vcell/solvers/mb/H5FileStructure.java +++ b/vcell-core/src/test/java/cbit/vcell/solvers/mb/H5FileStructure.java @@ -17,7 +17,6 @@ import org.junit.Test; import org.junit.experimental.categories.Category; import org.vcell.test.Fast; -import org.vcell.util.BeanUtils; import ncsa.hdf.object.Dataset; import ncsa.hdf.object.Datatype; @@ -25,6 +24,7 @@ import ncsa.hdf.object.Group; import ncsa.hdf.object.HObject; import ncsa.hdf.object.h5.H5File; +import org.vcell.util.CastingUtils; /** *

@@ -113,7 +113,7 @@ private static void printGroup(Group g, String indent) throws Exception { if (obj instanceof Group) { printGroup((Group) obj, indent); } - Dataset ds = BeanUtils.downcast(Dataset.class, obj); + Dataset ds = CastingUtils.downcast(Dataset.class, obj); if (ds != null && ds.getName().equals("elements")) { // if (ds != null && ds.getName().equals("boundaries")) { VH5Dataset vds = new VH5Dataset(ds); @@ -123,13 +123,6 @@ private static void printGroup(Group g, String indent) throws Exception { } } - /** - * create the file and add groups and dataset into the file, which is the - * same as javaExample.H5DatasetCreate - * - * @see javaExample.HDF5DatasetCreate - * @throws Exception - */ private static void createFile() throws Exception { // retrieve an instance of H5File FileFormat fileFormat = FileFormat.getFileFormat(FileFormat.FILE_TYPE_HDF5); diff --git a/vcell-core/src/test/java/cbit/vcell/solvers/mb/VH5Dataset.java b/vcell-core/src/test/java/cbit/vcell/solvers/mb/VH5Dataset.java index c2b398a51c..34b874bee5 100644 --- a/vcell-core/src/test/java/cbit/vcell/solvers/mb/VH5Dataset.java +++ b/vcell-core/src/test/java/cbit/vcell/solvers/mb/VH5Dataset.java @@ -7,7 +7,7 @@ import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; -import org.vcell.util.BeanUtils; +import org.vcell.util.CastingUtils; import org.vcell.util.VCAssert; import edu.uchc.connjur.wb.ExecutionTrace; @@ -29,11 +29,11 @@ public void info( ) { try { System.out.println(dataset.getName()); System.out.println(dataset.getFullName()); - H5ScalarDS sds = BeanUtils.downcast(H5ScalarDS.class,dataset); + H5ScalarDS sds = CastingUtils.downcast(H5ScalarDS.class,dataset); if (sds != null) { info(sds); } - H5CompoundDS cds = BeanUtils.downcast(H5CompoundDS.class,dataset); + H5CompoundDS cds = CastingUtils.downcast(H5CompoundDS.class,dataset); int rank = dataset.getRank(); long[] d = dataset.getDims( ); long[] s = dataset.getSelectedDims(); @@ -103,7 +103,7 @@ public void info(H5CompoundDS ds) throws Exception { System.out.println(dt.getFullName()); System.out.println(dt.getDatatypeDescription()); Object obj = ds.read(); - Collection coll = BeanUtils.downcast(Collection.class, obj); + Collection coll = CastingUtils.downcast(Collection.class, obj); VCAssert.assertTrue(coll.size() == mn.length, "collection matches names"); int i = 0; for (Object o : coll) { @@ -127,7 +127,7 @@ public void meta( ) { private void analyze(Object o) { Objects.requireNonNull(o); - Vector v = BeanUtils.downcast(Vector.class, o); + Vector v = CastingUtils.downcast(Vector.class, o); if (v != null) { analyzeVector(v); return; diff --git a/vcell-util/src/main/java/org/vcell/util/BeanUtils.java b/vcell-util/src/main/java/org/vcell/util/BeanUtils.java index eeae645393..9ac3bb995a 100644 --- a/vcell-util/src/main/java/org/vcell/util/BeanUtils.java +++ b/vcell-util/src/main/java/org/vcell/util/BeanUtils.java @@ -237,19 +237,19 @@ public static String getStackTrace() { * @return {@link Throwable#getMessage()}, recursively */ public static String getMessageRecursive(Throwable throwable) { - String rval = throwable.getMessage(); + StringBuilder rval = new StringBuilder(throwable.getMessage()); Throwable cause = throwable.getCause(); while (cause != null) { - rval += " caused by " + cause.getMessage(); + rval.append(" caused by ").append(cause.getMessage()); cause = cause.getCause(); } - return rval; + return rval.toString(); } public static void sendSMTP(String smtpHost, int smtpPort,String from, String to,String subject, String content) - throws AddressException, MessagingException { + throws MessagingException { // Create a mail session java.util.Properties props = new java.util.Properties(); @@ -269,22 +269,16 @@ public static void sendSMTP(String smtpHost, int smtpPort,String from, String to } public static String readBytesFromFile(File file, ClientTaskStatusSupport clientTaskStatusSupport) throws IOException { - StringBuffer stringBuffer = new StringBuffer(); - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new FileReader(file)); - String line = new String(); - while((line = bufferedReader.readLine()) != null) { - stringBuffer.append(line + "\n"); - if (clientTaskStatusSupport!=null && clientTaskStatusSupport.isInterrupted()){ - break; - } - } - }finally{ - if (bufferedReader != null){ - bufferedReader.close(); - } - } + StringBuilder stringBuffer = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + stringBuffer.append(line).append("\n"); + if (clientTaskStatusSupport != null && clientTaskStatusSupport.isInterrupted()) { + break; + } + } + } return stringBuffer.toString(); } @@ -296,7 +290,7 @@ private enum FLAG_STATE {START,FINISHED,INTERRUPTED,FAILED} * @param url not null * @param clientTaskStatusSupport could be null, in which case default status messages printed * @return downloadedString - * @throws RuntimeException + * @throws RuntimeException somehow */ public static String downloadBytes(final URL url,final ClientTaskStatusSupport clientTaskStatusSupport){ final ChannelFuture[] connectFuture = new ChannelFuture[1]; @@ -341,9 +335,8 @@ public void run() { }else{ throw new RuntimeException(exceptionMessage(connectFuture[0].getCause())); } - } else { - // Connection established successfully - } + } // else: Connection established successfully + // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url.toURI().toASCIIString()); @@ -371,16 +364,14 @@ public void run() { }else{ throw new RuntimeException(exceptionMessage(closeFuture[0].getCause())); } - } else { - // Connection established successfully - } + } // else Connection established successfully bFlag[0] = FLAG_STATE.FINISHED; } catch (Exception e) { lg.error("Error while downloading bytes from server: " + e.getMessage(), e); bFlag[0] = FLAG_STATE.FAILED; - exception[0] = new RuntimeException("contacting outside server " + url.toString() + " failed.\n" + exceptionMessage(e)); + exception[0] = new RuntimeException("contacting outside server " + url + " failed.\n" + exceptionMessage(e)); } finally { if (bootstrap != null) { // Shut down executor threads to exit. @@ -397,7 +388,7 @@ public void run() { while(true){ try { Thread.sleep(100); - } catch (Exception e) { } + } catch (Exception e) { if (lg.isInfoEnabled()) lg.info(e.getMessage(), e); } long elapsedTime_ms = System.currentTimeMillis()-startTime_ms; if(clientTaskStatusSupport != null && clientTaskStatusSupport.isInterrupted()){ bFlag[0] = FLAG_STATE.INTERRUPTED; @@ -480,8 +471,7 @@ public static String exceptionMessage(Throwable e){ public static final String SQL_ESCAPE_CHARACTER = "/"; public static String convertToSQLSearchString(String searchString){ if(searchString == null || searchString.isEmpty()){return searchString;} - String convertedLikeString = getConvertedLikeString(searchString); - return convertedLikeString; + return getConvertedLikeString(searchString); } private static String getConvertedLikeString(String searchString) { @@ -509,7 +499,7 @@ private static String getConvertedLikeString(String searchString) { } /** - * @param clzz + * @param clzz class to get leaf from * @return class name without package info * @throws NullPointerException if clzz null */ @@ -522,167 +512,18 @@ public static String leafName(Class clzz) { return cname; } - /** - * customize error message for null pointers - * @param clzz type of obj - * @param obj to check for null - * @return obj (not null) - * @throws NullPointerException if obj is null - */ - public static T notNull(Class clzz, T obj) { - if (obj != null) { - return obj; - } - throw new NullPointerException("unexpected " + clzz.getName() + " null pointer"); - } - /** * see if numerator / divisor is integer using decimal (base 10) arithmetic instead of * floating point (base 2) - * @param numerator - * @param divisor + * @param numerator the numerator + * @param divisor the divisor * @return true if decimal numerator / decimal divisor is integer */ - public static boolean isIntegerMultiple(double numerator, double divisor) { + public static boolean isNotAnIntegerMultiple(double numerator, double divisor) { BigDecimal n = BigDecimal.valueOf(numerator); BigDecimal d = BigDecimal.valueOf(divisor); BigDecimal remainder = n.remainder(d); - return remainder.compareTo(BigDecimal.ZERO) == 0; - } - - /** - * convert ordinal to Enum - * @param clzz may not be null - * @param ordinal - * @return e with e.ordinal( ) == ordinal - * @throws IllegalArgumentException if ordinal out of range - */ - public static > E lookupEnum(Class clzz, int ordinal) { - EnumSet set = EnumSet.allOf(clzz); - if (ordinal < set.size()) { - Iterator iter = set.iterator(); - for (int i = 0; i < ordinal; i++) { - iter.next(); - } - E rval = iter.next(); - assert(rval.ordinal() == ordinal); - return rval; - } - throw new IllegalArgumentException("Invalid value " + ordinal + " for " + ExecutionTrace.justClassName(clzz) + ", must be < " + set.size()); - } - - /** - * downcast to object or return null - * @param clzz return type, not null - * @param obj may be null - * @return obj as T or null if obj is null or not of type T - */ - public static T downcast(Class clzz, Object obj) { - if (obj != null && clzz.isAssignableFrom(obj.getClass())) { - @SuppressWarnings("unchecked") - T rval = (T) obj; - return rval; - } - return null; - } - - public interface CastInfo { - /** - * was cast successful? - */ - boolean isGood( ); - /** - * return type converted object - * @return non null pointer - * @throws ProgrammingException if {@link #isGood()} returns false - */ - T get( ); - /** - * @return name of desired class if {@link #isGood()} returns false - */ - String requiredName( ); - /** - * @return name of provided object if {@link #isGood()} returns false - */ - String actualName( ); - - /** - * @return message explaining cast - */ - String castMessage( ); - } - - /** - * attempt to class object to specified type - * @param clzz desired type, not null - * @param obj object to cast; if null returns !isGood( ) CastInfo - * @return CastInfo object describing results - */ - public static CastInfo attemptCast(Class clzz, Object obj) { - final String rname = clzz.getName(); - if (obj != null) { - final String aname = obj.getClass().getName(); - T result = downcast(clzz, obj); - if (result == null) { - return new FailInfo<>(rname, aname); - } - return new SucceedInfo<>(rname,aname,result); - } - return new FailInfo<>(rname, "null"); - } - - private abstract static class CiBase implements CastInfo { - final String rname; - final String aname; - protected CiBase(String rname, String aname) { - this.rname = rname; - this.aname = aname; - } - public String requiredName() { return rname; } - public String actualName() { return aname; } - public String castMessage( ) { - return "cast from " + aname + " to " + rname; - } - } - private static class FailInfo extends CiBase { - - FailInfo(String rname, String aname) { - super(rname,aname); - } - public boolean isGood() { - return false; - } - public T get() { - String msg = "Programming exception, " + castMessage() + " failed"; - throw new ProgrammingException(msg); - } - } - - private static class SucceedInfo extends CiBase { - final T obj; - - SucceedInfo(String rname,String aname, T obj) { - super(rname,aname); - this.obj = obj; - } - public boolean isGood() { - return true; - } - public T get() { - return obj; - } - } - - public static Range calculateValueDomain(double[] values,BitSet domainValid){ - double min=Double.POSITIVE_INFINITY; - double max=Double.NEGATIVE_INFINITY; - for (int i = 0; i < values.length; i++) { - if((domainValid == null || domainValid.get(i) || domainValid.isEmpty()) && !Double.isNaN(values[i]) && !Double.isInfinite(values[i])){ - if(values[i] < min){min = values[i];} - if(values[i] > max){max = values[i];} - } - } - return new Range(min,max); + return remainder.compareTo(BigDecimal.ZERO) != 0; } public static String generateDateTimeString(){ @@ -691,17 +532,8 @@ public static String generateDateTimeString(){ int month = calendar.get(Calendar.MONTH)+1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); - int min = calendar.get(Calendar.MINUTE); - int sec = calendar.get(Calendar.SECOND); - String imageName = - year+""+ - (month < 10?"0"+month:month)+""+ - (day < 10?"0"+day:day)+ - "_"+ - (hour < 10?"0"+hour:hour)+""+ - (min < 10?"0"+min:min)+""+ - (sec < 10?"0"+sec:sec); - - return imageName; + int minute = calendar.get(Calendar.MINUTE); + int second = calendar.get(Calendar.SECOND); + return String.format("%d%02d%02d_%02d%02d%02d", year, month, day, hour, minute, second); } } diff --git a/vcell-util/src/main/java/org/vcell/util/CastingUtils.java b/vcell-util/src/main/java/org/vcell/util/CastingUtils.java new file mode 100644 index 0000000000..433bf6c604 --- /dev/null +++ b/vcell-util/src/main/java/org/vcell/util/CastingUtils.java @@ -0,0 +1,107 @@ +package org.vcell.util; + +public class CastingUtils { + + /** + * downcast to object or return null + * @param clzz return type, not null + * @param obj may be null + * @return obj as T or null if obj is null or not of type T + */ + public static T downcast(Class clzz, Object obj) { + if (obj != null && clzz.isAssignableFrom(obj.getClass())) { + @SuppressWarnings("unchecked") + T rval = (T) obj; + return rval; + } + return null; + } + + /** + * attempt to class object to specified type + * @param clzz desired type, not null + * @param obj object to cast; if null returns !isGood( ) CastInfo + * @return CastInfo object describing results + */ + public static CastInfo attemptCast(Class clzz, Object obj) { + final String rname = clzz.getName(); + if (obj != null) { + final String aname = obj.getClass().getName(); + T result = downcast(clzz, obj); + if (result == null) { + return new FailInfo<>(rname, aname); + } + return new SucceedInfo<>(rname,aname,result); + } + return new FailInfo<>(rname, "null"); + } + + public interface CastInfo { + /** + * was cast successful? + */ + boolean isGood( ); + /** + * return type converted object + * @return non null pointer + * @throws ProgrammingException if {@link #isGood()} returns false + */ + T get( ); + /** + * @return name of desired class if {@link #isGood()} returns false + */ + String requiredName( ); + /** + * @return name of provided object if {@link #isGood()} returns false + */ + String actualName( ); + + /** + * @return message explaining cast + */ + String castMessage( ); + } + + private abstract static class CiBase implements CastInfo { + final String rname; + final String aname; + protected CiBase(String rname, String aname) { + this.rname = rname; + this.aname = aname; + } + public String requiredName() { return rname; } + public String actualName() { return aname; } + public String castMessage( ) { + return "cast from " + aname + " to " + rname; + } + } + + private static class FailInfo extends CiBase { + + FailInfo(String rname, String aname) { + super(rname,aname); + } + public boolean isGood() { + return false; + } + public T get() { + String msg = "Programming exception, " + castMessage() + " failed"; + throw new ProgrammingException(msg); + } + } + + private static class SucceedInfo extends CiBase { + final T obj; + + SucceedInfo(String rname,String aname, T obj) { + super(rname,aname); + this.obj = obj; + } + public boolean isGood() { + return true; + } + public T get() { + return obj; + } + } +} diff --git a/vcell-util/src/main/java/org/vcell/util/Compare.java b/vcell-util/src/main/java/org/vcell/util/Compare.java index f0e8a550a4..9655ffd821 100644 --- a/vcell-util/src/main/java/org/vcell/util/Compare.java +++ b/vcell-util/src/main/java/org/vcell/util/Compare.java @@ -694,9 +694,9 @@ public static boolean isEqualFields(Matchable lhs, Matchable rhs) { } for ( Field f : lClass.getDeclaredFields()) { f.setAccessible(true); - Matchable lMatch = BeanUtils.downcast(Matchable.class, f.get(lhs) ); + Matchable lMatch = CastingUtils.downcast(Matchable.class, f.get(lhs) ); if (lMatch != null) { - Matchable rMatch = BeanUtils.downcast(Matchable.class, f.get(rhs) ); + Matchable rMatch = CastingUtils.downcast(Matchable.class, f.get(rhs) ); if (!isEqual(lMatch, rMatch)) { return false; } diff --git a/vcell-util/src/test/java/org/vcell/util/BeansUtilTest.java b/vcell-util/src/test/java/org/vcell/util/BeanUtilsTest.java similarity index 64% rename from vcell-util/src/test/java/org/vcell/util/BeansUtilTest.java rename to vcell-util/src/test/java/org/vcell/util/BeanUtilsTest.java index a287af5b54..bd88a36ca0 100644 --- a/vcell-util/src/test/java/org/vcell/util/BeansUtilTest.java +++ b/vcell-util/src/test/java/org/vcell/util/BeanUtilsTest.java @@ -1,166 +1,129 @@ -package org.vcell.util; - -import static org.junit.Assert.assertTrue; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Frame; -import java.awt.Window; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.concurrent.TimeUnit; -import java.util.function.BiFunction; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.vcell.test.Fast; - -@Category(Fast.class) -public class BeansUtilTest { - - @SuppressWarnings("null") - //@Test - public void tryIt( ) { - try { - String n = null; - System.out.print(n.length()); - - } catch(NullPointerException npe) { - npe.printStackTrace(); - } - - try { - String n = null; - System.out.print(BeanUtils.notNull(String.class, n)); - - } catch(NullPointerException npe) { - npe.printStackTrace(); - } - - } - - @Test - public void lookupTest( ) { - java.util.concurrent.TimeUnit tu = BeanUtils.lookupEnum(TimeUnit.class, 3); - Assert.assertEquals(tu.toString(),"SECONDS"); - } - - @Test - public void downcast( ) { - Integer i = 3; - Number n = i; - Integer back = BeanUtils.downcast(Integer.class,n); - Double fail = BeanUtils.downcast(Double.class,n); - assertTrue(back == i); - assertTrue(fail == null); - Double notThere = BeanUtils.downcast(Double.class,null); - assertTrue(notThere == null); - } - - private void eenie( ) { - meenie( ); - } - - private void meenie( ) { - mo( ); - - } - - private void mo( ) { - System.out.println(BeanUtils.getStackTrace()); - } - - @Ignore - @Test - public void stackTrace( ) { - eenie( ); - } - - public void downloadString(ClientTaskStatusSupport taskSupport ) throws MalformedURLException { - URL url = new URL("http://code3.cam.uchc.edu/slowdownload.php"); - System.out.println("starting download ..."); - String out = BeanUtils.downloadBytes(url, taskSupport); - System.out.println(out); - } - - @Ignore - @Test - public void downloadWatch( ) throws MalformedURLException { - downloadString(new TaskSupport( )); - } - - @Ignore - @Test - public void downloadSilent( ) throws MalformedURLException { - downloadString(new SilentTaskSupport( )); - } - - @Ignore - @Test - public void downloadNull( ) throws MalformedURLException { - downloadString(null); - } - - private static class SilentTaskSupport implements ClientTaskStatusSupport { - - @Override - public void setMessage(String message) { } - - @Override - public void setProgress(int progress) { } - - @Override - public int getProgress() { - return 0; - } - - @Override - public boolean isInterrupted() { - return false; - } - - @Override public void addProgressDialogListener(ProgressDialogListener progressDialogListener) { } - - } - private static class TaskSupport implements ClientTaskStatusSupport { - - private int progress; - - @Override - public void setMessage(String message) { - System.out.println("message " + message); - - - } - - @Override - public void setProgress(int progress) { - this.progress = progress; - System.out.println("progress " + progress); - - } - - @Override - public int getProgress() { - return progress; - } - - @Override - public boolean isInterrupted() { - return false; - } - - @Override - public void addProgressDialogListener(ProgressDialogListener progressDialogListener) { - System.out.println("adpdl"); - } - } - -} +package org.vcell.util; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.vcell.test.Fast; + +import static org.junit.Assert.*; + +@Category(Fast.class) +public class BeanUtilsTest { + + @Test + public void downcast( ) { + Integer i = 3; + Number n = i; + Integer back = CastingUtils.downcast(Integer.class,n); + Double fail = CastingUtils.downcast(Double.class,n); + assertSame(back, i); + assertNull(fail); + Double notThere = CastingUtils.downcast(Double.class,null); + assertNull(notThere); + } + + private void eenie( ) { + meenie( ); + } + + private void meenie( ) { + mo( ); + + } + + private void mo( ) { + System.out.println(BeanUtils.getStackTrace()); + } + + @Ignore + @Test + public void stackTrace( ) { + eenie( ); + } + + public void downloadString(ClientTaskStatusSupport taskSupport ) throws MalformedURLException { + URL url = new URL("http://code3.cam.uchc.edu/slowdownload.php"); + System.out.println("starting download ..."); + String out = BeanUtils.downloadBytes(url, taskSupport); + System.out.println(out); + } + + @Ignore + @Test + public void downloadWatch( ) throws MalformedURLException { + downloadString(new TaskSupport( )); + } + + @Ignore + @Test + public void downloadSilent( ) throws MalformedURLException { + downloadString(new SilentTaskSupport( )); + } + + @Ignore + @Test + public void downloadNull( ) throws MalformedURLException { + downloadString(null); + } + + private static class SilentTaskSupport implements ClientTaskStatusSupport { + + @Override + public void setMessage(String message) { } + + @Override + public void setProgress(int progress) { } + + @Override + public int getProgress() { + return 0; + } + + @Override + public boolean isInterrupted() { + return false; + } + + @Override public void addProgressDialogListener(ProgressDialogListener progressDialogListener) { } + + } + private static class TaskSupport implements ClientTaskStatusSupport { + + private int progress; + + @Override + public void setMessage(String message) { + System.out.println("message " + message); + + + } + + @Override + public void setProgress(int progress) { + this.progress = progress; + System.out.println("progress " + progress); + + } + + @Override + public int getProgress() { + return progress; + } + + @Override + public boolean isInterrupted() { + return false; + } + + @Override + public void addProgressDialogListener(ProgressDialogListener progressDialogListener) { + System.out.println("adpdl"); + } + } + +}