target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void badZmsg( ) { try { index.rollup(0,0,mZ); Assert.fail("should have thrown an exception"); } catch (RuntimeException re) { } } | public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } | DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } } | DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); } | DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); } | DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); } |
@Test public void test() { try { EventRateLimiter eventRateLimiter = new EventRateLimiter(); long testStartTime = System.currentTimeMillis(); System.out.println("Starting at " + testStartTime); int approvedEventCount = 0; while (System.currentTimeMillis() < testStartTime + 60000) { if (eventRateLimiter.isOkayToFireEventNow()) { approvedEventCount++; System.out.println("Now it is "+ System.currentTimeMillis()); } } if ((approvedEventCount > 67) && (approvedEventCount < 73)) { System.out.println(String.valueOf(approvedEventCount)+ " events approved in one minute"); } else { System.out.println(String.valueOf(approvedEventCount)+" events approved in one minute is out of expected bounds"); fail(String.valueOf(approvedEventCount)+" events approved in one minute is out of expected bounds"); } } catch (Exception e) { fail("Exception occured: "+e.getMessage()); } } | public boolean isOkayToFireEventNow(){ long totalElapsedTimeNow = timeRightNow()-startTime; int currentTimeRegimeIndex = 0; for (int i=0; i<intervals.length; i++) { currentTimeRegimeIndex = i; if (totalElapsedTimeNow < intervals[i][TIME_INTERVAL_REGIME]){ break; } } if (timeSinceLastApprovedEvent() < intervals[currentTimeRegimeIndex][TIME_INTERVAL_PER_REGIME]){ return false; } else { timeOfLastEvent = timeRightNow(); return true; } } | EventRateLimiter { public boolean isOkayToFireEventNow(){ long totalElapsedTimeNow = timeRightNow()-startTime; int currentTimeRegimeIndex = 0; for (int i=0; i<intervals.length; i++) { currentTimeRegimeIndex = i; if (totalElapsedTimeNow < intervals[i][TIME_INTERVAL_REGIME]){ break; } } if (timeSinceLastApprovedEvent() < intervals[currentTimeRegimeIndex][TIME_INTERVAL_PER_REGIME]){ return false; } else { timeOfLastEvent = timeRightNow(); return true; } } } | EventRateLimiter { public boolean isOkayToFireEventNow(){ long totalElapsedTimeNow = timeRightNow()-startTime; int currentTimeRegimeIndex = 0; for (int i=0; i<intervals.length; i++) { currentTimeRegimeIndex = i; if (totalElapsedTimeNow < intervals[i][TIME_INTERVAL_REGIME]){ break; } } if (timeSinceLastApprovedEvent() < intervals[currentTimeRegimeIndex][TIME_INTERVAL_PER_REGIME]){ return false; } else { timeOfLastEvent = timeRightNow(); return true; } } EventRateLimiter(long[][] specifiedIntervals); EventRateLimiter(); } | EventRateLimiter { public boolean isOkayToFireEventNow(){ long totalElapsedTimeNow = timeRightNow()-startTime; int currentTimeRegimeIndex = 0; for (int i=0; i<intervals.length; i++) { currentTimeRegimeIndex = i; if (totalElapsedTimeNow < intervals[i][TIME_INTERVAL_REGIME]){ break; } } if (timeSinceLastApprovedEvent() < intervals[currentTimeRegimeIndex][TIME_INTERVAL_PER_REGIME]){ return false; } else { timeOfLastEvent = timeRightNow(); return true; } } EventRateLimiter(long[][] specifiedIntervals); EventRateLimiter(); boolean isOkayToFireEventNow(); static void main(String[] args); } | EventRateLimiter { public boolean isOkayToFireEventNow(){ long totalElapsedTimeNow = timeRightNow()-startTime; int currentTimeRegimeIndex = 0; for (int i=0; i<intervals.length; i++) { currentTimeRegimeIndex = i; if (totalElapsedTimeNow < intervals[i][TIME_INTERVAL_REGIME]){ break; } } if (timeSinceLastApprovedEvent() < intervals[currentTimeRegimeIndex][TIME_INTERVAL_PER_REGIME]){ return false; } else { timeOfLastEvent = timeRightNow(); return true; } } EventRateLimiter(long[][] specifiedIntervals); EventRateLimiter(); boolean isOkayToFireEventNow(); static void main(String[] args); } |
@Test public void testSystemTempDir( ) throws IOException { File tempDir = PropertyLoader.getSystemTemporaryDirectory(); System.out.println(tempDir); File secondCall = PropertyLoader.getSystemTemporaryDirectory(); assertTrue(tempDir == secondCall); } | public static File getSystemTemporaryDirectory( ) throws IOException { if (systemTemporaryDirectory != null) { return systemTemporaryDirectory; } File query = File.createTempFile("PropertyLoaderQuery",null); systemTemporaryDirectory = query.getParentFile(); query.delete(); return systemTemporaryDirectory; } | PropertyLoader { public static File getSystemTemporaryDirectory( ) throws IOException { if (systemTemporaryDirectory != null) { return systemTemporaryDirectory; } File query = File.createTempFile("PropertyLoaderQuery",null); systemTemporaryDirectory = query.getParentFile(); query.delete(); return systemTemporaryDirectory; } } | PropertyLoader { public static File getSystemTemporaryDirectory( ) throws IOException { if (systemTemporaryDirectory != null) { return systemTemporaryDirectory; } File query = File.createTempFile("PropertyLoaderQuery",null); systemTemporaryDirectory = query.getParentFile(); query.delete(); return systemTemporaryDirectory; } PropertyLoader(); } | PropertyLoader { public static File getSystemTemporaryDirectory( ) throws IOException { if (systemTemporaryDirectory != null) { return systemTemporaryDirectory; } File query = File.createTempFile("PropertyLoaderQuery",null); systemTemporaryDirectory = query.getParentFile(); query.delete(); return systemTemporaryDirectory; } PropertyLoader(); static void sendErrorsToMongo( ); static File getSystemTemporaryDirectory( ); final static boolean getBooleanProperty(String propertyName, boolean defaultValue); final static int getIntProperty(String propertyName, int defaultValue); final static long getLongProperty(String propertyName, long defaultValue); final static String getProperty(String propertyName, String defaultValue); final static File getRequiredDirectory(String propertyName); final static File getOptionalDirectory(String propertyName); final static synchronized String getRequiredProperty(String propertyName); final static void loadProperties(String[] required); @Deprecated final static void loadProperties(boolean throwException, boolean validate); final static void loadProperties(); final static void show(); static String getSecretValue(String secretValueProperty, String secretFileProperty); } | PropertyLoader { public static File getSystemTemporaryDirectory( ) throws IOException { if (systemTemporaryDirectory != null) { return systemTemporaryDirectory; } File query = File.createTempFile("PropertyLoaderQuery",null); systemTemporaryDirectory = query.getParentFile(); query.delete(); return systemTemporaryDirectory; } PropertyLoader(); static void sendErrorsToMongo( ); static File getSystemTemporaryDirectory( ); final static boolean getBooleanProperty(String propertyName, boolean defaultValue); final static int getIntProperty(String propertyName, int defaultValue); final static long getLongProperty(String propertyName, long defaultValue); final static String getProperty(String propertyName, String defaultValue); final static File getRequiredDirectory(String propertyName); final static File getOptionalDirectory(String propertyName); final static synchronized String getRequiredProperty(String propertyName); final static void loadProperties(String[] required); @Deprecated final static void loadProperties(boolean throwException, boolean validate); final static void loadProperties(); final static void show(); static String getSecretValue(String secretValueProperty, String secretFileProperty); static final String ADMINISTRATOR_ACCOUNT; static final String ADMINISTRATOR_ID; static final String propertyFileProperty; static final String vcellServerIDProperty; static final String simPerUserMemoryLimitFile; static final String primarySimDataDirInternalProperty; static final String secondarySimDataDirInternalProperty; static final String primarySimDataDirExternalProperty; static final String secondarySimDataDirExternalProperty; static final String simDataDirArchiveHost; static final String PARALLEL_DATA_DIR_EXTERNAL; static final String jobMemoryOverheadMB; static final String htcBatchSystemQueue; static final String htcLogDirExternal; static final String htcLogDirInternal; static final String htcUser; static final String htcPbsHome; static final String htcSgeHome; static final String htcNodeList; static final String slurm_cmd_sbatch; static final String slurm_cmd_scancel; static final String slurm_cmd_sacct; static final String slurm_cmd_squeue; static final String slurm_cmd_scontrol; static final String slurm_cmd_sinfo; static final String slurm_partition; static final String slurm_reservation; static final String slurm_partition_pu; static final String slurm_reservation_pu; static final String slurm_tmpdir; static final String slurm_local_singularity_dir; static final String slurm_central_singularity_dir; static final String sgeModulePath; static final String pbsModulePath; static final String MPI_HOME_INTERNAL; static final String MPI_HOME_EXTERNAL; static final String nativeSolverDir_External; static final String comsolRootDir; static final String comsolJarDir; static final String vcellServerHost; static final String pythonExe; static final String vcellapiKeystoreFile; static final String vcellapiKeystorePswd; static final String vcellapiKeystorePswdFile; static final String bioformatsJarFileName; static final String bioformatsJarDownloadURL; static final String COPASI_WEB_URL; static final String SMOLDYN_WEB_URL; static final String BIONETGEN_WEB_URL; static final String NFSIM_WEB_URL; static final String ACKNOWLEGE_PUB__WEB_URL; static final String VCELL_URL; static final String VC_BNG_INDEX_URL; static final String VC_BNG_FAQ_URL; static final String VC_BNG_TUTORIAL_URL; static final String VC_BNG_SAMPLES_URL; static final String VC_SUPPORT_URL; static final String VC_GOOGLE_DISCUSS_URL; static final String VC_TUT_PERMISSION_URL; static final String BMDB_URL; static final String CONTINUUM_URL; static final String DOI_URL; static final String BMDB_DOWNLOAD_URL; static final String PATHWAY_QUERY_URL; static final String PATHWAY_WEB_DO_URL; static final String SABIO_SRCH_KINETIC_URL; static final String SABIO_DIRECT_IFRAME_URL; static final String COPASI_TIKI_URL; static final String BIONUMBERS_SRCH1_URL; static final String BIONUMBERS_SRCH2_URL; static final String SIGNALLING_QUERY_URL; static final String BIOPAX_RSABIO12_URL; static final String BIOPAX_RSABIO11452_URL; static final String BIOPAX_RSABIO65_URL; static final String BIOPAX_RKEGGR01026_URL; static final String COMSOL_URL; static final String databaseThreadsProperty; static final String exportdataThreadsProperty; static final String simdataThreadsProperty; static final String htcworkerThreadsProperty; static final String databaseCacheSizeProperty; static final String simdataCacheSizeProperty; static final String exportBaseURLProperty; static final String exportBaseDirInternalProperty; static final String exportMaxInMemoryLimit; static final String dbDriverName; static final String dbConnectURL; static final String dbUserid; static final String dbPasswordValue; static final String dbPasswordFile; static final String jmsIntHostInternal; static final String jmsIntPortInternal; static final String jmsSimHostInternal; static final String jmsSimPortInternal; static final String jmsSimRestPortInternal; static final String jmsSimHostExternal; static final String jmsSimPortExternal; static final String jmsSimRestPortExternal; static final String jmsUser; static final String jmsPasswordValue; static final String jmsPasswordFile; static final String jmsRestPasswordFile; static final String jmsSimReqQueue; static final String jmsDataRequestQueue; static final String jmsDbRequestQueue; static final String jmsSimJobQueue; static final String jmsWorkerEventQueue; static final String jmsServiceControlTopic; static final String jmsDaemonControlTopic; static final String jmsClientStatusTopic; static final String jmsBlobMessageMinSize; static final String jmsBlobMessageTempDir; static final String jmsBlobMessageUseMongo; static final String vcellClientTimeoutMS; static final String maxOdeJobsPerUser; static final String maxPdeJobsPerUser; static final String maxJobsPerScan; static final String vcellSoftwareVersion; static final String vcellThirdPartyLicense; static final String vcellPublicationHost; static final String vcellSMTPHostName; static final String vcellSMTPPort; static final String vcellSMTPEmailAddress; static final String vcellbatch_docker_name; static final String vcellbatch_singularity_image; static final String javaSimulationExecutable; static final String simulationPreprocessor; static final String simulationPostprocessor; final static String mongodbHostInternal; final static String mongodbPortInternal; final static String mongodbHostExternal; final static String mongodbPortExternal; final static String mongodbDatabase; final static String mongodbLoggingCollection; final static String mongodbThreadSleepMS; static final String amplistorVCellServiceURL; static final String amplistorVCellServiceUser; static final String amplistorVCellServicePassword; static final String installationRoot; static final String vcellDownloadDir; static final String autoflushStandardOutAndErr; static final String suppressQStatStandardOutLogging; static final String nagiosMonitorPort; static final String imageJVcellPluginURL; static final String NATIVE_LIB_DIR; static final String USE_CURRENT_WORKING_DIRECTORY; } |
@Test public void testDoDataOperation() throws DataAccessException { boolean bIncludeStartValuesInfo = true; DataOperation dataOperation = new DataOperation.DataProcessingOutputInfoOP(vcDataIdentifier,bIncludeStartValuesInfo, outputContext); DataProcessingOutputInfo results = (DataProcessingOutputInfo)dsc.doDataOperation(dataOperation); String[] varNames = results.getVariableNames(); String[] expectedVarNames = { "C_cyt_average", "C_cyt_total", "C_cyt_min", "C_cyt_max", "Ran_cyt_average", "Ran_cyt_total", "Ran_cyt_min", "Ran_cyt_max", "RanC_cyt_average", "RanC_cyt_total", "RanC_cyt_min", "RanC_cyt_max", "RanC_nuc_average", "RanC_nuc_total", "RanC_nuc_min", "RanC_nuc_max", "s2_average", "s2_total", "s2_min", "s2_max"}; String[] expectedUnits = { "uM", "molecules", "uM", "uM", "uM", "molecules", "uM", "uM", "uM", "molecules", "uM", "uM", "uM", "molecules", "uM", "uM", "molecules.um-2", "molecules", "uM", "uM"}; double[] expectedTimePoints = {0.0, 0.5, 1.0}; double[] expectedStatistics_RanC_cyt_max = {8.9, 3.5890337679723476, 3.057119332620108}; Assert.assertArrayEquals(varNames,expectedVarNames); Assert.assertArrayEquals(expectedTimePoints, results.getVariableTimePoints(), 1e-8); for (int i = 0; i<expectedVarNames.length; i++){ Assert.assertEquals(results.getVariableUnits(expectedVarNames[i]), expectedUnits[i]); } Assert.assertArrayEquals(expectedStatistics_RanC_cyt_max, results.getVariableStatValues().get("RanC_cyt_max"), 1e-8); } | public DataOperationResults doDataOperation(DataOperation dataOperation) throws DataAccessException{ VCDataJobID vcDataJobID = null; try{ if(dataOperation instanceof DataOperation.DataProcessingOutputTimeSeriesOP){ vcDataJobID = ((DataOperation.DataProcessingOutputTimeSeriesOP)dataOperation).getTimeSeriesJobSpec().getVcDataJobID(); } if(!(getVCData(dataOperation.getVCDataIdentifier()) instanceof SimulationData)){ return null; } File dataProcessingOutputFileHDF5 = ((SimulationData)getVCData(dataOperation.getVCDataIdentifier())).getDataProcessingOutputSourceFileHDF5(); DataOperationResults dataOperationResults = getDataProcessingOutput(dataOperation,dataProcessingOutputFileHDF5); if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_COMPLETE, dataOperation.getVCDataIdentifier(), new Double(0), ((DataOperationResults.DataProcessingOutputTimeSeriesValues)dataOperationResults).getTimeSeriesJobResults(),null); } return dataOperationResults; }catch(Exception e){ if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_FAILURE, dataOperation.getVCDataIdentifier(), new Double(0), null,e); } if(e instanceof DataAccessException){ throw (DataAccessException)e; }else{ throw new DataAccessException("Datasetcontrollerimpl.doDataOperation error: "+e.getMessage(),e); } } } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataOperationResults doDataOperation(DataOperation dataOperation) throws DataAccessException{ VCDataJobID vcDataJobID = null; try{ if(dataOperation instanceof DataOperation.DataProcessingOutputTimeSeriesOP){ vcDataJobID = ((DataOperation.DataProcessingOutputTimeSeriesOP)dataOperation).getTimeSeriesJobSpec().getVcDataJobID(); } if(!(getVCData(dataOperation.getVCDataIdentifier()) instanceof SimulationData)){ return null; } File dataProcessingOutputFileHDF5 = ((SimulationData)getVCData(dataOperation.getVCDataIdentifier())).getDataProcessingOutputSourceFileHDF5(); DataOperationResults dataOperationResults = getDataProcessingOutput(dataOperation,dataProcessingOutputFileHDF5); if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_COMPLETE, dataOperation.getVCDataIdentifier(), new Double(0), ((DataOperationResults.DataProcessingOutputTimeSeriesValues)dataOperationResults).getTimeSeriesJobResults(),null); } return dataOperationResults; }catch(Exception e){ if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_FAILURE, dataOperation.getVCDataIdentifier(), new Double(0), null,e); } if(e instanceof DataAccessException){ throw (DataAccessException)e; }else{ throw new DataAccessException("Datasetcontrollerimpl.doDataOperation error: "+e.getMessage(),e); } } } } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataOperationResults doDataOperation(DataOperation dataOperation) throws DataAccessException{ VCDataJobID vcDataJobID = null; try{ if(dataOperation instanceof DataOperation.DataProcessingOutputTimeSeriesOP){ vcDataJobID = ((DataOperation.DataProcessingOutputTimeSeriesOP)dataOperation).getTimeSeriesJobSpec().getVcDataJobID(); } if(!(getVCData(dataOperation.getVCDataIdentifier()) instanceof SimulationData)){ return null; } File dataProcessingOutputFileHDF5 = ((SimulationData)getVCData(dataOperation.getVCDataIdentifier())).getDataProcessingOutputSourceFileHDF5(); DataOperationResults dataOperationResults = getDataProcessingOutput(dataOperation,dataProcessingOutputFileHDF5); if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_COMPLETE, dataOperation.getVCDataIdentifier(), new Double(0), ((DataOperationResults.DataProcessingOutputTimeSeriesValues)dataOperationResults).getTimeSeriesJobResults(),null); } return dataOperationResults; }catch(Exception e){ if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_FAILURE, dataOperation.getVCDataIdentifier(), new Double(0), null,e); } if(e instanceof DataAccessException){ throw (DataAccessException)e; }else{ throw new DataAccessException("Datasetcontrollerimpl.doDataOperation error: "+e.getMessage(),e); } } } DataSetControllerImpl(Cachetable aCacheTable, File primaryDir, File secondDir); } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataOperationResults doDataOperation(DataOperation dataOperation) throws DataAccessException{ VCDataJobID vcDataJobID = null; try{ if(dataOperation instanceof DataOperation.DataProcessingOutputTimeSeriesOP){ vcDataJobID = ((DataOperation.DataProcessingOutputTimeSeriesOP)dataOperation).getTimeSeriesJobSpec().getVcDataJobID(); } if(!(getVCData(dataOperation.getVCDataIdentifier()) instanceof SimulationData)){ return null; } File dataProcessingOutputFileHDF5 = ((SimulationData)getVCData(dataOperation.getVCDataIdentifier())).getDataProcessingOutputSourceFileHDF5(); DataOperationResults dataOperationResults = getDataProcessingOutput(dataOperation,dataProcessingOutputFileHDF5); if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_COMPLETE, dataOperation.getVCDataIdentifier(), new Double(0), ((DataOperationResults.DataProcessingOutputTimeSeriesValues)dataOperationResults).getTimeSeriesJobResults(),null); } return dataOperationResults; }catch(Exception e){ if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_FAILURE, dataOperation.getVCDataIdentifier(), new Double(0), null,e); } if(e instanceof DataAccessException){ throw (DataAccessException)e; }else{ throw new DataAccessException("Datasetcontrollerimpl.doDataOperation error: "+e.getMessage(),e); } } } DataSetControllerImpl(Cachetable aCacheTable, File primaryDir, File secondDir); void addDataJobListener(DataJobListener newListener); DataOperationResults doDataOperation(DataOperation dataOperation); static DataOperationResults getDataProcessingOutput(DataOperation dataOperation,File dataProcessingOutputFileHDF5); FieldDataFileOperationResults fieldDataFileOperation(FieldDataFileOperationSpec fieldDataFileOperationSpec); DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID); double[] getDataSetTimes(VCDataIdentifier vcdID); AnnotatedFunction getFunction(OutputContext outputContext,VCDataIdentifier vcdID,String variableName); AnnotatedFunction[] getFunctions(OutputContext outputContext,VCDataIdentifier vcdID); PlotData getLineScan(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time, SpatialSelection spatialSelection); CartesianMesh getMesh(VCDataIdentifier vcdID); ODEDataBlock getODEDataBlock(VCDataIdentifier vcdID); ParticleDataBlock getParticleDataBlock(VCDataIdentifier vcdID, double time); boolean getParticleDataExists(VCDataIdentifier vcdID); SimDataBlock getSimDataBlock(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time); TimeSeriesJobResults getTimeSeriesValues(OutputContext outputContext,final VCDataIdentifier vcdID,final TimeSeriesJobSpec timeSeriesJobSpec); VCData getVCData(VCDataIdentifier vcdID); void removeDataJobListener(DataJobListener djListener); void setAllowOptimizedTimeDataRetrieval(boolean bAllowOptimizedTimeDataRetrieval); boolean isAllowOptimizedTimeDataRetrieval(); void writeFieldFunctionData(
OutputContext outputContext,
FieldDataIdentifierSpec[] argFieldDataIDSpecs,
boolean[] bResampleFlags,
CartesianMesh newMesh,
SimResampleInfoProvider simResampleInfoProvider,
int simResampleMembraneDataLength,
int handleExistingResampleMode); DataSetMetadata getDataSetMetadata(VCDataIdentifier vcdataID); DataSetTimeSeries getDataSetTimeSeries(VCDataIdentifier vcdataID, String[] variableNames); boolean getIsChombo(VCDataIdentifier vcdataID); boolean getIsMovingBoundary(VCDataIdentifier vcdataID); boolean getIsComsol(VCDataIdentifier vcdataID); ChomboFiles getChomboFiles(VCDataIdentifier vcdataID); VCellSimFiles getVCellSimFiles(VCDataIdentifier vcdataID); MovingBoundarySimFiles getMovingBoundarySimFiles(VCDataIdentifier vcdataID); ComsolSimFiles getComsolSimFiles(VCDataIdentifier vcdataID); VtuFileContainer getEmptyVtuMeshFiles(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(ChomboFiles chomboFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(VCellSimFiles vcellSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(MovingBoundarySimFiles movingBoundarySimFiles, VCDataIdentifier vcdataID, int timeIndex); double[] getVtuTimes(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID); double[] getVtuMeshData(ComsolSimFiles comsolSimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(MovingBoundarySimFiles movingBoundarySimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); VtuVarInfo[] getVtuVarInfos(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(MovingBoundarySimFiles movingBoundaryFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ComsolSimFiles comsolFiles, OutputContext outputContext, VCDataIdentifier vcdataID); NFSimMolecularConfigurations getNFSimMolecularConfigurations(VCDataIdentifier vcdID); } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataOperationResults doDataOperation(DataOperation dataOperation) throws DataAccessException{ VCDataJobID vcDataJobID = null; try{ if(dataOperation instanceof DataOperation.DataProcessingOutputTimeSeriesOP){ vcDataJobID = ((DataOperation.DataProcessingOutputTimeSeriesOP)dataOperation).getTimeSeriesJobSpec().getVcDataJobID(); } if(!(getVCData(dataOperation.getVCDataIdentifier()) instanceof SimulationData)){ return null; } File dataProcessingOutputFileHDF5 = ((SimulationData)getVCData(dataOperation.getVCDataIdentifier())).getDataProcessingOutputSourceFileHDF5(); DataOperationResults dataOperationResults = getDataProcessingOutput(dataOperation,dataProcessingOutputFileHDF5); if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_COMPLETE, dataOperation.getVCDataIdentifier(), new Double(0), ((DataOperationResults.DataProcessingOutputTimeSeriesValues)dataOperationResults).getTimeSeriesJobResults(),null); } return dataOperationResults; }catch(Exception e){ if(vcDataJobID != null){ fireDataJobEventIfNecessary(vcDataJobID,MessageEvent.DATA_FAILURE, dataOperation.getVCDataIdentifier(), new Double(0), null,e); } if(e instanceof DataAccessException){ throw (DataAccessException)e; }else{ throw new DataAccessException("Datasetcontrollerimpl.doDataOperation error: "+e.getMessage(),e); } } } DataSetControllerImpl(Cachetable aCacheTable, File primaryDir, File secondDir); void addDataJobListener(DataJobListener newListener); DataOperationResults doDataOperation(DataOperation dataOperation); static DataOperationResults getDataProcessingOutput(DataOperation dataOperation,File dataProcessingOutputFileHDF5); FieldDataFileOperationResults fieldDataFileOperation(FieldDataFileOperationSpec fieldDataFileOperationSpec); DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID); double[] getDataSetTimes(VCDataIdentifier vcdID); AnnotatedFunction getFunction(OutputContext outputContext,VCDataIdentifier vcdID,String variableName); AnnotatedFunction[] getFunctions(OutputContext outputContext,VCDataIdentifier vcdID); PlotData getLineScan(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time, SpatialSelection spatialSelection); CartesianMesh getMesh(VCDataIdentifier vcdID); ODEDataBlock getODEDataBlock(VCDataIdentifier vcdID); ParticleDataBlock getParticleDataBlock(VCDataIdentifier vcdID, double time); boolean getParticleDataExists(VCDataIdentifier vcdID); SimDataBlock getSimDataBlock(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time); TimeSeriesJobResults getTimeSeriesValues(OutputContext outputContext,final VCDataIdentifier vcdID,final TimeSeriesJobSpec timeSeriesJobSpec); VCData getVCData(VCDataIdentifier vcdID); void removeDataJobListener(DataJobListener djListener); void setAllowOptimizedTimeDataRetrieval(boolean bAllowOptimizedTimeDataRetrieval); boolean isAllowOptimizedTimeDataRetrieval(); void writeFieldFunctionData(
OutputContext outputContext,
FieldDataIdentifierSpec[] argFieldDataIDSpecs,
boolean[] bResampleFlags,
CartesianMesh newMesh,
SimResampleInfoProvider simResampleInfoProvider,
int simResampleMembraneDataLength,
int handleExistingResampleMode); DataSetMetadata getDataSetMetadata(VCDataIdentifier vcdataID); DataSetTimeSeries getDataSetTimeSeries(VCDataIdentifier vcdataID, String[] variableNames); boolean getIsChombo(VCDataIdentifier vcdataID); boolean getIsMovingBoundary(VCDataIdentifier vcdataID); boolean getIsComsol(VCDataIdentifier vcdataID); ChomboFiles getChomboFiles(VCDataIdentifier vcdataID); VCellSimFiles getVCellSimFiles(VCDataIdentifier vcdataID); MovingBoundarySimFiles getMovingBoundarySimFiles(VCDataIdentifier vcdataID); ComsolSimFiles getComsolSimFiles(VCDataIdentifier vcdataID); VtuFileContainer getEmptyVtuMeshFiles(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(ChomboFiles chomboFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(VCellSimFiles vcellSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(MovingBoundarySimFiles movingBoundarySimFiles, VCDataIdentifier vcdataID, int timeIndex); double[] getVtuTimes(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID); double[] getVtuMeshData(ComsolSimFiles comsolSimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(MovingBoundarySimFiles movingBoundarySimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); VtuVarInfo[] getVtuVarInfos(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(MovingBoundarySimFiles movingBoundaryFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ComsolSimFiles comsolFiles, OutputContext outputContext, VCDataIdentifier vcdataID); NFSimMolecularConfigurations getNFSimMolecularConfigurations(VCDataIdentifier vcdID); static final Logger lg; } |
@Test public void testGetDataIdentifiers() throws FileNotFoundException, DataAccessException, IOException { DataIdentifier[] dataIdentifiers = dsc.getDataIdentifiers(outputContext, vcDataIdentifier); String[] varNames = Arrays.asList(dataIdentifiers) .stream() .map (a -> a.getName()) .collect(Collectors.toList()).toArray(new String[0]); String[] expectedVarNames = { "C_cyt","Ran_cyt","RanC_cyt","RanC_nuc","s2", "vcRegionVolume","vcRegionArea","vcRegionVolume_subdomain1","vcRegionVolume_subdomain0","J_flux0", "J_r0","KFlux_nm_cyt","KFlux_nm_nuc","RanC_cyt_init_uM","Size_cyt", "Size_EC","Size_nm","Size_nuc","Size_pm","sobj_subdomain11_subdomain00_size", "vobj_subdomain00_size","vobj_subdomain11_size" }; Assert.assertArrayEquals(expectedVarNames, varNames); } | public DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID) throws DataAccessException, IOException, FileNotFoundException { if (lg.isTraceEnabled()) lg.trace("DataSetControllerImpl.getDataIdentifiers("+vcdID.getID()+")"); VCData simData = getVCData(vcdID); DataIdentifier[] dataIdentifiersIncludingOutsideAndInside = simData.getVarAndFunctionDataIdentifiers(outputContext); Vector<DataIdentifier> v = new Vector<DataIdentifier>(); for (int i = 0; i < dataIdentifiersIncludingOutsideAndInside.length; i++){ DataIdentifier di = dataIdentifiersIncludingOutsideAndInside[i]; if (!di.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX) && !di.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) { if (di.getVariableType() == null || di.getVariableType().equals(VariableType.UNKNOWN)) { if (di.isFunction()) { AnnotatedFunction f = getFunction(outputContext,vcdID,di.getName()); VariableType varType = getVariableTypeForFieldFunction(outputContext,vcdID, f); di = new DataIdentifier(di.getName(), varType, di.getDomain(), di.isFunction(), f.getDisplayName()); } } v.addElement(di); } } DataIdentifier[] ids = new DataIdentifier[v.size()]; v.copyInto(ids); return ids; } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID) throws DataAccessException, IOException, FileNotFoundException { if (lg.isTraceEnabled()) lg.trace("DataSetControllerImpl.getDataIdentifiers("+vcdID.getID()+")"); VCData simData = getVCData(vcdID); DataIdentifier[] dataIdentifiersIncludingOutsideAndInside = simData.getVarAndFunctionDataIdentifiers(outputContext); Vector<DataIdentifier> v = new Vector<DataIdentifier>(); for (int i = 0; i < dataIdentifiersIncludingOutsideAndInside.length; i++){ DataIdentifier di = dataIdentifiersIncludingOutsideAndInside[i]; if (!di.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX) && !di.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) { if (di.getVariableType() == null || di.getVariableType().equals(VariableType.UNKNOWN)) { if (di.isFunction()) { AnnotatedFunction f = getFunction(outputContext,vcdID,di.getName()); VariableType varType = getVariableTypeForFieldFunction(outputContext,vcdID, f); di = new DataIdentifier(di.getName(), varType, di.getDomain(), di.isFunction(), f.getDisplayName()); } } v.addElement(di); } } DataIdentifier[] ids = new DataIdentifier[v.size()]; v.copyInto(ids); return ids; } } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID) throws DataAccessException, IOException, FileNotFoundException { if (lg.isTraceEnabled()) lg.trace("DataSetControllerImpl.getDataIdentifiers("+vcdID.getID()+")"); VCData simData = getVCData(vcdID); DataIdentifier[] dataIdentifiersIncludingOutsideAndInside = simData.getVarAndFunctionDataIdentifiers(outputContext); Vector<DataIdentifier> v = new Vector<DataIdentifier>(); for (int i = 0; i < dataIdentifiersIncludingOutsideAndInside.length; i++){ DataIdentifier di = dataIdentifiersIncludingOutsideAndInside[i]; if (!di.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX) && !di.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) { if (di.getVariableType() == null || di.getVariableType().equals(VariableType.UNKNOWN)) { if (di.isFunction()) { AnnotatedFunction f = getFunction(outputContext,vcdID,di.getName()); VariableType varType = getVariableTypeForFieldFunction(outputContext,vcdID, f); di = new DataIdentifier(di.getName(), varType, di.getDomain(), di.isFunction(), f.getDisplayName()); } } v.addElement(di); } } DataIdentifier[] ids = new DataIdentifier[v.size()]; v.copyInto(ids); return ids; } DataSetControllerImpl(Cachetable aCacheTable, File primaryDir, File secondDir); } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID) throws DataAccessException, IOException, FileNotFoundException { if (lg.isTraceEnabled()) lg.trace("DataSetControllerImpl.getDataIdentifiers("+vcdID.getID()+")"); VCData simData = getVCData(vcdID); DataIdentifier[] dataIdentifiersIncludingOutsideAndInside = simData.getVarAndFunctionDataIdentifiers(outputContext); Vector<DataIdentifier> v = new Vector<DataIdentifier>(); for (int i = 0; i < dataIdentifiersIncludingOutsideAndInside.length; i++){ DataIdentifier di = dataIdentifiersIncludingOutsideAndInside[i]; if (!di.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX) && !di.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) { if (di.getVariableType() == null || di.getVariableType().equals(VariableType.UNKNOWN)) { if (di.isFunction()) { AnnotatedFunction f = getFunction(outputContext,vcdID,di.getName()); VariableType varType = getVariableTypeForFieldFunction(outputContext,vcdID, f); di = new DataIdentifier(di.getName(), varType, di.getDomain(), di.isFunction(), f.getDisplayName()); } } v.addElement(di); } } DataIdentifier[] ids = new DataIdentifier[v.size()]; v.copyInto(ids); return ids; } DataSetControllerImpl(Cachetable aCacheTable, File primaryDir, File secondDir); void addDataJobListener(DataJobListener newListener); DataOperationResults doDataOperation(DataOperation dataOperation); static DataOperationResults getDataProcessingOutput(DataOperation dataOperation,File dataProcessingOutputFileHDF5); FieldDataFileOperationResults fieldDataFileOperation(FieldDataFileOperationSpec fieldDataFileOperationSpec); DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID); double[] getDataSetTimes(VCDataIdentifier vcdID); AnnotatedFunction getFunction(OutputContext outputContext,VCDataIdentifier vcdID,String variableName); AnnotatedFunction[] getFunctions(OutputContext outputContext,VCDataIdentifier vcdID); PlotData getLineScan(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time, SpatialSelection spatialSelection); CartesianMesh getMesh(VCDataIdentifier vcdID); ODEDataBlock getODEDataBlock(VCDataIdentifier vcdID); ParticleDataBlock getParticleDataBlock(VCDataIdentifier vcdID, double time); boolean getParticleDataExists(VCDataIdentifier vcdID); SimDataBlock getSimDataBlock(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time); TimeSeriesJobResults getTimeSeriesValues(OutputContext outputContext,final VCDataIdentifier vcdID,final TimeSeriesJobSpec timeSeriesJobSpec); VCData getVCData(VCDataIdentifier vcdID); void removeDataJobListener(DataJobListener djListener); void setAllowOptimizedTimeDataRetrieval(boolean bAllowOptimizedTimeDataRetrieval); boolean isAllowOptimizedTimeDataRetrieval(); void writeFieldFunctionData(
OutputContext outputContext,
FieldDataIdentifierSpec[] argFieldDataIDSpecs,
boolean[] bResampleFlags,
CartesianMesh newMesh,
SimResampleInfoProvider simResampleInfoProvider,
int simResampleMembraneDataLength,
int handleExistingResampleMode); DataSetMetadata getDataSetMetadata(VCDataIdentifier vcdataID); DataSetTimeSeries getDataSetTimeSeries(VCDataIdentifier vcdataID, String[] variableNames); boolean getIsChombo(VCDataIdentifier vcdataID); boolean getIsMovingBoundary(VCDataIdentifier vcdataID); boolean getIsComsol(VCDataIdentifier vcdataID); ChomboFiles getChomboFiles(VCDataIdentifier vcdataID); VCellSimFiles getVCellSimFiles(VCDataIdentifier vcdataID); MovingBoundarySimFiles getMovingBoundarySimFiles(VCDataIdentifier vcdataID); ComsolSimFiles getComsolSimFiles(VCDataIdentifier vcdataID); VtuFileContainer getEmptyVtuMeshFiles(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(ChomboFiles chomboFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(VCellSimFiles vcellSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(MovingBoundarySimFiles movingBoundarySimFiles, VCDataIdentifier vcdataID, int timeIndex); double[] getVtuTimes(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID); double[] getVtuMeshData(ComsolSimFiles comsolSimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(MovingBoundarySimFiles movingBoundarySimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); VtuVarInfo[] getVtuVarInfos(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(MovingBoundarySimFiles movingBoundaryFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ComsolSimFiles comsolFiles, OutputContext outputContext, VCDataIdentifier vcdataID); NFSimMolecularConfigurations getNFSimMolecularConfigurations(VCDataIdentifier vcdID); } | DataSetControllerImpl implements SimDataConstants,DataJobListenerHolder { public DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID) throws DataAccessException, IOException, FileNotFoundException { if (lg.isTraceEnabled()) lg.trace("DataSetControllerImpl.getDataIdentifiers("+vcdID.getID()+")"); VCData simData = getVCData(vcdID); DataIdentifier[] dataIdentifiersIncludingOutsideAndInside = simData.getVarAndFunctionDataIdentifiers(outputContext); Vector<DataIdentifier> v = new Vector<DataIdentifier>(); for (int i = 0; i < dataIdentifiersIncludingOutsideAndInside.length; i++){ DataIdentifier di = dataIdentifiersIncludingOutsideAndInside[i]; if (!di.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX) && !di.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) { if (di.getVariableType() == null || di.getVariableType().equals(VariableType.UNKNOWN)) { if (di.isFunction()) { AnnotatedFunction f = getFunction(outputContext,vcdID,di.getName()); VariableType varType = getVariableTypeForFieldFunction(outputContext,vcdID, f); di = new DataIdentifier(di.getName(), varType, di.getDomain(), di.isFunction(), f.getDisplayName()); } } v.addElement(di); } } DataIdentifier[] ids = new DataIdentifier[v.size()]; v.copyInto(ids); return ids; } DataSetControllerImpl(Cachetable aCacheTable, File primaryDir, File secondDir); void addDataJobListener(DataJobListener newListener); DataOperationResults doDataOperation(DataOperation dataOperation); static DataOperationResults getDataProcessingOutput(DataOperation dataOperation,File dataProcessingOutputFileHDF5); FieldDataFileOperationResults fieldDataFileOperation(FieldDataFileOperationSpec fieldDataFileOperationSpec); DataIdentifier[] getDataIdentifiers(OutputContext outputContext, VCDataIdentifier vcdID); double[] getDataSetTimes(VCDataIdentifier vcdID); AnnotatedFunction getFunction(OutputContext outputContext,VCDataIdentifier vcdID,String variableName); AnnotatedFunction[] getFunctions(OutputContext outputContext,VCDataIdentifier vcdID); PlotData getLineScan(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time, SpatialSelection spatialSelection); CartesianMesh getMesh(VCDataIdentifier vcdID); ODEDataBlock getODEDataBlock(VCDataIdentifier vcdID); ParticleDataBlock getParticleDataBlock(VCDataIdentifier vcdID, double time); boolean getParticleDataExists(VCDataIdentifier vcdID); SimDataBlock getSimDataBlock(OutputContext outputContext, VCDataIdentifier vcdID, String varName, double time); TimeSeriesJobResults getTimeSeriesValues(OutputContext outputContext,final VCDataIdentifier vcdID,final TimeSeriesJobSpec timeSeriesJobSpec); VCData getVCData(VCDataIdentifier vcdID); void removeDataJobListener(DataJobListener djListener); void setAllowOptimizedTimeDataRetrieval(boolean bAllowOptimizedTimeDataRetrieval); boolean isAllowOptimizedTimeDataRetrieval(); void writeFieldFunctionData(
OutputContext outputContext,
FieldDataIdentifierSpec[] argFieldDataIDSpecs,
boolean[] bResampleFlags,
CartesianMesh newMesh,
SimResampleInfoProvider simResampleInfoProvider,
int simResampleMembraneDataLength,
int handleExistingResampleMode); DataSetMetadata getDataSetMetadata(VCDataIdentifier vcdataID); DataSetTimeSeries getDataSetTimeSeries(VCDataIdentifier vcdataID, String[] variableNames); boolean getIsChombo(VCDataIdentifier vcdataID); boolean getIsMovingBoundary(VCDataIdentifier vcdataID); boolean getIsComsol(VCDataIdentifier vcdataID); ChomboFiles getChomboFiles(VCDataIdentifier vcdataID); VCellSimFiles getVCellSimFiles(VCDataIdentifier vcdataID); MovingBoundarySimFiles getMovingBoundarySimFiles(VCDataIdentifier vcdataID); ComsolSimFiles getComsolSimFiles(VCDataIdentifier vcdataID); VtuFileContainer getEmptyVtuMeshFiles(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(ChomboFiles chomboFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(VCellSimFiles vcellSimFiles, VCDataIdentifier vcdataID, int timeIndex); VtuFileContainer getEmptyVtuMeshFiles(MovingBoundarySimFiles movingBoundarySimFiles, VCDataIdentifier vcdataID, int timeIndex); double[] getVtuTimes(ComsolSimFiles comsolSimFiles, VCDataIdentifier vcdataID); double[] getVtuMeshData(ComsolSimFiles comsolSimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(MovingBoundarySimFiles movingBoundarySimFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); double[] getVtuMeshData(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID, VtuVarInfo var, double time); VtuVarInfo[] getVtuVarInfos(VCellSimFiles vcellFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ChomboFiles chomboFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(MovingBoundarySimFiles movingBoundaryFiles, OutputContext outputContext, VCDataIdentifier vcdataID); VtuVarInfo[] getVtuVarInfos(ComsolSimFiles comsolFiles, OutputContext outputContext, VCDataIdentifier vcdataID); NFSimMolecularConfigurations getNFSimMolecularConfigurations(VCDataIdentifier vcdID); static final Logger lg; } |
@Test(expected = IllegalArgumentException.class) public void noZero( ) { KeyValue kv = new KeyValue("8675904"); String now = SimulationData.createCanonicalSmoldynOutputFileName(kv, 0, 0); System.out.println("never see " + now); } | public static String createCanonicalSmoldynOutputFileName(KeyValue fieldDataKey,int jobIndex,int timeIndex){ if (timeIndex > 0) { String rval = createSimIDWithJobIndex(fieldDataKey,jobIndex,false) + String.format("_%03d",timeIndex) + SimDataConstants.SMOLDYN_OUTPUT_FILE_EXTENSION; return rval; } throw new IllegalArgumentException("smoldyn output index must be > 0"); } | SimulationData extends VCData { public static String createCanonicalSmoldynOutputFileName(KeyValue fieldDataKey,int jobIndex,int timeIndex){ if (timeIndex > 0) { String rval = createSimIDWithJobIndex(fieldDataKey,jobIndex,false) + String.format("_%03d",timeIndex) + SimDataConstants.SMOLDYN_OUTPUT_FILE_EXTENSION; return rval; } throw new IllegalArgumentException("smoldyn output index must be > 0"); } } | SimulationData extends VCData { public static String createCanonicalSmoldynOutputFileName(KeyValue fieldDataKey,int jobIndex,int timeIndex){ if (timeIndex > 0) { String rval = createSimIDWithJobIndex(fieldDataKey,jobIndex,false) + String.format("_%03d",timeIndex) + SimDataConstants.SMOLDYN_OUTPUT_FILE_EXTENSION; return rval; } throw new IllegalArgumentException("smoldyn output index must be > 0"); } SimulationData(VCDataIdentifier argVCDataID, File primaryUserDir, File secondaryUserDir,SimDataAmplistorInfo simDataAmplistorInfo); } | SimulationData extends VCData { public static String createCanonicalSmoldynOutputFileName(KeyValue fieldDataKey,int jobIndex,int timeIndex){ if (timeIndex > 0) { String rval = createSimIDWithJobIndex(fieldDataKey,jobIndex,false) + String.format("_%03d",timeIndex) + SimDataConstants.SMOLDYN_OUTPUT_FILE_EXTENSION; return rval; } throw new IllegalArgumentException("smoldyn output index must be > 0"); } SimulationData(VCDataIdentifier argVCDataID, File primaryUserDir, File secondaryUserDir,SimDataAmplistorInfo simDataAmplistorInfo); static VCDataIdentifier createScanFriendlyVCDataID(VCDataIdentifier inVCDID); AnnotatedFunction simplifyFunction(AnnotatedFunction function); synchronized long getDataBlockTimeStamp(int dataType, double timepoint); synchronized double[] getDataTimesPostProcess(OutputContext outputContext); synchronized double[] getDataTimes(); SymbolTableEntry getEntry(String identifier); AnnotatedFunction getFunction(OutputContext outputContext,String identifier); AnnotatedFunction[] getFunctions(OutputContext outputContext); synchronized boolean getIsODEData(); File getLogFilePrivate(); synchronized CartesianMesh getPostProcessingMesh(String varName,OutputContext outputContext); synchronized CartesianMesh getMesh(); synchronized ODEDataBlock getODEDataBlock(); synchronized ParticleDataBlock getParticleDataBlock(double time); synchronized boolean getParticleDataExists(); synchronized VCDataIdentifier getResultsInfoObject(); synchronized SimDataBlock getSimDataBlock(OutputContext outputContext, String varName, double time); synchronized long getSizeInBytes(); synchronized DataIdentifier[] getVarAndFunctionDataIdentifiers(OutputContext outputContext); boolean isChombo(); @Override boolean isMovingBoundary(); @Override boolean isComsol(); synchronized void removeAllResults(); static String createCanonicalSimFilePathName(KeyValue fieldDataKey,int timeIndex,int jobIndex,boolean isOldStyle); static String createCanonicalSimTaskXMLFilePathName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalFieldDataLogFileName(KeyValue fieldDataKey); static String createCanonicalFieldFunctionSyntax(String externalDataIdentifierName,String varName,double beginTime,String extDataIdVariableTypeName); static String createCanonicalSimZipFileName(KeyValue fieldDataKey,Integer zipIndex,int jobIndex,boolean isOldStyle,boolean bHDF5); static String createCanonicalSimLogFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalSmoldynOutputFileName(KeyValue fieldDataKey,int jobIndex,int timeIndex); static String createCanonicalPostProcessFileName(VCDataIdentifier vcdID); static String createCanonicalNFSimOutputFileName(KeyValue fieldDataKey,int jobIndex); static String createCanonicalMeshFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalMeshMetricsFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalMovingBoundaryOutputFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalComsolOutputFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalFunctionsFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalSubdomainFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalResampleFileName(SimResampleInfoProvider simResampleInfoProvider,FieldFunctionArguments fieldFuncArgs); static String createSimIDWithJobIndex(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); void getEntries(Map<String, SymbolTableEntry> entryMap); boolean isPostProcessing(OutputContext outputContext,String varName); File getDataProcessingOutputSourceFileHDF5(); File getFieldDataFile(SimResampleInfoProvider simResampleInfoProvider,FieldFunctionArguments fieldFunctionArguments); File getMeshFile(boolean bHDF5); File getFunctionsFile(boolean bFirst); File getZipFile(boolean bHDF5,Integer zipIndex); File getSubdomainFile(); File getLogFile(); File getSmoldynOutputFile(int timeIndex); @Override ChomboFiles getChomboFiles(); @Override VCellSimFiles getVCellSimFiles(); @Override MovingBoundarySimFiles getMovingBoundarySimFiles(); @Override ComsolSimFiles getComsolSimFiles(); VCDataIdentifier getVcDataId(); synchronized SimDataBlock getChomboExtrapolatedValues(String varName, double time); static final VariableType getVariableTypeFromLength(CartesianMesh mesh, int dataLength); static String getDefaultFieldDataFileNameForSimulation(FieldFunctionArguments fieldFuncArgs); } | SimulationData extends VCData { public static String createCanonicalSmoldynOutputFileName(KeyValue fieldDataKey,int jobIndex,int timeIndex){ if (timeIndex > 0) { String rval = createSimIDWithJobIndex(fieldDataKey,jobIndex,false) + String.format("_%03d",timeIndex) + SimDataConstants.SMOLDYN_OUTPUT_FILE_EXTENSION; return rval; } throw new IllegalArgumentException("smoldyn output index must be > 0"); } SimulationData(VCDataIdentifier argVCDataID, File primaryUserDir, File secondaryUserDir,SimDataAmplistorInfo simDataAmplistorInfo); static VCDataIdentifier createScanFriendlyVCDataID(VCDataIdentifier inVCDID); AnnotatedFunction simplifyFunction(AnnotatedFunction function); synchronized long getDataBlockTimeStamp(int dataType, double timepoint); synchronized double[] getDataTimesPostProcess(OutputContext outputContext); synchronized double[] getDataTimes(); SymbolTableEntry getEntry(String identifier); AnnotatedFunction getFunction(OutputContext outputContext,String identifier); AnnotatedFunction[] getFunctions(OutputContext outputContext); synchronized boolean getIsODEData(); File getLogFilePrivate(); synchronized CartesianMesh getPostProcessingMesh(String varName,OutputContext outputContext); synchronized CartesianMesh getMesh(); synchronized ODEDataBlock getODEDataBlock(); synchronized ParticleDataBlock getParticleDataBlock(double time); synchronized boolean getParticleDataExists(); synchronized VCDataIdentifier getResultsInfoObject(); synchronized SimDataBlock getSimDataBlock(OutputContext outputContext, String varName, double time); synchronized long getSizeInBytes(); synchronized DataIdentifier[] getVarAndFunctionDataIdentifiers(OutputContext outputContext); boolean isChombo(); @Override boolean isMovingBoundary(); @Override boolean isComsol(); synchronized void removeAllResults(); static String createCanonicalSimFilePathName(KeyValue fieldDataKey,int timeIndex,int jobIndex,boolean isOldStyle); static String createCanonicalSimTaskXMLFilePathName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalFieldDataLogFileName(KeyValue fieldDataKey); static String createCanonicalFieldFunctionSyntax(String externalDataIdentifierName,String varName,double beginTime,String extDataIdVariableTypeName); static String createCanonicalSimZipFileName(KeyValue fieldDataKey,Integer zipIndex,int jobIndex,boolean isOldStyle,boolean bHDF5); static String createCanonicalSimLogFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalSmoldynOutputFileName(KeyValue fieldDataKey,int jobIndex,int timeIndex); static String createCanonicalPostProcessFileName(VCDataIdentifier vcdID); static String createCanonicalNFSimOutputFileName(KeyValue fieldDataKey,int jobIndex); static String createCanonicalMeshFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalMeshMetricsFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalMovingBoundaryOutputFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalComsolOutputFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalFunctionsFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalSubdomainFileName(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); static String createCanonicalResampleFileName(SimResampleInfoProvider simResampleInfoProvider,FieldFunctionArguments fieldFuncArgs); static String createSimIDWithJobIndex(KeyValue fieldDataKey,int jobIndex,boolean isOldStyle); void getEntries(Map<String, SymbolTableEntry> entryMap); boolean isPostProcessing(OutputContext outputContext,String varName); File getDataProcessingOutputSourceFileHDF5(); File getFieldDataFile(SimResampleInfoProvider simResampleInfoProvider,FieldFunctionArguments fieldFunctionArguments); File getMeshFile(boolean bHDF5); File getFunctionsFile(boolean bFirst); File getZipFile(boolean bHDF5,Integer zipIndex); File getSubdomainFile(); File getLogFile(); File getSmoldynOutputFile(int timeIndex); @Override ChomboFiles getChomboFiles(); @Override VCellSimFiles getVCellSimFiles(); @Override MovingBoundarySimFiles getMovingBoundarySimFiles(); @Override ComsolSimFiles getComsolSimFiles(); VCDataIdentifier getVcDataId(); synchronized SimDataBlock getChomboExtrapolatedValues(String varName, double time); static final VariableType getVariableTypeFromLength(CartesianMesh mesh, int dataLength); static String getDefaultFieldDataFileNameForSimulation(FieldFunctionArguments fieldFuncArgs); } |
@Test public void test_getSimTaskInfoFromSimJobName() throws NumberFormatException, HtcException { System.setProperty(PropertyLoader.vcellServerIDProperty,"ALPHA"); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_ALPHA_115785823_0_0")); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_BETA_115785823_0_0")); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_REL_115785823_0_0")); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_TEST_115785823_0_0")); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_TEST2_115785823_0_0")); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_TEST3_115785823_0_0")); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_TEST4_115785823_0_0")); Assert.assertEquals(new SimTaskInfo(new KeyValue("115785823"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_JUNK_115785823_0_0")); Assert.assertNotEquals(new SimTaskInfo(new KeyValue("555"),0,0), HtcProxy.getSimTaskInfoFromSimJobName("V_ALPHA_115785823_0_0")); try { HtcProxy.getSimTaskInfoFromSimJobName("V_ALPHA_115785823_0"); Assert.fail("SimTaskInfo "+"V_ALPHA_115785823_0"+" should have failed"); }catch (HtcException e){ } try { HtcProxy.getSimTaskInfoFromSimJobName("ALPHA_115785823_0_0"); Assert.fail("SimTaskInfo "+"V_ALPHA_115785823_0"+" should have failed"); }catch (HtcException e){ } } | public static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName) throws HtcException{ StringTokenizer tokens = new StringTokenizer(simJobName,"_"); String PREFIX = null; if (tokens.hasMoreTokens()){ PREFIX = tokens.nextToken(); } String SITE = null; if (tokens.hasMoreTokens()){ SITE = tokens.nextToken(); } String simIdString = null; if (tokens.hasMoreTokens()){ simIdString = tokens.nextToken(); } String jobIndexString = null; if (tokens.hasMoreTokens()){ jobIndexString = tokens.nextToken(); } String taskIdString = null; if (tokens.hasMoreTokens()){ taskIdString = tokens.nextToken(); } if (PREFIX.equals("V") && SITE!=null && simIdString!=null && jobIndexString!=null && taskIdString!=null){ KeyValue simId = new KeyValue(simIdString); int jobIndex = Integer.valueOf(jobIndexString); int taskId = Integer.valueOf(taskIdString); return new SimTaskInfo(simId,jobIndex,taskId); }else{ throw new HtcException("simJobName : "+simJobName+" not in expected format for a simulation job name"); } } | HtcProxy { public static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName) throws HtcException{ StringTokenizer tokens = new StringTokenizer(simJobName,"_"); String PREFIX = null; if (tokens.hasMoreTokens()){ PREFIX = tokens.nextToken(); } String SITE = null; if (tokens.hasMoreTokens()){ SITE = tokens.nextToken(); } String simIdString = null; if (tokens.hasMoreTokens()){ simIdString = tokens.nextToken(); } String jobIndexString = null; if (tokens.hasMoreTokens()){ jobIndexString = tokens.nextToken(); } String taskIdString = null; if (tokens.hasMoreTokens()){ taskIdString = tokens.nextToken(); } if (PREFIX.equals("V") && SITE!=null && simIdString!=null && jobIndexString!=null && taskIdString!=null){ KeyValue simId = new KeyValue(simIdString); int jobIndex = Integer.valueOf(jobIndexString); int taskId = Integer.valueOf(taskIdString); return new SimTaskInfo(simId,jobIndex,taskId); }else{ throw new HtcException("simJobName : "+simJobName+" not in expected format for a simulation job name"); } } } | HtcProxy { public static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName) throws HtcException{ StringTokenizer tokens = new StringTokenizer(simJobName,"_"); String PREFIX = null; if (tokens.hasMoreTokens()){ PREFIX = tokens.nextToken(); } String SITE = null; if (tokens.hasMoreTokens()){ SITE = tokens.nextToken(); } String simIdString = null; if (tokens.hasMoreTokens()){ simIdString = tokens.nextToken(); } String jobIndexString = null; if (tokens.hasMoreTokens()){ jobIndexString = tokens.nextToken(); } String taskIdString = null; if (tokens.hasMoreTokens()){ taskIdString = tokens.nextToken(); } if (PREFIX.equals("V") && SITE!=null && simIdString!=null && jobIndexString!=null && taskIdString!=null){ KeyValue simId = new KeyValue(simIdString); int jobIndex = Integer.valueOf(jobIndexString); int taskId = Integer.valueOf(taskIdString); return new SimTaskInfo(simId,jobIndex,taskId); }else{ throw new HtcException("simJobName : "+simJobName+" not in expected format for a simulation job name"); } } HtcProxy(CommandService commandService, String htcUser); } | HtcProxy { public static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName) throws HtcException{ StringTokenizer tokens = new StringTokenizer(simJobName,"_"); String PREFIX = null; if (tokens.hasMoreTokens()){ PREFIX = tokens.nextToken(); } String SITE = null; if (tokens.hasMoreTokens()){ SITE = tokens.nextToken(); } String simIdString = null; if (tokens.hasMoreTokens()){ simIdString = tokens.nextToken(); } String jobIndexString = null; if (tokens.hasMoreTokens()){ jobIndexString = tokens.nextToken(); } String taskIdString = null; if (tokens.hasMoreTokens()){ taskIdString = tokens.nextToken(); } if (PREFIX.equals("V") && SITE!=null && simIdString!=null && jobIndexString!=null && taskIdString!=null){ KeyValue simId = new KeyValue(simIdString); int jobIndex = Integer.valueOf(jobIndexString); int taskId = Integer.valueOf(taskIdString); return new SimTaskInfo(simId,jobIndex,taskId); }else{ throw new HtcException("simJobName : "+simJobName+" not in expected format for a simulation job name"); } } HtcProxy(CommandService commandService, String htcUser); static boolean isMyJob(HtcJobInfo htcJobInfo); abstract void killJobSafe(HtcJobInfo htcJobInfo); abstract void killJobUnsafe(HtcJobID htcJobId); abstract void killJobs(String htcJobSubstring); abstract Map<HtcJobInfo,HtcJobStatus> getJobStatus(List<HtcJobInfo> requestedHtcJobInfos); abstract HtcJobID submitJob(String jobName, File sub_file_internal, File sub_file_external, ExecutableCommand.Container commandSet,
int ncpus, double memSize, Collection<PortableCommand> postProcessingCommands, SimulationTask simTask,File primaryUserDirExternal); abstract HtcJobID submitOptimizationJob(String jobName, File sub_file_internal, File sub_file_external,File optProblemInput,File optProblemOutput); abstract HtcProxy cloneThreadsafe(); abstract Map<HtcJobInfo,HtcJobStatus> getRunningJobs(); abstract PartitionStatistics getPartitionStatistics(); final CommandService getCommandService(); final String getHtcUser(); static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName); static String createHtcSimJobName(SimTaskInfo simTaskInfo); static void writeUnixStyleTextFile(File file, String javaString); abstract String getSubmissionFileExtension(); static MemLimitResults getMemoryLimit(String vcellUserid,KeyValue simID,SolverDescription solverDescription,double estimatedMemSizeMB); static boolean isStochMultiTrial(SimulationTask simTask); } | HtcProxy { public static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName) throws HtcException{ StringTokenizer tokens = new StringTokenizer(simJobName,"_"); String PREFIX = null; if (tokens.hasMoreTokens()){ PREFIX = tokens.nextToken(); } String SITE = null; if (tokens.hasMoreTokens()){ SITE = tokens.nextToken(); } String simIdString = null; if (tokens.hasMoreTokens()){ simIdString = tokens.nextToken(); } String jobIndexString = null; if (tokens.hasMoreTokens()){ jobIndexString = tokens.nextToken(); } String taskIdString = null; if (tokens.hasMoreTokens()){ taskIdString = tokens.nextToken(); } if (PREFIX.equals("V") && SITE!=null && simIdString!=null && jobIndexString!=null && taskIdString!=null){ KeyValue simId = new KeyValue(simIdString); int jobIndex = Integer.valueOf(jobIndexString); int taskId = Integer.valueOf(taskIdString); return new SimTaskInfo(simId,jobIndex,taskId); }else{ throw new HtcException("simJobName : "+simJobName+" not in expected format for a simulation job name"); } } HtcProxy(CommandService commandService, String htcUser); static boolean isMyJob(HtcJobInfo htcJobInfo); abstract void killJobSafe(HtcJobInfo htcJobInfo); abstract void killJobUnsafe(HtcJobID htcJobId); abstract void killJobs(String htcJobSubstring); abstract Map<HtcJobInfo,HtcJobStatus> getJobStatus(List<HtcJobInfo> requestedHtcJobInfos); abstract HtcJobID submitJob(String jobName, File sub_file_internal, File sub_file_external, ExecutableCommand.Container commandSet,
int ncpus, double memSize, Collection<PortableCommand> postProcessingCommands, SimulationTask simTask,File primaryUserDirExternal); abstract HtcJobID submitOptimizationJob(String jobName, File sub_file_internal, File sub_file_external,File optProblemInput,File optProblemOutput); abstract HtcProxy cloneThreadsafe(); abstract Map<HtcJobInfo,HtcJobStatus> getRunningJobs(); abstract PartitionStatistics getPartitionStatistics(); final CommandService getCommandService(); final String getHtcUser(); static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName); static String createHtcSimJobName(SimTaskInfo simTaskInfo); static void writeUnixStyleTextFile(File file, String javaString); abstract String getSubmissionFileExtension(); static MemLimitResults getMemoryLimit(String vcellUserid,KeyValue simID,SolverDescription solverDescription,double estimatedMemSizeMB); static boolean isStochMultiTrial(SimulationTask simTask); static final Logger LG; final static String HTC_SIMULATION_JOB_NAME_PREFIX; static final boolean bDebugMemLimit; } |
@Test public void publisherTest( ) { User u = new User("schaff", testKey( )); Assert.assertTrue(u.isPublisher()); u = new User("fido", testKey( )); Assert.assertFalse(u.isPublisher()); } | public boolean isPublisher() { return Arrays.asList(publishers).contains(userName); } | User implements java.io.Serializable, Matchable, Immutable { public boolean isPublisher() { return Arrays.asList(publishers).contains(userName); } } | User implements java.io.Serializable, Matchable, Immutable { public boolean isPublisher() { return Arrays.asList(publishers).contains(userName); } User(String userid, KeyValue key); } | User implements java.io.Serializable, Matchable, Immutable { public boolean isPublisher() { return Arrays.asList(publishers).contains(userName); } User(String userid, KeyValue key); static String createGuestErrorMessage(String theOffendingOp); static boolean isGuest(String checkThisName); boolean compareEqual(Matchable obj); boolean equals(Object obj); KeyValue getID(); String getName(); int hashCode(); boolean isPublisher(); boolean isTestAccount(); static boolean isTestAccount(String accountName); String toString(); } | User implements java.io.Serializable, Matchable, Immutable { public boolean isPublisher() { return Arrays.asList(publishers).contains(userName); } User(String userid, KeyValue key); static String createGuestErrorMessage(String theOffendingOp); static boolean isGuest(String checkThisName); boolean compareEqual(Matchable obj); boolean equals(Object obj); KeyValue getID(); String getName(); int hashCode(); boolean isPublisher(); boolean isTestAccount(); static boolean isTestAccount(String accountName); String toString(); static final String[] publishers; static final User tempUser; static final String VCELL_GUEST; } |
@Test public void testAcctTest( ) { User u = new User("vcelltestaccount", testKey( )); Assert.assertTrue(u.isTestAccount()); u = new User("fido", testKey( )); Assert.assertFalse(u.isTestAccount()); } | public boolean isTestAccount() { return isTestAccount(getName( )); } | User implements java.io.Serializable, Matchable, Immutable { public boolean isTestAccount() { return isTestAccount(getName( )); } } | User implements java.io.Serializable, Matchable, Immutable { public boolean isTestAccount() { return isTestAccount(getName( )); } User(String userid, KeyValue key); } | User implements java.io.Serializable, Matchable, Immutable { public boolean isTestAccount() { return isTestAccount(getName( )); } User(String userid, KeyValue key); static String createGuestErrorMessage(String theOffendingOp); static boolean isGuest(String checkThisName); boolean compareEqual(Matchable obj); boolean equals(Object obj); KeyValue getID(); String getName(); int hashCode(); boolean isPublisher(); boolean isTestAccount(); static boolean isTestAccount(String accountName); String toString(); } | User implements java.io.Serializable, Matchable, Immutable { public boolean isTestAccount() { return isTestAccount(getName( )); } User(String userid, KeyValue key); static String createGuestErrorMessage(String theOffendingOp); static boolean isGuest(String checkThisName); boolean compareEqual(Matchable obj); boolean equals(Object obj); KeyValue getID(); String getName(); int hashCode(); boolean isPublisher(); boolean isTestAccount(); static boolean isTestAccount(String accountName); String toString(); static final String[] publishers; static final User tempUser; static final String VCELL_GUEST; } |
@Test public <T> void ctest( ) { ArrayList<Delta<Integer>> dt = new ArrayList<VCCollections.Delta<Integer>>( ); b.addAll(a); assertTrue(VCCollections.equal(a, b, cmp, null)); assertTrue(VCCollections.equal(a, b, cmp, dt)); for (int i = 0; i < 10 ;i++) { Collections.shuffle(b); assertTrue(VCCollections.equal(a, b, cmp, null)); assertTrue(VCCollections.equal(a, b, cmp, dt)); } b.add(7); assertFalse(VCCollections.equal(a, b, cmp, null)); assertFalse(VCCollections.equal(a, b, cmp, dt)); a.add(8); assertFalse(VCCollections.equal(a, b, cmp, null)); assertFalse(VCCollections.equal(a, b, cmp, dt)); } | public static <T> boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp) { return equal(a,b,cmp,null); } | VCCollections { public static <T> boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp) { return equal(a,b,cmp,null); } } | VCCollections { public static <T> boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp) { return equal(a,b,cmp,null); } } | VCCollections { public static <T> boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp) { return equal(a,b,cmp,null); } static boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp); static boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp , Collection<Delta<T> > diffs); } | VCCollections { public static <T> boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp) { return equal(a,b,cmp,null); } static boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp); static boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp , Collection<Delta<T> > diffs); } |
@Test public void tryIt( ) { insert(7,10); validate(7,8,9,10); list.clear(); insert(1,23); validate(19,20,21,22,23); list.add(7); validate(20,21,22,23,7); } | @Override public boolean add(E e) { storage.add(e); while (storage.size() > capacity()) { storage.pop(); } return true; } | CircularList extends AbstractCollection<E> { @Override public boolean add(E e) { storage.add(e); while (storage.size() > capacity()) { storage.pop(); } return true; } } | CircularList extends AbstractCollection<E> { @Override public boolean add(E e) { storage.add(e); while (storage.size() > capacity()) { storage.pop(); } return true; } CircularList(int capacity); } | CircularList extends AbstractCollection<E> { @Override public boolean add(E e) { storage.add(e); while (storage.size() > capacity()) { storage.pop(); } return true; } CircularList(int capacity); int capacity(); @Override boolean add(E e); @Override Iterator<E> iterator(); @Override int size(); } | CircularList extends AbstractCollection<E> { @Override public boolean add(E e) { storage.add(e); while (storage.size() > capacity()) { storage.pop(); } return true; } CircularList(int capacity); int capacity(); @Override boolean add(E e); @Override Iterator<E> iterator(); @Override int size(); } |
@Ignore @Test public void fetchAndConsume( ) { ReferenceQueue<CachedDataBaseReferenceReader> rq = new ReferenceQueue<CachedDataBaseReferenceReader>(); WeakReference<CachedDataBaseReferenceReader> weakR = new WeakReference<CachedDataBaseReferenceReader>( CachedDataBaseReferenceReader.getCachedReader(),rq); boolean outOfMem = false; ArrayList<int[]> pig = new ArrayList<int[]>( ); for (int size = 10;!outOfMem;size*=10) { try { assertFalse(weakR.isEnqueued()); pig.add(new int[size]); CachedDataBaseReferenceReader w = weakR.get( ); assertTrue(w == CachedDataBaseReferenceReader.getCachedReader()); } catch(OutOfMemoryError error) { assertTrue(weakR.isEnqueued()); assertTrue(weakR.get( ) == null); outOfMem = true; } } pig.clear(); CachedDataBaseReferenceReader dbReader = CachedDataBaseReferenceReader.getCachedReader(); assertTrue(dbReader != null); } | public static CachedDataBaseReferenceReader getCachedReader( ) { CachedDataBaseReferenceReader r = dbReader.get(); if (r != null) { return r; } synchronized(dbReader) { r = dbReader.get(); if (r != null) { return r; } r = new CachedDataBaseReferenceReader(); dbReader = new SoftReference<CachedDataBaseReferenceReader>(r); } return r; } | CachedDataBaseReferenceReader { public static CachedDataBaseReferenceReader getCachedReader( ) { CachedDataBaseReferenceReader r = dbReader.get(); if (r != null) { return r; } synchronized(dbReader) { r = dbReader.get(); if (r != null) { return r; } r = new CachedDataBaseReferenceReader(); dbReader = new SoftReference<CachedDataBaseReferenceReader>(r); } return r; } } | CachedDataBaseReferenceReader { public static CachedDataBaseReferenceReader getCachedReader( ) { CachedDataBaseReferenceReader r = dbReader.get(); if (r != null) { return r; } synchronized(dbReader) { r = dbReader.get(); if (r != null) { return r; } r = new CachedDataBaseReferenceReader(); dbReader = new SoftReference<CachedDataBaseReferenceReader>(r); } return r; } private CachedDataBaseReferenceReader( ); } | CachedDataBaseReferenceReader { public static CachedDataBaseReferenceReader getCachedReader( ) { CachedDataBaseReferenceReader r = dbReader.get(); if (r != null) { return r; } synchronized(dbReader) { r = dbReader.get(); if (r != null) { return r; } r = new CachedDataBaseReferenceReader(); dbReader = new SoftReference<CachedDataBaseReferenceReader>(r); } return r; } private CachedDataBaseReferenceReader( ); static CachedDataBaseReferenceReader getCachedReader( ); String getMoleculeDataBaseReference(String molId); String getChEBIName(String chebiId); String getGOTerm(String goId); String getMoleculeDataBaseReference(String db, String id); } | CachedDataBaseReferenceReader { public static CachedDataBaseReferenceReader getCachedReader( ) { CachedDataBaseReferenceReader r = dbReader.get(); if (r != null) { return r; } synchronized(dbReader) { r = dbReader.get(); if (r != null) { return r; } r = new CachedDataBaseReferenceReader(); dbReader = new SoftReference<CachedDataBaseReferenceReader>(r); } return r; } private CachedDataBaseReferenceReader( ); static CachedDataBaseReferenceReader getCachedReader( ); String getMoleculeDataBaseReference(String molId); String getChEBIName(String chebiId); String getGOTerm(String goId); String getMoleculeDataBaseReference(String db, String id); } |
@Test public void test_isMyJob(){ System.setProperty(PropertyLoader.vcellServerIDProperty,"ALPHA"); Assert.assertTrue(HtcProxy.isMyJob(new HtcJobInfo(new HtcJobID("1200725", BatchSystemType.SLURM),"V_ALPHA_115785823_0_0"))); Assert.assertFalse(HtcProxy.isMyJob(new HtcJobInfo(new HtcJobID("1200725", BatchSystemType.SLURM),"V_BETA_115785823_0_0"))); System.setProperty(PropertyLoader.vcellServerIDProperty,"BETA"); Assert.assertTrue(HtcProxy.isMyJob(new HtcJobInfo(new HtcJobID("1200725", BatchSystemType.SLURM),"V_BETA_115785823_0_0"))); } | public static boolean isMyJob(HtcJobInfo htcJobInfo){ return htcJobInfo.getJobName().startsWith(jobNamePrefix()); } | HtcProxy { public static boolean isMyJob(HtcJobInfo htcJobInfo){ return htcJobInfo.getJobName().startsWith(jobNamePrefix()); } } | HtcProxy { public static boolean isMyJob(HtcJobInfo htcJobInfo){ return htcJobInfo.getJobName().startsWith(jobNamePrefix()); } HtcProxy(CommandService commandService, String htcUser); } | HtcProxy { public static boolean isMyJob(HtcJobInfo htcJobInfo){ return htcJobInfo.getJobName().startsWith(jobNamePrefix()); } HtcProxy(CommandService commandService, String htcUser); static boolean isMyJob(HtcJobInfo htcJobInfo); abstract void killJobSafe(HtcJobInfo htcJobInfo); abstract void killJobUnsafe(HtcJobID htcJobId); abstract void killJobs(String htcJobSubstring); abstract Map<HtcJobInfo,HtcJobStatus> getJobStatus(List<HtcJobInfo> requestedHtcJobInfos); abstract HtcJobID submitJob(String jobName, File sub_file_internal, File sub_file_external, ExecutableCommand.Container commandSet,
int ncpus, double memSize, Collection<PortableCommand> postProcessingCommands, SimulationTask simTask,File primaryUserDirExternal); abstract HtcJobID submitOptimizationJob(String jobName, File sub_file_internal, File sub_file_external,File optProblemInput,File optProblemOutput); abstract HtcProxy cloneThreadsafe(); abstract Map<HtcJobInfo,HtcJobStatus> getRunningJobs(); abstract PartitionStatistics getPartitionStatistics(); final CommandService getCommandService(); final String getHtcUser(); static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName); static String createHtcSimJobName(SimTaskInfo simTaskInfo); static void writeUnixStyleTextFile(File file, String javaString); abstract String getSubmissionFileExtension(); static MemLimitResults getMemoryLimit(String vcellUserid,KeyValue simID,SolverDescription solverDescription,double estimatedMemSizeMB); static boolean isStochMultiTrial(SimulationTask simTask); } | HtcProxy { public static boolean isMyJob(HtcJobInfo htcJobInfo){ return htcJobInfo.getJobName().startsWith(jobNamePrefix()); } HtcProxy(CommandService commandService, String htcUser); static boolean isMyJob(HtcJobInfo htcJobInfo); abstract void killJobSafe(HtcJobInfo htcJobInfo); abstract void killJobUnsafe(HtcJobID htcJobId); abstract void killJobs(String htcJobSubstring); abstract Map<HtcJobInfo,HtcJobStatus> getJobStatus(List<HtcJobInfo> requestedHtcJobInfos); abstract HtcJobID submitJob(String jobName, File sub_file_internal, File sub_file_external, ExecutableCommand.Container commandSet,
int ncpus, double memSize, Collection<PortableCommand> postProcessingCommands, SimulationTask simTask,File primaryUserDirExternal); abstract HtcJobID submitOptimizationJob(String jobName, File sub_file_internal, File sub_file_external,File optProblemInput,File optProblemOutput); abstract HtcProxy cloneThreadsafe(); abstract Map<HtcJobInfo,HtcJobStatus> getRunningJobs(); abstract PartitionStatistics getPartitionStatistics(); final CommandService getCommandService(); final String getHtcUser(); static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName); static String createHtcSimJobName(SimTaskInfo simTaskInfo); static void writeUnixStyleTextFile(File file, String javaString); abstract String getSubmissionFileExtension(); static MemLimitResults getMemoryLimit(String vcellUserid,KeyValue simID,SolverDescription solverDescription,double estimatedMemSizeMB); static boolean isStochMultiTrial(SimulationTask simTask); static final Logger LG; final static String HTC_SIMULATION_JOB_NAME_PREFIX; static final boolean bDebugMemLimit; } |
@Test public void example( ) { Assert.assertEquals("uM*s^-1", new UnitSymbol("uM.s-1").getUnitSymbolAsInfix()); } | public String getUnitSymbolAsInfix() { return rootNode.toInfix(); } | UnitSymbol implements Serializable { public String getUnitSymbolAsInfix() { return rootNode.toInfix(); } } | UnitSymbol implements Serializable { public String getUnitSymbolAsInfix() { return rootNode.toInfix(); } UnitSymbol(String unitStr); } | UnitSymbol implements Serializable { public String getUnitSymbolAsInfix() { return rootNode.toInfix(); } UnitSymbol(String unitStr); String getUnitSymbolAsInfix(); String getUnitSymbolAsInfixWithoutFloatScale(); double getNumericScale(); String getUnitSymbol(); String getUnitSymbolUnicode(); String getUnitSymbolHtml(); } | UnitSymbol implements Serializable { public String getUnitSymbolAsInfix() { return rootNode.toInfix(); } UnitSymbol(String unitStr); String getUnitSymbolAsInfix(); String getUnitSymbolAsInfixWithoutFloatScale(); double getNumericScale(); String getUnitSymbol(); String getUnitSymbolUnicode(); String getUnitSymbolHtml(); } |
@Test public void notSwingCheck( ) { VCellThreadChecker.checkCpuIntensiveInvocation(); checkQuiet( ); } | public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } |
@Test public void swingCheck( ) throws InvocationTargetException, InterruptedException { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { VCellThreadChecker.checkSwingInvocation(); } }); checkQuiet( ); } | public static void checkSwingInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (!guiThreadChecker.isEventDispatchThread()) { System.out.println("!!!!!!!!!!!!!! --calling swing from non-swing thread-----"); Thread.dumpStack(); } } | VCellThreadChecker { public static void checkSwingInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (!guiThreadChecker.isEventDispatchThread()) { System.out.println("!!!!!!!!!!!!!! --calling swing from non-swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkSwingInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (!guiThreadChecker.isEventDispatchThread()) { System.out.println("!!!!!!!!!!!!!! --calling swing from non-swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkSwingInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (!guiThreadChecker.isEventDispatchThread()) { System.out.println("!!!!!!!!!!!!!! --calling swing from non-swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } | VCellThreadChecker { public static void checkSwingInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (!guiThreadChecker.isEventDispatchThread()) { System.out.println("!!!!!!!!!!!!!! --calling swing from non-swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } |
@Test public void swingCheckSupp( ) throws InvocationTargetException, InterruptedException { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try (VCellThreadChecker.SuppressIntensive si = new VCellThreadChecker.SuppressIntensive()) { subCall( ); VCellThreadChecker.checkCpuIntensiveInvocation(); } } }); checkQuiet( ); } | public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } |
@Test(expected=IllegalStateException.class) public void swingCheckNotSupp( ) throws InvocationTargetException, InterruptedException { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try (VCellThreadChecker.SuppressIntensive si = new VCellThreadChecker.SuppressIntensive()) { } VCellThreadChecker.checkCpuIntensiveInvocation(); } }); checkQuiet( ); } | public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } | VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); } |
@Test public void goodConvert( ) { ArrayList<Object> al = new ArrayList<Object>( ); for (int i = 0; i < 5; i++) { al.add(Integer.valueOf(i)); } List<Integer> asIntArray = GenericUtils.convert(al, Integer.class); for (int i = 0; i < 5; i++) { assertTrue(asIntArray.get(i) == i); } } | @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } @SuppressWarnings("unchecked") static java.util.List<T> convert(java.util.List<?> list, Class<T> clzz); } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } @SuppressWarnings("unchecked") static java.util.List<T> convert(java.util.List<?> list, Class<T> clzz); } |
@Test(expected = RuntimeException.class) public void badConvert( ) { ArrayList<Object> al = new ArrayList<Object>( ); for (int i = 0; i < 5; i++) { al.add(Integer.valueOf(i)); } List<String> asIntArray = GenericUtils.convert(al, String.class); System.out.println(asIntArray); } | @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } @SuppressWarnings("unchecked") static java.util.List<T> convert(java.util.List<?> list, Class<T> clzz); } | GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } @SuppressWarnings("unchecked") static java.util.List<T> convert(java.util.List<?> list, Class<T> clzz); } |
@Test public void testStreamingResultSet() throws IOException { BufferedReader bufferedReader = new BufferedReader(new StringReader("?s\t?p\t?o\n" + "<http: + "<http: + "<http: List<Map<String, Node>> result = new ArrayList<>(); try (StreamingResultSet resultSet = new StreamingResultSet(bufferedReader)) { assertArrayEquals(new String[] {"s", "p", "o"}, resultSet.getResultVars()); int rowsRead = 0; assertEquals(rowsRead, resultSet.getRowNumber()); while (resultSet.hasNext()) { Map<String, Node> rs = resultSet.next(); System.out.println(rs); result.add(rs); rowsRead++; assertEquals(rowsRead, resultSet.getRowNumber()); } } assertEquals(3, result.size()); } | public StreamingResultSet(BufferedReader in) throws IOException { this.in = in; tsvParser = new TsvParser(in); if ((currentTuple = tsvParser.getTuple()) == null) { hasNext = false; } } | StreamingResultSet implements Iterator<Map<String, Node>>, Closeable { public StreamingResultSet(BufferedReader in) throws IOException { this.in = in; tsvParser = new TsvParser(in); if ((currentTuple = tsvParser.getTuple()) == null) { hasNext = false; } } } | StreamingResultSet implements Iterator<Map<String, Node>>, Closeable { public StreamingResultSet(BufferedReader in) throws IOException { this.in = in; tsvParser = new TsvParser(in); if ((currentTuple = tsvParser.getTuple()) == null) { hasNext = false; } } StreamingResultSet(BufferedReader in); StreamingResultSet(HttpURLConnection conn); } | StreamingResultSet implements Iterator<Map<String, Node>>, Closeable { public StreamingResultSet(BufferedReader in) throws IOException { this.in = in; tsvParser = new TsvParser(in); if ((currentTuple = tsvParser.getTuple()) == null) { hasNext = false; } } StreamingResultSet(BufferedReader in); StreamingResultSet(HttpURLConnection conn); @Override Map<String, Node> next(); String[] getResultVars(); @Override void close(); @Override boolean hasNext(); } | StreamingResultSet implements Iterator<Map<String, Node>>, Closeable { public StreamingResultSet(BufferedReader in) throws IOException { this.in = in; tsvParser = new TsvParser(in); if ((currentTuple = tsvParser.getTuple()) == null) { hasNext = false; } } StreamingResultSet(BufferedReader in); StreamingResultSet(HttpURLConnection conn); @Override Map<String, Node> next(); String[] getResultVars(); @Override void close(); @Override boolean hasNext(); } |
@Test public void testResourceEnding() throws IOException { Map<String, Node> result = parseSingleTuple("?s\n" + "<http: assertEquals(NodeFactoryExtra.parseNode("<http: } | private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } |
@Test public void testEmptyVariablesInResult() throws IOException { Map<String, Node> result = parseSingleTuple("?s\t?p\t?o\n" + "<http: assertEquals(NodeFactoryExtra.parseNode("<http: assertFalse(result.containsKey("p")); assertEquals(NodeFactoryExtra.parseNode("\"o2\""), result.get("o")); } | private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } |
@Test public void testMultipleEmptyVariablesInResult() throws IOException { Map<String, Node> result; result = parseSingleTuple("?s\t?p\t?o\n" + "\t\t\"o2\"\n"); assertFalse(result.containsKey("s")); assertFalse(result.containsKey("p")); assertEquals(NodeFactoryExtra.parseNode("\"o2\""), result.get("o")); result = parseSingleTuple("?s\t?p\t?o\n" + "<http: assertEquals(NodeFactoryExtra.parseNode("<http: assertFalse(result.containsKey("p")); assertFalse(result.containsKey("o")); result = parseSingleTuple("?s\t?p\t?o\n" + "\t\t\t\n"); assertEquals(0, result.size()); } | private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } |
@Test public void testNodeParser() { Node parseNode = NodeFactoryExtra.parseNode("\"Hallo \\\"Echo\\\"!\"@de"); assertEquals("de", parseNode.getLiteralLanguage()); assertEquals("Hallo \"Echo\"!", parseNode.getLiteralValue()); } | private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } | TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); } |
@Test public void testConversionForFXDependency() { IFeaturePlugin featurePlugin = Mockito.mock(IFeaturePlugin.class); Mockito.when(featurePlugin.getId()).thenReturn(FEATURE_PLUGIN_ID_FX); Mockito.when(featurePlugin.getVersion()).thenReturn(FEATURE_PLUGIN_VERSION_FX); Set<Dependency> dependencies = FeaturePluginToMavenDependencyConverter.convert(new HashSet<>(Arrays.asList(featurePlugin))); assertThat(dependencies.size(), equalTo(1)); if (dependencies.size() == 1) { Dependency dependency = dependencies.iterator().next(); assertThat(dependency.getGroupId(), equalTo("at.bestsolution.efxclipse.rt")); assertThat(dependency.getArtifactId(), equalTo(FEATURE_PLUGIN_ID_FX)); assertThat(dependency.getVersion(), equalTo("3.0.0")); } } | static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } |
@Test public void testConversionForNonFXDependency() { IFeaturePlugin featurePlugin = Mockito.mock(IFeaturePlugin.class); Mockito.when(featurePlugin.getId()).thenReturn(FEATURE_PLUGIN_ID_NON_FX); Mockito.when(featurePlugin.getVersion()).thenReturn(FEATURE_PLUGIN_VERSION_NON_FX); Set<Dependency> dependencies = FeaturePluginToMavenDependencyConverter.convert(new HashSet<>(Arrays.asList(featurePlugin))); assertThat(dependencies.size(), equalTo(1)); if (dependencies.size() == 1) { Dependency dependency = dependencies.iterator().next(); assertThat(dependency.getGroupId(), equalTo("at.bestsolution.efxclipse.eclipse")); assertThat(dependency.getArtifactId(), equalTo(FEATURE_PLUGIN_ID_NON_FX)); assertThat(dependency.getVersion(), equalTo("0.10.0")); } } | static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } | FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } } |
@Test public void testRead() { try { InputStream inputStream = JarAccessor.readEntry(JarAccessorTest.class.getResource(FEATURE_TEST_JAR).toURI().toString(), FEATURE_TEST_XML); assertNotNull(inputStream); } catch (URISyntaxException e) { e.printStackTrace(); fail(); } } | static InputStream readEntry(String jarUrl, String entryName) { try { URL url = new URL(convertToJarUrl(jarUrl)); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); return jarFile.getInputStream(jarFile.getEntry(entryName)); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } return null; } | JarAccessor { static InputStream readEntry(String jarUrl, String entryName) { try { URL url = new URL(convertToJarUrl(jarUrl)); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); return jarFile.getInputStream(jarFile.getEntry(entryName)); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } return null; } } | JarAccessor { static InputStream readEntry(String jarUrl, String entryName) { try { URL url = new URL(convertToJarUrl(jarUrl)); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); return jarFile.getInputStream(jarFile.getEntry(entryName)); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } return null; } } | JarAccessor { static InputStream readEntry(String jarUrl, String entryName) { try { URL url = new URL(convertToJarUrl(jarUrl)); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); return jarFile.getInputStream(jarFile.getEntry(entryName)); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } return null; } } | JarAccessor { static InputStream readEntry(String jarUrl, String entryName) { try { URL url = new URL(convertToJarUrl(jarUrl)); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); return jarFile.getInputStream(jarFile.getEntry(entryName)); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } return null; } } |
@Test public void testDependencyAdder() { InputStream resource = FeaturePluginFilter.class.getResourceAsStream(ADDITIONAL_DEPENDENCIES_FILE); Set<Dependency> dependencies = AdditionalDependencyProvider.readAdditionalDependencies(resource); assertThat(dependencies.size(), equalTo(1)); if (dependencies.size() == 1) { Dependency dependency = dependencies.iterator().next(); assertThat(dependency.getGroupId(), equalTo(GROUP_ID)); assertThat(dependency.getArtifactId(), equalTo(ARTIFACT_ID)); assertThat(dependency.getVersion(), equalTo(VERSION)); } } | static Set<Dependency> readAdditionalDependencies(InputStream additionalDependenciesFile) { Set<Dependency> additionalDependencies = new HashSet<>(); try (Scanner sc = new Scanner(additionalDependenciesFile)) { while (sc.hasNextLine()) { handleDependency(additionalDependencies, sc.nextLine(), additionalDependenciesFile.toString()); } } return additionalDependencies; } | AdditionalDependencyProvider { static Set<Dependency> readAdditionalDependencies(InputStream additionalDependenciesFile) { Set<Dependency> additionalDependencies = new HashSet<>(); try (Scanner sc = new Scanner(additionalDependenciesFile)) { while (sc.hasNextLine()) { handleDependency(additionalDependencies, sc.nextLine(), additionalDependenciesFile.toString()); } } return additionalDependencies; } } | AdditionalDependencyProvider { static Set<Dependency> readAdditionalDependencies(InputStream additionalDependenciesFile) { Set<Dependency> additionalDependencies = new HashSet<>(); try (Scanner sc = new Scanner(additionalDependenciesFile)) { while (sc.hasNextLine()) { handleDependency(additionalDependencies, sc.nextLine(), additionalDependenciesFile.toString()); } } return additionalDependencies; } } | AdditionalDependencyProvider { static Set<Dependency> readAdditionalDependencies(InputStream additionalDependenciesFile) { Set<Dependency> additionalDependencies = new HashSet<>(); try (Scanner sc = new Scanner(additionalDependenciesFile)) { while (sc.hasNextLine()) { handleDependency(additionalDependencies, sc.nextLine(), additionalDependenciesFile.toString()); } } return additionalDependencies; } } | AdditionalDependencyProvider { static Set<Dependency> readAdditionalDependencies(InputStream additionalDependenciesFile) { Set<Dependency> additionalDependencies = new HashSet<>(); try (Scanner sc = new Scanner(additionalDependenciesFile)) { while (sc.hasNextLine()) { handleDependency(additionalDependencies, sc.nextLine(), additionalDependenciesFile.toString()); } } return additionalDependencies; } } |
@Test public void testExtractFeaturePlugins() { Set<IFeaturePlugin> featurePlugins = FeaturePluginExtractor .extractFeaturePlugins(getClass().getResourceAsStream(FEATURE_TEST_XML)); assertThat(featurePlugins.size(), equalTo(1)); if (featurePlugins.size() == 1) { IFeaturePlugin featurePlugin = featurePlugins.iterator().next(); assertThat(featurePlugin.getId(), equalTo(FEATURE_ID)); assertThat(featurePlugin.getVersion(), equalTo(FEATURE_VERSION)); } } | static Set<IFeaturePlugin> extractFeaturePlugins(InputStream featureInputStream) { WorkspaceFeatureModel fmodel = new WorkspaceFeatureModel(new FileWrapper(featureInputStream)); fmodel.load(); Map<String, IFeaturePlugin> map = new HashMap<>(); Arrays.stream(fmodel.getFeature().getPlugins()).forEach(p -> map.put(p.getId(), p)); return new HashSet<>(map.values()); } | FeaturePluginExtractor { static Set<IFeaturePlugin> extractFeaturePlugins(InputStream featureInputStream) { WorkspaceFeatureModel fmodel = new WorkspaceFeatureModel(new FileWrapper(featureInputStream)); fmodel.load(); Map<String, IFeaturePlugin> map = new HashMap<>(); Arrays.stream(fmodel.getFeature().getPlugins()).forEach(p -> map.put(p.getId(), p)); return new HashSet<>(map.values()); } } | FeaturePluginExtractor { static Set<IFeaturePlugin> extractFeaturePlugins(InputStream featureInputStream) { WorkspaceFeatureModel fmodel = new WorkspaceFeatureModel(new FileWrapper(featureInputStream)); fmodel.load(); Map<String, IFeaturePlugin> map = new HashMap<>(); Arrays.stream(fmodel.getFeature().getPlugins()).forEach(p -> map.put(p.getId(), p)); return new HashSet<>(map.values()); } } | FeaturePluginExtractor { static Set<IFeaturePlugin> extractFeaturePlugins(InputStream featureInputStream) { WorkspaceFeatureModel fmodel = new WorkspaceFeatureModel(new FileWrapper(featureInputStream)); fmodel.load(); Map<String, IFeaturePlugin> map = new HashMap<>(); Arrays.stream(fmodel.getFeature().getPlugins()).forEach(p -> map.put(p.getId(), p)); return new HashSet<>(map.values()); } } | FeaturePluginExtractor { static Set<IFeaturePlugin> extractFeaturePlugins(InputStream featureInputStream) { WorkspaceFeatureModel fmodel = new WorkspaceFeatureModel(new FileWrapper(featureInputStream)); fmodel.load(); Map<String, IFeaturePlugin> map = new HashMap<>(); Arrays.stream(fmodel.getFeature().getPlugins()).forEach(p -> map.put(p.getId(), p)); return new HashSet<>(map.values()); } } |
@Test public void testExctractRelativeUrl() { String jarPath = UpdateSiteAccessor.extractRelativeTargetPlatformFeatureJarUrl(getClass().getResourceAsStream(SITE_TEST_XML), JAR_PREFIX); assertThat(jarPath, equalTo(JAR_PATH)); } | static String extractRelativeTargetPlatformFeatureJarUrl(InputStream siteInputStream, String urlPrefix) { WorkspaceSiteModel model = new WorkspaceSiteModel(new FileWrapper(siteInputStream)); model.load(); for (ISiteFeature f : model.getSite().getFeatures()) { if (f.getURL().startsWith(urlPrefix)) { return f.getURL(); } } return null; } | UpdateSiteAccessor { static String extractRelativeTargetPlatformFeatureJarUrl(InputStream siteInputStream, String urlPrefix) { WorkspaceSiteModel model = new WorkspaceSiteModel(new FileWrapper(siteInputStream)); model.load(); for (ISiteFeature f : model.getSite().getFeatures()) { if (f.getURL().startsWith(urlPrefix)) { return f.getURL(); } } return null; } } | UpdateSiteAccessor { static String extractRelativeTargetPlatformFeatureJarUrl(InputStream siteInputStream, String urlPrefix) { WorkspaceSiteModel model = new WorkspaceSiteModel(new FileWrapper(siteInputStream)); model.load(); for (ISiteFeature f : model.getSite().getFeatures()) { if (f.getURL().startsWith(urlPrefix)) { return f.getURL(); } } return null; } } | UpdateSiteAccessor { static String extractRelativeTargetPlatformFeatureJarUrl(InputStream siteInputStream, String urlPrefix) { WorkspaceSiteModel model = new WorkspaceSiteModel(new FileWrapper(siteInputStream)); model.load(); for (ISiteFeature f : model.getSite().getFeatures()) { if (f.getURL().startsWith(urlPrefix)) { return f.getURL(); } } return null; } } | UpdateSiteAccessor { static String extractRelativeTargetPlatformFeatureJarUrl(InputStream siteInputStream, String urlPrefix) { WorkspaceSiteModel model = new WorkspaceSiteModel(new FileWrapper(siteInputStream)); model.load(); for (ISiteFeature f : model.getSite().getFeatures()) { if (f.getURL().startsWith(urlPrefix)) { return f.getURL(); } } return null; } } |
@Test public void testReadRelativeUrl() { try { URL resource = getClass().getResource(SITE_TEST_XML); String jarPath = UpdateSiteAccessor.readRelativeTargetPlatformFeatureJarUrl(resource.toURI().toString(), JAR_PREFIX, null); assertThat(jarPath, equalTo(JAR_PATH)); } catch (URISyntaxException e) { fail(e.getMessage()); } } | static String readRelativeTargetPlatformFeatureJarUrl(String siteUrl, String targetJarUrlPrefix, Proxy proxy) { try { URL url = new URL(siteUrl); if (proxy != null) { LoggingSupport.logInfoMessage("Using proxy (" + proxy.address() + ") for getting the targetplatform feature at URL " + siteUrl); } URLConnection connection = proxy != null ? url.openConnection(proxy) : url.openConnection(); InputStream siteInputStream = connection.getInputStream(); return extractRelativeTargetPlatformFeatureJarUrl(siteInputStream, targetJarUrlPrefix); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); return null; } } | UpdateSiteAccessor { static String readRelativeTargetPlatformFeatureJarUrl(String siteUrl, String targetJarUrlPrefix, Proxy proxy) { try { URL url = new URL(siteUrl); if (proxy != null) { LoggingSupport.logInfoMessage("Using proxy (" + proxy.address() + ") for getting the targetplatform feature at URL " + siteUrl); } URLConnection connection = proxy != null ? url.openConnection(proxy) : url.openConnection(); InputStream siteInputStream = connection.getInputStream(); return extractRelativeTargetPlatformFeatureJarUrl(siteInputStream, targetJarUrlPrefix); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); return null; } } } | UpdateSiteAccessor { static String readRelativeTargetPlatformFeatureJarUrl(String siteUrl, String targetJarUrlPrefix, Proxy proxy) { try { URL url = new URL(siteUrl); if (proxy != null) { LoggingSupport.logInfoMessage("Using proxy (" + proxy.address() + ") for getting the targetplatform feature at URL " + siteUrl); } URLConnection connection = proxy != null ? url.openConnection(proxy) : url.openConnection(); InputStream siteInputStream = connection.getInputStream(); return extractRelativeTargetPlatformFeatureJarUrl(siteInputStream, targetJarUrlPrefix); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); return null; } } } | UpdateSiteAccessor { static String readRelativeTargetPlatformFeatureJarUrl(String siteUrl, String targetJarUrlPrefix, Proxy proxy) { try { URL url = new URL(siteUrl); if (proxy != null) { LoggingSupport.logInfoMessage("Using proxy (" + proxy.address() + ") for getting the targetplatform feature at URL " + siteUrl); } URLConnection connection = proxy != null ? url.openConnection(proxy) : url.openConnection(); InputStream siteInputStream = connection.getInputStream(); return extractRelativeTargetPlatformFeatureJarUrl(siteInputStream, targetJarUrlPrefix); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); return null; } } } | UpdateSiteAccessor { static String readRelativeTargetPlatformFeatureJarUrl(String siteUrl, String targetJarUrlPrefix, Proxy proxy) { try { URL url = new URL(siteUrl); if (proxy != null) { LoggingSupport.logInfoMessage("Using proxy (" + proxy.address() + ") for getting the targetplatform feature at URL " + siteUrl); } URLConnection connection = proxy != null ? url.openConnection(proxy) : url.openConnection(); InputStream siteInputStream = connection.getInputStream(); return extractRelativeTargetPlatformFeatureJarUrl(siteInputStream, targetJarUrlPrefix); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); return null; } } } |
@Test public void testPomGeneration() throws IOException { File pomFile = createDestinationFile(); Set<Dependency> dependencies = generateDependencies(); PomWriter.writePom(pomFile, GROUP_ID, ARTIFACT_ID, VERSION, dependencies); Scanner scanner = new Scanner(pomFile); StringWriter writer = new StringWriter(); String generatedFileContent = scanner.useDelimiter(DELIMITER).next(); IOUtils.copy(getClass().getResourceAsStream(POM_CMP_XML), writer); String expectedFileContent = writer.toString(); scanner.close(); assertThat(generatedFileContent.replaceAll("\\s+", ""), equalTo(expectedFileContent.replaceAll("\\s+", ""))); pomFile.delete(); } | static void writePom(File file, String groupId, String artifactId, String version, Set<Dependency> dependencies) { Model model = new Model(); model.setModelVersion(MAVEN_MODEL_VERSION); model.setArtifactId(artifactId); model.setGroupId(groupId); model.setVersion(version); model.setPackaging(PACKAGING_TYPE); model.setDependencies(new ArrayList<>(dependencies)); DefaultModelWriter writer = new DefaultModelWriter(); try { writer.write(file, (Map<String, Object>) null, model); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } } | PomWriter { static void writePom(File file, String groupId, String artifactId, String version, Set<Dependency> dependencies) { Model model = new Model(); model.setModelVersion(MAVEN_MODEL_VERSION); model.setArtifactId(artifactId); model.setGroupId(groupId); model.setVersion(version); model.setPackaging(PACKAGING_TYPE); model.setDependencies(new ArrayList<>(dependencies)); DefaultModelWriter writer = new DefaultModelWriter(); try { writer.write(file, (Map<String, Object>) null, model); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } } } | PomWriter { static void writePom(File file, String groupId, String artifactId, String version, Set<Dependency> dependencies) { Model model = new Model(); model.setModelVersion(MAVEN_MODEL_VERSION); model.setArtifactId(artifactId); model.setGroupId(groupId); model.setVersion(version); model.setPackaging(PACKAGING_TYPE); model.setDependencies(new ArrayList<>(dependencies)); DefaultModelWriter writer = new DefaultModelWriter(); try { writer.write(file, (Map<String, Object>) null, model); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } } } | PomWriter { static void writePom(File file, String groupId, String artifactId, String version, Set<Dependency> dependencies) { Model model = new Model(); model.setModelVersion(MAVEN_MODEL_VERSION); model.setArtifactId(artifactId); model.setGroupId(groupId); model.setVersion(version); model.setPackaging(PACKAGING_TYPE); model.setDependencies(new ArrayList<>(dependencies)); DefaultModelWriter writer = new DefaultModelWriter(); try { writer.write(file, (Map<String, Object>) null, model); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } } } | PomWriter { static void writePom(File file, String groupId, String artifactId, String version, Set<Dependency> dependencies) { Model model = new Model(); model.setModelVersion(MAVEN_MODEL_VERSION); model.setArtifactId(artifactId); model.setGroupId(groupId); model.setVersion(version); model.setPackaging(PACKAGING_TYPE); model.setDependencies(new ArrayList<>(dependencies)); DefaultModelWriter writer = new DefaultModelWriter(); try { writer.write(file, (Map<String, Object>) null, model); } catch (IOException e) { LoggingSupport.logErrorMessage(e.getMessage(), e); } } } |
@Test public void composer() throws Exception { Intent someIntent = new Intent(); ActivityResult testResult = new ActivityResult(Activity.RESULT_OK, Activity.RESULT_OK, someIntent); TestObserver<ActivityResult> composerTest = trigger().compose(rxActivityResults.composer(someIntent)).test(); rxActivityResults.onActivityResult(testResult.getResultCode(), someIntent); composerTest.assertNoErrors() .assertSubscribed() .assertComplete() .assertValueCount(1) .assertValue(testResult); } | public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } RxActivityResults(@NonNull Activity activity); } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } |
@Test(expected = IllegalArgumentException.class) public void requestNullIntent() throws Exception { TestObserver<ActivityResult> composerTest = trigger().compose(rxActivityResults.composer(null)).test(); composerTest.assertError(IllegalArgumentException.class) .assertSubscribed() .assertComplete() .assertValueCount(0); } | public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } RxActivityResults(@NonNull Activity activity); } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } | RxActivityResults { public <T> ObservableTransformer<T, ActivityResult> composer(final Intent intent) { return new ObservableTransformer<T, ActivityResult>() { @Override public ObservableSource<ActivityResult> apply(@NonNull Observable<T> upstream) { return request(upstream, intent); } }; } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } |
@Test public void ensureOkResult() throws Exception { Intent someIntent = new Intent(); ActivityResult testResult = new ActivityResult(Activity.RESULT_OK, Activity.RESULT_OK, someIntent); TestObserver<Boolean> composerTest = trigger().compose(rxActivityResults.ensureOkResult(someIntent)).test(); rxActivityResults.onActivityResult(testResult.getResultCode(), someIntent); composerTest.assertNoErrors() .assertSubscribed() .assertComplete() .assertValueCount(1) .assertValue(testResult.isOk()); } | public <T> ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent) { return new ObservableTransformer<T, Boolean>() { @Override public ObservableSource<Boolean> apply(@NonNull Observable<T> upstream) { return request(upstream, intent).map(new Function<ActivityResult, Boolean>() { @Override public Boolean apply(@NonNull ActivityResult activityResult) throws Exception { return activityResult.isOk(); } }); } }; } | RxActivityResults { public <T> ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent) { return new ObservableTransformer<T, Boolean>() { @Override public ObservableSource<Boolean> apply(@NonNull Observable<T> upstream) { return request(upstream, intent).map(new Function<ActivityResult, Boolean>() { @Override public Boolean apply(@NonNull ActivityResult activityResult) throws Exception { return activityResult.isOk(); } }); } }; } } | RxActivityResults { public <T> ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent) { return new ObservableTransformer<T, Boolean>() { @Override public ObservableSource<Boolean> apply(@NonNull Observable<T> upstream) { return request(upstream, intent).map(new Function<ActivityResult, Boolean>() { @Override public Boolean apply(@NonNull ActivityResult activityResult) throws Exception { return activityResult.isOk(); } }); } }; } RxActivityResults(@NonNull Activity activity); } | RxActivityResults { public <T> ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent) { return new ObservableTransformer<T, Boolean>() { @Override public ObservableSource<Boolean> apply(@NonNull Observable<T> upstream) { return request(upstream, intent).map(new Function<ActivityResult, Boolean>() { @Override public Boolean apply(@NonNull ActivityResult activityResult) throws Exception { return activityResult.isOk(); } }); } }; } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } | RxActivityResults { public <T> ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent) { return new ObservableTransformer<T, Boolean>() { @Override public ObservableSource<Boolean> apply(@NonNull Observable<T> upstream) { return request(upstream, intent).map(new Function<ActivityResult, Boolean>() { @Override public Boolean apply(@NonNull ActivityResult activityResult) throws Exception { return activityResult.isOk(); } }); } }; } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } |
@Test public void start() throws Exception { Intent someIntent = new Intent(); ActivityResult testResult = new ActivityResult(Activity.RESULT_OK, Activity.RESULT_OK, someIntent); TestObserver<ActivityResult> composerTest = rxActivityResults.start(someIntent).test(); rxActivityResults.onActivityResult(testResult.getResultCode(), someIntent); verify(rxActivityResults.mRxActivityResultsFragment) .onActivityResult(any(Integer.class), eq(testResult.getResultCode()), any(Intent.class)); composerTest.assertNoErrors() .assertSubscribed() .assertComplete() .assertValueCount(1) .assertValue(testResult); } | public Observable<ActivityResult> start(Intent intent) { return Observable.just(TRIGGER).compose(this.composer(intent)); } | RxActivityResults { public Observable<ActivityResult> start(Intent intent) { return Observable.just(TRIGGER).compose(this.composer(intent)); } } | RxActivityResults { public Observable<ActivityResult> start(Intent intent) { return Observable.just(TRIGGER).compose(this.composer(intent)); } RxActivityResults(@NonNull Activity activity); } | RxActivityResults { public Observable<ActivityResult> start(Intent intent) { return Observable.just(TRIGGER).compose(this.composer(intent)); } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } | RxActivityResults { public Observable<ActivityResult> start(Intent intent) { return Observable.just(TRIGGER).compose(this.composer(intent)); } RxActivityResults(@NonNull Activity activity); ObservableTransformer<T, ActivityResult> composer(final Intent intent); ObservableTransformer<T, Boolean> ensureOkResult(final Intent intent); Observable<ActivityResult> start(Intent intent); void setLogging(boolean logging); } |
@Test public void equalsTrue() throws Exception { ActivityResult testResult = new ActivityResult(Activity.RESULT_OK, resultCode, intent); assertTrue(activityResult.equals(testResult)); assertTrue(activityResult.equals(activityResult)); } | @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } ActivityResult(int okResultCode, int resultCode, Intent data); } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void equalsFalse() throws Exception { ActivityResult testResult = new ActivityResult(Activity.RESULT_OK, resultCode - 1, intent); assertFalse(activityResult.equals(testResult)); assertFalse(activityResult.equals(intent)); } | @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } ActivityResult(int okResultCode, int resultCode, Intent data); } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } | ActivityResult { @Override public boolean equals(Object obj) { if (obj instanceof ActivityResult) { if (this == obj) { return true; } ActivityResult activityResult = (ActivityResult) obj; return activityResult.data == data && activityResult.resultCode == resultCode; } else { return false; } } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void isOkTest() throws Exception { ActivityResult faultyResult = new ActivityResult(Activity.RESULT_OK, resultCode - 1, intent); assertFalse(faultyResult.isOk()); ActivityResult okResult = new ActivityResult(Activity.RESULT_OK, Activity.RESULT_OK, intent); assertTrue(okResult.isOk()); } | public boolean isOk() { return resultCode == okResultCode; } | ActivityResult { public boolean isOk() { return resultCode == okResultCode; } } | ActivityResult { public boolean isOk() { return resultCode == okResultCode; } ActivityResult(int okResultCode, int resultCode, Intent data); } | ActivityResult { public boolean isOk() { return resultCode == okResultCode; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } | ActivityResult { public boolean isOk() { return resultCode == okResultCode; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void toStringTest() throws Exception { String testResult = "ActivityResult { ResultCode" + " = " + resultCode + ", Data = " + intent + " }"; assertEquals(activityResult.toString(), testResult); } | @Override public String toString() { return "ActivityResult { ResultCode = " + resultCode + ", Data = " + data + " }"; } | ActivityResult { @Override public String toString() { return "ActivityResult { ResultCode = " + resultCode + ", Data = " + data + " }"; } } | ActivityResult { @Override public String toString() { return "ActivityResult { ResultCode = " + resultCode + ", Data = " + data + " }"; } ActivityResult(int okResultCode, int resultCode, Intent data); } | ActivityResult { @Override public String toString() { return "ActivityResult { ResultCode = " + resultCode + ", Data = " + data + " }"; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } | ActivityResult { @Override public String toString() { return "ActivityResult { ResultCode = " + resultCode + ", Data = " + data + " }"; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void getData() { assertEquals(activityResult.getData(), intent); } | public Intent getData() { return data; } | ActivityResult { public Intent getData() { return data; } } | ActivityResult { public Intent getData() { return data; } ActivityResult(int okResultCode, int resultCode, Intent data); } | ActivityResult { public Intent getData() { return data; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } | ActivityResult { public Intent getData() { return data; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void getResultCode() { assertEquals(activityResult.getResultCode(), resultCode); } | public int getResultCode() { return resultCode; } | ActivityResult { public int getResultCode() { return resultCode; } } | ActivityResult { public int getResultCode() { return resultCode; } ActivityResult(int okResultCode, int resultCode, Intent data); } | ActivityResult { public int getResultCode() { return resultCode; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } | ActivityResult { public int getResultCode() { return resultCode; } ActivityResult(int okResultCode, int resultCode, Intent data); Intent getData(); int getResultCode(); boolean isOk(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void getByName_shouldReturnPolicy_whenClientReturnsNotUniqueResult() throws Exception { when(responseMock.readEntity(AlertsPolicyList.class)).thenReturn(new AlertsPolicyList(asList( AlertsPolicy.builder().name("policy").build(), AlertsPolicy.builder().name("policy1").build() ))); Optional<AlertsPolicy> policyOptional = testee.getByName("policy"); assertThat(policyOptional).isNotEmpty(); } | @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); @Override Optional<AlertsPolicy> getByName(String alertsPolicyName); @Override AlertsPolicy create(AlertsPolicy policy); @Override AlertsPolicy delete(int policyId); @Override AlertsPolicyChannels updateChannels(AlertsPolicyChannels channels); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); @Override Optional<AlertsPolicy> getByName(String alertsPolicyName); @Override AlertsPolicy create(AlertsPolicy policy); @Override AlertsPolicy delete(int policyId); @Override AlertsPolicyChannels updateChannels(AlertsPolicyChannels channels); } |
@Test public void getByName_shouldNotReturnApplication_whenClientReturnsNotMatchingResult() throws Exception { when(responseMock.readEntity(ApplicationList.class)).thenReturn(new ApplicationList(Collections.singletonList( Application.builder().name("app1").build() ))); Optional<Application> applicationOptional = testee.getByName("app"); assertThat(applicationOptional).isEmpty(); } | @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); @Override Optional<Application> getByName(String applicationName); @Override Application update(int applicationId, Application application); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); @Override Optional<Application> getByName(String applicationName); @Override Application update(int applicationId, Application application); } |
@Test public void getByName_shouldNotReturnApplication_whenClientReturnsEmptyList() throws Exception { when(responseMock.readEntity(ApplicationList.class)).thenReturn(new ApplicationList(Collections.emptyList())); Optional<Application> applicationOptional = testee.getByName("app"); assertThat(applicationOptional).isEmpty(); } | @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); @Override Optional<Application> getByName(String applicationName); @Override Application update(int applicationId, Application application); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); @Override Optional<Application> getByName(String applicationName); @Override Application update(int applicationId, Application application); } |
@Test public void shouldNotSynchronizeAnything_whenNoConfigurationsSet() { testee.sync(); InOrder order = inOrder(applicationConfiguratorMock, policyConfiguratorMock, conditionConfiguratorMock, externalServiceConditionConfiguratorMock, nrqlConditionConfiguratorMock, syntheticsConditionConfiguratorMock, channelConfiguratorMock); order.verifyNoMoreInteractions(); } | public void sync() { for (ApplicationConfiguration applicationConfiguration : applicationConfigurations) { applicationConfigurator.sync(applicationConfiguration); } for (PolicyConfiguration configuration : policyConfigurations) { policyConfigurator.sync(configuration); conditionConfigurator.sync(configuration); externalServiceConditionConfigurator.sync(configuration); nrqlConditionConfigurator.sync(configuration); syntheticsConditionConfigurator.sync(configuration); channelConfigurator.sync(configuration); } } | Configurator { public void sync() { for (ApplicationConfiguration applicationConfiguration : applicationConfigurations) { applicationConfigurator.sync(applicationConfiguration); } for (PolicyConfiguration configuration : policyConfigurations) { policyConfigurator.sync(configuration); conditionConfigurator.sync(configuration); externalServiceConditionConfigurator.sync(configuration); nrqlConditionConfigurator.sync(configuration); syntheticsConditionConfigurator.sync(configuration); channelConfigurator.sync(configuration); } } } | Configurator { public void sync() { for (ApplicationConfiguration applicationConfiguration : applicationConfigurations) { applicationConfigurator.sync(applicationConfiguration); } for (PolicyConfiguration configuration : policyConfigurations) { policyConfigurator.sync(configuration); conditionConfigurator.sync(configuration); externalServiceConditionConfigurator.sync(configuration); nrqlConditionConfigurator.sync(configuration); syntheticsConditionConfigurator.sync(configuration); channelConfigurator.sync(configuration); } } Configurator(@NonNull String apiKey); Configurator(ApplicationConfigurator applicationConfigurator,
PolicyConfigurator policyConfigurator,
ConditionConfigurator conditionConfigurator,
ExternalServiceConditionConfigurator externalServiceConditionConfigurator,
NrqlConditionConfigurator nrqlConditionConfigurator,
SyntheticsConditionConfigurator syntheticsConditionConfigurator,
ChannelConfigurator channelConfigurator); } | Configurator { public void sync() { for (ApplicationConfiguration applicationConfiguration : applicationConfigurations) { applicationConfigurator.sync(applicationConfiguration); } for (PolicyConfiguration configuration : policyConfigurations) { policyConfigurator.sync(configuration); conditionConfigurator.sync(configuration); externalServiceConditionConfigurator.sync(configuration); nrqlConditionConfigurator.sync(configuration); syntheticsConditionConfigurator.sync(configuration); channelConfigurator.sync(configuration); } } Configurator(@NonNull String apiKey); Configurator(ApplicationConfigurator applicationConfigurator,
PolicyConfigurator policyConfigurator,
ConditionConfigurator conditionConfigurator,
ExternalServiceConditionConfigurator externalServiceConditionConfigurator,
NrqlConditionConfigurator nrqlConditionConfigurator,
SyntheticsConditionConfigurator syntheticsConditionConfigurator,
ChannelConfigurator channelConfigurator); void sync(); void setApplicationConfigurations(@NonNull Collection<ApplicationConfiguration> applicationConfigurations); void setPolicyConfigurations(@NonNull Collection<PolicyConfiguration> policyConfigurations); } | Configurator { public void sync() { for (ApplicationConfiguration applicationConfiguration : applicationConfigurations) { applicationConfigurator.sync(applicationConfiguration); } for (PolicyConfiguration configuration : policyConfigurations) { policyConfigurator.sync(configuration); conditionConfigurator.sync(configuration); externalServiceConditionConfigurator.sync(configuration); nrqlConditionConfigurator.sync(configuration); syntheticsConditionConfigurator.sync(configuration); channelConfigurator.sync(configuration); } } Configurator(@NonNull String apiKey); Configurator(ApplicationConfigurator applicationConfigurator,
PolicyConfigurator policyConfigurator,
ConditionConfigurator conditionConfigurator,
ExternalServiceConditionConfigurator externalServiceConditionConfigurator,
NrqlConditionConfigurator nrqlConditionConfigurator,
SyntheticsConditionConfigurator syntheticsConditionConfigurator,
ChannelConfigurator channelConfigurator); void sync(); void setApplicationConfigurations(@NonNull Collection<ApplicationConfiguration> applicationConfigurations); void setPolicyConfigurations(@NonNull Collection<PolicyConfiguration> policyConfigurations); } |
@Test public void shouldThrowException_whenPolicyDoesNotExist() { when(alertsPoliciesApiMock.getByName(POLICY_NAME)).thenReturn(Optional.empty()); PolicyConfiguration policyConfiguration = buildPolicyConfiguration(); expectedException.expect(NewRelicSyncException.class); expectedException.expectMessage(format("Policy %s does not exist", POLICY_NAME)); testee.sync(policyConfiguration); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldDoNothing_whenEmptyChannelsInConfiguration() { PolicyConfiguration policyConfiguration = buildPolicyConfiguration(); testee.sync(policyConfiguration); InOrder order = inOrder(alertsChannelsApiMock); order.verify(alertsChannelsApiMock).list(); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldDoNothing_whenNullChannelsInConfiguration() { PolicyConfiguration policyConfiguration = PolicyConfiguration.builder() .policyName(POLICY_NAME) .incidentPreference(INCIDENT_PREFERENCE) .build(); testee.sync(policyConfiguration); verifyNoMoreInteractions(alertsChannelsApiMock); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldCreateRequiredChannels() { when(alertsChannelsApiMock.list()).thenReturn(ImmutableList.of(savedUserChannel)); PolicyConfiguration policyConfiguration = buildPolicyConfiguration(EMAIL_CHANNEL, SLACK_CHANNEL); testee.sync(policyConfiguration); AlertsPolicyChannels expected = AlertsPolicyChannels.builder() .policyId(POLICY_ID) .channelIds(ImmutableSet.of(savedEmailChannel.getId(), savedSlackChannel.getId())) .build(); InOrder order = inOrder(alertsChannelsApiMock, alertsPoliciesApiMock); order.verify(alertsChannelsApiMock).list(); order.verify(alertsChannelsApiMock).create(configuredEmailChannel); order.verify(alertsChannelsApiMock).create(configuredSlackChannel); order.verify(alertsPoliciesApiMock).updateChannels(expected); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldRemoveOldChannelsAndCreateNewOne_whenChannelUpdated() { int updatedEmailChannelId = 10; EmailChannel updatedEmailChannel = EmailChannel.builder() .channelName(EMAIL_CHANNEL_NAME) .emailAddress("different recipients") .build(); AlertsChannel updatedEmailAlertChannel = createAlertChannel(updatedEmailChannel); when(alertsChannelsApiMock.create(updatedEmailAlertChannel)) .thenReturn(createAlertChannel(updatedEmailChannelId, updatedEmailChannel)); AlertsChannel emailChannelInPolicy = channelInPolicy(savedEmailChannel, POLICY_ID); when(alertsChannelsApiMock.list()).thenReturn(ImmutableList.of( savedUserChannel, emailChannelInPolicy, channelInPolicy(savedSlackChannel, POLICY_ID) )); when(alertsChannelsApiMock.deleteFromPolicy(POLICY_ID, emailChannelInPolicy.getId())) .thenReturn(emailChannelInPolicy); PolicyConfiguration policyConfiguration = buildPolicyConfiguration(updatedEmailChannel, SLACK_CHANNEL); testee.sync(policyConfiguration); AlertsPolicyChannels expected = AlertsPolicyChannels.builder() .policyId(POLICY_ID) .channelIds(ImmutableSet.of(updatedEmailChannelId, savedSlackChannel.getId())) .build(); InOrder order = inOrder(alertsChannelsApiMock, alertsPoliciesApiMock); order.verify(alertsChannelsApiMock).list(); order.verify(alertsChannelsApiMock).create(updatedEmailAlertChannel); order.verify(alertsPoliciesApiMock).updateChannels(expected); order.verify(alertsChannelsApiMock).deleteFromPolicy(POLICY_ID, savedEmailChannel.getId()); order.verify(alertsChannelsApiMock).delete(savedEmailChannel.getId()); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldNotRemoveUnsuedChannel_whenChannelBelongsToDifferentPolicy() { AlertsChannel emailChannelInPolicy = channelInPolicy(savedEmailChannel, POLICY_ID, POLICY_ID + 1); when(alertsChannelsApiMock.list()).thenReturn(ImmutableList.of( savedUserChannel, emailChannelInPolicy, channelInPolicy(savedSlackChannel, POLICY_ID) )); when(alertsChannelsApiMock.deleteFromPolicy(POLICY_ID, emailChannelInPolicy.getId())) .thenReturn(emailChannelInPolicy); PolicyConfiguration policyConfiguration = buildPolicyConfiguration(SLACK_CHANNEL); testee.sync(policyConfiguration); AlertsPolicyChannels expected = AlertsPolicyChannels.builder() .policyId(POLICY_ID) .channelIds(ImmutableSet.of(savedSlackChannel.getId())) .build(); InOrder order = inOrder(alertsChannelsApiMock, alertsPoliciesApiMock); order.verify(alertsChannelsApiMock).list(); order.verify(alertsPoliciesApiMock).updateChannels(expected); order.verify(alertsChannelsApiMock).deleteFromPolicy(POLICY_ID, savedEmailChannel.getId()); order.verify(alertsChannelsApiMock, never()).delete(savedEmailChannel.getId()); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldRemoveUnusedPolicyChannel() { AlertsChannel emailChannelInPolicy = channelInPolicy(savedEmailChannel, POLICY_ID); when(alertsChannelsApiMock.list()).thenReturn(ImmutableList.of( savedUserChannel, emailChannelInPolicy, channelInPolicy(savedSlackChannel, POLICY_ID) )); when(alertsChannelsApiMock.deleteFromPolicy(POLICY_ID, emailChannelInPolicy.getId())) .thenReturn(emailChannelInPolicy); PolicyConfiguration policyConfiguration = buildPolicyConfiguration(SLACK_CHANNEL); testee.sync(policyConfiguration); AlertsPolicyChannels expected = AlertsPolicyChannels.builder() .policyId(POLICY_ID) .channelIds(ImmutableSet.of(savedSlackChannel.getId())) .build(); InOrder order = inOrder(alertsChannelsApiMock, alertsPoliciesApiMock); order.verify(alertsChannelsApiMock).list(); order.verify(alertsPoliciesApiMock).updateChannels(expected); order.verify(alertsChannelsApiMock).deleteFromPolicy(POLICY_ID, savedEmailChannel.getId()); order.verify(alertsChannelsApiMock).delete(savedEmailChannel.getId()); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void getByName_shouldNotReturnPolicy_whenClientReturnsNotMatchingResult() throws Exception { when(responseMock.readEntity(AlertsPolicyList.class)).thenReturn(new AlertsPolicyList(Collections.singletonList( AlertsPolicy.builder().name("policy1").build() ))); Optional<AlertsPolicy> policyOptional = testee.getByName("policy"); assertThat(policyOptional).isEmpty(); } | @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); @Override Optional<AlertsPolicy> getByName(String alertsPolicyName); @Override AlertsPolicy create(AlertsPolicy policy); @Override AlertsPolicy delete(int policyId); @Override AlertsPolicyChannels updateChannels(AlertsPolicyChannels channels); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); @Override Optional<AlertsPolicy> getByName(String alertsPolicyName); @Override AlertsPolicy create(AlertsPolicy policy); @Override AlertsPolicy delete(int policyId); @Override AlertsPolicyChannels updateChannels(AlertsPolicyChannels channels); } |
@Test public void shouldThrowException_whenUserChannelDosNotExist() { PolicyConfiguration policyConfiguration = buildPolicyConfiguration(USER_CHANNEL); expectedException.expect(NewRelicSyncException.class); expectedException.expectMessage("Alerts channel with configuration"); testee.sync(policyConfiguration); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldNotCreateUserChannel() { when(alertsChannelsApiMock.list()).thenReturn(ImmutableList.of(savedUserChannel)); PolicyConfiguration policyConfiguration = buildPolicyConfiguration(USER_CHANNEL); AlertsPolicyChannels expected = AlertsPolicyChannels.builder() .policyId(POLICY.getId()) .channelIds(ImmutableSet.of(savedUserChannel.getId())) .build(); testee.sync(policyConfiguration); InOrder order = inOrder(alertsChannelsApiMock, alertsPoliciesApiMock); order.verify(alertsChannelsApiMock).list(); order.verify(alertsPoliciesApiMock).updateChannels(expected); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldNotRemoveUnusedUserChannel() { AlertsChannel userChannelInPolicy = channelInPolicy(savedUserChannel, POLICY_ID); when(alertsChannelsApiMock.list()).thenReturn(ImmutableList.of(userChannelInPolicy)); when(alertsChannelsApiMock.deleteFromPolicy(POLICY_ID, userChannelInPolicy.getId())) .thenReturn(userChannelInPolicy); PolicyConfiguration policyConfiguration = buildPolicyConfiguration(); testee.sync(policyConfiguration); AlertsPolicyChannels expected = AlertsPolicyChannels.builder() .policyId(POLICY_ID) .channelIds(emptySet()) .build(); InOrder order = inOrder(alertsChannelsApiMock, alertsPoliciesApiMock); order.verify(alertsChannelsApiMock).list(); order.verify(alertsPoliciesApiMock).updateChannels(expected); order.verify(alertsChannelsApiMock).deleteFromPolicy(POLICY_ID, savedUserChannel.getId()); order.verify(alertsChannelsApiMock, never()).delete(savedUserChannel.getId()); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } | ChannelConfigurator { void sync(@NonNull PolicyConfiguration config) { if (!config.getChannels().isPresent()) { LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing alerts channels for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); Set<Integer> policyChannelsToCleanup = createOrUpdatePolicyAlertsChannels(policy, config.getChannels().get()); cleanupPolicyAlertsChannels(policy, policyChannelsToCleanup); LOG.info("Alerts channels for policy {} synchronized", config.getPolicyName()); } ChannelConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldThrowException_whenApplicationDoesNotExist() { when(applicationsApiMock.getByName(APPLICATION_NAME)).thenReturn(Optional.empty()); expectedException.expect(NewRelicSyncException.class); expectedException.expectMessage(format("Application %s does not exist", APPLICATION_NAME)); testee.sync(CONFIGURATION); } | void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } ApplicationConfigurator(@NonNull NewRelicApi api); } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } ApplicationConfigurator(@NonNull NewRelicApi api); } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } ApplicationConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldUpdateApplication() { when(applicationsApiMock.getByName(APPLICATION_NAME)).thenReturn(Optional.of(APPLICATION)); ApplicationSettings expectedSettings = ApplicationSettings.builder() .appApdexThreshold(APP_APDEX_THRESHOLD) .endUserApdexThreshold(USER_APDEX_THRESHOLD) .enableRealUserMonitoring(ENABLE_REAL_USER_MONITORING) .build(); Application expectedApplicationUpdate = Application.builder() .name(APPLICATION_NAME) .settings(expectedSettings) .build(); testee.sync(CONFIGURATION); verify(applicationsApiMock).update(APPLICATION.getId(), expectedApplicationUpdate); } | void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } ApplicationConfigurator(@NonNull NewRelicApi api); } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } ApplicationConfigurator(@NonNull NewRelicApi api); } | ApplicationConfigurator { void sync(@NonNull ApplicationConfiguration config) { LOG.info("Synchronizing application {}...", config.getApplicationName()); Application application = api.getApplicationsApi().getByName(config.getApplicationName()).orElseThrow( () -> new NewRelicSyncException(format("Application %s does not exist", config.getApplicationName()))); ApplicationSettings settings = ApplicationSettings.builder() .appApdexThreshold(config.getAppApdexThreshold()) .endUserApdexThreshold(config.getEndUserApdexThreshold()) .enableRealUserMonitoring(config.isEnableRealUserMonitoring()) .build(); Application applicationUpdate = Application.builder() .name(config.getApplicationName()) .settings(settings) .build(); api.getApplicationsApi().update(application.getId(), applicationUpdate); LOG.info("Application {} synchronized", config.getApplicationName()); } ApplicationConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldThrowException_whenPolicyDoesNotExist() { when(alertsPoliciesApiMock.getByName(POLICY_NAME)).thenReturn(Optional.empty()); expectedException.expect(NewRelicSyncException.class); expectedException.expectMessage(format("Policy %s does not exist", POLICY_NAME)); testee.sync(getPolicyConfiguration()); } | @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } |
@Test public void shouldDoNothing_whenNullConditionsInConfiguration() { PolicyItemApi<U> itemApiMock = getPolicyItemApiMock(); PolicyConfiguration config = PolicyConfiguration.builder() .policyName(POLICY_NAME) .incidentPreference(PolicyConfiguration.IncidentPreference.PER_POLICY) .build(); testee.sync(config); verifyZeroInteractions(itemApiMock); } | @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } |
@Test public void shouldDoNothing_whenEmptyConditionsInConfiguration() { PolicyItemApi<U> itemApiMock = getPolicyItemApiMock(); PolicyConfiguration config = PolicyConfiguration.builder() .policyName(POLICY_NAME) .incidentPreference(PolicyConfiguration.IncidentPreference.PER_POLICY) .conditions(Collections.emptyList()) .nrqlConditions(Collections.emptyList()) .externalServiceConditions(Collections.emptyList()) .build(); testee.sync(config); InOrder order = inOrder(itemApiMock); order.verify(itemApiMock).list(POLICY.getId()); order.verifyNoMoreInteractions(); } | @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } |
@Test public void shouldCreateCondition() { U itemFromConfig = getItemFromConfig(); U itemSame = getItemSame(); PolicyConfiguration policyConfiguration = getPolicyConfiguration(); PolicyItemApi<U> itemApiMock = getPolicyItemApiMock(); when(itemApiMock.list(POLICY.getId())).thenReturn(ImmutableList.of()); when(itemApiMock.create(POLICY.getId(), itemFromConfig)).thenReturn(itemSame); testee.sync(policyConfiguration); InOrder order = inOrder(itemApiMock); order.verify(itemApiMock).list(POLICY.getId()); order.verify(itemApiMock).create(POLICY.getId(), itemFromConfig); order.verifyNoMoreInteractions(); } | @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } |
@Test public void shouldUpdateCondition() { U itemFromConfig = getItemFromConfig(); U itemUpdated = getItemUpdated(); PolicyConfiguration policyConfiguration = getPolicyConfiguration(); PolicyItemApi<U> itemApiMock = getPolicyItemApiMock(); when(itemApiMock.list(POLICY.getId())).thenReturn(ImmutableList.of(itemUpdated)); when(itemApiMock.update(itemUpdated.getId(), itemFromConfig)).thenReturn(itemUpdated); testee.sync(policyConfiguration); InOrder order = inOrder(itemApiMock); order.verify(itemApiMock).list(POLICY.getId()); order.verify(itemApiMock).update(itemUpdated.getId(), itemFromConfig); order.verifyNoMoreInteractions(); } | @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } |
@Test public void getByName_shouldNotReturnPolicy_whenClientReturnsEmptyList() throws Exception { when(responseMock.readEntity(AlertsPolicyList.class)).thenReturn(new AlertsPolicyList(Collections.emptyList())); Optional<AlertsPolicy> policyOptional = testee.getByName("policy"); assertThat(policyOptional).isEmpty(); } | @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); @Override Optional<AlertsPolicy> getByName(String alertsPolicyName); @Override AlertsPolicy create(AlertsPolicy policy); @Override AlertsPolicy delete(int policyId); @Override AlertsPolicyChannels updateChannels(AlertsPolicyChannels channels); } | DefaultAlertsPoliciesApi extends ApiBase implements AlertsPoliciesApi { @Override public Optional<AlertsPolicy> getByName(String alertsPolicyName) { Invocation.Builder builder = client .target(POLICIES_URL) .queryParam("filter[name]", alertsPolicyName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, AlertsPolicyList.class) .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName)) .getSingle(); } DefaultAlertsPoliciesApi(NewRelicClient client); @Override Optional<AlertsPolicy> getByName(String alertsPolicyName); @Override AlertsPolicy create(AlertsPolicy policy); @Override AlertsPolicy delete(int policyId); @Override AlertsPolicyChannels updateChannels(AlertsPolicyChannels channels); } |
@Test public void shouldRemoveOldCondition() { U itemFromConfig = getItemFromConfig(); U itemSame = getItemSame(); U itemDifferent = getItemDifferent(); PolicyConfiguration policyConfiguration = getPolicyConfiguration(); PolicyItemApi<U> itemApiMock = getPolicyItemApiMock(); when(itemApiMock.list(POLICY.getId())).thenReturn(ImmutableList.of(itemDifferent)); when(itemApiMock.create(POLICY.getId(), itemFromConfig)).thenReturn(itemSame); testee.sync(policyConfiguration); InOrder order = inOrder(itemApiMock); order.verify(itemApiMock).list(POLICY.getId()); order.verify(itemApiMock).create(POLICY.getId(), itemFromConfig); order.verify(itemApiMock).delete(itemDifferent.getId()); order.verifyNoMoreInteractions(); } | @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } | AbstractPolicyItemConfigurator implements PolicyItemConfigurator { @Override public void sync(@NonNull PolicyConfiguration config) { if (! getConfigItems(config).isPresent()) { LOG.info("No items for policy {} - skipping...", config.getPolicyName()); return; } LOG.info("Synchronizing items for policy {}...", config.getPolicyName()); AlertsPolicy policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()).orElseThrow( () -> new NewRelicSyncException(format("Policy %s does not exist", config.getPolicyName()))); List<T> allItems = getItemsApi().list(policy.getId()); List<Integer> updatedItemsIds = createOrUpdateAlertsNrqlConditions(policy, getConfigItems(config).get(), allItems); cleanupOldItems(policy, allItems, updatedItemsIds); LOG.info("Items for policy {} synchronized", config.getPolicyName()); } AbstractPolicyItemConfigurator(@NonNull NewRelicApi api); @Override void sync(@NonNull PolicyConfiguration config); } |
@Test public void shouldCreateNewPolicy_whenPolicyDoesNotExist() { when(alertsPoliciesApiMock.getByName(POLICY_NAME)).thenReturn(Optional.empty()); AlertsPolicy expectedPolicy = AlertsPolicy.builder().name(POLICY_NAME).incidentPreference(INCIDENT_PREFERENCE.name()).build(); testee.sync(CONFIGURATION); InOrder order = inOrder(alertsPoliciesApiMock); order.verify(alertsPoliciesApiMock).getByName(POLICY_NAME); order.verify(alertsPoliciesApiMock).create(expectedPolicy); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldDeleteAndCreateNewPolicy_whenPolicyUpdated() { when(alertsPoliciesApiMock.getByName(POLICY_NAME)).thenReturn(Optional.of(ALERT_POLICY_DIFFERENT)); AlertsPolicy expectedPolicy = AlertsPolicy.builder().name(POLICY_NAME).incidentPreference(INCIDENT_PREFERENCE.name()).build(); testee.sync(CONFIGURATION); InOrder order = inOrder(alertsPoliciesApiMock); order.verify(alertsPoliciesApiMock).getByName(POLICY_NAME); order.verify(alertsPoliciesApiMock).delete(ALERT_POLICY_DIFFERENT.getId()); order.verify(alertsPoliciesApiMock).create(expectedPolicy); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } |
@Test public void shouldDoNothing_whenPolicyNotUpdated() { when(alertsPoliciesApiMock.getByName(POLICY_NAME)).thenReturn(Optional.of(ALERT_POLICY_SAME)); testee.sync(CONFIGURATION); InOrder order = inOrder(alertsPoliciesApiMock); order.verify(alertsPoliciesApiMock).getByName(POLICY_NAME); order.verifyNoMoreInteractions(); } | void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } | PolicyConfigurator { void sync(@NonNull PolicyConfiguration config) { LOG.info("Synchronizing policy {}...", config.getPolicyName()); AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder() .name(config.getPolicyName()) .incidentPreference(config.getIncidentPreference().name()) .build(); Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName()); if (policy.isPresent()) { AlertsPolicy oldPolicy = policy.get(); if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) { api.getAlertsPoliciesApi().delete(oldPolicy.getId()); api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info(format("Policy %s updated", config.getPolicyName())); } } else { api.getAlertsPoliciesApi().create(alertsPolicyFromConfig); LOG.info("Policy {} created", config.getPolicyName()); } LOG.info("Policy {} synchronized", config.getPolicyName()); } PolicyConfigurator(@NonNull NewRelicApi api); } |
@Test public void getByTitle_shouldReturnDashboards_whenClientReturnsNotUniqueResult() { when(responseMock.readEntity(DashboardList.class)).thenReturn(new DashboardList(asList( Dashboard.builder().title(DASHBOARD_FILTER_VALUE).build(), Dashboard.builder().title("dashboard1").build() ))); List<Dashboard> dashboard = testee.getByTitle(DASHBOARD_FILTER_VALUE); assertThat(dashboard).isNotEmpty(); assertThat(dashboard).hasSize(2); } | @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); @Override Dashboard getById(int dashboardId); @Override List<Dashboard> getByTitle(String dashboardTitle); @Override Dashboard create(Dashboard dashboard); @Override Dashboard update(Dashboard dashboard); @Override Dashboard delete(int dashboardId); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); @Override Dashboard getById(int dashboardId); @Override List<Dashboard> getByTitle(String dashboardTitle); @Override Dashboard create(Dashboard dashboard); @Override Dashboard update(Dashboard dashboard); @Override Dashboard delete(int dashboardId); } |
@Test public void getByTitle_shouldReturnDashboard_whenClientReturnsResultContainingQueriedTitle() { when(responseMock.readEntity(DashboardList.class)).thenReturn(new DashboardList(Collections.singletonList( Dashboard.builder().title("dashboard1").build() ))); List<Dashboard> dashboard = testee.getByTitle(DASHBOARD_FILTER_VALUE); assertThat(dashboard).isNotEmpty(); } | @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); @Override Dashboard getById(int dashboardId); @Override List<Dashboard> getByTitle(String dashboardTitle); @Override Dashboard create(Dashboard dashboard); @Override Dashboard update(Dashboard dashboard); @Override Dashboard delete(int dashboardId); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); @Override Dashboard getById(int dashboardId); @Override List<Dashboard> getByTitle(String dashboardTitle); @Override Dashboard create(Dashboard dashboard); @Override Dashboard update(Dashboard dashboard); @Override Dashboard delete(int dashboardId); } |
@Test public void getByTitle_shouldNotReturnDashboard_whenClientReturnsEmptyList() { when(responseMock.readEntity(DashboardList.class)).thenReturn(new DashboardList(Collections.emptyList())); List<Dashboard> dashboard = testee.getByTitle(DASHBOARD_FILTER_VALUE); assertThat(dashboard).isEmpty(); } | @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); @Override Dashboard getById(int dashboardId); @Override List<Dashboard> getByTitle(String dashboardTitle); @Override Dashboard create(Dashboard dashboard); @Override Dashboard update(Dashboard dashboard); @Override Dashboard delete(int dashboardId); } | DefaultDashboardsApi extends ApiBase implements DashboardsApi { @Override public List<Dashboard> getByTitle(String dashboardTitle) { String dashboardTitleEncoded = UriComponent.encode(dashboardTitle, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(DASHBOARDS_URL) .queryParam("filter[title]", dashboardTitleEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, DashboardList.class) .getList(); } DefaultDashboardsApi(NewRelicClient client); @Override Dashboard getById(int dashboardId); @Override List<Dashboard> getByTitle(String dashboardTitle); @Override Dashboard create(Dashboard dashboard); @Override Dashboard update(Dashboard dashboard); @Override Dashboard delete(int dashboardId); } |
@Test public void getByName_shouldReturnServer_whenClientReturnsNotUniqueResult() throws Exception { when(responseMock.readEntity(ServerList.class)).thenReturn(new ServerList(asList( Server.builder().name("server").build(), Server.builder().name("server1").build() ))); Optional<Server> serverOptional = testee.getByName("server"); assertThat(serverOptional).isNotEmpty(); } | @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); @Override Optional<Server> getByName(String serverName); @Override Server getById(int serverId); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); @Override Optional<Server> getByName(String serverName); @Override Server getById(int serverId); } |
@Test public void getByName_shouldNotReturnServer_whenClientReturnsNotMatchingResult() throws Exception { when(responseMock.readEntity(ServerList.class)).thenReturn(new ServerList(Collections.singletonList( Server.builder().name("server1").build() ))); Optional<Server> serverOptional = testee.getByName("server"); assertThat(serverOptional).isEmpty(); } | @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); @Override Optional<Server> getByName(String serverName); @Override Server getById(int serverId); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); @Override Optional<Server> getByName(String serverName); @Override Server getById(int serverId); } |
@Test public void getByName_shouldNotReturnServer_whenClientReturnsEmptyList() throws Exception { when(responseMock.readEntity(ServerList.class)).thenReturn(new ServerList(Collections.emptyList())); Optional<Server> serverOptional = testee.getByName("server"); assertThat(serverOptional).isEmpty(); } | @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); @Override Optional<Server> getByName(String serverName); @Override Server getById(int serverId); } | DefaultServersApi extends ApiBase implements ServersApi { @Override public Optional<Server> getByName(String serverName) { String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(SERVERS_URL) .queryParam("filter[name]", serverNameEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ServerList.class) .filter(application -> application.getName().equals(serverName)) .getSingle(); } DefaultServersApi(NewRelicClient client); @Override Optional<Server> getByName(String serverName); @Override Server getById(int serverId); } |
@Test public void getByName_shouldReturnApplication_whenClientReturnsNotUniqueResult() throws Exception { when(responseMock.readEntity(ApplicationList.class)).thenReturn(new ApplicationList(asList( Application.builder().name("app").build(), Application.builder().name("app1").build() ))); Optional<Application> applicationOptional = testee.getByName("app"); assertThat(applicationOptional).isNotEmpty(); } | @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); @Override Optional<Application> getByName(String applicationName); @Override Application update(int applicationId, Application application); } | DefaultApplicationsApi extends ApiBase implements ApplicationsApi { @Override public Optional<Application> getByName(String applicationName) { Invocation.Builder builder = client .target(APPLICATIONS_URL) .queryParam("filter[name]", applicationName) .request(APPLICATION_JSON_TYPE); return getPageable(builder, ApplicationList.class) .filter(application -> application.getName().equals(applicationName)) .getSingle(); } DefaultApplicationsApi(NewRelicClient client); @Override Optional<Application> getByName(String applicationName); @Override Application update(int applicationId, Application application); } |
@DisplayName("Create EmbeddedJMSBrokerHolder instance") @Test void create() throws Exception { try (final EmbeddedJMSBrokerHolder embeddedJmsBrokerHolder = EmbeddedJMSBrokerHolder .create("name", false, false)) { assertNotNull(embeddedJmsBrokerHolder.getBrokerService()); assertFalse(embeddedJmsBrokerHolder.getBrokerService().isStarted()); } } | public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } EmbeddedJMSBrokerHolder(final BrokerService brokerService, final File tempDir); } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } EmbeddedJMSBrokerHolder(final BrokerService brokerService, final File tempDir); BrokerService getBrokerService(); @Override ConnectionFactory getConnectionFactory(); @Override ActiveMQConnectionFactory getActiveMQConnectionFactory(); @Override URI getBrokerUri(); static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent); void start(); @Override void close(); } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } EmbeddedJMSBrokerHolder(final BrokerService brokerService, final File tempDir); BrokerService getBrokerService(); @Override ConnectionFactory getConnectionFactory(); @Override ActiveMQConnectionFactory getActiveMQConnectionFactory(); @Override URI getBrokerUri(); static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent); void start(); @Override void close(); } |
@DisplayName("Creating a broker using an illegal URI as name should fail") @Test void createFails() { assertThrows(IllegalStateException.class, () -> EmbeddedJMSBrokerHolder .create("\\\\\\", false, false)); } | public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } EmbeddedJMSBrokerHolder(final BrokerService brokerService, final File tempDir); } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } EmbeddedJMSBrokerHolder(final BrokerService brokerService, final File tempDir); BrokerService getBrokerService(); @Override ConnectionFactory getConnectionFactory(); @Override ActiveMQConnectionFactory getActiveMQConnectionFactory(); @Override URI getBrokerUri(); static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent); void start(); @Override void close(); } | EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor { public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) { final File tempDir = Files.createTempDir(); LOGGER.debug("Created temporary directory: \"{}\"", tempDir.getAbsolutePath()); return new EmbeddedJMSBrokerHolder(createAndConfigureBrokerService(new BrokerSettings(name, marshal, persistent, tempDir)), tempDir); } EmbeddedJMSBrokerHolder(final BrokerService brokerService, final File tempDir); BrokerService getBrokerService(); @Override ConnectionFactory getConnectionFactory(); @Override ActiveMQConnectionFactory getActiveMQConnectionFactory(); @Override URI getBrokerUri(); static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent); void start(); @Override void close(); } |
@Test(expected = IllegalStateException.class) public void connectionFactory() throws Exception { final EmbeddedJmsRuleImpl rule = new EmbeddedJmsRuleImpl("predefined", true, false); rule.connectionFactory(); } | @Override public ConnectionFactory connectionFactory() { return activeMqConnectionFactory(); } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ConnectionFactory connectionFactory() { return activeMqConnectionFactory(); } } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ConnectionFactory connectionFactory() { return activeMqConnectionFactory(); } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ConnectionFactory connectionFactory() { return activeMqConnectionFactory(); } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); @Override ConnectionFactory connectionFactory(); @Override ActiveMQConnectionFactory activeMqConnectionFactory(); @Override URI brokerUri(); @Override Statement apply(final Statement base, final Description description); } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ConnectionFactory connectionFactory() { return activeMqConnectionFactory(); } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); @Override ConnectionFactory connectionFactory(); @Override ActiveMQConnectionFactory activeMqConnectionFactory(); @Override URI brokerUri(); @Override Statement apply(final Statement base, final Description description); } |
@Test(expected = IllegalStateException.class) public void activeMqConnectionFactory() throws Exception { final EmbeddedJmsRuleImpl rule = new EmbeddedJmsRuleImpl("predefined", true, false); rule.activeMqConnectionFactory(); } | @Override public ActiveMQConnectionFactory activeMqConnectionFactory() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create ConnectionFactory before the broker has started"); } else { return jmsBrokerHolder.getActiveMQConnectionFactory(); } } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ActiveMQConnectionFactory activeMqConnectionFactory() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create ConnectionFactory before the broker has started"); } else { return jmsBrokerHolder.getActiveMQConnectionFactory(); } } } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ActiveMQConnectionFactory activeMqConnectionFactory() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create ConnectionFactory before the broker has started"); } else { return jmsBrokerHolder.getActiveMQConnectionFactory(); } } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ActiveMQConnectionFactory activeMqConnectionFactory() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create ConnectionFactory before the broker has started"); } else { return jmsBrokerHolder.getActiveMQConnectionFactory(); } } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); @Override ConnectionFactory connectionFactory(); @Override ActiveMQConnectionFactory activeMqConnectionFactory(); @Override URI brokerUri(); @Override Statement apply(final Statement base, final Description description); } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public ActiveMQConnectionFactory activeMqConnectionFactory() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create ConnectionFactory before the broker has started"); } else { return jmsBrokerHolder.getActiveMQConnectionFactory(); } } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); @Override ConnectionFactory connectionFactory(); @Override ActiveMQConnectionFactory activeMqConnectionFactory(); @Override URI brokerUri(); @Override Statement apply(final Statement base, final Description description); } |
@Test(expected = IllegalStateException.class) public void brokerUri() throws Exception { final EmbeddedJmsRuleImpl rule = new EmbeddedJmsRuleImpl("predefined", true, false); rule.brokerUri(); } | @Override public URI brokerUri() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create broker URI before the broker has started"); } else { return jmsBrokerHolder.getBrokerUri(); } } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public URI brokerUri() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create broker URI before the broker has started"); } else { return jmsBrokerHolder.getBrokerUri(); } } } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public URI brokerUri() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create broker URI before the broker has started"); } else { return jmsBrokerHolder.getBrokerUri(); } } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public URI brokerUri() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create broker URI before the broker has started"); } else { return jmsBrokerHolder.getBrokerUri(); } } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); @Override ConnectionFactory connectionFactory(); @Override ActiveMQConnectionFactory activeMqConnectionFactory(); @Override URI brokerUri(); @Override Statement apply(final Statement base, final Description description); } | EmbeddedJmsRuleImpl implements EmbeddedJmsRule { @Override public URI brokerUri() { if (jmsBrokerHolder == null) { throw new IllegalStateException("Can not create broker URI before the broker has started"); } else { return jmsBrokerHolder.getBrokerUri(); } } EmbeddedJmsRuleImpl(final String predefinedName, final boolean marshal, final boolean persistent); @Override ConnectionFactory connectionFactory(); @Override ActiveMQConnectionFactory activeMqConnectionFactory(); @Override URI brokerUri(); @Override Statement apply(final Statement base, final Description description); } |
@Test void testHashCode() { assertEquals(BrokerConfigurationBuilder.instance().build().hashCode(), BrokerConfigurationBuilder.instance().build().hashCode()); } | @Override public int hashCode() { return Objects.hash(name, marshal, persistenceEnabled); } | BrokerConfiguration { @Override public int hashCode() { return Objects.hash(name, marshal, persistenceEnabled); } } | BrokerConfiguration { @Override public int hashCode() { return Objects.hash(name, marshal, persistenceEnabled); } BrokerConfiguration(final String name, final Boolean marshal, final Boolean persistenceEnabled); } | BrokerConfiguration { @Override public int hashCode() { return Objects.hash(name, marshal, persistenceEnabled); } BrokerConfiguration(final String name, final Boolean marshal, final Boolean persistenceEnabled); String getName(); Boolean getMarshal(); Boolean getPersistenceEnabled(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | BrokerConfiguration { @Override public int hashCode() { return Objects.hash(name, marshal, persistenceEnabled); } BrokerConfiguration(final String name, final Boolean marshal, final Boolean persistenceEnabled); String getName(); Boolean getMarshal(); Boolean getPersistenceEnabled(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); static final BrokerConfiguration DEFAULT; } |
@Test void testToString() { assertEquals(BrokerConfigurationBuilder.instance().build().toString(), BrokerConfigurationBuilder.instance().build().toString()); } | @Override public String toString() { final StringBuilder sb = new StringBuilder("BrokerConfiguration{"); sb.append("name='").append(name).append('\''); sb.append(", marshal=").append(marshal); sb.append(", persistenceEnabled=").append(persistenceEnabled); sb.append('}'); return sb.toString(); } | BrokerConfiguration { @Override public String toString() { final StringBuilder sb = new StringBuilder("BrokerConfiguration{"); sb.append("name='").append(name).append('\''); sb.append(", marshal=").append(marshal); sb.append(", persistenceEnabled=").append(persistenceEnabled); sb.append('}'); return sb.toString(); } } | BrokerConfiguration { @Override public String toString() { final StringBuilder sb = new StringBuilder("BrokerConfiguration{"); sb.append("name='").append(name).append('\''); sb.append(", marshal=").append(marshal); sb.append(", persistenceEnabled=").append(persistenceEnabled); sb.append('}'); return sb.toString(); } BrokerConfiguration(final String name, final Boolean marshal, final Boolean persistenceEnabled); } | BrokerConfiguration { @Override public String toString() { final StringBuilder sb = new StringBuilder("BrokerConfiguration{"); sb.append("name='").append(name).append('\''); sb.append(", marshal=").append(marshal); sb.append(", persistenceEnabled=").append(persistenceEnabled); sb.append('}'); return sb.toString(); } BrokerConfiguration(final String name, final Boolean marshal, final Boolean persistenceEnabled); String getName(); Boolean getMarshal(); Boolean getPersistenceEnabled(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | BrokerConfiguration { @Override public String toString() { final StringBuilder sb = new StringBuilder("BrokerConfiguration{"); sb.append("name='").append(name).append('\''); sb.append(", marshal=").append(marshal); sb.append(", persistenceEnabled=").append(persistenceEnabled); sb.append('}'); return sb.toString(); } BrokerConfiguration(final String name, final Boolean marshal, final Boolean persistenceEnabled); String getName(); Boolean getMarshal(); Boolean getPersistenceEnabled(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); static final BrokerConfiguration DEFAULT; } |
@Test public void resolveNetworkClientPort() throws Exception { final String port = resolver.resolve("${zeebe.network.client.port}"); assertThat(port).isEqualTo("123"); } | @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } @Override void setBeanFactory(final BeanFactory beanFactory); @SuppressWarnings("unchecked") T resolve(final String value); } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } @Override void setBeanFactory(final BeanFactory beanFactory); @SuppressWarnings("unchecked") T resolve(final String value); } |
@Test public void useValueIfNoExpression() throws Exception { final String normalString = resolver.resolve("normalString"); assertThat(normalString).isEqualTo("normalString"); } | @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } @Override void setBeanFactory(final BeanFactory beanFactory); @SuppressWarnings("unchecked") T resolve(final String value); } | ZeebeExpressionResolver implements BeanFactoryAware { @SuppressWarnings("unchecked") public <T> T resolve(final String value) { final String resolvedValue = resolve.apply(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return (T) resolvedValue; } return (T) this.resolver.evaluate(resolvedValue, this.expressionContext); } @Override void setBeanFactory(final BeanFactory beanFactory); @SuppressWarnings("unchecked") T resolve(final String value); } |
@Test public void shouldDeploySingleResourceTest() { ClassInfo classInfo = ClassInfo.builder() .build(); ZeebeDeploymentValue zeebeDeploymentValue = ZeebeDeploymentValue.builder() .classPathResources(Collections.singletonList("/1.bpmn")) .build(); when(reader.applyOrThrow(classInfo)).thenReturn(zeebeDeploymentValue); when(client.newDeployCommand()).thenReturn(deployStep1); when(deployStep1.addResourceFromClasspath(anyString())).thenReturn(deployStep2); when(deployStep2.send()).thenReturn(zeebeFuture); when(zeebeFuture.join()).thenReturn(deploymentEvent); when(deploymentEvent.getWorkflows()).thenReturn(Collections.singletonList(getWorkFlow())); deploymentPostProcessor.apply(classInfo).accept(client); verify(deployStep1).addResourceFromClasspath(eq("/1.bpmn")); verify(deployStep2).send(); verify(zeebeFuture).join(); } | @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } @Override boolean test(final ClassInfo beanInfo); @Override Consumer<ZeebeClient> apply(final ClassInfo beanInfo); } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } @Override boolean test(final ClassInfo beanInfo); @Override Consumer<ZeebeClient> apply(final ClassInfo beanInfo); } |
@Test public void shouldDeployMultipleResourcesTest() { ClassInfo classInfo = ClassInfo.builder() .build(); ZeebeDeploymentValue zeebeDeploymentValue = ZeebeDeploymentValue.builder() .classPathResources(Arrays.asList("/1.bpmn", "/2.bpmn")) .build(); when(reader.applyOrThrow(classInfo)).thenReturn(zeebeDeploymentValue); when(client.newDeployCommand()).thenReturn(deployStep1); when(deployStep1.addResourceFromClasspath(anyString())).thenReturn(deployStep2); when(deployStep2.send()).thenReturn(zeebeFuture); when(zeebeFuture.join()).thenReturn(deploymentEvent); when(deploymentEvent.getWorkflows()).thenReturn(Collections.singletonList(getWorkFlow())); deploymentPostProcessor.apply(classInfo).accept(client); verify(deployStep1).addResourceFromClasspath(eq("/1.bpmn")); verify(deployStep1).addResourceFromClasspath(eq("/2.bpmn")); verify(deployStep2).send(); verify(zeebeFuture).join(); } | @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } @Override boolean test(final ClassInfo beanInfo); @Override Consumer<ZeebeClient> apply(final ClassInfo beanInfo); } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } @Override boolean test(final ClassInfo beanInfo); @Override Consumer<ZeebeClient> apply(final ClassInfo beanInfo); } |
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionOnNoResourcesToDeploy() { ClassInfo classInfo = ClassInfo.builder() .build(); ZeebeDeploymentValue zeebeDeploymentValue = ZeebeDeploymentValue.builder() .classPathResources(Collections.emptyList()) .build(); when(reader.applyOrThrow(classInfo)).thenReturn(zeebeDeploymentValue); when(client.newDeployCommand()).thenReturn(deployStep1); when(deployStep1.addResourceFromClasspath(anyString())).thenReturn(deployStep2); deploymentPostProcessor.apply(classInfo).accept(client); } | @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } @Override boolean test(final ClassInfo beanInfo); @Override Consumer<ZeebeClient> apply(final ClassInfo beanInfo); } | DeploymentPostProcessor extends BeanInfoPostProcessor { @Override public Consumer<ZeebeClient> apply(final ClassInfo beanInfo) { final ZeebeDeploymentValue value = reader.applyOrThrow(beanInfo); log.info("deployment: {}", value); return client -> { DeployWorkflowCommandStep1 deployWorkflowCommand = client .newDeployCommand(); DeploymentEvent deploymentResult = value.getClassPathResources() .stream() .map(deployWorkflowCommand::addResourceFromClasspath) .reduce((first, second) -> second) .orElseThrow(() -> new IllegalArgumentException("Requires at least one resource to deploy")) .send() .join(); log.info( "Deployed: {}", deploymentResult .getWorkflows() .stream() .map(wf -> String.format("<%s:%d>", wf.getBpmnProcessId(), wf.getVersion())) .collect(Collectors.joining(","))); }; } @Override boolean test(final ClassInfo beanInfo); @Override Consumer<ZeebeClient> apply(final ClassInfo beanInfo); } |
@Test public void shouldReadSingleClassPathResourceTest() { ClassInfo classInfo = ClassInfo.builder() .bean(new WithSingleClassPathResource()) .build(); when(expressionResolver.resolve(anyString())).thenAnswer(inv -> inv.getArgument(0)); ZeebeDeploymentValue expectedDeploymentValue = ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources(Collections.singletonList("/1.bpmn")) .build(); Optional<ZeebeDeploymentValue> valueForClass = readZeebeDeploymentValue.apply(classInfo); assertTrue(valueForClass.isPresent()); assertEquals(expectedDeploymentValue, valueForClass.get()); } | @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); @Override Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); @Override Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo); } |
@Test public void shouldReadMultipleClassPathResourcesTest() { ClassInfo classInfo = ClassInfo.builder() .bean(new WithMultipleClassPathResource()) .build(); when(expressionResolver.resolve(anyString())).thenAnswer(inv -> inv.getArgument(0)); ZeebeDeploymentValue expectedDeploymentValue = ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources(Arrays.asList("/1.bpmn", "/2.bpmn")) .build(); Optional<ZeebeDeploymentValue> valueForClass = readZeebeDeploymentValue.apply(classInfo); assertTrue(valueForClass.isPresent()); assertEquals(expectedDeploymentValue, valueForClass.get()); } | @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); @Override Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); @Override Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo); } |
@Test public void shouldReadNoClassPathResourcesTest() { ClassInfo classInfo = ClassInfo.builder() .bean(new WithoutAnnotation()) .build(); when(expressionResolver.resolve(anyString())).thenAnswer(inv -> inv.getArgument(0)); Optional<ZeebeDeploymentValue> valueForClass = readZeebeDeploymentValue.apply(classInfo); assertFalse(valueForClass.isPresent()); } | @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); @Override Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo); } | ReadZeebeDeploymentValue extends ReadAnnotationValue<ClassInfo, ZeebeDeployment, ZeebeDeploymentValue> { @Override public Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo) { return classInfo .getAnnotation(annotationType) .map( annotation -> ZeebeDeploymentValue.builder() .beanInfo(classInfo) .classPathResources( resolveResources(annotation.classPathResources()) ) .build()); } ReadZeebeDeploymentValue(final ZeebeExpressionResolver resolver); @Override Optional<ZeebeDeploymentValue> apply(final ClassInfo classInfo); } |
@Test public void testExperiment() { final Alphabet<Character> alphabet = Alphabets.characters('a', 'c'); final CompactDFA<Character> target = RandomAutomata.randomDFA(RANDOM, 5, alphabet); final CompactDFA<Character> intermediateTarget = RandomAutomata.randomDFA(RANDOM, target.size() - 1, alphabet); final MockUpLearner<Character> learner = new MockUpLearner<>(target, intermediateTarget); final DFAEquivalenceOracle<Character> eq = new MockUpOracle<>(intermediateTarget); DFAExperiment<Character> experiment = new DFAExperiment<>(learner, eq, alphabet); experiment.setProfile(true); Assert.assertThrows(experiment::getFinalHypothesis); experiment.run(); Assert.assertThrows(experiment::run); DFA<?, Character> finalModel = experiment.getFinalHypothesis(); Assert.assertNotNull(experiment.getFinalHypothesis()); Assert.assertSame(finalModel, target); Assert.assertTrue(learner.startLearningCalled); Assert.assertEquals(learner.refinementSteps, REFINEMENT_STEPS); Assert.assertNotNull(SimpleProfiler.cumulated(Experiment.LEARNING_PROFILE_KEY)); Assert.assertNotNull(SimpleProfiler.cumulated(Experiment.COUNTEREXAMPLE_PROFILE_KEY)); } | public <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm, EquivalenceOracle<? super A, I, D> equivalenceAlgorithm, Alphabet<I> inputs) { this.impl = new ExperimentImpl<>(learningAlgorithm, equivalenceAlgorithm, inputs); } | Experiment { public <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm, EquivalenceOracle<? super A, I, D> equivalenceAlgorithm, Alphabet<I> inputs) { this.impl = new ExperimentImpl<>(learningAlgorithm, equivalenceAlgorithm, inputs); } } | Experiment { public <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm, EquivalenceOracle<? super A, I, D> equivalenceAlgorithm, Alphabet<I> inputs) { this.impl = new ExperimentImpl<>(learningAlgorithm, equivalenceAlgorithm, inputs); } <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm,
EquivalenceOracle<? super A, I, D> equivalenceAlgorithm,
Alphabet<I> inputs); } | Experiment { public <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm, EquivalenceOracle<? super A, I, D> equivalenceAlgorithm, Alphabet<I> inputs) { this.impl = new ExperimentImpl<>(learningAlgorithm, equivalenceAlgorithm, inputs); } <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm,
EquivalenceOracle<? super A, I, D> equivalenceAlgorithm,
Alphabet<I> inputs); A run(); A getFinalHypothesis(); void setLogModels(boolean logModels); void setProfile(boolean profile); Counter getRounds(); } | Experiment { public <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm, EquivalenceOracle<? super A, I, D> equivalenceAlgorithm, Alphabet<I> inputs) { this.impl = new ExperimentImpl<>(learningAlgorithm, equivalenceAlgorithm, inputs); } <I, D> Experiment(LearningAlgorithm<? extends A, I, D> learningAlgorithm,
EquivalenceOracle<? super A, I, D> equivalenceAlgorithm,
Alphabet<I> inputs); A run(); A getFinalHypothesis(); void setLogModels(boolean logModels); void setProfile(boolean profile); Counter getRounds(); static final String LEARNING_PROFILE_KEY; static final String COUNTEREXAMPLE_PROFILE_KEY; } |
@Test public void testFindCounterExample() { final DefaultQuery<Character, D> cex = bfio.findCounterExample(automaton, ALPHABET); Assert.assertEquals(cex, query); } | @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { return super.findCounterExample(hypothesis, inputs); } | AbstractBFInclusionOracle extends AbstractBFOracle<A, I, D> implements InclusionOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { return super.findCounterExample(hypothesis, inputs); } } | AbstractBFInclusionOracle extends AbstractBFOracle<A, I, D> implements InclusionOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { return super.findCounterExample(hypothesis, inputs); } AbstractBFInclusionOracle(MembershipOracle<I, D> membershipOracle, double multiplier); } | AbstractBFInclusionOracle extends AbstractBFOracle<A, I, D> implements InclusionOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { return super.findCounterExample(hypothesis, inputs); } AbstractBFInclusionOracle(MembershipOracle<I, D> membershipOracle, double multiplier); @Override boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, D output); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); } | AbstractBFInclusionOracle extends AbstractBFOracle<A, I, D> implements InclusionOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { return super.findCounterExample(hypothesis, inputs); } AbstractBFInclusionOracle(MembershipOracle<I, D> membershipOracle, double multiplier); @Override boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, D output); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); } |
@Test public void testGetPropertyOracles() { Assert.assertEquals(oracle.getPropertyOracles().size(), 2); } | @Override public List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles() { return propertyOracles; } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles() { return propertyOracles; } } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles() { return propertyOracles; } CExFirstOracle(); CExFirstOracle(PropertyOracle<I, A, ?, D> propertyOracle); CExFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles() { return propertyOracles; } CExFirstOracle(); CExFirstOracle(PropertyOracle<I, A, ?, D> propertyOracle); CExFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); @Override List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles(); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles() { return propertyOracles; } CExFirstOracle(); CExFirstOracle(PropertyOracle<I, A, ?, D> propertyOracle); CExFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); @Override List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles(); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); } |
@Test public void testFindCounterExample() { final DefaultQuery<Boolean, Boolean> ce = oracle.findCounterExample(automaton, inputs); Assert.assertEquals(ce, query); Mockito.verify(po1).disprove(automaton, inputs); Mockito.verify(po2, Mockito.never()).disprove(automaton, inputs); Mockito.verify(po2, Mockito.never()).findCounterExample(automaton, inputs); } | @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { for (PropertyOracle<I, ? super A, ?, D> propertyOracle : propertyOracles) { final DefaultQuery<I, D> result = propertyOracle.findCounterExample(hypothesis, inputs); if (result != null) { assert isCounterExample(hypothesis, result.getInput(), result.getOutput()); return result; } } return null; } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { for (PropertyOracle<I, ? super A, ?, D> propertyOracle : propertyOracles) { final DefaultQuery<I, D> result = propertyOracle.findCounterExample(hypothesis, inputs); if (result != null) { assert isCounterExample(hypothesis, result.getInput(), result.getOutput()); return result; } } return null; } } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { for (PropertyOracle<I, ? super A, ?, D> propertyOracle : propertyOracles) { final DefaultQuery<I, D> result = propertyOracle.findCounterExample(hypothesis, inputs); if (result != null) { assert isCounterExample(hypothesis, result.getInput(), result.getOutput()); return result; } } return null; } CExFirstOracle(); CExFirstOracle(PropertyOracle<I, A, ?, D> propertyOracle); CExFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { for (PropertyOracle<I, ? super A, ?, D> propertyOracle : propertyOracles) { final DefaultQuery<I, D> result = propertyOracle.findCounterExample(hypothesis, inputs); if (result != null) { assert isCounterExample(hypothesis, result.getInput(), result.getOutput()); return result; } } return null; } CExFirstOracle(); CExFirstOracle(PropertyOracle<I, A, ?, D> propertyOracle); CExFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); @Override List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles(); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); } | CExFirstOracle implements BlackBoxOracle<A, I, D> { @Override public @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs) { for (PropertyOracle<I, ? super A, ?, D> propertyOracle : propertyOracles) { final DefaultQuery<I, D> result = propertyOracle.findCounterExample(hypothesis, inputs); if (result != null) { assert isCounterExample(hypothesis, result.getInput(), result.getOutput()); return result; } } return null; } CExFirstOracle(); CExFirstOracle(PropertyOracle<I, A, ?, D> propertyOracle); CExFirstOracle(Collection<? extends PropertyOracle<I, ? super A, ?, D>> propertyOracles); @Override List<PropertyOracle<I, ? super A, ?, D>> getPropertyOracles(); @Override @Nullable DefaultQuery<I, D> findCounterExample(A hypothesis, Collection<? extends I> inputs); } |
@Test public void testOracle() { final DummySUL dummySUL = new DummySUL(); final MealyEquivalenceOracle<Character, Character> mOracle = new RandomWalkEQOracle<>(dummySUL, 0.01, MAX_LENGTH, new Random(42)); final DefaultQuery<Character, Word<Character>> ce = mOracle.findCounterExample(new DummyMealy(ALPHABET), ALPHABET); Assert.assertNull(ce); Assert.assertTrue(dummySUL.isCalledPost()); } | @Override public @Nullable DefaultQuery<I, Word<O>> findCounterExample(MealyMachine<?, I, ?, O> hypothesis, Collection<? extends I> inputs) { return doFindCounterExample(hypothesis, inputs); } | RandomWalkEQOracle implements MealyEquivalenceOracle<I, O> { @Override public @Nullable DefaultQuery<I, Word<O>> findCounterExample(MealyMachine<?, I, ?, O> hypothesis, Collection<? extends I> inputs) { return doFindCounterExample(hypothesis, inputs); } } | RandomWalkEQOracle implements MealyEquivalenceOracle<I, O> { @Override public @Nullable DefaultQuery<I, Word<O>> findCounterExample(MealyMachine<?, I, ?, O> hypothesis, Collection<? extends I> inputs) { return doFindCounterExample(hypothesis, inputs); } RandomWalkEQOracle(SUL<I, O> sul,
double restartProbability,
long maxSteps,
boolean resetStepCount,
Random random); RandomWalkEQOracle(SUL<I, O> sul, double restartProbability, long maxSteps, Random random); } | RandomWalkEQOracle implements MealyEquivalenceOracle<I, O> { @Override public @Nullable DefaultQuery<I, Word<O>> findCounterExample(MealyMachine<?, I, ?, O> hypothesis, Collection<? extends I> inputs) { return doFindCounterExample(hypothesis, inputs); } RandomWalkEQOracle(SUL<I, O> sul,
double restartProbability,
long maxSteps,
boolean resetStepCount,
Random random); RandomWalkEQOracle(SUL<I, O> sul, double restartProbability, long maxSteps, Random random); @Override @Nullable DefaultQuery<I, Word<O>> findCounterExample(MealyMachine<?, I, ?, O> hypothesis,
Collection<? extends I> inputs); } | RandomWalkEQOracle implements MealyEquivalenceOracle<I, O> { @Override public @Nullable DefaultQuery<I, Word<O>> findCounterExample(MealyMachine<?, I, ?, O> hypothesis, Collection<? extends I> inputs) { return doFindCounterExample(hypothesis, inputs); } RandomWalkEQOracle(SUL<I, O> sul,
double restartProbability,
long maxSteps,
boolean resetStepCount,
Random random); RandomWalkEQOracle(SUL<I, O> sul, double restartProbability, long maxSteps, Random random); @Override @Nullable DefaultQuery<I, Word<O>> findCounterExample(MealyMachine<?, I, ?, O> hypothesis,
Collection<? extends I> inputs); } |
@Test public void testResetIdempotency() { final SUL<Character, Integer> mock = Mockito.spy(sul); final SULSymbolQueryOracle<Character, Integer> oracle = new SULSymbolQueryOracle<>(mock); Mockito.verify(mock, Mockito.times(0)).pre(); Mockito.verify(mock, Mockito.times(0)).post(); oracle.reset(); oracle.reset(); oracle.reset(); Mockito.verify(mock, Mockito.times(0)).pre(); Mockito.verify(mock, Mockito.times(0)).post(); } | @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } SULSymbolQueryOracle(final SUL<I, O> sul); } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } SULSymbolQueryOracle(final SUL<I, O> sul); @Override O query(I i); @Override void reset(); } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } SULSymbolQueryOracle(final SUL<I, O> sul); @Override O query(I i); @Override void reset(); } |
@Test public void testQueriesAndCleanUp() { final SUL<Character, Integer> mock = Mockito.spy(sul); final SULSymbolQueryOracle<Character, Integer> oracle = new SULSymbolQueryOracle<>(mock); Mockito.verify(mock, Mockito.times(0)).pre(); Mockito.verify(mock, Mockito.times(0)).post(); final Word<Character> i1 = Word.fromCharSequence("abcabcabc"); final Word<Integer> o1 = oracle.answerQuery(i1); oracle.reset(); Assert.assertEquals(o1, example.getReferenceAutomaton().computeOutput(i1)); Mockito.verify(mock, Mockito.times(1)).pre(); Mockito.verify(mock, Mockito.times(1)).post(); Mockito.verify(mock, Mockito.times(i1.size())).step(Mockito.anyChar()); final Word<Character> i2 = Word.fromCharSequence("cba"); final Word<Integer> o2 = oracle.answerQuery(i2); oracle.reset(); oracle.reset(); Assert.assertEquals(o2, example.getReferenceAutomaton().computeOutput(i2)); Mockito.verify(mock, Mockito.times(2)).pre(); Mockito.verify(mock, Mockito.times(2)).post(); Mockito.verify(mock, Mockito.times(i1.size() + i2.size())).step(Mockito.anyChar()); } | @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } SULSymbolQueryOracle(final SUL<I, O> sul); } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } SULSymbolQueryOracle(final SUL<I, O> sul); @Override O query(I i); @Override void reset(); } | SULSymbolQueryOracle implements SymbolQueryOracle<I, O> { @Override public void reset() { if (postRequired) { this.sul.post(); this.postRequired = false; } this.preRequired = true; } SULSymbolQueryOracle(final SUL<I, O> sul); @Override O query(I i); @Override void reset(); } |
@Test public void testDFASimulatorOmegaOracle() { DFA<Integer, Symbol> dfa = ExamplePaulAndMary.constructMachine(); DFASimulatorOmegaOracle<Integer, Symbol> oracle = new DFASimulatorOmegaOracle<>(dfa); List<OmegaQuery<Symbol, Boolean>> queries = new ArrayList<>(); OmegaQuery<Symbol, Boolean> q1 = new OmegaQuery<>(Word.epsilon(), Word.fromSymbols(ExamplePaulAndMary.IN_PAUL, ExamplePaulAndMary.IN_LOVES, ExamplePaulAndMary.IN_MARY), 1); OmegaQuery<Symbol, Boolean> q2 = new OmegaQuery<>(Word.fromSymbols(ExamplePaulAndMary.IN_MARY), Word.fromSymbols(ExamplePaulAndMary.IN_MARY, ExamplePaulAndMary.IN_LOVES, ExamplePaulAndMary.IN_PAUL), 1); queries.add(q1); queries.add(q2); Assert.assertEquals(queries.get(0).getLoop().size(), 3); Assert.assertEquals(queries.get(1).getLoop().size(), 3); oracle.processQueries(queries); Assert.assertFalse(queries.get(0).isUltimatelyPeriodic()); Assert.assertTrue(queries.get(1).isUltimatelyPeriodic()); Assert.assertEquals(queries.get(1).getOutput(), Boolean.FALSE); } | @Override public void processQueries(Collection<? extends OmegaQuery<I, D>> queries) { MQUtil.answerOmegaQueries(this, queries); } | SimulatorOmegaOracle implements SingleQueryOmegaOracle<S, I, D> { @Override public void processQueries(Collection<? extends OmegaQuery<I, D>> queries) { MQUtil.answerOmegaQueries(this, queries); } } | SimulatorOmegaOracle implements SingleQueryOmegaOracle<S, I, D> { @Override public void processQueries(Collection<? extends OmegaQuery<I, D>> queries) { MQUtil.answerOmegaQueries(this, queries); } <A extends SuffixOutput<I, D> & SimpleDTS<S, I>> SimulatorOmegaOracle(A automaton, SimulatorOracle<I, D> simulatorOracle); } | SimulatorOmegaOracle implements SingleQueryOmegaOracle<S, I, D> { @Override public void processQueries(Collection<? extends OmegaQuery<I, D>> queries) { MQUtil.answerOmegaQueries(this, queries); } <A extends SuffixOutput<I, D> & SimpleDTS<S, I>> SimulatorOmegaOracle(A automaton, SimulatorOracle<I, D> simulatorOracle); @Override MembershipOracle<I, D> getMembershipOracle(); @Override boolean isSameState(Word<I> input1, S s1, Word<I> input2, S s2); @Override void processQueries(Collection<? extends OmegaQuery<I, D>> queries); @Override Pair<D, Integer> answerQuery(Word<I> prefix, Word<I> loop, int repeat); } | SimulatorOmegaOracle implements SingleQueryOmegaOracle<S, I, D> { @Override public void processQueries(Collection<? extends OmegaQuery<I, D>> queries) { MQUtil.answerOmegaQueries(this, queries); } <A extends SuffixOutput<I, D> & SimpleDTS<S, I>> SimulatorOmegaOracle(A automaton, SimulatorOracle<I, D> simulatorOracle); @Override MembershipOracle<I, D> getMembershipOracle(); @Override boolean isSameState(Word<I> input1, S s1, Word<I> input2, S s2); @Override void processQueries(Collection<? extends OmegaQuery<I, D>> queries); @Override Pair<D, Integer> answerQuery(Word<I> prefix, Word<I> loop, int repeat); } |
Subsets and Splits