file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
RawStoreManager.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/RawStoreManager.java
package store; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import config.profile.SqlColProfile; import store.entity.database.MainData; import javax.inject.Inject; import javax.inject.Singleton; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @Slf4j @Singleton public class RawStoreManager { private StoreManager storeManager; private ConvertManager convertManager; @Getter @Setter private List<SqlColProfile> sqlColMetadatumPojos; @Inject public RawStoreManager(StoreManager storeManager, ConvertManager convertManager) { this.storeManager = storeManager; this.convertManager = convertManager; } public void loadData(long sampleTime, List<Map<Integer, Object>> rows0){ if (!rows0.isEmpty()) { this.storeManager.getDatabaseDAO().getMainDataDAO().putMainDataNoOverwrite( new MainData(sampleTime, loadFromCollectionToArray(rows0)) ); } } private int [][] loadFromCollectionToArray(List<Map<Integer, Object>> rows){ int numberOfCol = rows.stream().findFirst().get().size(); int [][] out = new int[rows.size()][numberOfCol]; AtomicInteger atomicInt = new AtomicInteger(0); rows.stream().forEach(e -> { int [] rowOut = new int[numberOfCol]; try { for (int i = 0; i < e.entrySet().size(); i++) { rowOut[i] = this.convertManager.convertFromRawToInt(sqlColMetadatumPojos.get(i), e.get(i)); } } catch (Exception err) { log.error(err.getMessage()); log.error(Arrays.toString(err.getStackTrace())); } out [atomicInt.getAndIncrement()] = rowOut; }); return out; } }
1,970
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OlapCacheManager.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/OlapCacheManager.java
package store; import core.manager.ConstantManager; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import profile.IProfile; import store.cache.CompositeKeyCache; import store.entity.olap.AshAggrMinData; import store.entity.olap.AshAggrMinData15Sec; import store.entity.olap.AshAggrMinData1Min; import store.service.OlapDAO; import javax.inject.Inject; import javax.inject.Singleton; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @Slf4j @Singleton public class OlapCacheManager { private OlapDAO olapDAO; @Getter @Setter private IProfile iProfile; // cache public enum AggregationTime {OneSecond, FifteenSecond, OneMinute} private long cache1SecLongId = 0; private long cache15SecLongId = 0; private long cache1MinLongId = 0; private Map<CompositeKeyCache, Map<Integer,Integer>> hashmap1SecCache = new HashMap<>(); private Map<CompositeKeyCache, Map<Integer,Integer>> hashmap15SecCache = new HashMap<>(); private Map<CompositeKeyCache, Map<Integer,Integer>> hashmap1MinCache = new HashMap<>(); @Inject public OlapCacheManager (OlapDAO olapDAO){ this.olapDAO = olapDAO; } /** *<pre> *{@code Load RAW data from ASH online to aggregate set of tables. * * @param dt dateId of row * @param parameter of aggregations by sqlId, sessionId+serial#, etc * @param additional parameters (OpName, Program, UserId etc.) * @param waitEvent wait class or event * @param waitClass group by type of wait class or event * CPU used = 0, * System I/O = 1, etc *} * </pre> */ public void loadAshRawData(LocalDateTime dt, String parameter, String[] additionalParams, String waitEvent, byte waitClass){ // Check directory int paramIdSec = olapDAO.getCheckOrLoadParameter(parameter, additionalParams); // 1 sec/min int waitEventI = olapDAO.getCheckOrLoadWaitEvent(waitEvent, waitClass); LocalDateTime beginDtS = LocalDateTime.of( dt.getYear(), dt.getMonth(), dt.getDayOfMonth(), dt.getHour(), dt.getMinute(), dt.getSecond()); loadAshRawData(beginDtS, paramIdSec, waitEventI, cache1SecLongId, hashmap1SecCache, String.valueOf(AggregationTime.OneSecond)); LocalDateTime beginDtS15 = LocalDateTime.of( dt.getYear(), dt.getMonth(), dt.getDayOfMonth(), dt.getHour(), dt.getMinute(), getLocalDateTime15Sec(dt.getSecond())); loadAshRowData15(beginDtS15, paramIdSec, waitEventI, cache15SecLongId, hashmap15SecCache, String.valueOf(AggregationTime.FifteenSecond)); LocalDateTime beginDtM = LocalDateTime.of( dt.getYear(), dt.getMonth(), dt.getDayOfMonth(), dt.getHour(), dt.getMinute()); loadAshRawData(beginDtM, paramIdSec, waitEventI, cache1MinLongId, hashmap1MinCache, String.valueOf(AggregationTime.OneMinute)); } private void loadAshRawData(LocalDateTime dt, int paramId, int waitEventId, long cacheId, Map<CompositeKeyCache, Map<Integer, Integer>> hashmapCache, String aggregationTime){ long dateIdSec = dt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); CompositeKeyCache compositeKeyCacheSec = new CompositeKeyCache(dateIdSec, paramId); if (cacheId == dateIdSec) { //update cache data with new values this.updateCacheData(hashmapCache, compositeKeyCacheSec, waitEventId); } else { cacheId = dateIdSec; this.loadDataToLocalDb(hashmapCache, aggregationTime);//load data to bdb hashmapCache.clear(); this.updateCacheData(hashmapCache, compositeKeyCacheSec, waitEventId); } } private void loadAshRowData15(LocalDateTime dt, int paramId, int waitEventId, long cacheId, Map<CompositeKeyCache, Map<Integer, Integer>> hashmapCache, String aggregationTime){ long dateIdSec = dt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); CompositeKeyCache compositeKeyCacheSec = new CompositeKeyCache(dateIdSec, paramId); this.updateCacheData(hashmapCache, compositeKeyCacheSec, waitEventId); cache15SecLongId = dateIdSec; } public void unloadCacheToDB() { if (hashmap1SecCache.entrySet().stream().findAny().isPresent()) { cache1SecLongId = hashmap1SecCache.entrySet().stream().findAny().get().getKey().getDateId(); this.loadDataToLocalDb(hashmap1SecCache, String.valueOf(AggregationTime.OneSecond));//load data to bdb hashmap1SecCache.clear(); } } public void unloadCacheToDB15(long currentDbSysdate){ if ((long) hashmap15SecCache.entrySet().size() > 1) { if (hashmap15SecCache.entrySet().stream().max(Map.Entry.comparingByKey()).isPresent()) { Map<CompositeKeyCache, Map<Integer, Integer>> hashMapTmp = new HashMap<>(); long maxV = hashmap15SecCache.entrySet().stream().max(Map.Entry.comparingByKey()).get().getKey().getDateId(); hashmap15SecCache.entrySet().stream() .filter(s -> s.getKey().getDateId() == maxV) .forEach(e -> hashMapTmp.putIfAbsent(e.getKey(), e.getValue())); hashmap15SecCache.keySet().removeIf(val -> val.getDateId() == maxV); this.loadDataToLocalDb(hashmap15SecCache, String.valueOf(AggregationTime.FifteenSecond));//load data to bdb hashmap15SecCache.clear(); hashmap15SecCache = hashMapTmp; } } else if ((long) hashmap15SecCache.entrySet().size() == 1) { if (hashmap15SecCache.entrySet().stream().max(Map.Entry.comparingByKey()).isPresent()) { long maxV = hashmap15SecCache.entrySet().stream().max(Map.Entry.comparingByKey()).get().getKey().getDateId(); if ((currentDbSysdate - maxV) > 15000) { this.loadDataToLocalDb(hashmap15SecCache, String.valueOf(AggregationTime.FifteenSecond));//load data to bdb hashmap15SecCache.clear(); } } } } private void updateCacheData(Map<CompositeKeyCache, Map<Integer,Integer>> hashmapCache, CompositeKeyCache compositeKeyCache, int waitEventI){ if (hashmapCache.containsKey(compositeKeyCache)){ if (hashmapCache.get(compositeKeyCache).containsKey(waitEventI)){ int tmp = hashmapCache.get(compositeKeyCache).get(waitEventI); hashmapCache.get(compositeKeyCache).put(waitEventI, tmp + 1); } else { hashmapCache.get(compositeKeyCache).put(waitEventI, 1); } } else { hashmapCache.put(compositeKeyCache, new HashMap<>()); hashmapCache.get(compositeKeyCache).put(waitEventI, 1); } } private void loadDataToLocalDb(Map<CompositeKeyCache, Map<Integer,Integer>> hashmapCache, String aggregationTime){ hashmapCache.entrySet().forEach(e -> { int[] waitId = new int[e.getValue().size()]; int[] waitClass = new int[e.getValue().size()]; int[] sum = new int[e.getValue().size()]; int index = 0; for (Map.Entry<Integer, Integer> mapEntry : e.getValue().entrySet()) { waitId[index] = mapEntry.getKey(); waitClass[index] = this.olapDAO.getClassIdForWaitEventId(mapEntry.getKey()); sum[index] = mapEntry.getValue(); index++; } boolean isExist = putDataOverwrite(aggregationTime, e.getKey().getDateId(), e.getKey().getParamId(), waitId, waitClass, sum); if (!isExist){ Map<Integer, Integer> allWaitId0 = ConstantManager.zipToMap(ConstantManager.toList(waitId), ConstantManager.toList(sum)); Map<Integer, Integer> allWaitId1 = ConstantManager.zipToMap( ConstantManager.toList( getMatrixValues(0, aggregationTime, e.getKey())), //mtrx[0]::waitId; ConstantManager.toList( getMatrixValues(2, aggregationTime, e.getKey()))); //mtrx[2]::sum; Map<Integer, Integer> mx = Stream.of(allWaitId0, allWaitId1) .map(Map::entrySet) .flatMap(Collection::stream) .collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, Integer::sum ) ); int[] waitId0 = new int[mx.size()]; int[] waitClass0 = new int[mx.size()]; int[] sum0 = new int[mx.size()]; int index0 = 0; for (Map.Entry<Integer, Integer> mapEntry0 : mx.entrySet()) { waitId0[index0] = mapEntry0.getKey(); waitClass0[index0] = this.olapDAO.getClassIdForWaitEventId(mapEntry0.getKey()); sum0[index0] = mapEntry0.getValue(); index0++; } putDataOverwrite(aggregationTime, e.getKey().getDateId(), e.getKey().getParamId(), waitId0, waitClass0, sum0); } }); } private int[] getMatrixValues(int id, String aggregationTime, CompositeKeyCache compositeKeyCache){ switch (aggregationTime) { case "OneSecond": AshAggrMinData aggrMinData1Sec = this.olapDAO.getAshAggrMinDataDAO().getAshAggrMinDataRange( compositeKeyCache.getDateId(), compositeKeyCache.getParamId()); return aggrMinData1Sec.getMatrixValues()[id]; case "FifteenSecond": AshAggrMinData15Sec aggrMinData15Sec = this.olapDAO.getAshAggrMinData15SecDAO().getAshAggrMinDataRange( compositeKeyCache.getDateId(), compositeKeyCache.getParamId()); return aggrMinData15Sec.getMatrixValues()[id]; case "OneMinute": AshAggrMinData1Min aggrMinData1Min = this.olapDAO.getAshAggrMinData1MinDAO().getAshAggrMinDataRange( compositeKeyCache.getDateId(), compositeKeyCache.getParamId()); return aggrMinData1Min.getMatrixValues()[id]; default: throw new IllegalArgumentException("Invalid aggregation time"); } } private boolean putDataOverwrite(String aggregationTime, long dateId, int paramId, int[] waitId, int[] waitClass, int[] sum){ switch (aggregationTime) { case "OneSecond": AshAggrMinData obj1sec = new AshAggrMinData(dateId, paramId, waitId, waitClass, sum); return olapDAO.getAshAggrMinDataDAO().putDataNoOverwrite(obj1sec); case "FifteenSecond": AshAggrMinData15Sec obj15sec = new AshAggrMinData15Sec(dateId, paramId, waitId, waitClass, sum); return olapDAO.getAshAggrMinData15SecDAO().putDataNoOverwrite(obj15sec); case "OneMinute": AshAggrMinData1Min obj1min = new AshAggrMinData1Min(dateId, paramId, waitId, waitClass, sum); return olapDAO.getAshAggrMinData1MinDAO().putDataNoOverwrite(obj1min); default: throw new IllegalArgumentException("Invalid aggregation time"); } } private int getLocalDateTime15Sec(int seconds){ if (seconds >= 0 & seconds < 15){ return 0; } else if (seconds >= 15 & seconds < 30){ return 15; } else if (seconds >= 30 & seconds < 45) { return 30; } else if (seconds >= 45 & seconds <= 59) { return 45; } else { return 0; } } }
12,878
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StoreManager.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/StoreManager.java
package store; import com.sleepycat.je.DatabaseException; import config.FileConfig; import core.manager.ConfigurationManager; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import store.service.DatabaseDAO; import store.service.OlapDAO; import utility.StackTraceUtil; import javax.inject.Inject; import javax.inject.Singleton; import java.io.IOException; @Slf4j @Singleton public class StoreManager { private FileConfig fileConfig; @Getter private OlapCacheManager olapCacheManager; @Getter private ConfigurationManager configurationManager; @Getter private BerkleyDB berkleyDB; @Getter private DatabaseDAO databaseDAO; @Getter private OlapDAO olapDAO; @Getter @Setter private long lastLoadTimeMark; @Inject public StoreManager(FileConfig fileConfig, OlapCacheManager olapCacheManager, ConfigurationManager configurationManager, BerkleyDB berkleyDB, DatabaseDAO databaseDAO, OlapDAO olapDAO) { try { this.fileConfig = fileConfig; this.olapCacheManager = olapCacheManager; this.configurationManager = configurationManager; this.berkleyDB = berkleyDB; this.databaseDAO = databaseDAO; this.olapDAO = olapDAO; } catch (DatabaseException e) { log.error(StackTraceUtil.getCustomStackTrace(e)); System.exit(-1); } } public void setUpBDBAndDAO(String connName) throws IOException { String connNameDir = FileConfig.DATABASE_DIR + FileConfig.FILE_SEPARATOR + connName; fileConfig.setUpDirectory(connNameDir); berkleyDB.init(connNameDir); databaseDAO.init(); olapDAO.init(); } public void syncBdb() { if (this.berkleyDB.getStore() != null) { this.berkleyDB.getStore().sync(); } } public void closeDb() { if (this.berkleyDB.getStore() != null) { try {this.berkleyDB.getStore().close(); } catch (DatabaseException dbe) { log.error("Error closing store: " + dbe.toString()); } } if (this.berkleyDB.getEnv() != null) { try { this.berkleyDB.getEnv().close(); } catch (DatabaseException dbe) { log.error("Error closing env: " + dbe.toString()); } } } }
2,478
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ConvertManager.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/ConvertManager.java
package store; import config.Labels; import core.manager.ConstantManager; import lombok.extern.slf4j.Slf4j; import config.profile.SqlColProfile; import store.entity.database.MainData; import store.service.DatabaseDAO; import utility.BinaryDisplayConverter; import javax.inject.Inject; import javax.inject.Singleton; import java.math.BigDecimal; import java.sql.Clob; import java.sql.Date; import java.sql.SQLException; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import static java.lang.String.valueOf; @Slf4j @Singleton public class ConvertManager { private StoreManager storeManager; private enum OracleType {CLOB,VARCHAR2,CHAR,RAW,NUMBER,INT4,FLOAT8,DATE,TIMESTAMP,TIMESTAMPTZ,OID,TEXT,NAME,NUMERIC} private int intNullValue = Integer.MIN_VALUE; @Inject public ConvertManager(StoreManager storeManager){ this.storeManager = storeManager; } public String convertFromRawToString(String colType, Object obj) { if (obj == null){ return ConstantManager.NULL_VALUE; } switch (OracleType.valueOf(colType)) { case OID: // PG return valueOf(obj); case TEXT: // PG case NAME: // PG case VARCHAR2: case CHAR: return (String) obj; case INT4: Integer int0 = (Integer) obj; return valueOf(int0.intValue()); case FLOAT8: Double dbl0 = (Double) obj; return valueOf(dbl0.intValue()); case NUMBER: case NUMERIC: BigDecimal bgDec = (BigDecimal) obj; return valueOf(bgDec.longValue()); case DATE: case TIMESTAMP: case TIMESTAMPTZ: Timestamp dt = (Timestamp) obj; return valueOf(dt.getTime()); case RAW: return getByte(obj); case CLOB: Clob clobVal = (Clob) obj; try { return clobVal.getSubString(1, (int) clobVal.length()); } catch (SQLException e) { log.info("No data found while clob processing"); return "No clob data"; } default: return ConstantManager.NULL_VALUE; } } private String getByte(Object obj){ Byte[] useValue; byte[] bytes = (byte[]) obj; useValue = new Byte[bytes.length]; for (int m=0; m<bytes.length; m++) { useValue[m] = Byte.valueOf(bytes[m]); } return BinaryDisplayConverter.convertToString(useValue, BinaryDisplayConverter.HEX, false); } public int convertFromRawToInt(SqlColProfile sqlColProfile, Object obj){ switch (OracleType.valueOf(sqlColProfile.getColDbTypeName())) { case OID: // PG return storeManager.getDatabaseDAO() .getParameterStringDAO().getCheckOrLoadParameter (obj == null ? Labels.getLabel("local.null") : valueOf(obj)); case TEXT: // PG case NAME: // PG case VARCHAR2: case CHAR: return storeManager.getDatabaseDAO() .getParameterStringDAO().getCheckOrLoadParameter (obj == null ? Labels.getLabel("local.null") : (String) obj); case INT4:// PG Integer int0 = (Integer) obj; return int0 == null ? intNullValue : ((int0 >= 0) ? int0 : -1 * storeManager.getDatabaseDAO() .getParameterDoubleDAO().getCheckOrLoadParameter(int0.doubleValue()) ); case FLOAT8:// PG Double dbl0 = (Double) obj; return dbl0 == null ? intNullValue : ((dbl0.intValue() >= 0) ? dbl0.intValue() : -1 * storeManager.getDatabaseDAO() .getParameterDoubleDAO().getCheckOrLoadParameter(dbl0) ); case NUMBER: BigDecimal bigDecimal = (BigDecimal) obj; return bigDecimal == null ? intNullValue : ((bigDecimal.intValue() >= 0) ? bigDecimal.intValue() : -1 * storeManager.getDatabaseDAO() .getParameterDoubleDAO().getCheckOrLoadParameter(bigDecimal.doubleValue()) ); case DATE: case TIMESTAMP: case TIMESTAMPTZ: Timestamp dt = (Timestamp) obj; return (int) (dt == null ? intNullValue : dt.getTime()/1000); case RAW: return storeManager.getDatabaseDAO() .getParameterStringDAO().getCheckOrLoadParameter (obj == null ? Labels.getLabel("local.null") : getByte(obj)); default: return intNullValue; } } public Object getMatrixDataForJTable(String columnTypeCategoryId, int columnCategoryId, MainData sl, int row) { DatabaseDAO dao = storeManager.getDatabaseDAO(); int intval = sl.getMainMatrix()[row][columnCategoryId-1]; if (intval == intNullValue) return Labels.getLabel("local.null"); switch (OracleType.valueOf(columnTypeCategoryId)) { case OID: // PG case TEXT: // PG case NAME: // PG case VARCHAR2: case CHAR: case RAW: return dao.getParameterStringDAO().getParameterStrById(intval); case INT4: case FLOAT8: case NUMBER: if (intval < 0) { return valueOf0(dao.parameterDoubleDAO.getParameterStrById(-1 * intval)); } else { return String.valueOf(intval); } case DATE: case TIMESTAMP: case TIMESTAMPTZ: return getDateForLongShorted(intval); default: return intval; } } private String getDateForLongShorted(int longDate){ //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Labels.getLabel("gui.table.tabledatapanel.dateformat")); Date dtDate= new Date(((long)longDate)*1000L); return simpleDateFormat.format(dtDate); } public String valueOf0(double value) { DecimalFormat formatter; if(value - (int)value > 0.0) formatter = new DecimalFormat("0"); else formatter = new DecimalFormat("0"); return formatter.format(value); } }
6,876
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IParameterDoubleDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/IParameterDoubleDAO.java
package store.dao.database; public interface IParameterDoubleDAO { int getCheckOrLoadParameter(double parameter); double getParameterStrById(int id); }
161
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ISqlPlan.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/ISqlPlan.java
package store.dao.database; import com.sleepycat.persist.SecondaryIndex; import store.entity.database.SqlPlan; public interface ISqlPlan { boolean putSqlPlanNoOverwrite(SqlPlan sqlPlan); boolean checkSqlIdAndPlanHashValueExist(String sqlId, Long planHashValue); SecondaryIndex<String, Long, SqlPlan> getEnityCurSqlId(); SecondaryIndex<Long, Long, SqlPlan> getEnityCurPlanHashValue(); }
404
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IMainDataDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/IMainDataDAO.java
package store.dao.database; import com.sleepycat.persist.PrimaryIndex; import store.entity.database.MainData; public interface IMainDataDAO { boolean putMainDataNoOverwrite(MainData mainData); PrimaryIndex<Long, MainData> getPrimaryIndex(); }
253
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IParameterStringDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/IParameterStringDAO.java
package store.dao.database; public interface IParameterStringDAO { int getCheckOrLoadParameter(String parameter); String getParameterStrById(int id); }
161
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ParameterStringDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/ParameterStringDAO.java
package store.dao.database; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import com.sleepycat.persist.SecondaryIndex; import store.entity.database.ParameterString; public class ParameterStringDAO implements IParameterStringDAO { private EntityStore store; private PrimaryIndex<Integer, ParameterString> rdaStringParameterPrimIndex; private SecondaryIndex<String, Integer, ParameterString> rdaStringParameterSecIndex; public ParameterStringDAO(EntityStore store){ this.store = store; this.rdaStringParameterPrimIndex = store.getPrimaryIndex(Integer.class, ParameterString.class); this.rdaStringParameterSecIndex = store.getSecondaryIndex(rdaStringParameterPrimIndex, String.class, "paramValue"); } @Override public int getCheckOrLoadParameter(String parameter){ if (!this.rdaStringParameterSecIndex.contains(parameter)){ this.rdaStringParameterPrimIndex.putNoOverwrite( new ParameterString(0, parameter) ); } return this.rdaStringParameterSecIndex.get(parameter).getParamId(); } @Override public String getParameterStrById(int id){ return this.rdaStringParameterPrimIndex.get(id).getParamValue(); } }
1,280
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MainDataDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/MainDataDAO.java
package store.dao.database; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import store.entity.database.MainData; public class MainDataDAO implements IMainDataDAO { private EntityStore store; private PrimaryIndex<Long, MainData> mainDataPrimaryIndex; public MainDataDAO(EntityStore store) { this.store = store; this.mainDataPrimaryIndex = store.getPrimaryIndex(Long.class, MainData.class); } public boolean putMainDataNoOverwrite(MainData mainData){ return this.mainDataPrimaryIndex.putNoOverwrite(mainData); } @Override public PrimaryIndex<Long, MainData> getPrimaryIndex() { return mainDataPrimaryIndex; } }
722
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SqlPlanDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/SqlPlanDAO.java
package store.dao.database; import com.sleepycat.persist.EntityCursor; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import com.sleepycat.persist.SecondaryIndex; import store.entity.database.SqlPlan; public class SqlPlanDAO implements ISqlPlan{ private EntityStore store; private PrimaryIndex<Long, SqlPlan> mainDataPrimaryIndex; private SecondaryIndex<String, Long, SqlPlan> sqlIdSecIndex; private SecondaryIndex<Long, Long, SqlPlan> planHashValueSecIndex; public SqlPlanDAO(EntityStore store){ this.store = store; this.mainDataPrimaryIndex = store.getPrimaryIndex(Long.class, SqlPlan.class); this.sqlIdSecIndex = store.getSecondaryIndex(mainDataPrimaryIndex, String.class, "sqlId"); this.planHashValueSecIndex = store.getSecondaryIndex(mainDataPrimaryIndex, Long.class, "planHashValue"); } @Override public boolean putSqlPlanNoOverwrite(SqlPlan sqlPlan) { return this.mainDataPrimaryIndex.putNoOverwrite(sqlPlan); } @Override public boolean checkSqlIdAndPlanHashValueExist(String sqlId, Long planHashValue) { boolean isExist = false; EntityCursor<SqlPlan> sqlIdData = this.getEnityCurSqlId().subIndex(sqlId).entities(); try { for (SqlPlan metaEAV : sqlIdData) { if (metaEAV.getPlanHashValue() == planHashValue) isExist = true; } } finally { sqlIdData.close(); } return isExist; } @Override public SecondaryIndex<String, Long, SqlPlan> getEnityCurSqlId() { return sqlIdSecIndex; } @Override public SecondaryIndex<Long, Long, SqlPlan> getEnityCurPlanHashValue() { return planHashValueSecIndex; } }
1,772
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IParamStringStringDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/IParamStringStringDAO.java
package store.dao.database; public interface IParamStringStringDAO { void putNoOverwrite(String parameter, String value); String getValue (String parameter); boolean isExistValueByParameter (String parameter); }
225
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ParamStringStringDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/ParamStringStringDAO.java
package store.dao.database; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import com.sleepycat.persist.SecondaryIndex; import store.entity.database.ParamStringString; import java.util.Optional; public class ParamStringStringDAO implements IParamStringStringDAO { private EntityStore store; private PrimaryIndex<String, ParamStringString> rdaStringParameterPrimIndex; private SecondaryIndex<String, String, ParamStringString> rdaStringParameterSecIndex; public ParamStringStringDAO(EntityStore store){ this.store = store; this.rdaStringParameterPrimIndex = store.getPrimaryIndex(String.class, ParamStringString.class); this.rdaStringParameterSecIndex = store.getSecondaryIndex(rdaStringParameterPrimIndex, String.class, "paramValue"); } @Override public void putNoOverwrite(String parameter, String value){ this.rdaStringParameterPrimIndex.putNoOverwrite( new ParamStringString(parameter, value) ); } @Override public String getValue (String parameter){ return this.rdaStringParameterPrimIndex.get(parameter).getParamValue(); } @Override public boolean isExistValueByParameter (String parameter) { Optional<ParamStringString> opt = Optional.ofNullable(this.rdaStringParameterPrimIndex.get(parameter)); if (opt.isPresent()){ return !this.rdaStringParameterPrimIndex.get(parameter).getParamId().isEmpty(); } else { return false; } } }
1,550
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ParameterDoubleDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/database/ParameterDoubleDAO.java
package store.dao.database; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import com.sleepycat.persist.SecondaryIndex; import store.entity.database.ParameterDouble; public class ParameterDoubleDAO implements IParameterDoubleDAO { private EntityStore store; public PrimaryIndex<Integer, ParameterDouble> rdaStringParameterPrimIndex; public SecondaryIndex<Double, Integer, ParameterDouble> rdaStringParameterSecIndex; public ParameterDoubleDAO(EntityStore store){ this.store = store; this.rdaStringParameterPrimIndex = store.getPrimaryIndex(Integer.class, ParameterDouble.class); this.rdaStringParameterSecIndex = store.getSecondaryIndex(rdaStringParameterPrimIndex, Double.class, "paramDValue"); } @Override public int getCheckOrLoadParameter(double parameter){ if (!this.rdaStringParameterSecIndex.contains(parameter)){ this.rdaStringParameterPrimIndex.putNoOverwrite( new ParameterDouble(0, parameter) ); } return this.rdaStringParameterSecIndex.get(parameter).getParamId(); } @Override public double getParameterStrById(int id) { return this.rdaStringParameterPrimIndex.get(id).getParamDValue(); } }
1,277
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IAshAggrMinDataDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/olap/IAshAggrMinDataDAO.java
package store.dao.olap; import com.sleepycat.persist.EntityCursor; import store.entity.olap.AshAggrMinData; public interface IAshAggrMinDataDAO { boolean putDataNoOverwrite(AshAggrMinData iAshAggrMinDataDAO); AshAggrMinData getAshAggrMinDataRange(long dateId, int paramId); EntityCursor<AshAggrMinData> getAshAggrEntityCursorRangeQuery(long start, long end); }
385
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshAggrMinData15SecDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/olap/AshAggrMinData15SecDAO.java
package store.dao.olap; import com.sleepycat.je.DatabaseException; import com.sleepycat.persist.EntityCursor; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import com.sleepycat.persist.SecondaryIndex; import store.service.OlapDAO; import store.entity.olap.AshAggrMinData15Sec; import store.entity.olap.CompositeKey; public class AshAggrMinData15SecDAO implements IAshAggrMinData15SecDAO { private EntityStore store; private OlapDAO olapDAO; private PrimaryIndex<CompositeKey, AshAggrMinData15Sec> ashAggrMinDataPrimaryIndex; private SecondaryIndex<Long, CompositeKey, AshAggrMinData15Sec> ashAggrMinDataSecondaryIndexDateId; public AshAggrMinData15SecDAO(EntityStore store, OlapDAO olapDAO) throws DatabaseException { this.store = store; this.olapDAO = olapDAO; this.ashAggrMinDataPrimaryIndex = store.getPrimaryIndex(CompositeKey.class, AshAggrMinData15Sec.class); this.ashAggrMinDataSecondaryIndexDateId = store.getSecondaryIndex(ashAggrMinDataPrimaryIndex, Long.class, "dateId"); } @Override public boolean putDataNoOverwrite(AshAggrMinData15Sec iAshAggrMinDataDAO) { return this.ashAggrMinDataPrimaryIndex.putNoOverwrite(iAshAggrMinDataDAO); } @Override public AshAggrMinData15Sec getAshAggrMinDataRange(long dateId, int paramId) { return this.ashAggrMinDataPrimaryIndex.get(new CompositeKey(dateId, paramId)); } @Override public EntityCursor<AshAggrMinData15Sec> getAshAggrEntityCursorRangeQuery(long start, long end) { return this.olapDAO.doRangeQuery(this.ashAggrMinDataSecondaryIndexDateId, start, true, end, true); } }
1,691
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IAshAggrMinData1MinDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/olap/IAshAggrMinData1MinDAO.java
package store.dao.olap; import com.sleepycat.persist.EntityCursor; import store.entity.olap.AshAggrMinData1Min; public interface IAshAggrMinData1MinDAO { boolean putDataNoOverwrite(AshAggrMinData1Min iAshAggrMinDataDAO); AshAggrMinData1Min getAshAggrMinDataRange(long dateId, int paramId); EntityCursor<AshAggrMinData1Min> getAshAggrEntityCursorRangeQuery(long start, long end); }
405
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshAggrMinDataDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/olap/AshAggrMinDataDAO.java
package store.dao.olap; import com.sleepycat.je.DatabaseException; import com.sleepycat.persist.EntityCursor; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import com.sleepycat.persist.SecondaryIndex; import store.service.OlapDAO; import store.entity.olap.AshAggrMinData; import store.entity.olap.CompositeKey; public class AshAggrMinDataDAO implements IAshAggrMinDataDAO { private EntityStore store; private OlapDAO olapDAO; private PrimaryIndex<CompositeKey, AshAggrMinData> ashAggrMinDataPrimaryIndex; private SecondaryIndex<Long, CompositeKey, AshAggrMinData> ashAggrMinDataSecondaryIndexDateId; public AshAggrMinDataDAO(EntityStore store, OlapDAO olapDAO) throws DatabaseException { this.store = store; this.olapDAO = olapDAO; this.ashAggrMinDataPrimaryIndex = store.getPrimaryIndex(CompositeKey.class, AshAggrMinData.class); this.ashAggrMinDataSecondaryIndexDateId = store.getSecondaryIndex(ashAggrMinDataPrimaryIndex, Long.class, "dateId"); } @Override public boolean putDataNoOverwrite(AshAggrMinData iAshAggrMinDataDAO) { return this.ashAggrMinDataPrimaryIndex.putNoOverwrite(iAshAggrMinDataDAO); } @Override public AshAggrMinData getAshAggrMinDataRange(long dateId, int paramId) { return this.ashAggrMinDataPrimaryIndex.get(new CompositeKey(dateId, paramId)); } @Override public EntityCursor<AshAggrMinData> getAshAggrEntityCursorRangeQuery(long start, long end) { return this.olapDAO.doRangeQuery(this.ashAggrMinDataSecondaryIndexDateId, start, true, end, true); } }
1,642
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IAshAggrMinData15SecDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/olap/IAshAggrMinData15SecDAO.java
package store.dao.olap; import com.sleepycat.persist.EntityCursor; import store.entity.olap.AshAggrMinData15Sec; public interface IAshAggrMinData15SecDAO { boolean putDataNoOverwrite(AshAggrMinData15Sec iAshAggrMinDataDAO); AshAggrMinData15Sec getAshAggrMinDataRange(long dateId, int paramId); EntityCursor<AshAggrMinData15Sec> getAshAggrEntityCursorRangeQuery(long start, long end); }
410
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshAggrMinData1MinDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/dao/olap/AshAggrMinData1MinDAO.java
package store.dao.olap; import com.sleepycat.je.DatabaseException; import com.sleepycat.persist.EntityCursor; import com.sleepycat.persist.EntityStore; import com.sleepycat.persist.PrimaryIndex; import com.sleepycat.persist.SecondaryIndex; import store.service.OlapDAO; import store.entity.olap.AshAggrMinData1Min; import store.entity.olap.CompositeKey; public class AshAggrMinData1MinDAO implements IAshAggrMinData1MinDAO { private EntityStore store; private OlapDAO olapDAO; private PrimaryIndex<CompositeKey, AshAggrMinData1Min> ashAggrMinDataPrimaryIndex; private SecondaryIndex<Long, CompositeKey, AshAggrMinData1Min> ashAggrMinDataSecondaryIndexDateId; public AshAggrMinData1MinDAO(EntityStore store, OlapDAO olapDAO) throws DatabaseException { this.store = store; this.olapDAO = olapDAO; this.ashAggrMinDataPrimaryIndex = store.getPrimaryIndex(CompositeKey.class, AshAggrMinData1Min.class); this.ashAggrMinDataSecondaryIndexDateId = store.getSecondaryIndex(ashAggrMinDataPrimaryIndex, Long.class, "dateId"); } @Override public boolean putDataNoOverwrite(AshAggrMinData1Min iAshAggrMinDataDAO) { return this.ashAggrMinDataPrimaryIndex.putNoOverwrite(iAshAggrMinDataDAO); } @Override public AshAggrMinData1Min getAshAggrMinDataRange(long dateId, int paramId) { return this.ashAggrMinDataPrimaryIndex.get(new CompositeKey(dateId, paramId)); } @Override public EntityCursor<AshAggrMinData1Min> getAshAggrEntityCursorRangeQuery(long start, long end) { return this.olapDAO.doRangeQuery(this.ashAggrMinDataSecondaryIndexDateId, start, true, end, true); } }
1,682
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ParameterString.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/database/ParameterString.java
package store.entity.database; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; @Entity public class ParameterString { @PrimaryKey(sequence="StringParameterSeq") private int paramId; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private String paramValue; public ParameterString(){} public ParameterString(int paramId, String paramValue){ this.paramId = paramId; this.paramValue = paramValue; } public int getParamId() { return paramId; } public String getParamValue() { return paramValue; } }
716
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ParamStringString.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/database/ParamStringString.java
package store.entity.database; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; @Entity public class ParamStringString { @PrimaryKey private String paramId; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private String paramValue; public ParamStringString(){} public ParamStringString(String paramId, String paramValue){ this.paramId = paramId; this.paramValue = paramValue; } public String getParamId() { return paramId; } public String getParamValue() { return paramValue; } }
700
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ParameterDouble.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/database/ParameterDouble.java
package store.entity.database; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; @Entity public class ParameterDouble { @PrimaryKey(sequence="DoubleParameterSeq") private int paramId; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private double paramDValue; public ParameterDouble(){} public ParameterDouble(int paramId, double paramDValue){ this.paramId = paramId; this.paramDValue = paramDValue; } public int getParamId() { return paramId; } public double getParamDValue() { return paramDValue; } }
722
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SqlPlan.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/database/SqlPlan.java
/* *------------------- * The AshSqlPlanDetail.java is part of ASH Viewer *------------------- * * ASH Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASH Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ASH Viewer. If not, see <http://www.gnu.org/licenses/>. * * Copyright (c) 2009, Alex Kardapolov, All rights reserved. * */ package store.entity.database; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.SecondaryKey; import static com.sleepycat.persist.model.Relationship.MANY_TO_ONE; /** * Store sql plan for sqlid and plan hash value */ @Entity public class SqlPlan { /** The PK */ @PrimaryKey(sequence="SqlPlanId") long sqlPlanId; /** Address of the handle to the parent for this cursor */ String address; /** Hash value of the parent statement in the library cache */ Double hashValue; /** SQL identifier of the parent cursor in the library cache */ @SecondaryKey(relate = MANY_TO_ONE) String sqlId; /** Numerical representation of the SQL plan for the cursor */ @SecondaryKey(relate = MANY_TO_ONE) long planHashValue; /** Address of the child cursor*/ String childAddress; /** Number of the child cursor that uses this execution plan */ long childNumber; /** Date and time when the execution plan was generated */ long timestamp; /** Name of the internal operation performed in this step (for example, TABLE ACCESS) */ String operation; /** A variation on the operation described in the OPERATION column (for example, FULL) */ String options; /** Name of the database link used to reference the object (a table name or view name) */ String objectNode; /** Object number of the table or the index */ Double object; /** Name of the user who owns the schema containing the table or index */ String objectOwner; /** Name of the table or index */ String objectName; /** Alias for the object */ String objectAlias; /**Type of the object */ String objectType; /** Current mode of the optimizer for the first row in the plan (statement line), for example, CHOOSE */ String optimizer; /** A number assigned to each step in the execution plan */ long Id; /** ID of the next execution step that operates on the output of the current step */ long parentId; /** Depth (or level) of the operation in the tree */ long depth; /** Order of processing for all operations that have the same PARENT_ID */ long position; /** Number of index columns with start and stop keys (that is, the number of columns with matching predicates) */ long searchColumns; /** Cost of the operation as estimated by the optimizer's cost-based approach */ double cost; /** Estimate, by the cost-based optimizer, of the number of rows produced by the operation */ double cardinality; /** Estimate, by the cost-based optimizer, of the number of bytes produced by the operation */ double bytes; /** Describes the contents of the OTHER column. See EXPLAIN PLAN for values */ String otherTag; /** Start partition of a range of accessed partitions */ String partitionStart; /** Stop partition of a range of accessed partitions */ String partitionStop; /** Step that computes the pair of values of the PARTITION_START and PARTITION_STOP columns*/ double partitionId; /** Other information specific to the execution step that users may find useful. See EXPLAIN PLAN for values */ String other; /** Stores the method used to distribute rows from producer query servers to consumer query servers */ String distribution; /** CPU cost of the operation as estimated by the optimizer's cost-based approach */ double cpuCost; /** I/O cost of the operation as estimated by the optimizer's cost-based approach */ double ioCost; /** Temporary space usage of the operation (sort or hash-join) as estimated by the optimizer's cost-based approach */ double tempSpace; /** Predicates used to locate rows in an access structure. For example, start or stop predicates for an index range scan */ String accessPredicates; /** Predicates used to filter rows before producing them */ String filterPredicates; /** Expressions produced by the operation */ String projection; /** Elapsed time (in seconds) of the operation as estimated by the optimizer's cost-based approach */ double time; /** Name of the query block */ String qblockName; /** Remarks */ String remarks; /*** * Instantiates a new object */ public SqlPlan(long sqlPlanId, String address, Double hashValue, String sqlId, long planHashValue, String childAddress, long childNumber, long timestamp, String operation, String options, String objectNode, Double object, String objectOwner, String objectName, String objectAlias, String objectType, String optimizer, long Id, long parentId, long depth, long position, long searchColumns, double cost, double cardinality, double bytes, String otherTag, String partitionStart, String partitionStop, double partitionId, String other, String distribution, double cpuCost, double ioCost, double tempSpace, String accessPredicates, String filterPredicates, String projection, double time, String qblockName, String remarks ) { this.sqlPlanId = sqlPlanId; this.address = address; this.hashValue = hashValue; this.sqlId = sqlId; this.planHashValue = planHashValue; this.childAddress = childAddress; this.childNumber = childNumber; this.timestamp = timestamp; this.operation = operation; this.options = options; this.objectNode = objectNode; this.object = object; this.objectOwner = objectOwner; this.objectName = objectName; this.objectAlias = objectAlias; this.objectType = objectType; this.optimizer = optimizer; this.Id = Id; this.parentId = parentId; this.depth = depth; this.position = position; this.searchColumns = searchColumns; this.cost = cost; this.cardinality = cardinality; this.bytes = bytes; this.otherTag = otherTag; this.partitionStart = partitionStart; this.partitionStop = partitionStop; this.partitionId = partitionId; this.other = other; this.distribution = distribution; this.cpuCost = cpuCost; this.ioCost = ioCost; this.tempSpace = tempSpace; this.accessPredicates = accessPredicates; this.filterPredicates = filterPredicates; this.projection = projection; this.time = time; this.qblockName = qblockName; this.remarks = remarks; } /** * Instantiates a new SqlPlan */ private SqlPlan() { } // For bindings. public long getSqlPlanId() { return sqlPlanId; } public String getAddress() { return address; } public Double getHashValue() { return hashValue; } public String getSqlId() { return sqlId; } public double getPlanHashValue() { return planHashValue; } public String getChildAddress() { return childAddress; } public long getChildNumber() { return childNumber; } public long getTimestamp() { return timestamp; } public String getOperation() { return operation; } public String getOptions() { return options; } public String getObjectNode() { return objectNode; } public Double getObject() { return object; } public String getObjectOwner() { return objectOwner; } public String getObjectName() { return objectName; } public String getObjectAlias() { return objectAlias; } public String getObjectType() { return objectType; } public String getOptimizer() { return optimizer; } public long getId() { return Id; } public long getParentId() { return parentId; } public long getDepth() { return depth; } public long getPosition() { return position; } public long getSearchColumns() { return searchColumns; } public double getCost() { return cost; } public double getCardinality() { return cardinality; } public double getBytes() { return bytes; } public String getOtherTag() { return otherTag; } public String getPartitionStart() { return partitionStart; } public String getPartitionStop() { return partitionStop; } public double getPartitionId() { return partitionId; } public String getOther() { return other; } public String getDistribution() { return distribution; } public double getCpuCost() { return cpuCost; } public double getIoCost() { return ioCost; } public double getTempSpace() { return tempSpace; } public String getAccessPredicates() { return accessPredicates; } public String getFilterPredicates() { return filterPredicates; } public String getProjection() { return projection; } public double getTime() { return time; } public String getQblockName() { return qblockName; } public String getRemarks() { return remarks; } /** * Constructs a <code>String</code> with all attributes * in name = value format. * * @return a <code>String</code> representation * of this object. */ @Override public String toString() { final String TAB = " "; String retValue = ""; retValue = "SqlPlan ( " + super.toString() + TAB + "sqlPlanId = " + this.sqlPlanId + TAB + "address = " + this.address + TAB + "hashValue = " + this.hashValue + TAB + "sqlId = " + this.sqlId + TAB + "planHashValue = " + this.planHashValue + TAB + "childAddress = " + this.childAddress + TAB + "childNumber = " + this.childNumber + TAB + "timestamp = " + this.timestamp + TAB + "operations = " + this.operation + TAB + "options = " + this.options + TAB + "objectNode = " + this.objectNode + TAB + "object = " + this.object + TAB + "objectOwner = " + this.objectOwner + TAB + "objectName = " + this.objectName + TAB + "objectAlias = " + this.objectAlias + TAB + "objectType = " + this.objectType + TAB + "optimizer = " + this.optimizer + TAB + "Id = " + this.Id + TAB + "parentId = " + this.parentId + TAB + "depth = " + this.depth + TAB + "position = " + this.position + TAB + "searchColumns = " + this.searchColumns + TAB + "cost = " + this.cost + TAB + "cardinality = " + this.cardinality + TAB + "bytes = " + this.bytes + TAB + "otherTag = " + this.otherTag + TAB + "partitionStart = " + this.partitionStart + TAB + "partitionStop = " + this.partitionStop + TAB + "partitionId = " + this.partitionId + TAB + "other = " + this.other + TAB + "distribution = " + this.distribution + TAB + "cpuCost = " + this.cpuCost + TAB + "ioCost = " + this.ioCost + TAB + "tempSpace = " + this.tempSpace + TAB + "accessPredicates = " + this.accessPredicates + TAB + "filterPredicates = " + this.filterPredicates + TAB + "projection = " + this.projection + TAB + "time = " + this.time + TAB + "qblockName = " + this.qblockName + TAB + "remarks = " + this.remarks + TAB + " )"; return retValue; } }
11,555
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MainData.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/database/MainData.java
package store.entity.database; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; @Entity public class MainData { @PrimaryKey private long key; // Integer.MIN_VALUE means no data private int [][] mainMatrix; public MainData(){} public MainData(long key, int [][] mainMatrix){ this.key = key; this.mainMatrix = mainMatrix; } public long getKey() { return key; } public int [][] getMainMatrix(){ return mainMatrix; } }
542
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshUser.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/olap/AshUser.java
package store.entity.olap; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; @Entity public class AshUser { @PrimaryKey private int userId; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private String userName; public AshUser(){} public AshUser(int userId, String userName) { this.userId = userId; this.userName = userName; } public int getUserId() { return userId; } public String getUserName() { return userName; } }
642
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshAggrMinData.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/olap/AshAggrMinData.java
package store.entity.olap; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; import core.manager.ConstantManager; import java.util.LinkedList; /***** * <pre> * 1. CompositeKey contains dateId and paramId (sqlId, sessionId+serial, etc) * 2. dateId is secondary key * 3. waitId and sum contains matrix of WaitEventId and sum of occurrence in composite key * </pre> ****/ @Entity public class AshAggrMinData { @PrimaryKey private CompositeKey compositeKey; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private long dateId; private int[] waitId; private int[] waitClass; private int[] sum; public AshAggrMinData(){} public AshAggrMinData(long dateId, int paramId, int[] waitId, int[] waitClass, int[] sum){ this.compositeKey = new CompositeKey(dateId, paramId); this.dateId = dateId; this.waitId = waitId; this.waitClass = waitClass; this.sum = sum; } public CompositeKey getCompositeKey(){ return this.compositeKey; } public int [][] getMatrixValues(){ int[][] mtrx = new int[3][this.waitId.length]; mtrx [0] = this.waitId; mtrx [1] = this.waitClass; mtrx [2] = this.sum; return mtrx; } public int getSumValueByWaitClassId(int waitClassId){ int resOut = 0; for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ resOut = resOut + this.sum[i]; } } return resOut; } public int[] getWaitId() { return waitId; } public LinkedList<Integer> getWaitId(int waitClassId) { if (waitClassId == -1) return ConstantManager.toList(this.getWaitId()); LinkedList<Integer> l = new LinkedList<>(); for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ l.add(this.waitId[i]); } } return l; } public int[] getWaitClass() { return waitClass; } public int[] getSum() { return sum; } public LinkedList<Integer> getSum(int waitClassId) { if (waitClassId == -1) return ConstantManager.toList(this.getSum()); LinkedList<Integer> l = new LinkedList<>(); for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ l.add(this.sum[i]); } } return l; } }
2,627
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshWaitEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/olap/AshWaitEvent.java
package store.entity.olap; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; @Entity public class AshWaitEvent { @PrimaryKey(sequence="AshWaitEventSeq") private int eventId; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private String eventValue; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private byte waitClass; public AshWaitEvent(){} public AshWaitEvent(int eventId, String eventValue, byte wailClass) { this.eventId = eventId; this.eventValue = eventValue; this.waitClass = wailClass; } public int getEventId() { return eventId; } public String getEventValue() { return eventValue; } public byte getWaitClass() { return waitClass; } }
902
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CompositeKey.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/olap/CompositeKey.java
package store.entity.olap; import com.sleepycat.persist.model.KeyField; import com.sleepycat.persist.model.Persistent; @Persistent public class CompositeKey { @KeyField(1) private long dateId; @KeyField(2) private int paramId; CompositeKey() {} public CompositeKey(long dateId, int paramId) { this.dateId = dateId; this.paramId = paramId; } public long getDateId() { return this.dateId; } public int getParamId() { return this.paramId; } }
522
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshParameter.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/olap/AshParameter.java
package store.entity.olap; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; @Entity public class AshParameter { @PrimaryKey(sequence="AshParameterSeq") private int paramId; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private String paramValue; private String[] additionalParams; public AshParameter(){} public AshParameter(int paramId, String paramValue, String[] additionalParams) { this.paramId = paramId; this.paramValue = paramValue; this.additionalParams = additionalParams; } public int getParamId() { return paramId; } public String getParamValue() { return paramValue; } public String[] getAdditionalParams() {return additionalParams;} }
890
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshAggrMinData15Sec.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/olap/AshAggrMinData15Sec.java
package store.entity.olap; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; import core.manager.ConstantManager; import java.util.LinkedList; /***** * <pre> * 1. CompositeKey contains dateId and paramId (sqlId, sessionId+serial, etc) * 2. dateId is secondary key * 3. waitId and sum contains matrix of WaitEventId and sum of occurrence in composite key * </pre> ****/ @Entity public class AshAggrMinData15Sec { @PrimaryKey private CompositeKey compositeKey; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private long dateId; private int[] waitId; private int[] waitClass; private int[] sum; public AshAggrMinData15Sec(){} public AshAggrMinData15Sec(long dateId, int paramId, int[] waitId, int[] waitClass, int[] sum){ this.compositeKey = new CompositeKey(dateId, paramId); this.dateId = dateId; this.waitId = waitId; this.waitClass = waitClass; this.sum = sum; } public CompositeKey getCompositeKey(){ return this.compositeKey; } public int [][] getMatrixValues(){ int[][] mtrx = new int[3][this.waitId.length]; mtrx [0] = this.waitId; mtrx [1] = this.waitClass; mtrx [2] = this.sum; return mtrx; } public int getSumValueByWaitClassId(int waitClassId){ int resOut = 0; for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ resOut = resOut + this.sum[i]; } } return resOut; } public int[] getWaitId() { return waitId; } public LinkedList<Integer> getWaitId(int waitClassId) { if (waitClassId == -1) return ConstantManager.toList(this.getWaitId()); LinkedList<Integer> l = new LinkedList<>(); for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ l.add(this.waitId[i]); } } return l; } public int[] getWaitClass() { return waitClass; } public int[] getSum() { return sum; } public LinkedList<Integer> getSum(int waitClassId) { if (waitClassId == -1) return ConstantManager.toList(this.getSum()); LinkedList<Integer> l = new LinkedList<>(); for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ l.add(this.sum[i]); } } return l; } }
2,642
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AshAggrMinData1Min.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/entity/olap/AshAggrMinData1Min.java
package store.entity.olap; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; import core.manager.ConstantManager; import java.util.LinkedList; /***** * <pre> * 1. CompositeKey contains dateId and paramId (sqlId, sessionId+serial, etc) * 2. dateId is secondary key * 3. waitId and sum contains matrix of WaitEventId and sum of occurrence in composite key * </pre> ****/ @Entity public class AshAggrMinData1Min { @PrimaryKey private CompositeKey compositeKey; @SecondaryKey(relate = Relationship.MANY_TO_ONE) private long dateId; private int[] waitId; private int[] waitClass; private int[] sum; public AshAggrMinData1Min(){} public AshAggrMinData1Min(long dateId, int paramId, int[] waitId, int[] waitClass, int[] sum){ this.compositeKey = new CompositeKey(dateId, paramId); this.dateId = dateId; this.waitId = waitId; this.waitClass = waitClass; this.sum = sum; } public CompositeKey getCompositeKey(){ return this.compositeKey; } public int [][] getMatrixValues(){ int[][] mtrx = new int[3][this.waitId.length]; mtrx [0] = this.waitId; mtrx [1] = this.waitClass; mtrx [2] = this.sum; return mtrx; } public int getSumValueByWaitClassId(int waitClassId){ int resOut = 0; for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ resOut = resOut + this.sum[i]; } } return resOut; } public int[] getWaitId() { return waitId; } public LinkedList<Integer> getWaitId(int waitClassId) { if (waitClassId == -1) return ConstantManager.toList(this.getWaitId()); LinkedList<Integer> l = new LinkedList<>(); for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ l.add(this.waitId[i]); } } return l; } public int[] getWaitClass() { return waitClass; } public int[] getSum() { return sum; } public LinkedList<Integer> getSum(int waitClassId) { if (waitClassId == -1) return ConstantManager.toList(this.getSum()); LinkedList<Integer> l = new LinkedList<>(); for(int i=0;i<this.waitClass.length;i++){ if(this.waitClass[i]==waitClassId){ l.add(this.sum[i]); } } return l; } }
2,639
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
QueryService.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/service/QueryService.java
package store.service; import com.sleepycat.je.DatabaseException; import com.sleepycat.persist.EntityCursor; import com.sleepycat.persist.EntityIndex; public abstract class QueryService { public <K, V> EntityCursor<V> doRangeQuery(EntityIndex<K, V> index, K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) throws DatabaseException { assert (index != null); return index.entities(fromKey, fromInclusive, toKey, toInclusive); } }
740
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DatabaseDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/service/DatabaseDAO.java
package store.service; import com.sleepycat.je.DatabaseException; import com.sleepycat.persist.EntityCursor; import config.profile.SqlColProfile; import core.manager.ConfigurationManager; import core.parameter.ParameterBuilder; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import store.BerkleyDB; import store.ConvertManager; import store.dao.database.*; import store.entity.database.MainData; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; @Slf4j @Singleton public class DatabaseDAO extends QueryService { private BerkleyDB berkleyDB; private ConfigurationManager configurationManager; @Getter @Setter private ConvertManager convertManager; @Getter public IMainDataDAO mainDataDAO; @Getter public IParameterStringDAO parameterStringDAO; @Getter public IParameterDoubleDAO parameterDoubleDAO; @Getter public IParamStringStringDAO paramStringStringDAO; @Getter public ISqlPlan iSqlPlan; @Inject public DatabaseDAO (BerkleyDB berkleyDB, ConfigurationManager configurationManager) { this.berkleyDB = berkleyDB; this.configurationManager = configurationManager; } public void init () throws DatabaseException { this.mainDataDAO = new MainDataDAO(berkleyDB.getStore()); this.parameterStringDAO = new ParameterStringDAO(berkleyDB.getStore()); this.parameterDoubleDAO = new ParameterDoubleDAO(berkleyDB.getStore()); this.paramStringStringDAO = new ParamStringStringDAO(berkleyDB.getStore()); this.iSqlPlan = new SqlPlanDAO(berkleyDB.getStore()); } public long getMax(ParameterBuilder parameterBuilder) { long out = 0; long start = (long) parameterBuilder.getBeginTime(); long end = (long) parameterBuilder.getEndTime(); EntityCursor<Long> cursor = this.mainDataDAO.getPrimaryIndex().keys(start, true, end, true); if (cursor != null) { try { if (cursor.last() != null) out = cursor.last(); } finally { cursor.close(); } } return out; } public List<Object[][]> getMatrixDataForJTable(long begin, long end, String waitClassColName, String waitClassValue, List<SqlColProfile> colMetadataList){ List<Object[][]> out = new ArrayList<>(); EntityCursor<MainData> cursor = getAshAggrEntityCursorRangeQuery(begin, end); Iterator<MainData> iterator = cursor.iterator(); try { while (iterator.hasNext()) { MainData sl = iterator.next(); Object[][] data = new Object[sl.getMainMatrix().length][colMetadataList.size()]; for (int row = 0; row < sl.getMainMatrix().length; row++) { if (!waitClassValue.isEmpty()){ Stream<SqlColProfile> sqlColMetadataStream = colMetadataList.stream().filter(x -> x.getColName().equalsIgnoreCase(waitClassColName)); SqlColProfile sColMetaD = sqlColMetadataStream.findFirst().get(); String waitVal = (String) convertManager.getMatrixDataForJTable(sColMetaD.getColDbTypeName(), sColMetaD.getColId(), sl, row); if (!waitVal.isEmpty() & !waitVal.equalsIgnoreCase(waitClassValue)){ continue; } // CPU used - oracle/pg specific if (waitVal.isEmpty() & !waitClassValue.equalsIgnoreCase(configurationManager.getIProfile().getWaitClass((byte) 0))){ continue; } } int rowF = row; colMetadataList.forEach(e -> { data[rowF][e.getColId()-1] = convertManager.getMatrixDataForJTable(e.getColDbTypeName(), e.getColId(), sl, rowF); }); } out.add(data); } } finally { cursor.close(); } return out; } public EntityCursor<MainData> getAshAggrEntityCursorRangeQuery(long start, long end){ EntityCursor<MainData> entityCursor = doRangeQuery(this.mainDataDAO.getPrimaryIndex(), start, true, end, true); return entityCursor; } public void deleteMainData(long start, long end){ EntityCursor<MainData> entityCursor = doRangeQuery(this.mainDataDAO.getPrimaryIndex(), start, true, end, true); try { for (MainData entity = entityCursor.first(); entity != null; entity = entityCursor.next()) { entityCursor.delete(); } } catch (Exception e){ log.error(e.getMessage()); } finally { entityCursor.close(); } } }
5,337
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OlapDAO.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/service/OlapDAO.java
package store.service; import com.sleepycat.je.DatabaseException; import com.sleepycat.persist.*; import core.manager.ConstantManager; import gui.chart.CategoryTableXYDatasetRDA; import gui.chart.panel.NameChartDataset; import gui.chart.panel.StackChartPanel; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.jfree.chart.util.GanttParam; import profile.IProfile; import store.BerkleyDB; import store.dao.olap.*; import store.entity.olap.*; import javax.inject.Inject; import javax.inject.Singleton; import java.util.*; import java.util.concurrent.TimeUnit; @Slf4j @Singleton public class OlapDAO extends QueryService { private BerkleyDB berkleyDB; private EntityStore store; @Getter @Setter private IProfile iProfile; @Getter public IAshAggrMinDataDAO ashAggrMinDataDAO; @Getter public IAshAggrMinData15SecDAO ashAggrMinData15SecDAO; @Getter public IAshAggrMinData1MinDAO ashAggrMinData1MinDAO; private PrimaryIndex<Integer, AshParameter> ashParameterPrimaryIndex; private PrimaryIndex<Integer, AshWaitEvent> ashWaitEventPrimaryIndex; private PrimaryIndex<Integer, AshUser> ashUserPrimaryIndex; private SecondaryIndex<String, Integer, AshParameter> ashParameterSecondaryIndexStrValue; private SecondaryIndex<String, Integer, AshWaitEvent> ashWaitEventSecondaryIndexStrValue; private SecondaryIndex<Byte, Integer, AshWaitEvent> ashWaitEventSecondaryIndexByteValue; private SecondaryIndex<String, Integer, AshUser> ashUserSecondaryIndexStrValue; @Inject public OlapDAO(BerkleyDB berkleyDB) throws DatabaseException { this.berkleyDB = berkleyDB; } public void init () throws DatabaseException { this.store = this.berkleyDB.getStore(); this.ashAggrMinDataDAO = new AshAggrMinDataDAO(this.store, this); this.ashAggrMinData15SecDAO = new AshAggrMinData15SecDAO(this.store, this); this.ashAggrMinData1MinDAO = new AshAggrMinData1MinDAO(this.store, this); this.ashParameterPrimaryIndex = store.getPrimaryIndex(Integer.class, AshParameter.class); this.ashWaitEventPrimaryIndex = store.getPrimaryIndex(Integer.class, AshWaitEvent.class); this.ashUserPrimaryIndex = store.getPrimaryIndex(Integer.class, AshUser.class); this.ashParameterSecondaryIndexStrValue = store.getSecondaryIndex(ashParameterPrimaryIndex, String.class, "paramValue"); this.ashWaitEventSecondaryIndexStrValue = store.getSecondaryIndex(ashWaitEventPrimaryIndex, String.class, "eventValue"); this.ashWaitEventSecondaryIndexByteValue = store.getSecondaryIndex(ashWaitEventPrimaryIndex, Byte.class, "waitClass"); this.ashUserSecondaryIndexStrValue = store.getSecondaryIndex(ashUserPrimaryIndex, String.class, "userName"); } public void putUserIdUsername(AshUser ashUser){ this.ashUserPrimaryIndex.putNoOverwrite(ashUser); } public int getCheckOrLoadParameter(String parameter, String[] additionalParams){ if (!this.ashParameterSecondaryIndexStrValue.contains(parameter)){ this.ashParameterPrimaryIndex.putNoOverwrite( new AshParameter(0, parameter, additionalParams) ); } return this.ashParameterSecondaryIndexStrValue.get(parameter).getParamId(); } public String getStrParameterValueById(int paramId){ return this.ashParameterPrimaryIndex.get(paramId).getParamValue(); } public int getParameterIdByStrValue(String paramStrValue){ return this.ashParameterSecondaryIndexStrValue.get(paramStrValue).getParamId(); } public String[] getAdditStrArrayParameters(int paramId){ return this.ashParameterPrimaryIndex.get(paramId).getAdditionalParams(); } public int getCheckOrLoadWaitEvent(String waitEvent, byte waitClass){ if (!this.ashWaitEventSecondaryIndexStrValue.contains(waitEvent)){ this.ashWaitEventPrimaryIndex.putNoOverwrite( new AshWaitEvent(0, waitEvent, waitClass) ); } return this.ashWaitEventSecondaryIndexStrValue.get(waitEvent).getEventId(); } public byte getClassIdForWaitEventId(int waitId){ return this.ashWaitEventPrimaryIndex.get(waitId).getWaitClass(); } public String getEventStrValueForWaitEventId(int waitEventId){ return this.ashWaitEventPrimaryIndex.get(waitEventId).getEventValue(); } public String getUsername(int userId){ Optional<AshUser> opt = Optional.ofNullable(this.ashUserPrimaryIndex.get(userId)); if (opt.isPresent()){ return opt.get().getUserName(); } else { return ""; } } public int getEventGrp(int eventId){ if (this.ashWaitEventPrimaryIndex.contains(eventId)){ return this.ashWaitEventPrimaryIndex.get(eventId).getWaitClass(); } else { return -1; } } public void loadDataToCategoryTableXYDatasetRTVBySqlSessionID(GanttParam ganttParam, CategoryTableXYDatasetRDA categoryTableXYDatasetRDA, StackChartPanel stackChartPanel) { long start = (long) ganttParam.getBeginTime(); long end = (long) ganttParam.getEndTime(); String paramId; if (!ganttParam.getSqlId().isEmpty()) { // SQL_ID paramId = ganttParam.getSqlId(); } else { // SessionId + SerialId paramId = ganttParam.getSessionId() + "_" + ganttParam.getSerial(); } LinkedHashSet<Integer> uniqueLHashSetEventLst = new LinkedHashSet(); LinkedHashMap<Long, HashMap<Integer, Integer>> hashMap = new LinkedHashMap(); double range = (end - start) / ConstantManager.MAX_POINT_PER_GRAPH; // maxPointPerGraph default value is 260 for (long d = start; d <= end; d += Math.round(range)) { long end0 = d + Math.round(range); EntityCursor<AshAggrMinData15Sec> cursor = getAshAggrMinData15SecDAO().getAshAggrEntityCursorRangeQuery(d, end0); Iterator<AshAggrMinData15Sec> iterator = cursor.iterator(); hashMap.putIfAbsent(d, new HashMap<>()); ///////////////////////////////////////////// while (iterator.hasNext()) { AshAggrMinData15Sec sl = iterator.next(); boolean needToProcess; boolean checkParamId = getStrParameterValueById(sl.getCompositeKey().getParamId()).contains(paramId); if (!ganttParam.getSqlId().isEmpty() & checkParamId) { // SQL_ID needToProcess = true; } else if (!ganttParam.getSessionId().isEmpty() & checkParamId) { // SessionId + SerialId needToProcess = true; } else { needToProcess = false; } if (needToProcess) { int[] waitId = sl.getMatrixValues()[0]; int[] waitClass = sl.getMatrixValues()[1]; int[] sum = sl.getMatrixValues()[2]; for (int i = 0; i < waitClass.length; i++) { int eventId = waitId[i]; uniqueLHashSetEventLst.add(eventId); int tmpVal = hashMap.get(d).getOrDefault(eventId, 0); hashMap.get(d).put(eventId, tmpVal + sum[i]); } } } ///////////////////////////////////////////// cursor.close(); } LinkedHashMap<Integer, String> uniqueLHashSetEventLstStr = new LinkedHashMap<>(); uniqueLHashSetEventLst.stream().forEach(e -> uniqueLHashSetEventLstStr.put(e, getEventStrValueForWaitEventId(e))); uniqueLHashSetEventLstStr.entrySet().stream().forEach(u -> stackChartPanel.getStackedChart().setSeriesPaintDynamicDetail(u.getValue())); if (uniqueLHashSetEventLstStr.isEmpty()) return; final CategoryTableXYDatasetRDA catTabXYDtstRTVId = categoryTableXYDatasetRDA; hashMap.entrySet().stream().forEach(e -> { final double finalD = e.getKey(); uniqueLHashSetEventLstStr.entrySet().stream().forEach(kk -> { catTabXYDtstRTVId.addSeriesValue(finalD, (double) e.getValue().getOrDefault( uniqueLHashSetEventLstStr.entrySet().stream() .filter(l -> l.getValue().equals(kk.getValue())) .map(Map.Entry::getKey) .findFirst() .orElse(null) , 0) / (range / 1000), kk.getValue()); }); }); } public void loadDataToCategoryTableXYDatasetRTVHistoryTA(GanttParam ganttParam, CategoryTableXYDatasetRDA categoryTableXYDatasetRDA, StackChartPanel stackChartPanel) { long start = (long) ganttParam.getBeginTime(); long end = (long) ganttParam.getEndTime(); long diffInHours = TimeUnit.MILLISECONDS.toHours(end - start); LinkedHashMap<Long, HashMap<Integer, Integer>> hashMap = new LinkedHashMap(); double range = (end - start) / ConstantManager.MAX_POINT_PER_GRAPH; // maxPointPerGraph default value is 260 for (long d = start; d <= end; d += Math.round(range)) { long end0 = d + Math.round(range); if (diffInHours > 1){ loadDataFrom1MinEntityByWaitClass(hashMap, d, end0); } else { loadDataFrom1SecEntityByWaitClass(hashMap, d, end0); } } LinkedHashMap<Integer, String> uniqueLHashSetEventLstStr = new LinkedHashMap<>(); this.iProfile.getUniqueTreeEventListByWaitClass().stream().forEach(m -> { uniqueLHashSetEventLstStr.put((int) this.iProfile.getWaitClassId(m), m); }); uniqueLHashSetEventLstStr.entrySet().stream().forEach(u -> stackChartPanel.getStackedChart().setSeriesPaintDynamicDetail(u.getValue())); if (uniqueLHashSetEventLstStr.isEmpty()) return; final CategoryTableXYDatasetRDA catTabXYDtstRTVId = categoryTableXYDatasetRDA; hashMap.entrySet().stream().forEach(e -> { final double finalD = e.getKey(); uniqueLHashSetEventLstStr.entrySet().stream().forEach(kk -> { catTabXYDtstRTVId.addSeriesValue(finalD, (double) e.getValue().getOrDefault( uniqueLHashSetEventLstStr.entrySet().stream() .filter(l -> l.getValue().equals(kk.getValue())) .map(Map.Entry::getKey) .findFirst() .orElse(null) , 0) / (range / 1000), kk.getValue()); }); }); } private void loadDataFrom1MinEntityByWaitClass(LinkedHashMap<Long, HashMap<Integer, Integer>> hashMap, long d, long end0){ EntityCursor<AshAggrMinData1Min> cursor = getAshAggrMinData1MinDAO().getAshAggrEntityCursorRangeQuery(d, end0); Iterator<AshAggrMinData1Min> iterator = cursor.iterator(); hashMap.putIfAbsent(d, new HashMap<>()); while (iterator.hasNext()) { AshAggrMinData1Min sl = iterator.next(); int[] waitClass = sl.getMatrixValues()[1]; int[] sum = sl.getMatrixValues()[2]; for (int i = 0; i < waitClass.length; i++) { int waitIdI = waitClass[i]; int tmpVal = hashMap.get(d).getOrDefault(waitIdI, 0); hashMap.get(d).put(waitIdI, tmpVal + sum[i]); } } cursor.close(); } private void loadDataFrom15SecEntityByWaitClass(LinkedHashMap<Long, HashMap<Integer, Integer>> hashMap, long d, long end0){ EntityCursor<AshAggrMinData15Sec> cursor = getAshAggrMinData15SecDAO().getAshAggrEntityCursorRangeQuery(d, end0); Iterator<AshAggrMinData15Sec> iterator = cursor.iterator(); hashMap.putIfAbsent(d, new HashMap<>()); while (iterator.hasNext()) { AshAggrMinData15Sec sl = iterator.next(); int[] waitClass = sl.getMatrixValues()[1]; int[] sum = sl.getMatrixValues()[2]; for (int i = 0; i < waitClass.length; i++) { int waitIdI = waitClass[i]; int tmpVal = hashMap.get(d).getOrDefault(waitIdI, 0); hashMap.get(d).put(waitIdI, tmpVal + sum[i]); } } cursor.close(); } private void loadDataFrom1SecEntityByWaitClass(LinkedHashMap<Long, HashMap<Integer, Integer>> hashMap, long d, long end0){ EntityCursor<AshAggrMinData> cursor = getAshAggrMinDataDAO().getAshAggrEntityCursorRangeQuery(d, end0); Iterator<AshAggrMinData> iterator = cursor.iterator(); hashMap.putIfAbsent(d, new HashMap<>()); while (iterator.hasNext()) { AshAggrMinData sl = iterator.next(); int[] waitClass = sl.getMatrixValues()[1]; int[] sum = sl.getMatrixValues()[2]; for (int i = 0; i < waitClass.length; i++) { int waitIdI = waitClass[i]; int tmpVal = hashMap.get(d).getOrDefault(waitIdI, 0); hashMap.get(d).put(waitIdI, tmpVal + sum[i]); } } cursor.close(); } public void loadDataToCategoryTableXYDatasetRTVHistoryDetail(GanttParam ganttParam, LinkedHashSet<NameChartDataset> nameChartDatasetList) { long start = (long) ganttParam.getBeginTime(); long end = (long) ganttParam.getEndTime(); HashMap<Integer, LinkedHashSet<Integer>> uniqueLHashSetEventLst0 = new HashMap<>(); this.iProfile.getUniqueTreeEventListByWaitClass().stream().forEach(m -> { uniqueLHashSetEventLst0.put((int) this.iProfile.getWaitClassId(m), new LinkedHashSet()); }); LinkedHashMap<Long, HashMap<Integer, Integer>> hashMap = new LinkedHashMap(); double range = (end - start) / ConstantManager.MAX_POINT_PER_GRAPH; // maxPointPerGraph default value is 260 for (long d = start; d <= end; d += Math.round(range)) { long end0 = d + Math.round(range); /****/ EntityCursor<AshAggrMinData15Sec> cursor = getAshAggrMinData15SecDAO().getAshAggrEntityCursorRangeQuery(d, end0); Iterator<AshAggrMinData15Sec> iterator = cursor.iterator(); hashMap.putIfAbsent(d, new HashMap<>()); while (iterator.hasNext()) { AshAggrMinData15Sec sl = iterator.next(); int[] waitId = sl.getMatrixValues()[0]; int[] waitClass = sl.getMatrixValues()[1]; int[] sum = sl.getMatrixValues()[2]; for (int i = 0; i < waitClass.length; i++) { int eventId = waitId[i]; uniqueLHashSetEventLst0.get(waitClass[i]).add(eventId); int tmpVal = hashMap.get(d).getOrDefault(eventId, 0); hashMap.get(d).put(eventId, tmpVal + sum[i]); } } cursor.close(); } HashMap<Integer, LinkedHashMap<Integer, String>> uniqueLHashSetEventLstStr0 = new HashMap<>(); uniqueLHashSetEventLst0.entrySet() .stream() .forEach(e -> { uniqueLHashSetEventLstStr0.put(e.getKey(), new LinkedHashMap<>()); e.getValue().stream().forEach(m -> uniqueLHashSetEventLstStr0.get(e.getKey()) .put(m, getEventStrValueForWaitEventId(m))); }); nameChartDatasetList.stream().forEach(e -> { LinkedHashMap<Integer, String> uniqueLHashSetEventLstStr = uniqueLHashSetEventLstStr0.entrySet() .stream() .filter(f -> this.iProfile.getWaitClass((byte) (int) f.getKey()).equalsIgnoreCase(e.getName())) .findAny().get().getValue(); uniqueLHashSetEventLstStr.entrySet() .forEach(u -> { e.getStackChartPanel().getStackedChart().setSeriesPaintDynamicDetail(u.getValue()); }); final CategoryTableXYDatasetRDA catTabXYDtstRTVId = e.getDatasetRDA(); hashMap.entrySet().stream().forEach(k -> { final double finalD = k.getKey(); uniqueLHashSetEventLstStr.entrySet() .forEach(kk -> { catTabXYDtstRTVId.addSeriesValue(finalD, (double) k.getValue().getOrDefault( uniqueLHashSetEventLstStr.entrySet() .stream() .filter(l -> l.getValue().equals(kk.getValue())) .map(Map.Entry::getKey) .findFirst() .orElse(null) , 0) / (range / 1000), kk.getValue()); }); }); }); } public void deleteOlapData(long start, long end){ try (EntityCursor<AshAggrMinData> cursor = this.ashAggrMinDataDAO.getAshAggrEntityCursorRangeQuery(start, end)) { for (AshAggrMinData entity = cursor.first(); entity != null; entity = cursor.next()) { cursor.delete(); } } catch (Exception e) { log.error(e.getMessage()); } try (EntityCursor<AshAggrMinData15Sec> cursor = this.ashAggrMinData15SecDAO.getAshAggrEntityCursorRangeQuery(start, end)) { for (AshAggrMinData15Sec entity = cursor.first(); entity != null; entity = cursor.next()) { cursor.delete(); } } catch (Exception e) { log.error(e.getMessage()); } try (EntityCursor<AshAggrMinData1Min> cursor = this.ashAggrMinData1MinDAO.getAshAggrEntityCursorRangeQuery(start, end)) { for (AshAggrMinData1Min entity = cursor.first(); entity != null; entity = cursor.next()) { cursor.delete(); } } catch (Exception e) { log.error(e.getMessage()); } } }
19,094
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CompositeKeyCache2.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/cache/CompositeKeyCache2.java
package store.cache; public class CompositeKeyCache2 { private int paramId; private byte paramGrp; public CompositeKeyCache2(int paramId, byte paramGrp) { this.paramId = paramId; this.paramGrp = paramGrp; } public int getParamId() { return paramId; } public void setParamId(int paramId) { this.paramId = paramId; } @Override public boolean equals(Object obj) { if(obj instanceof CompositeKeyCache2) { CompositeKeyCache2 keyCache = (CompositeKeyCache2)obj; return (paramId == keyCache.paramId); } return false; } @Override public int hashCode() { return Integer.valueOf((paramGrp + paramId)).hashCode(); } }
757
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
TripleValueCache.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/cache/TripleValueCache.java
package store.cache; public class TripleValueCache { public final int waitEventId; public final byte waitClassId; public int sum; public int getWaitEventId() { return waitEventId; } public byte getWaitClassId() { return waitClassId; } public int getWaitClassIdInt() { return waitClassId; } public int getSum() { return sum; } public void setSum(int iSum) { this.sum = this.sum + iSum; } /** * @param waitEventId event id * @param waitClassId corresponding with the event id a wait class id * @param sum sum of entries by the wait Event id */ public TripleValueCache(int waitEventId, byte waitClassId, int sum) { this.waitEventId = waitEventId; this.waitClassId = waitClassId; this.sum = sum; } @Override public boolean equals(Object o) { if(o instanceof TripleValueCache) { TripleValueCache keyCache = (TripleValueCache)o; return (waitEventId == keyCache.waitEventId); } return false; } @Override public int hashCode() { return Integer.valueOf(waitEventId + waitClassId + sum).hashCode(); } }
1,227
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CompositeKeyCache.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/store/cache/CompositeKeyCache.java
package store.cache; public class CompositeKeyCache implements Comparable<CompositeKeyCache>{ private long dateId; private int paramId; public CompositeKeyCache(long dateId, int paramId) { this.dateId = dateId; this.paramId = paramId; } public long getDateId() { return dateId; } public int getParamId() { return paramId; } public void setParamId(int paramId) { this.paramId = paramId; } @Override public boolean equals(Object obj) { if(obj instanceof CompositeKeyCache) { CompositeKeyCache keyCache = (CompositeKeyCache)obj; return (dateId == keyCache.dateId) & (paramId == keyCache.paramId); } return false; } @Override public int hashCode() { return Integer.valueOf((int) (dateId + paramId)).hashCode(); } @Override public int compareTo(CompositeKeyCache o) { int result = 0; if (this.dateId == o.getDateId()){ result = 0; } else if (this.dateId < o.getDateId()){ result = -1; } else if (this.dateId > o.getDateId()){ result = 1; } return result; } }
1,218
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StateMachine.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/StateMachine.java
package core; import lombok.extern.slf4j.Slf4j; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReentrantReadWriteLock; @Slf4j @Singleton public class StateMachine { private volatile CurrrentState state = CurrrentState.STOP; public CurrrentState getState() { return state; } private ReentrantReadWriteLock listenersLock = new ReentrantReadWriteLock(); private List<StateTransitionListener> transitionListeners = new ArrayList<StateTransitionListener>(); @Inject public StateMachine(){} /** * Registers state transition listener. */ public void addTransitionListener(StateTransitionListener listener) { try { listenersLock.writeLock().lock(); transitionListeners.add(listener); } finally { listenersLock.writeLock().unlock(); } } /** * Unregisters the listener */ public void removeTransitionListener(StateTransitionListener listener) { try { listenersLock.writeLock().lock(); transitionListeners.remove(listener); } finally { listenersLock.writeLock().unlock(); } } public void transitionToNext() { transitionTo(state.next()); } /** * Transitions to the specified state, notifying all listeners. * Note: this method is intentionally not public, use specific methods to make desired transitions. */ void transitionTo(CurrrentState newState) { if (state != newState) { state = newState; notifyAboutTransition(); } } protected void notifyAboutTransition() { try { listenersLock.readLock().lock(); for (StateTransitionListener listener : transitionListeners) { listener.transitionTo(state); } } finally { listenersLock.readLock().unlock(); } } public void startScanning() { if (state == CurrrentState.START) { transitionTo(CurrrentState.START); } else { throw new IllegalStateException("Attempt to go scanning from " + state); } } /** * Transitions to the stopping state */ public void stopScanning() { if (state == CurrrentState.STOP) { transitionTo(CurrrentState.STOP); } else { throw new IllegalStateException("Attempt to stopScanning from " + state); } } }
2,613
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StateTransitionListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/StateTransitionListener.java
/** * This file is a part of Angry IP Scanner source code, * see http://www.angryip.org/ for more information. * Licensed under GPLv2. */ package core; /** * StateTransitionListener * * @author Anton Keks */ public interface StateTransitionListener { /** * Notifies on transition to the specified state. * @param state */ void transitionTo(CurrrentState state); }
384
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CurrrentState.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/CurrrentState.java
package core; public enum CurrrentState { START, STOP; /** * Transitions the state to the next one. * Note: not all states have the default next state; */ CurrrentState next() { switch (this) { case START: return STOP; case STOP: return START; default: return null; } } }
360
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ConfigurationManager.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/manager/ConfigurationManager.java
package core.manager; import com.github.windpapi4j.HResultException; import com.github.windpapi4j.InitializationFailedException; import com.github.windpapi4j.WinAPICallFailedException; import com.github.windpapi4j.WinDPAPI; import com.github.windpapi4j.WinDPAPI.CryptProtectFlag; import config.profile.ConfigProfile; import config.profile.ConnProfile; import config.profile.SqlColProfile; import config.security.BCFipsConfig; import config.security.ContainerConfig; import config.security.PassConfig; import config.yaml.YamlConfig; import core.manager.ConstantManager.Profile; import core.parameter.ConnectionBuilder; import excp.SqlColMetadataException; import gui.model.ContainerType; import gui.model.EncryptionType; import gui.model.RegistryKey; import java.security.GeneralSecurityException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import javax.crypto.SecretKey; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import profile.IProfile; import profile.OracleEE; import profile.OracleEE10g; import profile.OracleEEObject; import profile.OracleSE; import profile.Postgres; import profile.Postgres96; @Slf4j @Singleton public class ConfigurationManager { private YamlConfig yamlConfig; private PassConfig passConfig; private BCFipsConfig bcFipsConfig; private ContainerConfig containerConfig; private TreeMap<String, ConfigProfile> configList; @Getter @Setter private ConfigProfile currentConfiguration; @Getter @Setter private String configurationName; @Getter @Setter private IProfile iProfile; @Inject public ConfigurationManager(YamlConfig yamlConfig, PassConfig passConfig, BCFipsConfig bcFipsConfig, ContainerConfig containerConfig, @Named("ConfigList") TreeMap<String, ConfigProfile> configList) { this.yamlConfig = yamlConfig; this.passConfig = passConfig; this.bcFipsConfig = bcFipsConfig; this.containerConfig = containerConfig; this.configList = configList; } public void loadCurrentConfiguration(String configurationName) { ConfigProfile configProfile = getConnProfileList().stream() .filter(e -> e.getConfigName().equalsIgnoreCase(configurationName)) .findAny().get(); configProfile.setRunning(true); loadConfigToFile(configProfile); setIProfile(getProfileImpl(configProfile.getConnProfile().getProfileName())); setConfigurationName(configurationName); setCurrentConfiguration(configProfile); } public void loadSqlColumnMetadata(List<SqlColProfile> profilesDb) throws SqlColMetadataException { Optional<List<SqlColProfile>> profileCurr = Optional.ofNullable(getCurrentConfiguration().getSqlColProfileList()); if (!profileCurr.isPresent()) { getCurrentConfiguration().setSqlColProfileList(profilesDb); loadConfigToFile(getCurrentConfiguration()); } else { if (profilesDb.size() != profileCurr.get().size()) { throw new SqlColMetadataException("ASH sql column metadata changes detected.. " + "Create the new configuration profile!"); } } } public void loadConfigToFile(ConfigProfile configuration) { yamlConfig.saveConfigToFile(configuration); } public List<ConfigProfile> getConnProfileList() { return (List<ConfigProfile>) new ArrayList(configList.values()); } public void deleteConfig(String configurationName) { configList.remove(configurationName); yamlConfig.deleteConfig(configurationName); yamlConfig.loadConfigsFromFs(); } public ConnectionBuilder getConnectionParameters(String connName) { Map.Entry<String,ConfigProfile> other = new AbstractMap.SimpleImmutableEntry<>(connName, new ConfigProfile()); other.getValue().setConfigName(connName); other.getValue().setConnProfile(new ConnProfile()); other.getValue().getConnProfile().setPassword(""); Map.Entry<String, ConfigProfile> cfg = configList.entrySet().stream() .filter(e -> e.getValue().getConfigName().equalsIgnoreCase(connName)) .findAny().orElse(other); ConnProfile connOut = cfg.getValue().getConnProfile(); return new ConnectionBuilder.Builder(connName) .userName(connOut.getUserName()) .password(getPassword(cfg.getValue())) .url(connOut.getUrl()) .jar(connOut.getJar()) .profile(connOut.getProfileName()) .initialLoading(String.valueOf(cfg.getValue().getInitialLoading())) .rawRetainDays(String.valueOf(cfg.getValue().getRawRetainDays())) .olapRetainDays(String.valueOf(cfg.getValue().getOlapRetainDays())) .containerType(cfg.getValue().getContainerType()) .encryptionType(cfg.getValue().getEncryptionType()) .build(); } public void saveConnection(ConnectionBuilder connIn) { Map.Entry<String, ConfigProfile> other = new AbstractMap.SimpleImmutableEntry<>("", new ConfigProfile()); other.getValue().setConnProfile(new ConnProfile()); other.getValue().setConfigName(connIn.getConnectionName()); Map.Entry<String, ConfigProfile> cfg = configList.entrySet().stream() .filter(e -> e.getValue().getConfigName().equalsIgnoreCase(connIn.getConnectionName())) .findAny().orElse(other); try { savePassword(connIn, cfg); } catch (GeneralSecurityException e) { log.error(e.getMessage()); throw new RuntimeException(e); } connIn.cleanPassword(); ConnProfile connOut = cfg.getValue().getConnProfile(); connOut.setConnName(connIn.getConnectionName()); connOut.setUserName(connIn.getUserName()); connOut.setUrl(connIn.getUrl()); connOut.setJar(connIn.getJar()); connOut.setProfileName(connIn.getProfile()); connOut.setDriver(connIn.getDriverName()); cfg.getValue().setInitialLoading(Integer.parseInt(connIn.getInitialLoading())); cfg.getValue().setRawRetainDays(getRawRetainDays()); cfg.getValue().setOlapRetainDays(getOlapRetainDays()); cfg.getValue().setEncryptionType(connIn.getEncryptionType()); cfg.getValue().setContainerType(connIn.getContainerType()); yamlConfig.saveConfigToFile(cfg.getValue()); } private void savePassword(ConnectionBuilder connIn, Map.Entry<String, ConfigProfile> cfg) throws GeneralSecurityException { EncryptionType encryptionTypeCurrent = connIn.getEncryptionType(); ContainerType containerTypeCurrent = connIn.getContainerType(); ConnProfile connOut = cfg.getValue().getConnProfile(); // Clean values from previous configuration ContainerType containerTypePrev = cfg.getValue().getContainerType(); EncryptionType encryptionTypePrev = cfg.getValue().getEncryptionType(); if (containerTypeCurrent != null && encryptionTypeCurrent != null && ContainerType.CONFIGURATION.equals(containerTypePrev) && containerTypeCurrent.equals(containerTypePrev) && !encryptionTypeCurrent.equals(encryptionTypePrev)) { cfg.getValue().setKey(null); cfg.getValue().setIv(null); connOut.setPassword(null); } // Save current values if (EncryptionType.PBE.equals(encryptionTypeCurrent)) { String passwordEncrypted = passConfig.encrypt(connIn.getPassword()); if (ContainerType.DPAPI.equals(containerTypeCurrent)) { if(WinDPAPI.isPlatformSupported()) { try { WinDPAPI winDPAPI = WinDPAPI.newInstance(CryptProtectFlag.CRYPTPROTECT_UI_FORBIDDEN); byte[] cipherTextBytes = winDPAPI.protectData(passwordEncrypted.getBytes()); cfg.getValue().setKey(containerConfig.convertByteToString(cipherTextBytes)); cfg.getValue().setIv(null); connOut.setPassword(null); } catch (InitializationFailedException | WinAPICallFailedException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Windows Data Protection API (DPAPI) as secure container is not supported"); } } else if (ContainerType.REGISTRY.equals(containerTypeCurrent)) { containerConfig.setRegistryValue(cfg.getValue().getConfigName(), RegistryKey.PASSWORD, passwordEncrypted); cfg.getValue().setKey(null); cfg.getValue().setIv(null); connOut.setPassword(null); } else if (ContainerType.CONFIGURATION.equals(containerTypeCurrent)) { connOut.setPassword(passwordEncrypted); cfg.getValue().setKey(null); cfg.getValue().setIv(null); } } else if (EncryptionType.AES.equals(encryptionTypeCurrent)) { SecretKey secretKey = bcFipsConfig.generateKey(); byte[][] passwordEncrypted = bcFipsConfig.cfbEncrypt(secretKey, connIn.getPassword().getBytes()); if (ContainerType.DPAPI.equals(containerTypeCurrent)) { if(WinDPAPI.isPlatformSupported()) { try { WinDPAPI winDPAPI = WinDPAPI.newInstance(CryptProtectFlag.CRYPTPROTECT_UI_FORBIDDEN); byte[] cipherKeyBytes = winDPAPI.protectData(containerConfig.convertSecretKeyToString(secretKey).getBytes()); byte[] cipherIvBytes = winDPAPI.protectData(containerConfig.convertByteToString(passwordEncrypted[0]).getBytes()); byte[] cipherPassEncBytes = winDPAPI.protectData(containerConfig.convertByteToString(passwordEncrypted[1]).getBytes()); cfg.getValue().setKey(containerConfig.convertByteToString(cipherKeyBytes)); cfg.getValue().setIv(containerConfig.convertByteToString(cipherIvBytes)); connOut.setPassword(containerConfig.convertByteToString(cipherPassEncBytes)); } catch (InitializationFailedException | WinAPICallFailedException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Windows Data Protection API (DPAPI) as secure container is not supported"); } } else if (ContainerType.REGISTRY.equals(containerTypeCurrent)) { String cipherKey = containerConfig.convertSecretKeyToString(secretKey); String cipherIv = containerConfig.convertByteToString(passwordEncrypted[0]); String cipherPassEnc = containerConfig.convertByteToString(passwordEncrypted[1]); containerConfig.setRegistryValue(cfg.getValue().getConfigName(), RegistryKey.KEY, cipherKey); containerConfig.setRegistryValue(cfg.getValue().getConfigName(), RegistryKey.IV, cipherIv); containerConfig.setRegistryValue(cfg.getValue().getConfigName(), RegistryKey.PASSWORD, cipherPassEnc); cfg.getValue().setKey(null); cfg.getValue().setIv(null); connOut.setPassword(null); } else if (ContainerType.CONFIGURATION.equals(containerTypeCurrent)) { cfg.getValue().setKey(containerConfig.convertSecretKeyToString(secretKey)); cfg.getValue().setIv(containerConfig.convertByteToString(passwordEncrypted[0])); connOut.setPassword(containerConfig.convertByteToString(passwordEncrypted[1])); } } } public String getPassword(ConfigProfile configProfile) { EncryptionType encryptionType = configProfile.getEncryptionType(); ContainerType containerType = configProfile.getContainerType(); if (encryptionType == null && containerType == null) { try { return passConfig.decrypt(configProfile.getConnProfile().getPassword()); } catch (Exception e) { log.error("Config name: " + configProfile.getConfigName()); log.error("The most likely reason is running the configuration on another computer, delete or recreate it"); throw new RuntimeException(e); } } String password = ""; if (EncryptionType.PBE.equals(encryptionType)) { if (ContainerType.DPAPI.equals(containerType)) { if(WinDPAPI.isPlatformSupported()) { try { WinDPAPI winDPAPI = WinDPAPI.newInstance(CryptProtectFlag.CRYPTPROTECT_UI_FORBIDDEN); byte[] decryptedBytes = winDPAPI.unprotectData(containerConfig.convertStringToByte(configProfile.getKey())); password = passConfig.decrypt(new String(decryptedBytes)); } catch (InitializationFailedException | WinAPICallFailedException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Windows Data Protection API (DPAPI) as secure container is not supported"); } } else if (ContainerType.REGISTRY.equals(containerType)) { password = passConfig.decrypt(containerConfig.getRegistryValue(configProfile.getConfigName(), RegistryKey.PASSWORD)); } else if (ContainerType.CONFIGURATION.equals(containerType)) { password = passConfig.decrypt(configProfile.getConnProfile().getPassword()); } } else if (EncryptionType.AES.equals(encryptionType)) { if (ContainerType.DPAPI.equals(containerType)) { if(WinDPAPI.isPlatformSupported()) { try { WinDPAPI winDPAPI = WinDPAPI.newInstance(CryptProtectFlag.CRYPTPROTECT_UI_FORBIDDEN); String secretKeyStr = new String(winDPAPI.unprotectData(containerConfig.convertStringToByte(configProfile.getKey()))); String ivStr = new String(winDPAPI.unprotectData(containerConfig.convertStringToByte(configProfile.getIv()))); String pwdStr = new String(winDPAPI.unprotectData(containerConfig.convertStringToByte(configProfile.getConnProfile().getPassword()))); try { password = new String(bcFipsConfig.cfbDecrypt(containerConfig.convertStringToSecretKey(secretKeyStr), containerConfig.convertStringToByte(ivStr), containerConfig.convertStringToByte(pwdStr))); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } catch (InitializationFailedException | WinAPICallFailedException e) { log.error("Config name: " + configProfile.getConfigName()); log.error("The most likely reason is running the configuration on another computer, delete or recreate it"); throw new RuntimeException(e); } } else { throw new RuntimeException("Windows Data Protection API (DPAPI) as secure container is not supported"); } } else if (ContainerType.REGISTRY.equals(containerType)) { String secretKeyStr = containerConfig.getRegistryValue(configProfile.getConfigName(), RegistryKey.KEY); String ivStr = containerConfig.getRegistryValue(configProfile.getConfigName(), RegistryKey.IV); String pwdStr = containerConfig.getRegistryValue(configProfile.getConfigName(), RegistryKey.PASSWORD); try { password = new String(bcFipsConfig.cfbDecrypt(containerConfig.convertStringToSecretKey(secretKeyStr), containerConfig.convertStringToByte(ivStr), containerConfig.convertStringToByte(pwdStr))); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } else if (ContainerType.CONFIGURATION.equals(containerType)) { SecretKey secretKey = containerConfig.convertStringToSecretKey(configProfile.getKey()); byte[] iv = containerConfig.convertStringToByte(configProfile.getIv()); byte[] passwordEncrypted = containerConfig.convertStringToByte(configProfile.getConnProfile().getPassword()); try { password = new String(bcFipsConfig.cfbDecrypt(secretKey, iv, passwordEncrypted)); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } } return password; } public int getRawRetainDays() { return ConstantManager.RETAIN_DAYS_MAX; } public int getOlapRetainDays() { return ConstantManager.RETAIN_DAYS_MAX; } public void closeCurrentProfile() { if (currentConfiguration != null){ getCurrentConfiguration().setRunning(false); loadConfigToFile(getCurrentConfiguration()); } } public IProfile getProfileImpl(String profileName) { Profile profile = Profile.getValue(profileName); if (profile == null) { throw new IllegalArgumentException("Invalid profile name: " + profileName); } switch (profile) { case OracleEE: return new OracleEE(); case OracleEE10g: return new OracleEE10g(); case OracleEEObject: return new OracleEEObject(); case OracleSE: return new OracleSE(); case Postgres: return new Postgres(); case Postgres96: return new Postgres96(); default : throw new IllegalArgumentException("Unsupported profile name: " + profileName); } } }
18,089
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ColorManager.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/manager/ColorManager.java
package core.manager; import lombok.extern.slf4j.Slf4j; import org.rtv.Options; import javax.inject.Inject; import javax.inject.Singleton; import java.awt.*; import java.util.concurrent.ThreadLocalRandom; @Slf4j @Singleton public class ColorManager { private int min = 0; private int max = 255; private ThreadLocalRandom threadLocalRandom; @Inject public ColorManager() { this.threadLocalRandom = ThreadLocalRandom.current(); } public Color getColor(){ return new Color(getRandR(), getRandG(), getRandB()); } public Color getColor(String eventName){ return Options.getInstance().getColor(eventName); } public int getRandR() { return this.threadLocalRandom.nextInt(min,max); } public int getRandG() { return this.threadLocalRandom.nextInt(min,max); } public int getRandB() { return this.threadLocalRandom.nextInt(min,max); } }
923
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ConstantManager.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/manager/ConstantManager.java
package core.manager; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.rtv.Options; public final class ConstantManager { public static final int MAIN_PANEL_5MIN = 5; public static int MAIN_PANEL_15MIN = 15; public static int MAIN_PANEL_30MIN = 30; public static int MAIN_PANEL_60MIN = 60; public static String NULL_VALUE = "Null"; public enum Function {None, AsIs, Sum, Count, Delta} // Add profile implementation to src/profile public enum Profile { OracleEE, OracleSE, OracleEEObject, OracleEE10g, Postgres, Postgres96; public static final Profile getValue(String value) { for (Profile p: values()) { if (p.name().equals(value)) { return p; } } return null; } } public enum History {Hour8, Hour12, Day1, Week, Month, Custom} public enum RetainData {Never, Always}; public static int RETAIN_DAYS_MIN = 0; public static int RETAIN_DAYS_MAX = 101; public static int INITIAL_LOADING = -1; public static int INITIAL_LOADING_DEFAULT = 5; private static Map coreOpt = new LinkedHashMap(); private ConstantManager() {} public static <T> T[] reverse(T[] array) { Collections.reverse(Arrays.asList(array)); return array; } public static LinkedList<Integer> toList(int[] arr){ LinkedList<Integer> l = new LinkedList<>(); for(int i : arr) l.add(i); return l; } public static <K, V> Map<K, V> zipToMap(java.util.List<K> keys, java.util.List<V> values) { return IntStream.range(0, keys.size()).boxed() .collect(Collectors.toMap(keys::get, values::get)); } public static final String TEXT_PAINTER = "TxtPainter"; public static final long CURRENT_WINDOW = 3900000; public static final int MAX_POINT_PER_GRAPH = 240; public static byte getWaitClassId(String waitClass){ byte out = 0; switch (waitClass) { case Options.LBL_CPU: { // 0 out = 0; break; } case Options.LBL_SCHEDULER: { // 1 out = 1; break; } case Options.LBL_USERIO: { // 2 out = 2; break; } case Options.LBL_SYSTEMIO: { // 3 out = 3; break; } case Options.LBL_CONCURRENCY: { // 4 out = 4; break; } case Options.LBL_APPLICATION: { // 5 out = 5; break; } case Options.LBL_COMMIT: { // 6 out = 6; break; } case Options.LBL_CONFIGURATION: { // 7 out = 7; break; } case Options.LBL_ADMINISTRATIVE: { // 8 out = 8; break; } case Options.LBL_NETWORK: { // 9 out = 9; break; } case Options.LBL_QUEUEING: { // 10 out = 10; break; } case Options.LBL_CLUSTER: { // 11 out = 11; break; } case Options.LBL_OTHER: { // 12 out = 12; break; } case Options.LBL_IDLE: { // 13 out = 13; break; } } return out; } public static String getWaitClass(byte waitClassId){ switch (waitClassId) { case 0: { // 0 return Options.LBL_CPU; } case 1: { // 1 return Options.LBL_SCHEDULER; } case 2: { // 2 return Options.LBL_USERIO; } case 3: { // 3 return Options.LBL_SYSTEMIO; } case 4: { // 4 return Options.LBL_CONCURRENCY; } case 5: { // 5 return Options.LBL_APPLICATION; } case 6: { // 6 return Options.LBL_COMMIT; } case 7: { // 7 return Options.LBL_CONFIGURATION; } case 8: { // 8 return Options.LBL_ADMINISTRATIVE; } case 9: { // 9 return Options.LBL_NETWORK; } case 10: { // 10 return Options.LBL_QUEUEING; } case 11: { // 11 return Options.LBL_CLUSTER; } case 12: { // 12 return Options.LBL_OTHER; } case 13: { // 13 return Options.LBL_IDLE; } } return ""; } public static byte getWaitClassIdPG(String waitClass){ byte out = 0; switch (waitClass) { case Options.LBL_PG_CPU: { // 0 out = 0; break; } case Options.LBL_PG_IO: { // 1 out = 1; break; } case Options.LBL_PG_LOCK: { // 2 out = 2; break; } case Options.LBL_PG_LWLOCK: { // 3 out = 3; break; } case Options.LBL_PG_BUFFERPIN: { // 4 out = 4; break; } case Options.LBL_PG_ACTIVITY: { // 5 out = 5; break; } case Options.LBL_PG_EXTENSION: { // 6 out = 6; break; } case Options.LBL_PG_CLIENT: { // 7 out = 7; break; } case Options.LBL_PG_IPC: { // 8 out = 8; break; } case Options.LBL_PG_TIMEOUT: { // 9 out = 9; break; } } return out; } public static String getWaitClassPG(byte waitClassId){ switch (waitClassId) { case 0: { // 0 return Options.LBL_PG_CPU; } case 1: { // 1 return Options.LBL_PG_IO; } case 2: { // 2 return Options.LBL_PG_LOCK; } case 3: { // 3 return Options.LBL_PG_LWLOCK; } case 4: { // 4 return Options.LBL_PG_BUFFERPIN; } case 5: { // 5 return Options.LBL_PG_ACTIVITY; } case 6: { // 6 return Options.LBL_PG_EXTENSION; } case 7: { // 7 return Options.LBL_PG_CLIENT; } case 8: { // 8 return Options.LBL_PG_IPC; } case 9: { // 9 return Options.LBL_PG_TIMEOUT; } } return ""; } }
7,275
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
GetFromRemoteAndStore.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/processing/GetFromRemoteAndStore.java
package core.processing; import com.sleepycat.persist.EntityCursor; import config.Labels; import config.profile.ConfigProfile; import config.profile.ConnProfile; import config.profile.SqlColProfile; import core.manager.ColorManager; import core.manager.ConfigurationManager; import core.manager.ConstantManager; import core.parameter.ParameterBuilder; import gui.chart.CategoryTableXYDatasetRDA; import gui.chart.ChartDatasetManager; import gui.chart.panel.NameChartDataset; import gui.detail.explainplan.ExplainPlanModel10g2; import java.math.BigDecimal; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import java.util.Vector; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Inject; import javax.inject.Singleton; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jetbrains.annotations.NotNull; import org.rtv.Options; import pojo.SqlPlanPojo; import pojo.SqlPojo; import profile.IProfile; import profile.OracleEE; import profile.OracleEE10g; import profile.OracleEEObject; import profile.Postgres; import remote.RemoteDBManager; import store.ConvertManager; import store.OlapCacheManager; import store.RawStoreManager; import store.StoreManager; import store.entity.database.SqlPlan; import store.entity.olap.AshAggrMinData; import store.entity.olap.AshUser; import store.service.OlapDAO; import utility.StackTraceUtil; import utility.Utils; @Slf4j @Singleton public class GetFromRemoteAndStore { private RemoteDBManager remoteDBManager; private StoreManager storeManager; private ColorManager colorManager; private ConvertManager convertManager; private ChartDatasetManager chartDatasetManager; private RawStoreManager rawStoreManager; private ConfigurationManager configurationManager; private OlapDAO olapDAO; private OlapCacheManager olapCacheManager; private boolean isFirstRun = false; private long sampleTimeG = 0L; @Getter private long currServerTime = 0L; @Getter private ConnProfile connProfile; private Connection connection = null; private Connection connectionForTrace = null; private Map<String, List<SqlColProfile>> metadataMap = new HashMap<>(); private String modNameSysdateSql; private String modNameAshSql; @Getter @Setter private IProfile iProfile; // Detail private Map<String, LinkedHashMap<String, Integer>> mapDetail = new TreeMap<>(); private List<Integer> SqlIdAddColName = new LinkedList(); private List<Integer> SessAddColName = new LinkedList(); @Inject public GetFromRemoteAndStore(ColorManager colorManager, RemoteDBManager remoteDBManagers, StoreManager storeManager, OlapCacheManager olapCacheManager, ConvertManager convertManager, ChartDatasetManager chartDatasetManager, RawStoreManager rawStoreManager, ConfigurationManager configurationManager, OlapDAO olapDAO) { this.colorManager = colorManager; this.remoteDBManager = remoteDBManagers; this.storeManager = storeManager; this.olapCacheManager = olapCacheManager; this.convertManager = convertManager; this.chartDatasetManager = chartDatasetManager; this.rawStoreManager = rawStoreManager; this.configurationManager = configurationManager; this.olapDAO = olapDAO; } public void initConnection(ConfigProfile configProfile) throws SQLException{ this.chartDatasetManager.setGetFromRemoteAndStore(this); this.connProfile = configProfile.getConnProfile(); this.remoteDBManager.init(configProfile); this.initializeConnection(); } public void initProfile(IProfile iProfile) { this.iProfile = iProfile; } public void loadSqlsMetadata() { if (!this.isFirstRun) { this.olapCacheManager.setIProfile(this.iProfile); this.olapDAO.setIProfile(this.iProfile); this.loadMetadata(); this.rawStoreManager.setSqlColMetadatumPojos(metadataMap.get(modNameAshSql)); iProfile.getSqlIdAdditionalColName().stream().forEach(e -> SqlIdAddColName.add(this.getColumnIdForCol(e))); iProfile.getSessAdditionalColName().stream().forEach(e -> SessAddColName.add(this.getColumnIdForCol(e))); } } public void loadDataFromRemoteToLocalStore() { this.loadConvertManager(); this.loadSqlsMetadata(); log.info("Start loading"); try { if (!this.isFirstRun) { this.loadUsername(); // For main chart iProfile.getUniqueTreeEventListByWaitClass().forEach(e -> chartDatasetManager.getMainNameChartDataset() .getStackChartPanel().getStackedChart().setSeriesPaintDynamicDetail(e)); } log.info("Start loading olap"); this.loadDataToOlap(); log.info("Start loading stacked chart"); this.loadToMainStackedChart(); log.info("Stop loading olap"); if (!this.isFirstRun) { // resolve the issue with the gap for large amount of data in ASH this.isFirstRun = true; this.loadDataToOlap(); this.loadToMainStackedChart(); } } catch (Exception e) { e.printStackTrace(); } this.storeManager.syncBdb(); } public void loadConvertManager(){ this.storeManager.getDatabaseDAO().setConvertManager(this.convertManager); } private void loadUsername() { loadUserIdUsernameToLocalDB(iProfile.getSqlTextUserIdName()); } private void loadToMainStackedChart(){ long min; long max; if (!this.isFirstRun) { max = sampleTimeG; if (sampleTimeG < currServerTime) { max = currServerTime; } min = max - ConstantManager.CURRENT_WINDOW; } else { max = sampleTimeG; min = (long) chartDatasetManager.getMainNameChartDataset().getDatasetRDA().getLastDtVal(); if (sampleTimeG < currServerTime) { max = currServerTime; } } // Main LinkedList<String> waitClassList = new LinkedList(); iProfile.getWaitClass().entrySet().forEach(ks -> waitClassList.add(ks.getKey())); LinkedHashMap<Long, long[]> hashMap = new LinkedHashMap(); int waitClassCount = Math.toIntExact(waitClassList.stream().count()); int range = (int) (ConstantManager.CURRENT_WINDOW / ConstantManager.MAX_POINT_PER_GRAPH); chartDatasetManager.getMainNameChartDataset().getDatasetRDA().setLastDtVal(max); for (long d = min; d < max; d += range) { if (range > ((int) (max - d))) { chartDatasetManager.getMainNameChartDataset().getDatasetRDA().setLastDtVal(d); continue; } EntityCursor<AshAggrMinData> cursor = this.olapDAO.getAshAggrMinDataDAO().getAshAggrEntityCursorRangeQuery(d, (d + range)); Iterator<AshAggrMinData> iterator = cursor.iterator(); hashMap.putIfAbsent(d, new long[waitClassCount]); while (iterator.hasNext()) { AshAggrMinData sl = iterator.next(); final long finalStart0 = d; // Main waitClassList.iterator().forEachRemaining(k -> { long tmp = hashMap.get(finalStart0)[this.getIProfile().getWaitClassId(k)]; hashMap.get(finalStart0)[this.getIProfile().getWaitClassId(k)] = sl.getSumValueByWaitClassId(this.getIProfile().getWaitClassId(k)) + tmp; }); // Detail waitClassList.iterator().forEachRemaining(k -> { Map<String, Integer> out = mapDetail.computeIfAbsent(k, m -> new LinkedHashMap<>()); Map<Integer, Integer> allWaitId1 = ConstantManager.zipToMap(sl.getWaitId(this.getIProfile().getWaitClassId(k)), //mtrx[0]::waitId; sl.getSum(this.getIProfile().getWaitClassId(k))); //mtrx[2]::sum; allWaitId1.entrySet().stream().forEach(s -> { out.merge(olapDAO.getEventStrValueForWaitEventId(s.getKey()), s.getValue(), Integer::sum); }); }); } cursor.close(); // Load to detail chart final double dd = d; final long maxmax = max; chartDatasetManager.getNameChartDatasetDetail().forEach(e -> mapDetail.entrySet().forEach(k -> { if (k.getKey().equalsIgnoreCase(e.getName())){ k.getValue().entrySet().stream().forEach(l -> { if (!e.getDatasetRDA().getSeriesNames().isEmpty()){ e.getStackChartPanel().getStackedChart().setSeriesPaintDynamicDetail(l.getKey()); e.getDatasetRDA().addSeriesValue(dd, (double) l.getValue()/(range / 1000), l.getKey()); } else { generateDataUpToMinForDetail(e, l.getKey(), maxmax - ConstantManager.CURRENT_WINDOW, (long) dd, range); e.getDatasetRDA().addSeriesValue(dd, (double) l.getValue()/(range / 1000), l.getKey()); } }); } })); // Clear mapDetail mapDetail.entrySet().stream().forEach(l -> l.getValue().replaceAll((k, v) -> 0)); } // Load to main chart final CategoryTableXYDatasetRDA catTabXYDtstRTVId = chartDatasetManager.getMainNameChartDataset().getDatasetRDA(); hashMap.entrySet().stream().forEach(e -> { final double finalD = e.getKey(); waitClassList.iterator().forEachRemaining(k -> catTabXYDtstRTVId.addSeriesValue(finalD, (double) e.getValue()[this.getIProfile().getWaitClassId(k)] / (range / 1000), k)); }); chartDatasetManager.getMainNameChartDataset().getDatasetRDA().deleteValuesFromDatasetDetail(ConstantManager.MAX_POINT_PER_GRAPH); chartDatasetManager.getNameChartDatasetDetail().forEach(e -> e.getDatasetRDA().deleteValuesFromDatasetDetail(ConstantManager.MAX_POINT_PER_GRAPH)); } private void generateDataUpToMinForDetail(NameChartDataset nameChartDataset, String key, long min, long dd, int range) { nameChartDataset.getStackChartPanel().getStackedChart().setSeriesPaintDynamicDetail(key); if (dd > min) { for (long d = min; d < dd; d += range) { nameChartDataset.getDatasetRDA().addSeriesValue(d, 0, key); } } } private void loadMetadata() { try { modNameSysdateSql = "sysdate" + "_" + iProfile.getProfileName(); modNameAshSql = "ash" + "_" + iProfile.getProfileName(); metadataMap.put(modNameSysdateSql, loadSqlMetaData(modNameSysdateSql, iProfile.getSqlTextSysdate())); metadataMap.put(modNameAshSql, loadSqlMetaData(modNameAshSql, iProfile.getSqlTextAshOneRow())); // Store metadata in local config file configurationManager.loadSqlColumnMetadata(loadSqlMetaData(modNameAshSql, iProfile.getSqlTextAshOneRow())); } catch (Exception e) { log.error(e.getLocalizedMessage()); log.error(StackTraceUtil.getCustomStackTrace(e)); } } private void loadDataToOlap() { String LBL_CPU_LOCAL = iProfile instanceof Postgres ? Options.LBL_PG_CPU : Options.LBL_CPU; PreparedStatement s = null; ResultSet rs = null; int sampleTimeColNameId = this.getColumnIdForCol(iProfile.getSampleTimeColName()); int waitClassColNameId = this.getColumnIdForCol(iProfile.getWaitClassColName()); int eventColNameId = this.getColumnIdForCol(iProfile.getEventColName()); int sqlIdColNameId = this.getColumnIdForCol(iProfile.getSqlIdColName()); int sessionIdColNameId = this.getColumnIdForCol(iProfile.getSessColName()); int sessionSerialIdColNameId = this.getColumnIdForCol(iProfile.getSerialColName()); currServerTime = getOneRowOutputDateFromDB(iProfile.getSqlTextSysdate()); List<Map<Integer, Object>> rows = new ArrayList<>(); try { AtomicInteger currRow = new AtomicInteger(0); s = this.getStatementForAsh(); rs = s.executeQuery(); rs.setFetchSize(15000); // to speed up loading while (rs.next()) { AtomicInteger kk = new AtomicInteger(0); long sampleTime = 0; String waitClass = ""; String waitEvent = ""; String sqlId = ""; String sqlText = ""; long sessionId = 0; long seriailId = 0; String[] sqlAddParam = new String[SqlIdAddColName.size()]; String[] sessAddParam = new String[SessAddColName.size()]; Map<Integer, String> sqlTmp = new HashMap<>(); Map<Integer, String> sessTmp = new HashMap<>(); // Prepare collection of rows to store data Map<Integer, Object> columns = new LinkedHashMap<>(); for (int i = 0; i < metadataMap.get(modNameAshSql).size(); i++) { kk.getAndIncrement(); /** Load raw data **/ columns.put(i, rs.getObject(i+1)); if (kk.get() == sampleTimeColNameId) { Timestamp timestamp = (Timestamp) rs.getObject(i+1); sampleTime = timestamp.getTime(); continue; } else if (kk.get() == waitClassColNameId){ waitClass = rs.getObject(i+1) != null ? (String) rs.getObject(i+1) : LBL_CPU_LOCAL; continue; } else if (kk.get() == eventColNameId){ waitEvent = rs.getObject(i+1) != null ? (String) rs.getObject(i+1) : LBL_CPU_LOCAL; continue; } else if (kk.get() == sqlIdColNameId){ sqlId = rs.getObject(i+1) != null ? (String) rs.getObject(i+1) : ConstantManager.NULL_VALUE; continue; } else if (kk.get() == sessionIdColNameId){ if (iProfile instanceof Postgres){ sessionId = (Integer) rs.getObject(i+1); } else { BigDecimal bigDecimal = (BigDecimal) rs.getObject(i+1); sessionId = bigDecimal.longValue(); } continue; } else if (kk.get() == sessionSerialIdColNameId){ if (iProfile instanceof Postgres){ seriailId = (Integer) rs.getObject(i+1); } else { BigDecimal bigDecimal = (BigDecimal) rs.getObject(i+1); seriailId = bigDecimal.longValue(); } continue; } else if (SqlIdAddColName.contains(kk.get())){ String colName = metadataMap.get(modNameAshSql).stream().filter(e -> e.getColId() == kk.get()).findFirst().get().getColName(); String colType = metadataMap.get(modNameAshSql).stream().filter(e -> e.getColId() == kk.get()).findFirst().get().getColDbTypeName(); sqlTmp.put(iProfile.getSqlIdAdditionalColName().indexOf(colName), convertManager.convertFromRawToString(colType, rs.getObject(i+1))); continue; } else if (SessAddColName.contains(kk.get())){ String colName = metadataMap.get(modNameAshSql).stream().filter(e -> e.getColId() == kk.get()).findFirst().get().getColName(); String colType = metadataMap.get(modNameAshSql).stream().filter(e -> e.getColId() == kk.get()).findFirst().get().getColDbTypeName(); sessTmp.put(iProfile.getSessAdditionalColName().indexOf(colName), convertManager.convertFromRawToString(colType, rs.getObject(i+1))); continue; } else if ((iProfile instanceof Postgres)){ if (kk.get() == this.getColumnIdForCol(iProfile.getSqlTextColumn())){ sqlText = rs.getObject(i+1) != null ? (String) rs.getObject(i+1) : ConstantManager.NULL_VALUE; } continue; } } if (iProfile instanceof OracleEE) { if (sampleTime != sampleTimeG) { rawStoreManager.loadData(sampleTimeG, rows); rows.clear(); } } if (configurationManager.getRawRetainDays() > 0){ rows.add(columns); } LocalDateTime sampleTimeDt = LocalDateTime.ofInstant(Instant.ofEpochMilli(sampleTime), ZoneId.systemDefault()); // SqlId if (!sqlId.equalsIgnoreCase(ConstantManager.NULL_VALUE)){ sqlTmp.entrySet().stream() .sorted(Map.Entry.comparingByKey()).forEach(e -> sqlAddParam[e.getKey()] = e.getValue()); /** Additional dimension for sql detail **/ this.olapDAO.getCheckOrLoadParameter(sqlId, sqlAddParam); } // Sqltext (for postgres db only) if (iProfile instanceof Postgres){ storeManager.getDatabaseDAO() .getParamStringStringDAO().putNoOverwrite(sqlId, sqlText); } // SessionId + Serial# sessTmp.entrySet().stream() .sorted(Map.Entry.comparingByKey()).forEach(e -> sessAddParam[e.getKey()] = e.getValue()); // SqlId + SessionId + Serial# String[] addParamSqlSess = new String[1+SessAddColName.size()]; addParamSqlSess[0] = sqlAddParam[0]; addParamSqlSess[1] = sessAddParam[0]; addParamSqlSess[2] = sessAddParam[1]; this.olapCacheManager.loadAshRawData(sampleTimeDt, sqlId + "_" + sessionId + "_" + seriailId, addParamSqlSess, waitEvent, iProfile.getWaitClassId(waitClass)); /** Additional dimension for session detail **/ this.olapDAO.getCheckOrLoadParameter(sessionId + "_" + seriailId, sessAddParam); sampleTimeG = sampleTime; if (!this.isFirstRun & currRow.getAndIncrement() > 6000) { this.olapCacheManager.unloadCacheToDB15(sampleTimeG); } } rawStoreManager.loadData(sampleTimeG, rows); rows.clear(); this.olapCacheManager.unloadCacheToDB(); this.olapCacheManager.unloadCacheToDB15(getOneRowOutputDateFromDB(iProfile.getSqlTextSysdate())); rs.close(); s.close(); } catch (Exception e) { e.printStackTrace(); log.error(e.getLocalizedMessage()); } finally { if (s != null) { try { s.close(); } catch (Exception e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } } } private PreparedStatement getStatementForAsh() throws SQLException{ PreparedStatement s; String sqlText = iProfile.getSqlTextAsh(); String where = " WHERE " + iProfile.getSampleTimeColName() + " > ? "; String orderBy = " ORDER BY " + iProfile.getSampleTimeColName() + " ASC"; if (iProfile instanceof Postgres) { s = connection.prepareStatement(sqlText); } else if (iProfile instanceof OracleEE10g) { sqlText = sqlText + " and " + iProfile.getSampleTimeColName() + " > ? " + orderBy; s = getPreparedStatement(sqlText); } else if (iProfile instanceof OracleEEObject) { sqlText = sqlText + " and " + iProfile.getSampleTimeColName() + " > ? " + orderBy; s = getPreparedStatement(sqlText); } else { sqlText = sqlText + where + orderBy; s = getPreparedStatement(sqlText); } return s; } @NotNull private PreparedStatement getPreparedStatement(String sqlText) throws SQLException { PreparedStatement s; if (!this.isFirstRun) { s = connection.prepareStatement(sqlText); s.setTimestamp(1, new Timestamp(getSampleTimeValue(currServerTime))); } else { s = connection.prepareStatement(sqlText); s.setTimestamp(1, new Timestamp(sampleTimeG)); } return s; } private long getSampleTimeValue(long currServerTime) { ParameterBuilder param = new ParameterBuilder.Builder(currServerTime - ConstantManager.CURRENT_WINDOW, currServerTime) .build(); long sampleTime = this.storeManager.getDatabaseDAO().getMax(param); String initialLoadingStr = configurationManager .getConnectionParameters(connProfile.getConnName()).getInitialLoading(); if (!initialLoadingStr.equals("-1")) { long initialLoadingLong = Integer.parseInt(initialLoadingStr); long sampleTimeFromConfig = currServerTime - (initialLoadingLong*60*1000); sampleTime = Math.max(sampleTimeFromConfig, sampleTime); } return sampleTime; } private int getColumnIdForCol(String filterCol){ return metadataMap .get(modNameAshSql) .stream() .filter(e -> e.getColName().equalsIgnoreCase(filterCol)) .findFirst().get().getColId(); } private void initializeConnection() throws SQLException { this.connection = this.remoteDBManager.getConnection(); this.connectionForTrace = this.remoteDBManager.getConnection(); } private List<SqlColProfile> loadSqlMetaData(String sqlName, String sqlText) { PreparedStatement s = null; ResultSet rs = null; List<SqlColProfile> sqlColProfileList = new ArrayList<>(); try { s = connection.prepareStatement(sqlText); s.executeQuery(); rs = s.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { SqlColProfile columnPojo = new SqlColProfile(); columnPojo.setColId(i); columnPojo.setColName(rsmd.getColumnName(i).toUpperCase()); //PG bug here resolved :: lower-upper case columnPojo.setColDbTypeName(rsmd.getColumnTypeName(i).toUpperCase()); //PG bug here resolved :: lower-upper case columnPojo.setSqlAndColName(sqlName + rsmd.getColumnName(i).toUpperCase()); columnPojo.setColSizeDisplay(rsmd.getColumnDisplaySize(i)); columnPojo.setColSizeSqlType(rsmd.getColumnType(i)); sqlColProfileList.add(i - 1, columnPojo); } rs.close(); s.close(); } catch (Exception e) { log.error(Arrays.toString(e.getStackTrace())); e.printStackTrace(); // need to log it } finally { if (s != null) { try { s.close(); } catch (Exception e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } } return sqlColProfileList; } private long getOneRowOutputDateFromDB(String statement){ long out = 0; PreparedStatement s = null; ResultSet rs = null; try { s = connection.prepareStatement(statement); rs = s.executeQuery(); while (rs.next()) { Timestamp dt = (Timestamp) rs.getObject(1); out = dt.getTime(); } rs.close(); s.close(); } catch (SQLException e) { log.error("SQL error while executing the following statement:" + statement); log.error(Arrays.toString(e.getStackTrace())); } catch (NullPointerException e) { log.error("NullPointerException while executing the following statement:" + statement + ". Check you access rights to table or existence one."); log.error(Arrays.toString(e.getStackTrace())); } finally { if (s != null) { try { s.close(); } catch (Exception e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } } return out; } private void loadUserIdUsernameToLocalDB(String statement){ PreparedStatement s = null; ResultSet rs = null; try { s = connection.prepareStatement(statement); rs = s.executeQuery(); while (rs.next()) { this.olapDAO.putUserIdUsername(new AshUser(rs.getInt(1), rs.getString(2))); } rs.close(); s.close(); } catch (SQLException e) { log.error(Arrays.toString(e.getStackTrace())); e.printStackTrace(); // need to log it } finally { if (s != null) { try { s.close(); } catch (Exception e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } } } public Vector getVectorDataForRowToTableForSql(String parameter1, String parameter2, String sqlText){ Vector data = new Vector(); QueryRunner run = new QueryRunner(remoteDBManager.getBasicDataSource()); try { HashMap<String, String> result = run.query(sqlText, mapHV, parameter1, parameter2); result.entrySet().forEach(e -> { Vector row = new Vector(); row.add(e.getKey()); row.add(e.getValue()); data.add(row); }); } catch (SQLException e) { log.error("SQL exception::" + e.toString()); return data; } catch (NullPointerException e) { log.info("No data found"); return data; } return data; } public String getSqlFullText(String sqlId){ if (storeManager.getDatabaseDAO().getParamStringStringDAO().isExistValueByParameter(sqlId)){ return storeManager.getDatabaseDAO().getParamStringStringDAO().getValue(sqlId); } QueryRunner run = new QueryRunner(remoteDBManager.getBasicDataSource()); try { Object[] result = run.query(iProfile.getSqlFullText(), h, sqlId); Clob clobVal = (Clob) result[0]; String out = clobVal.getSubString(1, (int) clobVal.length()); storeManager.getDatabaseDAO().getParamStringStringDAO().putNoOverwrite(sqlId, out); return out; } catch (SQLException e) { log.error("SQL exception::" + e.toString()); } catch (NullPointerException e) { log.info("No data found"); return ""; } return ""; } // Get plan hash value list public List<SqlPojo> getSqlPlanHashValue(String sqlId){ List<SqlPojo> out = new ArrayList<>(); QueryRunner run = new QueryRunner(remoteDBManager.getBasicDataSource()); try { ResultSetHandler<List<SqlPojo>> resultSetHandler = new BeanListHandler<>(SqlPojo.class); return run.query(iProfile.getSqlForPlanHashValueList(), resultSetHandler, sqlId); } catch (SQLException e) { log.error("SQL exception::" + e.toString()); return out; } catch (NullPointerException e) { log.error("No data found"); return out; } } public String setTrace10046(int sid, int serial, boolean bool) { String out = ""; CallableStatement stmt = null; if (iProfile instanceof Postgres){ return Labels.getLabel("main.notsupported"); } try { if (bool) { stmt = connectionForTrace.prepareCall("begin " + "SYS.DBMS_MONITOR." + "SESSION_TRACE_ENABLE" + "(?,?,true,true); end;"); out = "SYS.DBMS_MONITOR.SESSION_TRACE_ENABLE successfully executed!"; } else { stmt = connectionForTrace.prepareCall("begin " + "SYS.DBMS_MONITOR." + "SESSION_TRACE_DISABLE" + "(?,?); end;"); out = "SYS.DBMS_MONITOR.SESSION_TRACE_DISABLE successfully executed!"; } stmt.setInt(1, sid); stmt.setInt(2, serial); stmt.execute(); } catch (SQLException e) { log.error("SQL exception::" + e.toString()); out = e.toString(); } catch (NullPointerException e) { log.info("No data found.."); out = e.toString(); } finally { try { if (stmt != null) { stmt.close(); // close the statement } } catch (SQLException ex) { log.info("Final SQLException.."); out = ex.toString(); } } return out; } // Create a ResultSetHandler implementation to convert the waitEventId row into an Object[]. ResultSetHandler<Object[]> h = rs -> { if (!rs.next()) { return null; } ResultSetMetaData meta = rs.getMetaData(); int cols = meta.getColumnCount(); Object[] result = new Object[cols]; for (int i = 0; i < cols; i++) { result[i] = rs.getObject(i + 1); } return result; }; ResultSetHandler<HashMap<String, String>> mapHV = rs -> { if (!rs.next()) { return null; } ResultSetMetaData meta = rs.getMetaData(); int cols = meta.getColumnCount(); HashMap<String, String> result = new HashMap<>(); for (int i = 0; i < cols; i++) { result.put(meta.getColumnName(i+1), convertManager.convertFromRawToString(meta.getColumnTypeName(i+1),rs.getObject(i+1))); } return result; }; public void loadSqlPlanHashValueFromRemoteToLocalBDB(String sqlId, long sqlPlanHashValue){ QueryRunner run = new QueryRunner(remoteDBManager.getBasicDataSource()); if (!this.storeManager.getDatabaseDAO().getISqlPlan().checkSqlIdAndPlanHashValueExist(sqlId, sqlPlanHashValue)){ try { ResultSetHandler<List<SqlPlanPojo>> resultSetHandler = new BeanListHandler<>(SqlPlanPojo.class); List<SqlPlanPojo> planPojoList = run.query(iProfile.getSqlPlanText(), resultSetHandler, sqlId); planPojoList.stream().forEach(e -> { if (e.getPlan_hash_value() == sqlPlanHashValue){ this.storeManager.getDatabaseDAO().getISqlPlan().putSqlPlanNoOverwrite( new SqlPlan (0, e.getAddress(), e.getHash_value(), sqlId, sqlPlanHashValue, "", e.getChild_number(),0, e.getOperation(), e.getOptions(),e.getObject_node(), e.getObj(),e.getObject_owner(),e.getObject_name(), e.getObject_alias(),e.getObject_type(), e.getOptimizer(), e.getId(), e.getParent_id(), e.getDepth(), e.getPosition(), e.getSearch_columns(), e.getCost(), e.getCardinality(), e.getBytes(), e.getOther_tag(), e.getPartition_start(),e.getPartition_stop(), e.getPartition_id(),e.getOther(), e.getDistribution(),e.getCpu_cost(), e.getIo_cost(),e.getTemp_space(), e.getAccess_predicates(), e.getFilter_predicates(), e.getProjection(),e.getTime(), e.getQblock_name(), e.getRemarks() ) ); } }); } catch (SQLException e) { log.error("SQL exception::" + e.toString()); } catch (NullPointerException e) { log.error("No data found"); } } } public TreeTableModel getSqlPlanModelByPlanHashValue(HashMap<Long, Long> idLevel, Long sqlPlanHashValue, String sqlId) { ExplainPlanModel10g2 model = null; ExplainPlanModel10g2.ExplainRow lastRow = null; long previousLevel = 1; boolean isRecalculateDepth = false; boolean exitFromCycle = false; boolean isChildNumberSaved = false; long childNumberBySql = 0; long ii = 0; try { while (!exitFromCycle) { exitFromCycle = true; try { EntityCursor<SqlPlan> sqlPlanBDB = this.storeManager.getDatabaseDAO().doRangeQuery( this.storeManager.getDatabaseDAO().getISqlPlan().getEnityCurPlanHashValue(), sqlPlanHashValue, true, sqlPlanHashValue, true); Iterator<SqlPlan> sqlPlanIterator = sqlPlanBDB.iterator(); while (sqlPlanIterator.hasNext()) { SqlPlan sqlPlan = sqlPlanIterator.next(); String sqlIdTmp = sqlPlan.getSqlId(); long childNumberTmp = sqlPlan.getChildNumber(); if (!isChildNumberSaved && sqlId.equalsIgnoreCase(sqlIdTmp)) { childNumberBySql = childNumberTmp; isChildNumberSaved = true; } else { if (!sqlId.equalsIgnoreCase(sqlIdTmp)) continue; } Long id = sqlPlan.getId(); if (id == ii && childNumberBySql == childNumberTmp) { exitFromCycle = false; String address = Optional.ofNullable(sqlPlan.getAddress()).orElse(""); Double hashValue = Optional.ofNullable(sqlPlan.getHashValue()).orElse(0D); String childAddress = Optional.ofNullable(sqlPlan.getChildAddress()).orElse(""); Long childNumber = Optional.ofNullable(sqlPlan.getChildNumber()).orElse(0L); String operation = Optional.ofNullable(sqlPlan.getOperation()).orElse(""); String options = Optional.ofNullable(sqlPlan.getOptions()).orElse(""); String objectNode = Optional.ofNullable(sqlPlan.getObjectNode()).orElse(""); Double object = Optional.ofNullable(sqlPlan.getObject()).orElse(0D); String objectOwner = Optional.ofNullable(sqlPlan.getObjectOwner()).orElse(""); String objectName = Optional.ofNullable(sqlPlan.getObjectName()).orElse(""); String objectAlias = Optional.ofNullable(sqlPlan.getObjectAlias()).orElse(""); String objectType = Optional.ofNullable(sqlPlan.getObjectType()).orElse(""); String optimizer = Optional.ofNullable(sqlPlan.getOptimizer()).orElse(""); Long Id = Optional.ofNullable(sqlPlan.getId()).orElse(0L); Long parentId = Optional.ofNullable(sqlPlan.getParentId()).orElse(0L); /*Depth/Level*/ Long level = !isRecalculateDepth ? sqlPlan.getDepth() + 1 : idLevel.get(id) == null ? sqlPlan.getId():idLevel.get(id) ; /*Depth/Level*/ Long position = Optional.ofNullable(sqlPlan.getPosition()).orElse(0L); Long searchColumns = Optional.ofNullable(sqlPlan.getSearchColumns()).orElse(0L); Double cost = Optional.ofNullable(sqlPlan.getCost()).orElse(0D); Double cardinality = Optional.ofNullable(sqlPlan.getCardinality()).orElse(0D); Double bytes = Optional.ofNullable(sqlPlan.getBytes()).orElse(0D); String otherTag = Optional.ofNullable(sqlPlan.getOtherTag()).orElse(""); String partitionStart = Optional.ofNullable(sqlPlan.getPartitionStart()).orElse(""); String partitionStop = Optional.ofNullable(sqlPlan.getPartitionStop()).orElse(""); Double partitionId = Optional.ofNullable(sqlPlan.getPartitionId()).orElse(0D); String other = Optional.ofNullable(sqlPlan.getOther()).orElse(""); String distribution = Optional.ofNullable(sqlPlan.getDistribution()).orElse(""); Double cpuCost = Optional.ofNullable(sqlPlan.getCpuCost()).orElse(0D); Double ioCost = Optional.ofNullable(sqlPlan.getIoCost()).orElse(0D); Double tempSpace = Optional.ofNullable(sqlPlan.getTempSpace()).orElse(0D); String accessPredicates = Optional.ofNullable(sqlPlan.getAccessPredicates()).orElse(""); String filterPredicates = Optional.ofNullable(sqlPlan.getFilterPredicates()).orElse(""); String projection = Optional.ofNullable(sqlPlan.getProjection()).orElse(""); Double time = Optional.ofNullable(sqlPlan.getTime()).orElse(0D); String qblockName = Optional.ofNullable(sqlPlan.getQblockName()).orElse(""); String remarks = Optional.ofNullable(sqlPlan.getRemarks()).orElse(""); ExplainPlanModel10g2.ExplainRow parent = null; if (level == 1) { long tmp = 0; ExplainPlanModel10g2.ExplainRow rowRoot = new ExplainPlanModel10g2.ExplainRow( parent, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, tmp, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); model = new ExplainPlanModel10g2(rowRoot); ExplainPlanModel10g2.ExplainRow row = new ExplainPlanModel10g2.ExplainRow( rowRoot, address.toString(), hashValue, sqlIdTmp, sqlPlanHashValue, childAddress.toString(), childNumber, operation, options, objectNode, object, objectOwner, objectName, objectAlias, objectType, optimizer, Id, parentId, /*Depth*/level, position, searchColumns, cost, cardinality, bytes, otherTag, partitionStart, partitionStop, partitionId, other, distribution, cpuCost, ioCost, tempSpace, accessPredicates, filterPredicates, projection, time, qblockName, remarks); rowRoot.addChild(row); lastRow = row; previousLevel = level; continue; } else if (previousLevel == level) { parent = ((ExplainPlanModel10g2.ExplainRow) lastRow .getParent().getParent()) .findChild(parentId.intValue()); } else if (level > previousLevel) { parent = ((ExplainPlanModel10g2.ExplainRow) lastRow .getParent()).findChild(parentId.intValue()); } else if (level < previousLevel) { parent = (ExplainPlanModel10g2.ExplainRow) lastRow.getParent(); for (long i = previousLevel - level; i >= 0; i--) { parent = (ExplainPlanModel10g2.ExplainRow) parent.getParent(); } parent = parent.findChild(parentId.intValue()); } if (parent == null && idLevel.isEmpty()) { isRecalculateDepth = true; break; } if (parent == null && !idLevel.isEmpty()) { isRecalculateDepth = false; break; } ExplainPlanModel10g2.ExplainRow row = new ExplainPlanModel10g2.ExplainRow( parent, address.toString(), hashValue, sqlIdTmp, sqlPlanHashValue, childAddress.toString(), childNumber, operation, options, objectNode, object, objectOwner, objectName, objectAlias, objectType, optimizer, Id, parentId, /*Depth*/level, position, searchColumns, cost, cardinality, bytes, otherTag, partitionStart, partitionStop, partitionId, other, distribution, cpuCost, ioCost, tempSpace, accessPredicates, filterPredicates, projection, time, qblockName, remarks); parent.addChild(row); lastRow = row; previousLevel = level; break; } } sqlPlanBDB.close(); ii++; } catch (Exception e) { log.error(e.toString()); } } } catch (Exception e){ log.error(e.toString()); } // Recalculate wrong node levels if (isRecalculateDepth) { HashMap<Long, Long> idParentId = new HashMap<>(); HashMap<Long, Long> idLevelRcl; try { EntityCursor<SqlPlan> sqlPlanBDB = this.storeManager.getDatabaseDAO().doRangeQuery( this.storeManager.getDatabaseDAO().getISqlPlan().getEnityCurPlanHashValue(), sqlPlanHashValue, true, sqlPlanHashValue, true); Iterator<SqlPlan> sqlPlanIterator = sqlPlanBDB.iterator(); while (sqlPlanIterator.hasNext()){ SqlPlan sqlPlan = sqlPlanIterator.next(); Long idP = sqlPlan.getId(); Long parent_idP = sqlPlan.getParentId(); long tmp = -1; if (idP == 0) { idParentId.put(idP, tmp); } else { idParentId.put(idP, parent_idP); } } idLevelRcl = Utils.getLevels(idParentId); model = (ExplainPlanModel10g2) this.getSqlPlanModelByPlanHashValue(idLevelRcl, sqlPlanHashValue, sqlId); sqlPlanBDB.close(); } catch (Exception e) { log.error(e.toString()); } finally { } } return model; } }
47,037
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ClearDatabaseThread.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/thread/ClearDatabaseThread.java
package core.thread; import core.manager.ConfigurationManager; import core.manager.ConstantManager; import core.processing.GetFromRemoteAndStore; import lombok.extern.slf4j.Slf4j; import store.StoreManager; import javax.inject.Inject; import javax.inject.Singleton; import java.time.Duration; import java.time.Instant; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; @Slf4j @Singleton public class ClearDatabaseThread { private StoreManager storeManager; private GetFromRemoteAndStore getFromRemoteAndStore; private ConfigurationManager configurationManager; private Timer timer = new Timer(); @Inject public ClearDatabaseThread(StoreManager storeManager, GetFromRemoteAndStore getFromRemoteAndStore, ConfigurationManager configurationManager) { this.storeManager = storeManager; this.getFromRemoteAndStore = getFromRemoteAndStore; this.configurationManager = configurationManager; } public void schedulerTimer(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 22); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date time = calendar.getTime(); timer.schedule(new clearDatabase(), time); } class clearDatabase extends TimerTask { public void run() { int intRawDays = configurationManager.getRawRetainDays(); int intOlapDays = configurationManager.getOlapRetainDays(); long start = 0L; long endRaw = getFromRemoteAndStore.getCurrServerTime() - TimeUnit.DAYS.toMillis(intRawDays); long endOlap = getFromRemoteAndStore.getCurrServerTime() - TimeUnit.DAYS.toMillis(intOlapDays); boolean isRawDataClean = (intRawDays > 0) & (intRawDays < ConstantManager.RETAIN_DAYS_MAX); boolean isOlapDataClean = (intOlapDays > 0) & (intOlapDays < ConstantManager.RETAIN_DAYS_MAX); if (isRawDataClean) { Instant startedAt = Instant.now(); log.info("Clearing of raw data started .."); storeManager.getDatabaseDAO().deleteMainData(start, endRaw); Instant endedAt = Instant.now(); Duration duration = Duration.between(startedAt , endedAt); String hms = String.format("%d hour %02d min %02d sec", duration.toHours(), duration.toMinutes(), duration.toMillis()/1000); log.info("Clearing of raw data takes " + hms); } if (isOlapDataClean) { Instant startedAt = Instant.now(); log.info("Clearing of OLAP data started .."); storeManager.getOlapDAO().deleteOlapData(start, endOlap); Instant endedAt = Instant.now(); Duration duration = Duration.between(startedAt , endedAt); String hms = String.format("%d hour %02d min %02d sec", duration.toHours(), duration.toMinutes(), duration.toMillis()/1000); log.info("Clearing of OLAP data takes " + hms); } } } }
3,483
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SqlExecutorThread.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/thread/SqlExecutorThread.java
package core.thread; import core.CurrrentState; import core.StateMachine; import core.StateTransitionListener; import core.processing.GetFromRemoteAndStore; import lombok.extern.slf4j.Slf4j; import store.OlapCacheManager; import store.StoreManager; import javax.inject.Inject; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @Slf4j public class SqlExecutorThread implements StateTransitionListener { private StateMachine stateMachine; private StoreManager storeManager; private GetFromRemoteAndStore getFromRemoteAndStore; private OlapCacheManager olapCacheManager; private ScheduledExecutorService service; private boolean isRunning; @Inject public SqlExecutorThread(StateMachine stateMachine, GetFromRemoteAndStore getFromRemoteAndStore, StoreManager storeManager, OlapCacheManager olapCacheManager){ this.stateMachine = stateMachine; this.getFromRemoteAndStore = getFromRemoteAndStore; this.storeManager = storeManager; this.olapCacheManager = olapCacheManager; this.isRunning = true; this.stateMachine.addTransitionListener(this); } public void startIt(){ service = Executors.newSingleThreadScheduledExecutor(); service.submit(taskThatFinishesEarlyOnInterruption()); } public void stopIt(){ try { service.shutdownNow(); service.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException ie) { log.error("InterruptedException while stopping service", ie); } } private Runnable taskThatFinishesEarlyOnInterruption() { return () -> { while (isRunning) { getFromRemoteAndStore.loadDataFromRemoteToLocalStore(); try { Thread.sleep(this.olapCacheManager.getIProfile().getInterval()); } catch (InterruptedException e) { log.error(e.getMessage()); break; } } }; } @Override public void transitionTo(CurrrentState state) { } }
2,274
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ConnectionBuilder.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/parameter/ConnectionBuilder.java
package core.parameter; import gui.model.ContainerType; import gui.model.EncryptionType; public class ConnectionBuilder { private final String connectionName; private final String userName; private String password; private final String url; private final String jar; private final String profile; private final String driverName; private final String initialLoading; private final String rawRetainDays; private final String olapRetainDays; private final EncryptionType encryptionType; private final ContainerType containerType; public String getConnectionName() { return connectionName; } public String getUserName() { return userName; } public String getPassword() { return password; } public String getUrl() { return url; } public String getJar() { return jar; } public String getProfile() { return profile; } public String getDriverName() { return driverName; } public String getInitialLoading() { return initialLoading; } public String getRawRetainDays() { return rawRetainDays; } public String getOlapRetainDays() { return olapRetainDays; } public EncryptionType getEncryptionType() { return encryptionType; } public ContainerType getContainerType() { return containerType; } public void cleanPassword() { password = ""; } public static class Builder { private final String connectionName; private String userName; private String password; private String url; private String jar; private String profile; private String driverName; private String initialLoading; private String rawRetainDays; private String olapRetainDays; private EncryptionType encryptionType; private ContainerType containerType; public Builder(String connectionName) { this.connectionName = connectionName; } public Builder userName(String un) { userName = un; return this; } public Builder password(String pw) { password = pw; return this; } public Builder url(String ul) { url = ul; return this; } public Builder jar(String jr) { jar = jr; return this; } public Builder profile(String pr) { profile = pr; return this; } public Builder driverName(String dr) { driverName = dr; return this; } public Builder initialLoading(String il) { initialLoading = il; return this; } public Builder rawRetainDays(String raw) { rawRetainDays = raw; return this; } public Builder olapRetainDays(String raw) { olapRetainDays = raw; return this; } public Builder encryptionType(EncryptionType raw) { encryptionType = raw; return this; } public Builder containerType(ContainerType raw) { containerType = raw; return this; } public ConnectionBuilder build() { return new ConnectionBuilder(this); } } private ConnectionBuilder(Builder builder){ connectionName = builder.connectionName; userName = builder.userName; password = builder.password; url = builder.url; jar = builder.jar; profile = builder.profile; driverName = builder.driverName; initialLoading = builder.initialLoading; rawRetainDays = builder.rawRetainDays; olapRetainDays = builder.olapRetainDays; encryptionType = builder.encryptionType; containerType = builder.containerType; } }
3,477
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ParameterBuilder.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/core/parameter/ParameterBuilder.java
package core.parameter; import java.util.List; import java.util.Map; public class ParameterBuilder { private final double beginTime; private final double endTime; private Map<String, List<String>> columnNameToData; private final String sqlName; private final String colNameFilter; public double getBeginTime() { return beginTime; } public double getEndTime() { return endTime; } public Map<String, List<String>> getColumnNameToData() { return columnNameToData; } public String getSqlName() { return sqlName; } public String getColNameFilter() { return colNameFilter; } public static class Builder { private final double beginTime; private final double endTime; private Map<String, List<String>> dbaFilesIdList = null; private String sqlName; private String colNameFilter; public Builder(double beginTime, double endTime) { this.beginTime = beginTime; this.endTime = endTime; } public Builder dbaFilesIdList(Map<String, List<String>> val) { dbaFilesIdList = val; return this; } public Builder sqlName(String val) { sqlName = val; return this; } public Builder colNameFilter(String val) { colNameFilter = val; return this; } public ParameterBuilder build() { return new ParameterBuilder(this); } } private ParameterBuilder(Builder builder){ beginTime = builder.beginTime; endTime = builder.endTime; columnNameToData = builder.dbaFilesIdList; sqlName = builder.sqlName; colNameFilter = builder.colNameFilter; } }
1,672
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OracleEE.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/profile/OracleEE.java
package profile; import core.manager.ConstantManager; import java.awt.Color; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import lombok.Data; import org.rtv.Options; @Data public class OracleEE implements IProfile { String profileName = "OracleEE"; String driverName = "oracle.jdbc.driver.OracleDriver"; String sqlTextSysdate = "SELECT sysdate FROM dual"; String sqlTextAsh = "SELECT * FROM v$active_session_history"; String sqlTextAshOneRow = "SELECT * FROM v$active_session_history WHERE rownum = 1"; String sqlTextUserIdName = "SELECT user_id, username FROM dba_users"; String sqlTextColumn = "QUERY"; String sampleTimeColName = "SAMPLE_TIME"; String waitClassColName = "WAIT_CLASS"; String eventColName = "EVENT"; String sqlIdColName = "SQL_ID"; List<String> sqlIdAdditionalColName = new LinkedList<>(); String sessColName = "SESSION_ID"; String serialColName = "SESSION_SERIAL#"; List<String> sessAdditionalColName = new LinkedList<>(); LinkedHashSet<String> uniqueTreeEventListByWaitClass = new LinkedHashSet<>(); /** Sql detail **/ String sqlFullText = "SELECT sql_fulltext FROM v$sql WHERE sql_id = ? and rownum < 2"; LinkedHashMap<String, String> sqlStatsQuery = new LinkedHashMap<>(); String sqlPlanText = "SELECT address, hash_value, sql_id, plan_hash_value, child_number," + " operation, options, object_node, object# obj, object_owner, object_name, object_alias," + " object_type, optimizer, id, parent_id, depth, position, search_columns, cost," + " cardinality, bytes, other_tag, partition_start, partition_stop, partition_id," + " other, distribution, cpu_cost, io_cost, temp_space, access_predicates, filter_predicates," + " projection, time, qblock_name, remarks" + " FROM v$sql_plan " + " WHERE sql_id = ?"; String sqlForPlanHashValueList = "SELECT sql_id, plan_hash_value, child_address FROM v$sql WHERE sql_id = ?"; /** Session detail **/ LinkedHashMap<String, String> sessionStatsQuery = new LinkedHashMap<>(); long interval = 5000; // 5 sec public OracleEE() { sqlIdAdditionalColName.add("SQL_OPNAME"); sessAdditionalColName.add("USER_ID"); sessAdditionalColName.add("PROGRAM"); uniqueTreeEventListByWaitClass.add(Options.LBL_CPU); uniqueTreeEventListByWaitClass.add(Options.LBL_SCHEDULER); uniqueTreeEventListByWaitClass.add(Options.LBL_USERIO); uniqueTreeEventListByWaitClass.add(Options.LBL_SYSTEMIO); uniqueTreeEventListByWaitClass.add(Options.LBL_CONCURRENCY); uniqueTreeEventListByWaitClass.add(Options.LBL_APPLICATION); uniqueTreeEventListByWaitClass.add(Options.LBL_COMMIT); uniqueTreeEventListByWaitClass.add(Options.LBL_CONFIGURATION); uniqueTreeEventListByWaitClass.add(Options.LBL_ADMINISTRATIVE); uniqueTreeEventListByWaitClass.add(Options.LBL_NETWORK); uniqueTreeEventListByWaitClass.add(Options.LBL_QUEUEING); uniqueTreeEventListByWaitClass.add(Options.LBL_CLUSTER); uniqueTreeEventListByWaitClass.add(Options.LBL_OTHER); uniqueTreeEventListByWaitClass.add(Options.LBL_IDLE); sqlStatsQuery.put("V$SQL", "SELECT * FROM v$sql WHERE sql_id = ? and child_address = ?"); // Do not use //statsSqlQuery.put("V$SQLAREA", "SELECT sa.* FROM v$sqlarea sa WHERE sa.sql_id in (select s.sql_id from v$sql s where s.sql_id = ? and s.child_address = ? and rownum < 2)"); sessionStatsQuery.put("V$SESSION", "SELECT * FROM v$session WHERE sid = ? and serial# = ?"); sessionStatsQuery.put("V$PROCESS", "select p.* from v$process p where p.addr in (select s.paddr from v$session s where s.sid = ? and s.serial# = ?)"); } @Override public LinkedHashMap<String, Color> getWaitClass(){ return Options.getOracleMainColor(); } @Override public byte getWaitClassId(String waitClass) { return ConstantManager.getWaitClassId(waitClass); } @Override public String getWaitClass(byte waitClassId) { return ConstantManager.getWaitClass(waitClassId); } }
4,237
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
Postgres.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/profile/Postgres.java
package profile; import core.manager.ConstantManager; import lombok.Data; import org.rtv.Options; import java.awt.*; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; @Data public class Postgres implements IProfile { String profileName = "Postgres"; String driverName = "org.postgresql.Driver"; String sqlTextSysdate = "SELECT now()"; String sqlTextAsh = "SELECT current_timestamp as SAMPLE_TIME, " + "datid, datname, " + "pid AS SESSION_ID, pid AS SESSION_SERIAL, usesysid AS USER_ID, " + "coalesce(usename, 'unknown') as usename, " + "concat(application_name,'::', backend_type, '::', coalesce(client_hostname, client_addr::text, 'localhost')) AS PROGRAM, " + "wait_event_type AS WAIT_CLASS, wait_event AS EVENT, query, substring(md5(query) from 0 for 15) AS SQL_ID, " + "left(query, strpos(query, ' ')) AS SQL_OPNAME, " + "coalesce(query_start, xact_start, backend_start) as query_start, " + "1000 * EXTRACT(EPOCH FROM (clock_timestamp()-coalesce(query_start, xact_start, backend_start))) as duration " + "from pg_stat_activity " // + "where state='active'"; // for test purposes.. + "where state='active' and pid != pg_backend_pid()"; String sqlTextUserIdName = "SELECT usesysid AS USER_ID, usename AS USERNAME FROM pg_catalog.pg_user"; String sqlTextColumn = "QUERY"; String sampleTimeColName = "SAMPLE_TIME"; String waitClassColName = "WAIT_CLASS"; String eventColName = "EVENT"; String sqlIdColName = "SQL_ID"; List<String> sqlIdAdditionalColName = new LinkedList<>(); String sessColName = "SESSION_ID"; String serialColName = "SESSION_SERIAL"; List<String> sessAdditionalColName = new LinkedList<>(); LinkedHashSet<String> uniqueTreeEventListByWaitClass = new LinkedHashSet<>(); /** Sql detail **/ String sqlFullText = "SELECT sql_fulltext FROM v$sql WHERE sql_id = ?"; LinkedHashMap<String, String> sqlStatsQuery = new LinkedHashMap<>(); String sqlPlanText = "SELECT 1 where '' != ? "; String sqlForPlanHashValueList = "SELECT 1 where '' != ? "; /** Session detail **/ LinkedHashMap<String, String> sessionStatsQuery = new LinkedHashMap<>(); long interval = 1000; // 1 sec public Postgres() { sqlIdAdditionalColName.add("SQL_OPNAME"); sessAdditionalColName.add("USER_ID"); sessAdditionalColName.add("PROGRAM"); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_CPU); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_IO); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_LOCK); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_LWLOCK); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_BUFFERPIN); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_ACTIVITY); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_EXTENSION); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_CLIENT); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_IPC); uniqueTreeEventListByWaitClass.add(Options.LBL_PG_TIMEOUT); } @Override public LinkedHashMap<String, Color> getWaitClass(){ return Options.getPgMainColor(); } @Override public byte getWaitClassId(String waitClass) { return ConstantManager.getWaitClassIdPG(waitClass); } @Override public String getWaitClass(byte waitClassId) { return ConstantManager.getWaitClassPG(waitClassId); } @Override public String getSqlTextAshOneRow() { return sqlTextAsh; } }
3,652
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IProfile.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/profile/IProfile.java
package profile; import java.awt.*; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; public interface IProfile { String getProfileName(); String getDriverName(); String getSqlTextSysdate(); String getSqlTextAsh(); String getSqlTextAshOneRow(); String getSqlTextUserIdName(); String getSqlTextColumn(); String getSampleTimeColName(); String getWaitClassColName(); String getEventColName(); String getSqlIdColName(); List<String> getSqlIdAdditionalColName(); String getSessColName(); String getSerialColName(); List<String> getSessAdditionalColName(); LinkedHashSet<String> getUniqueTreeEventListByWaitClass(); LinkedHashMap<String, Color> getWaitClass(); /** Sql detail **/ LinkedHashMap<String, String> getSqlStatsQuery(); String getSqlFullText(); String getSqlPlanText(); String getSqlForPlanHashValueList(); /** Session detail **/ LinkedHashMap<String, String> getSessionStatsQuery(); byte getWaitClassId(String waitClass); String getWaitClass(byte waitClassId); long getInterval(); }
1,145
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
Postgres96.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/profile/Postgres96.java
package profile; public class Postgres96 extends Postgres implements IProfile { String sqlTextAsh = "SELECT current_timestamp as SAMPLE_TIME, " + "datid, datname, " + "pid AS SESSION_ID, pid AS SESSION_SERIAL, usesysid AS USER_ID, " + "coalesce(usename, 'unknown') as usename, " + "concat(application_name,'::', '', '::', coalesce(client_hostname, client_addr::text, 'localhost')) AS PROGRAM, " + "wait_event_type AS WAIT_CLASS, wait_event AS EVENT, query, substring(md5(query) from 0 for 15) AS SQL_ID, " + "left(query, strpos(query, ' ')) AS SQL_OPNAME, " + "coalesce(query_start, xact_start, backend_start) as query_start, " + "1000 * EXTRACT(EPOCH FROM (clock_timestamp()-coalesce(query_start, xact_start, backend_start))) as duration " + "from pg_stat_activity " // + "where state='active'"; // for test purposes.. + "where state='active' and pid != pg_backend_pid()"; public Postgres96() {} @Override public String getSqlTextAsh() { return sqlTextAsh; } @Override public String getSqlTextAshOneRow() { return sqlTextAsh; } }
1,193
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OracleSE.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/profile/OracleSE.java
package profile; import java.util.LinkedList; import java.util.List; public class OracleSE extends OracleEE implements IProfile { String profileName = "OracleSE"; private String sqlTextAsh = "SELECT * FROM (SELECT sysdate SAMPLE_TIME, vs.sid SESSION_ID, vs.state SESSION_STATE, " + "vs.serial# SESSION_SERIAL#, vs.user# USER_ID, vs.sql_id SQL_ID, vs.type SESSION_TYPE, " + "vs.event# EVENT#, (CASE WHEN vs.wait_time != 0 THEN 'CPU used' ELSE vs.event END) EVENT, " + "vs.seq# SEQ#, vs.p1 P1, vs.p2 P2, vs.p3 P3, " + "vs.wait_time WAIT_TIME, vs.wait_class_id WAIT_CLASS_ID, vs.wait_class# WAIT_CLASS#, " + "(CASE WHEN vs.wait_time != 0 THEN 'CPU used' ELSE vs.wait_class END) WAIT_CLASS, vss.value TIME_WAITED, " + "vs.row_wait_obj# CURRENT_OBJ#, vs.row_wait_file# CURRENT_FILE#, vs.row_wait_block# CURRENT_BLOCK#, " + "vs.program PROGRAM, vs.module MODULE, vs.action ACTION, vs.fixed_table_sequence FIXED_TABLE_SEQUENCE, " + "nvl(au.name, 'UNKNOWN') COMMAND " + "FROM " + "v$session vs, v$sesstat vss, audit_actions au " + "WHERE vs.sid != ( select distinct sid from v$mystat where rownum < 2 ) " + "and vs.sid = vss.sid and vs.command = au.action(+) " + "and vss.statistic# = 12 and (vs.wait_class != 'Idle' or vs.wait_time != 0) )"; long interval = 1000; // 1 sec List<String> sqlIdAdditionalColName = new LinkedList<>(); public OracleSE() { sqlIdAdditionalColName.add("COMMAND"); } @Override public String getProfileName() { return profileName; } @Override public String getSqlTextAsh() { return sqlTextAsh; } @Override public String getSqlTextAshOneRow() { return sqlTextAsh; } @Override public List<String> getSqlIdAdditionalColName() { return sqlIdAdditionalColName; } @Override public long getInterval() { return interval; } }
1,986
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OracleEEObject.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/profile/OracleEEObject.java
package profile; public class OracleEEObject extends OracleEE implements IProfile { String profileName = "OracleEEObject"; String sqlTextAsh = "select a.*, b.object_name, b.object_type, subobject_name " + "from v$active_session_history a, all_objects b where a.current_obj# = b.object_id(+)"; String sqlTextAshOneRow = sqlTextAsh + " and rownum = 1"; public OracleEEObject() {} @Override public String getProfileName() { return profileName; } @Override public String getSqlTextAsh() { return sqlTextAsh; } @Override public String getSqlTextAshOneRow() { return sqlTextAshOneRow; } }
638
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OracleEE10g.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/profile/OracleEE10g.java
package profile; public class OracleEE10g extends OracleEE implements IProfile { String profileName = "OracleEE10g"; String sqlTextAsh = "select ash.*, decode(aa.name, 'UNKNOWN', null, aa.name) sql_opname " + "from v$active_session_history ash, audit_actions aa where ash.sql_opcode = aa.action(+)"; String sqlTextAshOneRow = sqlTextAsh + " and rownum = 1"; public OracleEE10g() {} @Override public String getProfileName() { return profileName; } @Override public String getSqlTextAsh() { return sqlTextAsh; } @Override public String getSqlTextAshOneRow() { return sqlTextAshOneRow; } }
642
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SqlPlanPojo.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/pojo/SqlPlanPojo.java
package pojo; import lombok.Data; @Data public class SqlPlanPojo { // Address of the handle to the parent for this cursor String address; // Hash value of the parent statement in the library cache Double hash_value; // SQL identifier of the parent cursor in the library cache String sql_id; // Numerical representation of the SQL plan for the cursor long plan_hash_value; // Address of the child cursor String child_address; // Number of the child cursor that uses this execution plan long child_number; // Date and time when the execution plan was generated long timestamp; // Name of the internal operation performed in this step (for example, TABLE ACCESS) String operation; // A variation on the operation described in the OPERATION column (for example, FULL) String options; // Name of the database link used to reference the object (a table name or view name) String object_node; // Object number of the table or the index !!! object# !!! Double obj; // Name of the user who owns the schema containing the table or index String object_owner; // Name of the table or index String object_name; // Alias for the object String object_alias; // Type of the object String object_type; // Current mode of the optimizer for the first row in the plan (statement line), for example, CHOOSE String optimizer; // A number assigned to each step in the execution plan long id; // ID of the next execution step that operates on the output of the current step long parent_id; // Depth (or level) of the operation in the tree long depth; // Order of processing for all operations that have the same PARENT_ID long position; // Number of index columns with start and stop keys (that is, the number of columns with matching predicates) long search_columns; // Cost of the operation as estimated by the optimizer's cost-based approach double cost; // Estimate, by the cost-based optimizer, of the number of rows produced by the operation double cardinality; // Estimate, by the cost-based optimizer, of the number of bytes produced by the operation double bytes; // Describes the contents of the OTHER column. See EXPLAIN PLAN for values String other_tag; // Start partition of a range of accessed partitions String partition_start; // Stop partition of a range of accessed partitions String partition_stop; // Step that computes the pair of values of the PARTITION_START and PARTITION_STOP columns double partition_id; // Other information specific to the execution step that users may find useful. See EXPLAIN PLAN for values String other; // Stores the method used to distribute rows from producer query servers to consumer query servers String distribution; // CPU cost of the operation as estimated by the optimizer's cost-based approach double cpu_cost; // I/O cost of the operation as estimated by the optimizer's cost-based approach double io_cost; // Temporary space usage of the operation (sort or hash-join) as estimated by the optimizer's cost-based approach double temp_space; // Predicates used to locate rows in an access structure. For example, start or stop predicates for an index range scan String access_predicates; // Predicates used to filter rows before producing them String filter_predicates; // Expressions produced by the operation String projection; // Elapsed time (in seconds) of the operation as estimated by the optimizer's cost-based approach double time; // Name of the query block String qblock_name; // Remarks String remarks; }
3,803
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SqlPojo.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/ashv/src/main/java/pojo/SqlPojo.java
package pojo; import lombok.Data; @Data public class SqlPojo { // SQL identifier of the parent cursor in the library cache String sql_id; // Numerical representation of the SQL plan for the cursor long plan_hash_value; // Address of the child cursor String child_address; }
300
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ComparableObjectSeriesTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/ComparableObjectSeriesTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------------- * ComparableObjectSeriesTests.java * -------------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * 31-Oct-2007 : New hashCode() test (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link ComparableObjectSeries} class. */ public class ComparableObjectSeriesTest { static class MyComparableObjectSeries extends ComparableObjectSeries { /** * Creates a new instance. * * @param key the series key. */ public MyComparableObjectSeries(Comparable key) { super(key); } /** * Creates a new instance. * * @param key the series key. * @param autoSort automatically sort by x-value? * @param allowDuplicateXValues allow duplicate values? */ public MyComparableObjectSeries(Comparable key, boolean autoSort, boolean allowDuplicateXValues) { super(key, autoSort, allowDuplicateXValues); } @Override public void add(Comparable x, Object y) { super.add(x, y); } @Override public ComparableObjectItem remove(Comparable x) { return super.remove(x); } } /** * Some checks for the constructor. */ @Test public void testConstructor1() { ComparableObjectSeries s1 = new ComparableObjectSeries("s1"); assertEquals("s1", s1.getKey()); assertNull(s1.getDescription()); assertTrue(s1.getAllowDuplicateXValues()); assertTrue(s1.getAutoSort()); assertEquals(0, s1.getItemCount()); assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount()); // try null key try { /*s1 = */new ComparableObjectSeries(null); fail("Should have thrown an IllegalArgumentException on null parameter"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { MyComparableObjectSeries s1 = new MyComparableObjectSeries("A"); MyComparableObjectSeries s2 = new MyComparableObjectSeries("A"); assertEquals(s1, s2); assertEquals(s2, s1); // key s1 = new MyComparableObjectSeries("B"); assertFalse(s1.equals(s2)); s2 = new MyComparableObjectSeries("B"); assertEquals(s1, s2); // autoSort s1 = new MyComparableObjectSeries("B", false, true); assertFalse(s1.equals(s2)); s2 = new MyComparableObjectSeries("B", false, true); assertEquals(s1, s2); // allowDuplicateXValues s1 = new MyComparableObjectSeries("B", false, false); assertFalse(s1.equals(s2)); s2 = new MyComparableObjectSeries("B", false, false); assertEquals(s1, s2); // add a value s1.add(new Integer(1), "ABC"); assertFalse(s1.equals(s2)); s2.add(new Integer(1), "ABC"); assertEquals(s1, s2); // add another value s1.add(new Integer(0), "DEF"); assertFalse(s1.equals(s2)); s2.add(new Integer(0), "DEF"); assertEquals(s1, s2); // remove an item s1.remove(new Integer(1)); assertFalse(s1.equals(s2)); s2.remove(new Integer(1)); assertEquals(s1, s2); } /** * Some checks for the clone() method. */ @Test public void testCloning() throws CloneNotSupportedException { MyComparableObjectSeries s1 = new MyComparableObjectSeries("A"); s1.add(new Integer(1), "ABC"); MyComparableObjectSeries s2 = (MyComparableObjectSeries) s1.clone(); assertNotSame(s1, s2); assertSame(s1.getClass(), s2.getClass()); assertEquals(s1, s2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { MyComparableObjectSeries s1 = new MyComparableObjectSeries("A"); s1.add(new Integer(1), "ABC"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); MyComparableObjectSeries s2 = (MyComparableObjectSeries) in.readObject(); in.close(); assertEquals(s1, s2); } /** * Some simple checks for the hashCode() method. */ @Test public void testHashCode() { MyComparableObjectSeries s1 = new MyComparableObjectSeries("Test"); MyComparableObjectSeries s2 = new MyComparableObjectSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add("A", "1"); s2.add("A", "1"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add("B", null); s2.add("B", null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add("C", "3"); s2.add("C", "3"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add("D", "4"); s2.add("D", "4"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } }
7,558
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
KeyedObjectTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/KeyedObjectTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * KeyedObjectTests.java * --------------------- * (C) Copyright 2004-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 27-Jan-2004 : Version 1 (DG); * 28-Sep-2007 : Added testCloning2() (DG); * */ package org.jfree.data; import org.jfree.data.general.DefaultPieDataset; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Tests for the {@link KeyedObject} class. */ public class KeyedObjectTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { KeyedObject ko1 = new KeyedObject("Test", "Object"); KeyedObject ko2 = new KeyedObject("Test", "Object"); assertEquals(ko1, ko2); assertEquals(ko2, ko1); ko1 = new KeyedObject("Test 1", "Object"); ko2 = new KeyedObject("Test 2", "Object"); assertFalse(ko1.equals(ko2)); ko1 = new KeyedObject("Test", "Object 1"); ko2 = new KeyedObject("Test", "Object 2"); assertFalse(ko1.equals(ko2)); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { KeyedObject ko1 = new KeyedObject("Test", "Object"); KeyedObject ko2 = (KeyedObject) ko1.clone(); assertNotSame(ko1, ko2); assertSame(ko1.getClass(), ko2.getClass()); assertEquals(ko1, ko2); } /** * Confirm special features of cloning. */ @Test public void testCloning2() throws CloneNotSupportedException { // case 1 - object is mutable but not PublicCloneable Object obj1 = new ArrayList(); KeyedObject ko1 = new KeyedObject("Test", obj1); KeyedObject ko2 = (KeyedObject) ko1.clone(); assertNotSame(ko1, ko2); assertSame(ko1.getClass(), ko2.getClass()); assertEquals(ko1, ko2); // the clone contains a reference to the original object assertSame(ko2.getObject(), obj1); // CASE 2 - object is mutable AND PublicCloneable obj1 = new DefaultPieDataset(); ko1 = new KeyedObject("Test", obj1); ko2 = (KeyedObject) ko1.clone(); assertNotSame(ko1, ko2); assertSame(ko1.getClass(), ko2.getClass()); assertEquals(ko1, ko2); // the clone contains a reference to a CLONE of the original object assertNotSame(ko2.getObject(), obj1); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { KeyedObject ko1 = new KeyedObject("Test", "Object"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(ko1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); KeyedObject ko2 = (KeyedObject) in.readObject(); in.close(); assertEquals(ko1, ko2); } }
4,852
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
package-info.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/package-info.java
/** * Test cases for the classes in com.jfree.data.*. */ package org.jfree.data;
83
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
KeyToGroupMapTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/KeyToGroupMapTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * KeyToGroupMapTests.java * ----------------------- * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 29-Apr-2004 : Version 1 (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** * Tests for the {@link KeyToGroupMap} class. */ public class KeyToGroupMapTest { /** * Tests the mapKeyToGroup() method. */ @Test public void testMapKeyToGroup() { KeyToGroupMap m1 = new KeyToGroupMap("G1"); // map a key to the default group m1.mapKeyToGroup("K1", "G1"); assertEquals("G1", m1.getGroup("K1")); // map a key to a new group m1.mapKeyToGroup("K2", "G2"); assertEquals("G2", m1.getGroup("K2")); // clear a mapping m1.mapKeyToGroup("K2", null); assertEquals("G1", m1.getGroup("K2")); // after clearing, reverts to // default group // check handling of null key try { m1.mapKeyToGroup(null, "G1"); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Tests that the getGroupCount() method returns the correct values under * various circumstances. */ @Test public void testGroupCount() { KeyToGroupMap m1 = new KeyToGroupMap("Default Group"); // a new map always has 1 group (the default group) assertEquals(1, m1.getGroupCount()); // if the default group is not mapped to, it should still count towards // the group count... m1.mapKeyToGroup("C1", "G1"); assertEquals(2, m1.getGroupCount()); // now when the default group is mapped to, it shouldn't increase the // group count... m1.mapKeyToGroup("C2", "Default Group"); assertEquals(2, m1.getGroupCount()); // complicate things a little... m1.mapKeyToGroup("C3", "Default Group"); m1.mapKeyToGroup("C4", "G2"); m1.mapKeyToGroup("C5", "G2"); m1.mapKeyToGroup("C6", "Default Group"); assertEquals(3, m1.getGroupCount()); // now overwrite group "G2"... m1.mapKeyToGroup("C4", "G1"); m1.mapKeyToGroup("C5", "G1"); assertEquals(2, m1.getGroupCount()); } /** * Tests that the getKeyCount() method returns the correct values under * various circumstances. */ @Test public void testKeyCount() { KeyToGroupMap m1 = new KeyToGroupMap("Default Group"); // a new map always has 1 group (the default group) assertEquals(0, m1.getKeyCount("Default Group")); // simple case m1.mapKeyToGroup("K1", "G1"); assertEquals(1, m1.getKeyCount("G1")); m1.mapKeyToGroup("K1", null); assertEquals(0, m1.getKeyCount("G1")); // if there is an explicit mapping to the default group, it is counted m1.mapKeyToGroup("K2", "Default Group"); assertEquals(1, m1.getKeyCount("Default Group")); // complicate things a little... m1.mapKeyToGroup("K3", "Default Group"); m1.mapKeyToGroup("K4", "G2"); m1.mapKeyToGroup("K5", "G2"); m1.mapKeyToGroup("K6", "Default Group"); assertEquals(3, m1.getKeyCount("Default Group")); assertEquals(2, m1.getKeyCount("G2")); // now overwrite group "G2"... m1.mapKeyToGroup("K4", "G1"); m1.mapKeyToGroup("K5", "G1"); assertEquals(2, m1.getKeyCount("G1")); assertEquals(0, m1.getKeyCount("G2")); } /** * Tests the getGroupIndex() method. */ @Test public void testGetGroupIndex() { KeyToGroupMap m1 = new KeyToGroupMap("Default Group"); // the default group is always at index 0 assertEquals(0, m1.getGroupIndex("Default Group")); // a non-existent group should return -1 assertEquals(-1, m1.getGroupIndex("G3")); // indices are assigned in the order that groups are originally mapped m1.mapKeyToGroup("K3", "G3"); m1.mapKeyToGroup("K1", "G1"); m1.mapKeyToGroup("K2", "G2"); assertEquals(1, m1.getGroupIndex("G3")); assertEquals(2, m1.getGroupIndex("G1")); assertEquals(3, m1.getGroupIndex("G2")); } /** * Tests the getGroup() method. */ @Test public void testGetGroup() { KeyToGroupMap m1 = new KeyToGroupMap("Default Group"); // a key that hasn't been mapped should return the default group assertEquals("Default Group", m1.getGroup("K1")); m1.mapKeyToGroup("K1", "G1"); assertEquals("G1", m1.getGroup("K1")); m1.mapKeyToGroup("K1", "G2"); assertEquals("G2", m1.getGroup("K1")); m1.mapKeyToGroup("K1", null); assertEquals("Default Group", m1.getGroup("K1")); // a null argument should throw an exception try { m1.getGroup(null); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { KeyToGroupMap m1 = new KeyToGroupMap("Default Group"); KeyToGroupMap m2 = new KeyToGroupMap("Default Group"); assertEquals(m1, m2); assertEquals(m2, m1); m1.mapKeyToGroup("K1", "G1"); assertFalse(m1.equals(m2)); m2.mapKeyToGroup("K1", "G1"); assertEquals(m1, m2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { KeyToGroupMap m1 = new KeyToGroupMap("Test"); m1.mapKeyToGroup("K1", "G1"); KeyToGroupMap m2 = (KeyToGroupMap) m1.clone(); assertNotSame(m1, m2); assertSame(m1.getClass(), m2.getClass()); assertEquals(m1, m2); // a small check for independence m1.mapKeyToGroup("K1", "G2"); assertFalse(m1.equals(m2)); m2.mapKeyToGroup("K1", "G2"); assertEquals(m1, m2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { KeyToGroupMap m1 = new KeyToGroupMap("Test"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(m1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); KeyToGroupMap m2 = (KeyToGroupMap) in.readObject(); in.close(); assertEquals(m1, m2); } }
8,802
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ComparableObjectItemTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/ComparableObjectItemTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------ * ComparableObjectItemTests.java * ------------------------------ * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link ComparableObjectItem} class. */ public class ComparableObjectItemTest { /** * Some checks for the constructor. */ @Test public void testConstructor() { // check null argument 1 try { /* ComparableObjectItem item1 = */ new ComparableObjectItem(null, "XYZ"); fail("Should have thrown an IllegalArgumentException on null parameter"); } catch (IllegalArgumentException e) { assertEquals("Null 'x' argument.", e.getMessage()); } } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { ComparableObjectItem item1 = new ComparableObjectItem(1, "XYZ"); ComparableObjectItem item2 = new ComparableObjectItem(1, "XYZ"); assertEquals(item1, item2); assertEquals(item2, item1); item1 = new ComparableObjectItem(2, "XYZ"); assertFalse(item1.equals(item2)); item2 = new ComparableObjectItem(2, "XYZ"); assertEquals(item1, item2); item1 = new ComparableObjectItem(2, null); assertFalse(item1.equals(item2)); item2 = new ComparableObjectItem(2, null); assertEquals(item1, item2); } /** * Some checks for the clone() method. */ @Test public void testCloning() throws CloneNotSupportedException { ComparableObjectItem item1 = new ComparableObjectItem(1, "XYZ"); ComparableObjectItem item2 = (ComparableObjectItem) item1.clone(); assertNotSame(item1, item2); assertSame(item1.getClass(), item2.getClass()); assertEquals(item1, item2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { ComparableObjectItem item1 = new ComparableObjectItem(1, "XYZ"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(item1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); ComparableObjectItem item2 = (ComparableObjectItem) in.readObject(); in.close(); assertEquals(item1, item2); } /** * Some checks for the compareTo() method. */ @Test public void testCompareTo() { ComparableObjectItem item1 = new ComparableObjectItem(1, "XYZ"); ComparableObjectItem item2 = new ComparableObjectItem(2, "XYZ"); ComparableObjectItem item3 = new ComparableObjectItem(3, "XYZ"); ComparableObjectItem item4 = new ComparableObjectItem(1, "XYZ"); assertTrue(item2.compareTo(item1) > 0); assertTrue(item3.compareTo(item1) > 0); assertSame(item4.compareTo(item1), 0); assertTrue(item1.compareTo(item2) < 0); } }
5,231
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
RangeTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/RangeTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2014, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * RangeTests.java * --------------- * (C) Copyright 2003-2014, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Sergei Ivanov; * * Changes * ------- * 14-Aug-2003 : Version 1 (DG); * 18-Dec-2007 : Additional tests from Sergei Ivanov (DG); * 08-Jan-2012 : Added test for combine() method (DG); * 23-Feb-2014 : Added isNaNRange() test (DG); * */ package org.jfree.data; import org.jfree.chart.TestUtilities; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link Range} class. */ public class RangeTest { /** * Confirm that the constructor initializes all the required fields. */ @Test public void testConstructor() { Range r1 = new Range(0.1, 1000.0); assertEquals(r1.getLowerBound(), 0.1, 0.0d); assertEquals(r1.getUpperBound(), 1000.0, 0.0d); try { /*Range r2 =*/ new Range(10.0, 0.0); fail("Lower bound cannot be greater than the upper"); } catch (Exception e) { // expected } } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { Range r1 = new Range(0.0, 1.0); Range r2 = new Range(0.0, 1.0); assertEquals(r1, r2); assertEquals(r2, r1); r1 = new Range(0.0, 1.0); r2 = new Range(0.5, 1.0); assertFalse(r1.equals(r2)); r1 = new Range(0.0, 1.0); r2 = new Range(0.0, 2.0); assertFalse(r1.equals(r2)); // a Range object cannot be equal to a different object type assertFalse(r1.equals(new Double(0.0))); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashCode() { Range a1 = new Range(1.0, 100.0); Range a2 = new Range(1.0, 100.0); assertEquals(a1.hashCode(), a2.hashCode()); a1 = new Range(-100.0, 2.0); a2 = new Range(-100.0, 2.0); assertEquals(a1.hashCode(), a2.hashCode()); } /** * Simple tests for the contains() method. */ @Test public void testContains() { Range r1 = new Range(0.0, 1.0); assertFalse(r1.contains(Double.NaN)); assertFalse(r1.contains(Double.NEGATIVE_INFINITY)); assertFalse(r1.contains(-1.0)); assertTrue(r1.contains(0.0)); assertTrue(r1.contains(0.5)); assertTrue(r1.contains(1.0)); assertFalse(r1.contains(2.0)); assertFalse(r1.contains(Double.POSITIVE_INFINITY)); } /** * Tests the constrain() method for various values. */ @Test public void testConstrain() { Range r1 = new Range(0.0, 1.0); double d = r1.constrain(0.5); assertEquals(0.5, d, 0.0000001); d = r1.constrain(0.0); assertEquals(0.0, d, 0.0000001); d = r1.constrain(1.0); assertEquals(1.0, d, 0.0000001); d = r1.constrain(-1.0); assertEquals(0.0, d, 0.0000001); d = r1.constrain(2.0); assertEquals(1.0, d, 0.0000001); d = r1.constrain(Double.POSITIVE_INFINITY); assertEquals(1.0, d, 0.0000001); d = r1.constrain(Double.NEGATIVE_INFINITY); assertEquals(0.0, d, 0.0000001); d = r1.constrain(Double.NaN); assertTrue(Double.isNaN(d)); } /** * Simple tests for the intersects() method. */ @Test public void testIntersects() { Range r1 = new Range(0.0, 1.0); assertFalse(r1.intersects(-2.0, -1.0)); assertFalse(r1.intersects(-2.0, 0.0)); assertTrue(r1.intersects(-2.0, 0.5)); assertTrue(r1.intersects(-2.0, 1.0)); assertTrue(r1.intersects(-2.0, 1.5)); assertTrue(r1.intersects(0.0, 0.5)); assertTrue(r1.intersects(0.0, 1.0)); assertTrue(r1.intersects(0.0, 1.5)); assertTrue(r1.intersects(0.5, 0.6)); assertTrue(r1.intersects(0.5, 1.0)); assertTrue(r1.intersects(0.5, 1.5)); assertFalse(r1.intersects(1.0, 1.1)); assertFalse(r1.intersects(1.5, 2.0)); } /** * A simple test for the expand() method. */ @Test public void testExpand() { Range r1 = new Range(0.0, 100.0); Range r2 = Range.expand(r1, 0.10, 0.10); assertEquals(-10.0, r2.getLowerBound(), 0.001); assertEquals(110.0, r2.getUpperBound(), 0.001); // Expand by 0% does not change the range r2 = Range.expand(r1, 0.0, 0.0); assertEquals(r1, r2); try { Range.expand(null, 0.1, 0.1); fail("Null value is accepted"); } catch (Exception e) { } // Lower > upper: mid point is used r2 = Range.expand(r1, -0.8, -0.5); assertEquals(65.0, r2.getLowerBound(), 0.001); assertEquals(65.0, r2.getUpperBound(), 0.001); } /** * A simple test for the scale() method. */ @Test public void testShift() { Range r1 = new Range(10.0, 20.0); Range r2 = Range.shift(r1, 20.0); assertEquals(30.0, r2.getLowerBound(), 0.001); assertEquals(40.0, r2.getUpperBound(), 0.001); r1 = new Range(0.0, 100.0); r2 = Range.shift(r1, -50.0, true); assertEquals(-50.0, r2.getLowerBound(), 0.001); assertEquals(50.0, r2.getUpperBound(), 0.001); r1 = new Range(-10.0, 20.0); r2 = Range.shift(r1, 20.0, true); assertEquals(10.0, r2.getLowerBound(), 0.001); assertEquals(40.0, r2.getUpperBound(), 0.001); r1 = new Range(-10.0, 20.0); r2 = Range.shift(r1, -30.0, true); assertEquals(-40.0, r2.getLowerBound(), 0.001); assertEquals(-10.0, r2.getUpperBound(), 0.001); r1 = new Range(-10.0, 20.0); r2 = Range.shift(r1, 20.0, false); assertEquals(0.0, r2.getLowerBound(), 0.001); assertEquals(40.0, r2.getUpperBound(), 0.001); r1 = new Range(-10.0, 20.0); r2 = Range.shift(r1, -30.0, false); assertEquals(-40.0, r2.getLowerBound(), 0.001); assertEquals(0.0, r2.getUpperBound(), 0.001); // Shifting with a delta of 0 does not change the range r2 = Range.shift(r1, 0.0); assertEquals(r1, r2); try { Range.shift(null, 0.1); fail("Null value is accepted"); } catch (Exception e) { } } /** * A simple test for the scale() method. */ @Test public void testScale() { Range r1 = new Range(0.0, 100.0); Range r2 = Range.scale(r1, 0.10); assertEquals(0.0, r2.getLowerBound(), 0.001); assertEquals(10.0, r2.getUpperBound(), 0.001); r1 = new Range(-10.0, 100.0); r2 = Range.scale(r1, 2.0); assertEquals(-20.0, r2.getLowerBound(), 0.001); assertEquals(200.0, r2.getUpperBound(), 0.001); // Scaling with a factor of 1 does not change the range r2 = Range.scale(r1, 1.0); assertEquals(r1, r2); try { Range.scale(null, 0.1); fail("Null value is accepted"); } catch (Exception e) { } try { Range.scale(r1, -0.5); fail("Negative factor accepted"); } catch (Exception e) { } } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { Range r1 = new Range(25.0, 133.42); Range r2 = (Range) TestUtilities.serialised(r1); assertEquals(r1, r2); } private static final double EPSILON = 0.0000000001; /** * Some checks for the combine method. */ @Test public void testCombine() { Range r1 = new Range(1.0, 2.0); Range r2 = new Range(1.5, 2.5); assertNull(Range.combine(null, null)); assertEquals(r1, Range.combine(r1, null)); assertEquals(r2, Range.combine(null, r2)); assertEquals(new Range(1.0, 2.5), Range.combine(r1, r2)); Range r3 = new Range(Double.NaN, 1.3); Range rr = Range.combine(r1, r3); assertTrue(Double.isNaN(rr.getLowerBound())); assertEquals(2.0, rr.getUpperBound(), EPSILON); Range r4 = new Range(1.7, Double.NaN); rr = Range.combine(r4, r1); assertEquals(1.0, rr.getLowerBound(), EPSILON); assertTrue(Double.isNaN(rr.getUpperBound())); } /** * Some checks for the combineIgnoringNaN() method. */ @Test public void testCombineIgnoringNaN() { Range r1 = new Range(1.0, 2.0); Range r2 = new Range(1.5, 2.5); assertNull(Range.combineIgnoringNaN(null, null)); assertEquals(r1, Range.combineIgnoringNaN(r1, null)); assertEquals(r2, Range.combineIgnoringNaN(null, r2)); assertEquals(new Range(1.0, 2.5), Range.combineIgnoringNaN(r1, r2)); Range r3 = new Range(Double.NaN, 1.3); Range rr = Range.combineIgnoringNaN(r1, r3); assertEquals(1.0, rr.getLowerBound(), EPSILON); assertEquals(2.0, rr.getUpperBound(), EPSILON); Range r4 = new Range(1.7, Double.NaN); rr = Range.combineIgnoringNaN(r4, r1); assertEquals(1.0, rr.getLowerBound(), EPSILON); assertEquals(2.0, rr.getUpperBound(), EPSILON); } @Test public void testIsNaNRange() { assertTrue(new Range(Double.NaN, Double.NaN).isNaNRange()); assertFalse(new Range(1.0, 2.0).isNaNRange()); assertFalse(new Range(Double.NaN, 2.0).isNaNRange()); assertFalse(new Range(1.0, Double.NaN).isNaNRange()); } }
11,182
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultKeyedValueTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/DefaultKeyedValueTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * DefaultKeyedValueTests.java * --------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Mar-2003 : Version 1 (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** * Tests for the {@link DefaultKeyedValue} class. */ public class DefaultKeyedValueTest { /** * Simple checks for the constructor. */ @Test public void testConstructor() { DefaultKeyedValue v = new DefaultKeyedValue("A", 1); assertEquals("A", v.getKey()); assertEquals(1, v.getValue()); // try null key try { /*v =*/ new DefaultKeyedValue(null, 1); fail("IllegalArgumentException should have been thrown on null parameter"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } // try a null value v = new DefaultKeyedValue("A", null); assertNull(v.getValue()); } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultKeyedValue v1 = new DefaultKeyedValue("Test", 45.5); DefaultKeyedValue v2 = new DefaultKeyedValue("Test", 45.5); assertEquals(v1, v2); assertEquals(v2, v1); v1 = new DefaultKeyedValue("Test 1", 45.5); v2 = new DefaultKeyedValue("Test 2", 45.5); assertFalse(v1.equals(v2)); v1 = new DefaultKeyedValue("Test", 45.5); v2 = new DefaultKeyedValue("Test", 45.6); assertFalse(v1.equals(v2)); } /** * Some checks for the clone() method. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultKeyedValue v1 = new DefaultKeyedValue("Test", 45.5); DefaultKeyedValue v2 = (DefaultKeyedValue) v1.clone(); assertNotSame(v1, v2); assertSame(v1.getClass(), v2.getClass()); assertEquals(v1, v2); // confirm that the clone is independent of the original v2.setValue(12.3); assertFalse(v1.equals(v2)); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultKeyedValue v1 = new DefaultKeyedValue("Test", 25.3); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(v1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); DefaultKeyedValue v2 = (DefaultKeyedValue) in.readObject(); in.close(); assertEquals(v1, v2); } }
4,650
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DataUtilitiesTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/DataUtilitiesTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * DataUtilitiesTests.java * ----------------------- * (C) Copyright 2005-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Mar-2005 : Version 1 (DG); * 28-Jan-2009 : Added tests for equal(double[][], double[][]) method (DG); * 28-Jan-2009 : Added tests for clone(double[][]) (DG); * 04-Feb-2009 : Added tests for new calculateColumnTotal/RowTotal methods (DG); * */ package org.jfree.data; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Some tests for the {@link DataUtilities} class. */ public class DataUtilitiesTest { /** * Tests the createNumberArray2D() method. */ @Test public void testCreateNumberArray2D() { double[][] d = new double[2][]; d[0] = new double[] {1.1, 2.2, 3.3, 4.4}; d[1] = new double[] {1.1, 2.2, 3.3, 4.4, 5.5}; Number[][] n = DataUtilities.createNumberArray2D(d); assertEquals(2, n.length); assertEquals(4, n[0].length); assertEquals(5, n[1].length); } private static final double EPSILON = 0.000000001; /** * Some checks for the calculateColumnTotal() method. */ @Test public void testCalculateColumnTotal() { DefaultKeyedValues2D table = new DefaultKeyedValues2D(); table.addValue(1.0, "R0", "C0"); table.addValue(2.0, "R0", "C1"); table.addValue(3.0, "R1", "C0"); table.addValue(4.0, "R1", "C1"); assertEquals(4.0, DataUtilities.calculateColumnTotal(table, 0), EPSILON); assertEquals(6.0, DataUtilities.calculateColumnTotal(table, 1), EPSILON); table.setValue(null, "R1", "C1"); assertEquals(2.0, DataUtilities.calculateColumnTotal(table, 1), EPSILON); } /** * Some checks for the calculateColumnTotal() method. */ @Test public void testCalculateColumnTotal2() { DefaultKeyedValues2D table = new DefaultKeyedValues2D(); table.addValue(1.0, "R0", "C0"); table.addValue(2.0, "R0", "C1"); table.addValue(3.0, "R1", "C0"); table.addValue(4.0, "R1", "C1"); assertEquals(4.0, DataUtilities.calculateColumnTotal(table, 0, new int[] {0, 1}), EPSILON); assertEquals(1.0, DataUtilities.calculateColumnTotal(table, 0, new int[] {0}), EPSILON); assertEquals(3.0, DataUtilities.calculateColumnTotal(table, 0, new int[] {1}), EPSILON); assertEquals(0.0, DataUtilities.calculateColumnTotal(table, 0, new int[] {}), EPSILON); assertEquals(6.0, DataUtilities.calculateColumnTotal(table, 1, new int[] {0, 1}), EPSILON); assertEquals(2.0, DataUtilities.calculateColumnTotal(table, 1, new int[] {0}), EPSILON); assertEquals(4.0, DataUtilities.calculateColumnTotal(table, 1, new int[] {1}), EPSILON); table.setValue(null, "R1", "C1"); assertEquals(2.0, DataUtilities.calculateColumnTotal(table, 1, new int[] {0, 1}), EPSILON); assertEquals(0.0, DataUtilities.calculateColumnTotal(table, 1, new int[] {1}), EPSILON); } /** * Some checks for the calculateRowTotal() method. */ @Test public void testCalculateRowTotal() { DefaultKeyedValues2D table = new DefaultKeyedValues2D(); table.addValue(1.0, "R0", "C0"); table.addValue(2.0, "R0", "C1"); table.addValue(3.0, "R1", "C0"); table.addValue(4.0, "R1", "C1"); assertEquals(3.0, DataUtilities.calculateRowTotal(table, 0), EPSILON); assertEquals(7.0, DataUtilities.calculateRowTotal(table, 1), EPSILON); table.setValue(null, "R1", "C1"); assertEquals(3.0, DataUtilities.calculateRowTotal(table, 1), EPSILON); } /** * Some checks for the calculateRowTotal() method. */ @Test public void testCalculateRowTotal2() { DefaultKeyedValues2D table = new DefaultKeyedValues2D(); table.addValue(1.0, "R0", "C0"); table.addValue(2.0, "R0", "C1"); table.addValue(3.0, "R1", "C0"); table.addValue(4.0, "R1", "C1"); assertEquals(3.0, DataUtilities.calculateRowTotal(table, 0, new int[] {0, 1}), EPSILON); assertEquals(1.0, DataUtilities.calculateRowTotal(table, 0, new int[] {0}), EPSILON); assertEquals(2.0, DataUtilities.calculateRowTotal(table, 0, new int[] {1}), EPSILON); assertEquals(0.0, DataUtilities.calculateRowTotal(table, 0, new int[] {}), EPSILON); assertEquals(7.0, DataUtilities.calculateRowTotal(table, 1, new int[] {0, 1}), EPSILON); assertEquals(3.0, DataUtilities.calculateRowTotal(table, 1, new int[] {0}), EPSILON); assertEquals(4.0, DataUtilities.calculateRowTotal(table, 1, new int[] {1}), EPSILON); assertEquals(0.0, DataUtilities.calculateRowTotal(table, 1, new int[] {}), EPSILON); table.setValue(null, "R1", "C1"); assertEquals(3.0, DataUtilities.calculateRowTotal(table, 1, new int[] {0, 1}), EPSILON); assertEquals(0.0, DataUtilities.calculateRowTotal(table, 1, new int[] {1}), EPSILON); } /** * Some tests for the equal(double[][], double[][]) method. */ @Test public void testEqual() { assertTrue(DataUtilities.equal(null, null)); double[][] a = new double[5][]; double[][] b = new double[5][]; assertTrue(DataUtilities.equal(a, b)); a = new double[4][]; assertFalse(DataUtilities.equal(a, b)); b = new double[4][]; assertTrue(DataUtilities.equal(a, b)); a[0] = new double[6]; assertFalse(DataUtilities.equal(a, b)); b[0] = new double[6]; assertTrue(DataUtilities.equal(a, b)); a[0][0] = 1.0; assertFalse(DataUtilities.equal(a, b)); b[0][0] = 1.0; assertTrue(DataUtilities.equal(a, b)); a[0][1] = Double.NaN; assertFalse(DataUtilities.equal(a, b)); b[0][1] = Double.NaN; assertTrue(DataUtilities.equal(a, b)); a[0][2] = Double.NEGATIVE_INFINITY; assertFalse(DataUtilities.equal(a, b)); b[0][2] = Double.NEGATIVE_INFINITY; assertTrue(DataUtilities.equal(a, b)); a[0][3] = Double.POSITIVE_INFINITY; assertFalse(DataUtilities.equal(a, b)); b[0][3] = Double.POSITIVE_INFINITY; assertTrue(DataUtilities.equal(a, b)); a[0][4] = Double.POSITIVE_INFINITY; assertFalse(DataUtilities.equal(a, b)); b[0][4] = Double.NEGATIVE_INFINITY; assertFalse(DataUtilities.equal(a, b)); b[0][4] = Double.POSITIVE_INFINITY; assertTrue(DataUtilities.equal(a, b)); } /** * Some tests for the clone() method. */ @Test public void testClone() { double[][] a = new double[1][]; double[][] b = DataUtilities.clone(a); assertTrue(DataUtilities.equal(a, b)); a[0] = new double[] { 3.0, 4.0 }; assertFalse(DataUtilities.equal(a, b)); b[0] = new double[] { 3.0, 4.0 }; assertTrue(DataUtilities.equal(a, b)); a = new double[2][3]; a[0][0] = 1.23; a[1][1] = Double.NaN; b = DataUtilities.clone(a); assertTrue(DataUtilities.equal(a, b)); a[0][0] = 99.9; assertFalse(DataUtilities.equal(a, b)); b[0][0] = 99.9; assertTrue(DataUtilities.equal(a, b)); } }
9,062
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultKeyedValuesTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/DefaultKeyedValuesTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * DefaultKeyedValuesTests.java * ---------------------------- * (C) Copyright 2003-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 05-Mar-2003 : Version 1 (DG); * 27-Aug-2003 : Moved SortOrder from org.jfree.data --> org.jfree.util (DG); * 31-Jul-2006 : Added test for new clear() method (DG); * 01-Aug-2006 : Extended testGetIndex() method (DG); * 30-Apr-2007 : Added some new tests (DG); * 03-Oct-2007 : Updated testRemoveValue() (DG); * 21-Nov-2007 : Added testGetIndex2() method (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.data; import org.jfree.chart.util.SortOrder; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link DefaultKeyedValues} class. */ public class DefaultKeyedValuesTest { /** * Checks that a new instance is empty. */ @Test public void testConstructor() { DefaultKeyedValues d = new DefaultKeyedValues(); assertEquals(0, d.getItemCount()); } /** * Some checks for the getItemCount() method. */ @Test public void testGetItemCount() { DefaultKeyedValues d = new DefaultKeyedValues(); assertEquals(0, d.getItemCount()); d.addValue("A", 1.0); assertEquals(1, d.getItemCount()); d.addValue("B", 2.0); assertEquals(2, d.getItemCount()); d.clear(); assertEquals(0, d.getItemCount()); } /** * Some checks for the getKeys() method. */ @Test public void testGetKeys() { DefaultKeyedValues d = new DefaultKeyedValues(); List keys = d.getKeys(); assertTrue(keys.isEmpty()); d.addValue("A", 1.0); keys = d.getKeys(); assertEquals(1, keys.size()); assertTrue(keys.contains("A")); d.addValue("B", 2.0); keys = d.getKeys(); assertEquals(2, keys.size()); assertTrue(keys.contains("A")); assertTrue(keys.contains("B")); d.clear(); keys = d.getKeys(); assertEquals(0, keys.size()); } /** * A simple test for the clear() method. */ @Test public void testClear() { DefaultKeyedValues v1 = new DefaultKeyedValues(); v1.addValue("A", 1.0); v1.addValue("B", 2.0); assertEquals(2, v1.getItemCount()); v1.clear(); assertEquals(0, v1.getItemCount()); } /** * Some checks for the getValue() methods. */ @Test public void testGetValue() { DefaultKeyedValues v1 = new DefaultKeyedValues(); try { /* Number n = */ v1.getValue(-1); fail("Should have thrown an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { /* Number n = */ v1.getValue(0); fail("Should have thrown an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } DefaultKeyedValues v2 = new DefaultKeyedValues(); v2.addValue("K1", new Integer(1)); v2.addValue("K2", new Integer(2)); v2.addValue("K3", new Integer(3)); assertEquals(3, v2.getValue(2)); try { /* Number n = */ v2.getValue("KK"); fail("Should have thrown an UnknownKeyException"); } catch (UnknownKeyException e) { assertEquals("Key not found: KK", e.getMessage()); } } /** * Some checks for the getKey() methods. */ @Test public void testGetKey() { DefaultKeyedValues v1 = new DefaultKeyedValues(); try { /* Comparable k = */ v1.getKey(-1); fail("Should have thrown an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { /* Comparable k = */ v1.getKey(0); fail("Should have thrown an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } DefaultKeyedValues v2 = new DefaultKeyedValues(); v2.addValue("K1", new Integer(1)); v2.addValue("K2", new Integer(2)); v2.addValue("K3", new Integer(3)); assertEquals("K2", v2.getKey(1)); } /** * Some checks for the getIndex() methods. */ @Test public void testGetIndex() { DefaultKeyedValues v1 = new DefaultKeyedValues(); assertEquals(-1, v1.getIndex("K1")); DefaultKeyedValues v2 = new DefaultKeyedValues(); v2.addValue("K1", new Integer(1)); v2.addValue("K2", new Integer(2)); v2.addValue("K3", new Integer(3)); assertEquals(2, v2.getIndex("K3")); // try null try { v2.getIndex(null); fail("Should have thrown an IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Another check for the getIndex(Comparable) method. */ @Test public void testGetIndex2() { DefaultKeyedValues v = new DefaultKeyedValues(); assertEquals(-1, v.getIndex("K1")); v.addValue("K1", 1.0); assertEquals(0, v.getIndex("K1")); v.removeValue("K1"); assertEquals(-1, v.getIndex("K1")); } /** * Some checks for the addValue() method. */ @Test public void testAddValue() { DefaultKeyedValues v1 = new DefaultKeyedValues(); v1.addValue("A", 1.0); assertEquals(1.0, v1.getValue("A")); v1.addValue("B", 2.0); assertEquals(2.0, v1.getValue("B")); v1.addValue("B", 3.0); assertEquals(3.0, v1.getValue("B")); assertEquals(2, v1.getItemCount()); v1.addValue("A", null); assertNull(v1.getValue("A")); assertEquals(2, v1.getItemCount()); try { v1.addValue(null, 99.9); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Some checks for the insertValue() method. */ @Test public void testInsertValue() { DefaultKeyedValues v1 = new DefaultKeyedValues(); v1.insertValue(0, "A", 1.0); assertEquals(1.0, v1.getValue(0)); v1.insertValue(0, "B", 2.0); assertEquals(2.0, v1.getValue(0)); assertEquals(1.0, v1.getValue(1)); // it's OK to use an index equal to the size of the list v1.insertValue(2, "C", 3.0); assertEquals(2.0, v1.getValue(0)); assertEquals(1.0, v1.getValue(1)); assertEquals(3.0, v1.getValue(2)); // try replacing an existing value v1.insertValue(2, "B", 4.0); assertEquals(1.0, v1.getValue(0)); assertEquals(3.0, v1.getValue(1)); assertEquals(4.0, v1.getValue(2)); } /** * Some checks for the clone() method. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultKeyedValues v1 = new DefaultKeyedValues(); v1.addValue("V1", new Integer(1)); v1.addValue("V2", null); v1.addValue("V3", new Integer(3)); DefaultKeyedValues v2 = (DefaultKeyedValues) v1.clone(); assertNotSame(v1, v2); assertSame(v1.getClass(), v2.getClass()); assertEquals(v1, v2); // confirm that the clone is independent of the original v2.setValue("V1", new Integer(44)); assertFalse(v1.equals(v2)); } /** * Check that inserting and retrieving values works as expected. */ @Test public void testInsertAndRetrieve() { DefaultKeyedValues data = new DefaultKeyedValues(); data.addValue("A", new Double(1.0)); data.addValue("B", new Double(2.0)); data.addValue("C", new Double(3.0)); data.addValue("D", null); // check key order assertEquals(data.getKey(0), "A"); assertEquals(data.getKey(1), "B"); assertEquals(data.getKey(2), "C"); assertEquals(data.getKey(3), "D"); // check retrieve value by key assertEquals(data.getValue("A"), 1.0); assertEquals(data.getValue("B"), 2.0); assertEquals(data.getValue("C"), 3.0); assertEquals(data.getValue("D"), null); // check retrieve value by index assertEquals(data.getValue(0), 1.0); assertEquals(data.getValue(1), 2.0); assertEquals(data.getValue(2), 3.0); assertEquals(data.getValue(3), null); } /** * Some tests for the removeValue() method. */ @Test public void testRemoveValue() { DefaultKeyedValues data = new DefaultKeyedValues(); data.addValue("A", new Double(1.0)); data.addValue("B", null); data.addValue("C", new Double(3.0)); data.addValue("D", new Double(2.0)); assertEquals(1, data.getIndex("B")); data.removeValue("B"); assertEquals(-1, data.getIndex("B")); try { data.removeValue("XXX"); fail("Should have thrown an UnknownKeyException"); } catch (UnknownKeyException e) { assertEquals("The key (XXX) is not recognised.", e.getMessage()); } } /** * Tests sorting of data by key (ascending). */ @Test public void testSortByKeyAscending() { DefaultKeyedValues data = new DefaultKeyedValues(); data.addValue("C", new Double(1.0)); data.addValue("B", null); data.addValue("D", new Double(3.0)); data.addValue("A", new Double(2.0)); data.sortByKeys(SortOrder.ASCENDING); // check key order assertEquals(data.getKey(0), "A"); assertEquals(data.getKey(1), "B"); assertEquals(data.getKey(2), "C"); assertEquals(data.getKey(3), "D"); // check retrieve value by key assertEquals(data.getValue("A"), 2.0); assertEquals(data.getValue("B"), null); assertEquals(data.getValue("C"), 1.0); assertEquals(data.getValue("D"), 3.0); // check retrieve value by index assertEquals(data.getValue(0), 2.0); assertEquals(data.getValue(1), null); assertEquals(data.getValue(2), 1.0); assertEquals(data.getValue(3), 3.0); } /** * Tests sorting of data by key (descending). */ @Test public void testSortByKeyDescending() { DefaultKeyedValues data = new DefaultKeyedValues(); data.addValue("C", new Double(1.0)); data.addValue("B", null); data.addValue("D", new Double(3.0)); data.addValue("A", new Double(2.0)); data.sortByKeys(SortOrder.DESCENDING); // check key order assertEquals(data.getKey(0), "D"); assertEquals(data.getKey(1), "C"); assertEquals(data.getKey(2), "B"); assertEquals(data.getKey(3), "A"); // check retrieve value by key assertEquals(data.getValue("A"), 2.0); assertEquals(data.getValue("B"), null); assertEquals(data.getValue("C"), 1.0); assertEquals(data.getValue("D"), 3.0); // check retrieve value by index assertEquals(data.getValue(0), 3.0); assertEquals(data.getValue(1), 1.0); assertEquals(data.getValue(2), null); assertEquals(data.getValue(3), 2.0); } /** * Tests sorting of data by value (ascending). */ @Test public void testSortByValueAscending() { DefaultKeyedValues data = new DefaultKeyedValues(); data.addValue("C", new Double(1.0)); data.addValue("B", null); data.addValue("D", new Double(3.0)); data.addValue("A", new Double(2.0)); data.sortByValues(SortOrder.ASCENDING); // check key order assertEquals(data.getKey(0), "C"); assertEquals(data.getKey(1), "A"); assertEquals(data.getKey(2), "D"); assertEquals(data.getKey(3), "B"); // check retrieve value by key assertEquals(data.getValue("A"), 2.0); assertEquals(data.getValue("B"), null); assertEquals(data.getValue("C"), 1.0); assertEquals(data.getValue("D"), 3.0); // check retrieve value by index assertEquals(data.getValue(0), 1.0); assertEquals(data.getValue(1), 2.0); assertEquals(data.getValue(2), 3.0); assertEquals(data.getValue(3), null); } /** * Tests sorting of data by key (descending). */ @Test public void testSortByValueDescending() { DefaultKeyedValues data = new DefaultKeyedValues(); data.addValue("C", new Double(1.0)); data.addValue("B", null); data.addValue("D", new Double(3.0)); data.addValue("A", new Double(2.0)); data.sortByValues(SortOrder.DESCENDING); // check key order assertEquals(data.getKey(0), "D"); assertEquals(data.getKey(1), "A"); assertEquals(data.getKey(2), "C"); assertEquals(data.getKey(3), "B"); // check retrieve value by key assertEquals(data.getValue("A"), 2.0); assertEquals(data.getValue("B"), null); assertEquals(data.getValue("C"), 1.0); assertEquals(data.getValue("D"), 3.0); // check retrieve value by index assertEquals(data.getValue(0), 3.0); assertEquals(data.getValue(1), 2.0); assertEquals(data.getValue(2), 1.0); assertEquals(data.getValue(3), null); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultKeyedValues v1 = new DefaultKeyedValues(); v1.addValue("Key 1", new Double(23)); v1.addValue("Key 2", null); v1.addValue("Key 3", new Double(42)); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(v1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); DefaultKeyedValues v2 = (DefaultKeyedValues) in.readObject(); in.close(); assertEquals(v1, v2); } }
16,342
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultKeyedValues2DTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/DefaultKeyedValues2DTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------ * DefaultKeyedValues2DTests.java * ------------------------------ * (C) Copyright 2003-2008 by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Mar-2003 : Version 1 (DG); * 15-Sep-2004 : Updated cloning test (DG); * 06-Oct-2005 : Added testEquals() (DG); * 18-Jan-2007 : Added testSparsePopulation() (DG); * 26-Feb-2007 : Added some basic tests (DG); * 30-Mar-2007 : Added a test for bug 1690654 (DG); * 21-Nov-2007 : Added testRemoveColumnByKey() method (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** * Tests for the {@link DefaultKeyedValues2D} class. */ public class DefaultKeyedValues2DTest { /** * Some checks for the getValue() method. */ @Test public void testGetValue() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(1.0, "R1", "C1"); assertEquals(1.0, d.getValue("R1", "C1")); try { d.getValue("XX", "C1"); fail("UnknownKeyException should have been thrown on unknown key"); } catch (UnknownKeyException e) { assertEquals("Unrecognised rowKey: XX", e.getMessage()); } try { d.getValue("R1", "XX"); fail("UnknownKeyException should have been thrown on unknown key"); } catch (UnknownKeyException e) { assertEquals("Unrecognised columnKey: XX", e.getMessage()); } } /** * Some checks for the clone() method. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultKeyedValues2D v1 = new DefaultKeyedValues2D(); v1.setValue(1, "V1", "C1"); v1.setValue(null, "V2", "C1"); v1.setValue(3, "V3", "C2"); DefaultKeyedValues2D v2 = (DefaultKeyedValues2D) v1.clone(); assertNotSame(v1, v2); assertSame(v1.getClass(), v2.getClass()); assertEquals(v1, v2); // check that clone is independent of the original v2.setValue(2, "V2", "C1"); assertFalse(v1.equals(v2)); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultKeyedValues2D kv2D1 = new DefaultKeyedValues2D(); kv2D1.addValue(234.2, "Row1", "Col1"); kv2D1.addValue(null, "Row1", "Col2"); kv2D1.addValue(345.9, "Row2", "Col1"); kv2D1.addValue(452.7, "Row2", "Col2"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(kv2D1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); DefaultKeyedValues2D kv2D2 = (DefaultKeyedValues2D) in.readObject(); in.close(); assertEquals(kv2D1, kv2D2); } /** * Some checks for the equals() method. */ @Test public void testEquals() { DefaultKeyedValues2D d1 = new DefaultKeyedValues2D(); DefaultKeyedValues2D d2 = new DefaultKeyedValues2D(); assertEquals(d1, d2); assertEquals(d2, d1); d1.addValue(1.0, 2.0, "S1"); assertFalse(d1.equals(d2)); d2.addValue(1.0, 2.0, "S1"); assertEquals(d1, d2); } /** * Populates a data structure with sparse entries, then checks that * the unspecified entries return null. */ @Test public void testSparsePopulation() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(11, "R1", "C1"); d.addValue(22, "R2", "C2"); assertEquals(11, d.getValue("R1", "C1")); assertNull(d.getValue("R1", "C2")); assertEquals(22, d.getValue("R2", "C2")); assertNull(d.getValue("R2", "C1")); } /** * Some basic checks for the getRowCount() method. */ @Test public void testRowCount() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); assertEquals(0, d.getRowCount()); d.addValue(1.0, "R1", "C1"); assertEquals(1, d.getRowCount()); d.addValue(2.0, "R2", "C1"); assertEquals(2, d.getRowCount()); } /** * Some basic checks for the getColumnCount() method. */ @Test public void testColumnCount() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); assertEquals(0, d.getColumnCount()); d.addValue(1.0, "R1", "C1"); assertEquals(1, d.getColumnCount()); d.addValue(2.0, "R1", "C2"); assertEquals(2, d.getColumnCount()); } private static final double EPSILON = 0.0000000001; /** * Some basic checks for the getValue(int, int) method. */ @Test public void testGetValue2() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); try { d.getValue(0, 0); fail("IndexOutOfBoundsException should have been thrown on querying empty set"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 0, Size: 0", e.getMessage()); } d.addValue(1.0, "R1", "C1"); assertEquals(1.0, d.getValue(0, 0).doubleValue(), EPSILON); d.addValue(2.0, "R2", "C2"); assertEquals(2.0, d.getValue(1, 1).doubleValue(), EPSILON); assertNull(d.getValue(1, 0)); assertNull(d.getValue(0, 1)); try { d.getValue(2, 0); fail("IndexOutOfBoundsException should have been thrown on index out of range"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 2, Size: 2", e.getMessage()); } } /** * Some basic checks for the getRowKey() method. */ @Test public void testGetRowKey() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); try { d.getRowKey(0); fail("IndexOutOfBoundsException should have been thrown on querying empty dataset"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 0, Size: 0", e.getMessage()); } d.addValue(1.0, "R1", "C1"); d.addValue(1.0, "R2", "C1"); assertEquals("R1", d.getRowKey(0)); assertEquals("R2", d.getRowKey(1)); // check sorted rows d = new DefaultKeyedValues2D(true); d.addValue(1.0, "R1", "C1"); assertEquals("R1", d.getRowKey(0)); d.addValue(0.0, "R0", "C1"); assertEquals("R0", d.getRowKey(0)); assertEquals("R1", d.getRowKey(1)); } /** * Some basic checks for the getColumnKey() method. */ @Test public void testGetColumnKey() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); try { d.getColumnKey(0); fail("Should have thrown an IndexOutOfBoundsException on querying empty dataset"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 0, Size: 0", e.getMessage()); } d.addValue(1.0, "R1", "C1"); d.addValue(1.0, "R1", "C2"); assertEquals("C1", d.getColumnKey(0)); assertEquals("C2", d.getColumnKey(1)); } /** * Some basic checks for the removeValue() method. */ @Test public void testRemoveValue() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.removeValue("R1", "C1"); d.addValue(1.0, "R1", "C1"); d.removeValue("R1", "C1"); assertEquals(0, d.getRowCount()); assertEquals(0, d.getColumnCount()); d.addValue(1.0, "R1", "C1"); d.addValue(2.0, "R2", "C1"); d.removeValue("R1", "C1"); assertEquals(2.0, d.getValue(0, 0)); } /** * A test for bug 1690654. */ @Test public void testRemoveValueBug1690654() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(1.0, "R1", "C1"); d.addValue(2.0, "R2", "C2"); assertEquals(2, d.getColumnCount()); assertEquals(2, d.getRowCount()); d.removeValue("R2", "C2"); assertEquals(1, d.getColumnCount()); assertEquals(1, d.getRowCount()); assertEquals(1.0, d.getValue(0, 0)); } /** * Some basic checks for the removeRow() method. */ @Test public void testRemoveRow() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); try { d.removeRow(0); fail("IndexOutOfBoundsException should have been thrown on querying emty dataset"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 0, Size: 0", e.getMessage()); } } /** * Some basic checks for the removeColumn(Comparable) method. */ @Test public void testRemoveColumnByKey() { DefaultKeyedValues2D d = new DefaultKeyedValues2D(); d.addValue(1.0, "R1", "C1"); d.addValue(2.0, "R2", "C2"); d.removeColumn("C2"); d.addValue(3.0, "R2", "C2"); assertEquals(3.0, d.getValue("R2", "C2").doubleValue(), EPSILON); // check for unknown column try { d.removeColumn("XXX"); fail("UnknownKeyException should have been thrown on querying unknown key"); } catch (UnknownKeyException e) { assertEquals("Unknown key: XXX", e.getMessage()); } } }
11,304
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
KeyedObjectsTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/KeyedObjectsTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * KeyedObjectsTests.java * ---------------------- * (C) Copyright 2004-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 27-Jan-2004 : Version 1 (DG); * 28-Sep-2007 : Added testCloning2() (DG); * 03-Oct-2007 : New tests (DG); * */ package org.jfree.data; import org.jfree.data.general.DefaultPieDataset; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** * Tests for the {@link KeyedObjects} class. */ public class KeyedObjectsTest { /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { KeyedObjects ko1 = new KeyedObjects(); ko1.addObject("V1", 1); ko1.addObject("V2", null); ko1.addObject("V3", 3); KeyedObjects ko2 = (KeyedObjects) ko1.clone(); assertNotSame(ko1, ko2); assertSame(ko1.getClass(), ko2.getClass()); assertEquals(ko1, ko2); } /** * Confirm special features of cloning. */ @Test public void testCloning2() throws CloneNotSupportedException { // case 1 - object is mutable but not PublicCloneable Object obj1 = new ArrayList(); KeyedObjects ko1 = new KeyedObjects(); ko1.addObject("K1", obj1); KeyedObjects ko2 = (KeyedObjects) ko1.clone(); assertNotSame(ko1, ko2); assertSame(ko1.getClass(), ko2.getClass()); assertEquals(ko1, ko2); // the clone contains a reference to the original object assertSame(ko2.getObject("K1"), obj1); // CASE 2 - object is mutable AND PublicCloneable obj1 = new DefaultPieDataset(); ko1 = new KeyedObjects(); ko1.addObject("K1", obj1); ko2 = (KeyedObjects) ko1.clone(); assertNotSame(ko1, ko2); assertSame(ko1.getClass(), ko2.getClass()); assertEquals(ko1, ko2); // the clone contains a reference to a CLONE of the original object assertNotSame(ko2.getObject("K1"), obj1); } /** * Check that inserting and retrieving values works as expected. */ @Test public void testInsertAndRetrieve() { KeyedObjects data = new KeyedObjects(); data.addObject("A", 1.0); data.addObject("B", 2.0); data.addObject("C", 3.0); data.addObject("D", null); // check key order assertEquals(data.getKey(0), "A"); assertEquals(data.getKey(1), "B"); assertEquals(data.getKey(2), "C"); assertEquals(data.getKey(3), "D"); // check retrieve value by key assertEquals(data.getObject("A"), 1.0); assertEquals(data.getObject("B"), 2.0); assertEquals(data.getObject("C"), 3.0); assertEquals(data.getObject("D"), null); try { data.getObject("Not a key"); fail("Should have thrown UnknownKeyException on unknown key"); } catch (UnknownKeyException e) { assertEquals("The key (Not a key) is not recognised.", e.getMessage()); } // check retrieve value by index assertEquals(data.getObject(0), 1.0); assertEquals(data.getObject(1), 2.0); assertEquals(data.getObject(2), 3.0); assertEquals(data.getObject(3), null); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { KeyedObjects ko1 = new KeyedObjects(); ko1.addObject("Key 1", "Object 1"); ko1.addObject("Key 2", null); ko1.addObject("Key 3", "Object 2"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(ko1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); KeyedObjects ko2 = (KeyedObjects) in.readObject(); in.close(); assertEquals(ko1, ko2); } /** * Simple checks for the getObject(int) method. */ @Test public void testGetObject() { // retrieve an item KeyedObjects ko1 = new KeyedObjects(); ko1.addObject("Key 1", "Object 1"); ko1.addObject("Key 2", null); ko1.addObject("Key 3", "Object 2"); assertEquals("Object 1", ko1.getObject(0)); assertNull(ko1.getObject(1)); assertEquals("Object 2", ko1.getObject(2)); // request with a negative index try { ko1.getObject(-1); fail("Should have thrown IndexOutOfBoundsException on negative key"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } // request width index == itemCount try { ko1.getObject(3); fail("Should have thrown IndexOutOfBoundsException on key out of range"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 3, Size: 3", e.getMessage()); } } /** * Simple checks for the getKey(int) method. */ @Test public void testGetKey() { // retrieve an item KeyedObjects ko1 = new KeyedObjects(); ko1.addObject("Key 1", "Object 1"); ko1.addObject("Key 2", null); ko1.addObject("Key 3", "Object 2"); assertEquals("Key 1", ko1.getKey(0)); assertEquals("Key 2", ko1.getKey(1)); assertEquals("Key 3", ko1.getKey(2)); // request with a negative index try { ko1.getKey(-1); fail("Should have thrown IndexOutOfBoundsException on negative key"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } // request width index == itemCount try { ko1.getKey(3); fail("Should have thrown IndexOutOfBoundsException on key out of range"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 3, Size: 3", e.getMessage()); } } /** * Simple checks for the getIndex(Comparable) method. */ @Test public void testGetIndex() { KeyedObjects ko1 = new KeyedObjects(); ko1.addObject("Key 1", "Object 1"); ko1.addObject("Key 2", null); ko1.addObject("Key 3", "Object 2"); assertEquals(0, ko1.getIndex("Key 1")); assertEquals(1, ko1.getIndex("Key 2")); assertEquals(2, ko1.getIndex("Key 3")); // check null argument try { ko1.getIndex(null); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Some checks for the setObject(Comparable, Object) method. */ @Test public void testSetObject() { KeyedObjects ko1 = new KeyedObjects(); ko1.setObject("Key 1", "Object 1"); ko1.setObject("Key 2", null); ko1.setObject("Key 3", "Object 2"); assertEquals("Object 1", ko1.getObject("Key 1")); assertEquals(null, ko1.getObject("Key 2")); assertEquals("Object 2", ko1.getObject("Key 3")); // replace an existing value ko1.setObject("Key 2", "AAA"); ko1.setObject("Key 3", "BBB"); assertEquals("AAA", ko1.getObject("Key 2")); assertEquals("BBB", ko1.getObject("Key 3")); // try a null key - should throw an exception try { ko1.setObject(null, "XX"); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Some checks for the removeValue() methods. */ @Test public void testRemoveValue() { KeyedObjects ko1 = new KeyedObjects(); ko1.setObject("Key 1", "Object 1"); ko1.setObject("Key 2", null); ko1.setObject("Key 3", "Object 2"); ko1.removeValue(1); assertEquals(2, ko1.getItemCount()); assertEquals(1, ko1.getIndex("Key 3")); ko1.removeValue("Key 1"); assertEquals(1, ko1.getItemCount()); assertEquals(0, ko1.getIndex("Key 3")); // try unknown key try { ko1.removeValue("UNKNOWN"); fail("Should have thrown UnknownKeyException on unknown key"); } catch (UnknownKeyException e) { assertEquals("The key (UNKNOWN) is not recognised.", e.getMessage()); } // try null argument try { ko1.removeValue(null); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Some checks for the removeValue(int) method. */ @Test public void testRemoveValueInt() { KeyedObjects ko1 = new KeyedObjects(); ko1.setObject("Key 1", "Object 1"); ko1.setObject("Key 2", null); ko1.setObject("Key 3", "Object 2"); ko1.removeValue(1); assertEquals(2, ko1.getItemCount()); assertEquals(1, ko1.getIndex("Key 3")); // try negative key index try { ko1.removeValue(-1); fail("Should have thrown IndexOutOfBoundsException on negative key"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } // try key index == itemCount try { ko1.removeValue(2); fail("Should have thrown IndexOutOfBoundsException on negative key"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 2, Size: 2", e.getMessage()); } } }
11,745
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
KeyedObjects2DTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/KeyedObjects2DTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * KeyedObjects2DTests.java * ------------------------ * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 01-Mar-2004 : Version 1 (DG); * 28-Sep-2007 : Added testEquals() and enhanced testClone() (DG); * 03-Oct-2007 : Added new tests (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** * Tests for the {@link KeyedObjects2D} class. */ public class KeyedObjects2DTest { /** * Some checks for the equals() method. */ @Test public void testEquals() { KeyedObjects2D k1 = new KeyedObjects2D(); KeyedObjects2D k2 = new KeyedObjects2D(); assertEquals(k1, k2); assertEquals(k2, k1); k1.addObject(99, "R1", "C1"); assertFalse(k1.equals(k2)); k2.addObject(99, "R1", "C1"); assertEquals(k1, k2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { KeyedObjects2D o1 = new KeyedObjects2D(); o1.setObject(1, "V1", "C1"); o1.setObject(null, "V2", "C1"); o1.setObject(3, "V3", "C2"); KeyedObjects2D o2 = (KeyedObjects2D) o1.clone(); assertNotSame(o1, o2); assertSame(o1.getClass(), o2.getClass()); assertEquals(o1, o2); // check independence o1.addObject("XX", "R1", "C1"); assertFalse(o1.equals(o2)); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { KeyedObjects2D ko2D1 = new KeyedObjects2D(); ko2D1.addObject(234.2, "Row1", "Col1"); ko2D1.addObject(null, "Row1", "Col2"); ko2D1.addObject(345.9, "Row2", "Col1"); ko2D1.addObject(452.7, "Row2", "Col2"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(ko2D1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); KeyedObjects2D ko2D2 = (KeyedObjects2D) in.readObject(); in.close(); assertEquals(ko2D1, ko2D2); } /** * Some checks for the getValue(int, int) method. */ @Test public void testGetValueByIndex() { KeyedObjects2D data = new KeyedObjects2D(); data.addObject("Obj1", "R1", "C1"); data.addObject("Obj2", "R2", "C2"); assertEquals("Obj1", data.getObject(0, 0)); assertEquals("Obj2", data.getObject(1, 1)); assertNull(data.getObject(0, 1)); assertNull(data.getObject(1, 0)); // check invalid indices try { data.getObject(-1, 0); fail("Should have thrown IndexOutOfBoundsException on negative key"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } try { data.getObject(0, -1); fail("Should have thrown IndexOutOfBoundsException on key out of bounds"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } try { data.getObject(2, 0); fail("Should have thrown IndexOutOfBoundsException on key out of bounds"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 2, Size: 2", e.getMessage()); } try { data.getObject(0, 2); fail("Should have thrown IndexOutOfBoundsException on key out of bounds"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 2, Size: 2", e.getMessage()); } } /** * Some checks for the getValue(Comparable, Comparable) method. */ @Test public void testGetValueByKey() { KeyedObjects2D data = new KeyedObjects2D(); data.addObject("Obj1", "R1", "C1"); data.addObject("Obj2", "R2", "C2"); assertEquals("Obj1", data.getObject("R1", "C1")); assertEquals("Obj2", data.getObject("R2", "C2")); assertNull(data.getObject("R1", "C2")); assertNull(data.getObject("R2", "C1")); // check invalid indices try { data.getObject("XX", "C1"); fail("Should have thrown UnknownKeyException unknown key"); } catch (UnknownKeyException e) { assertEquals("Row key (XX) not recognised.", e.getMessage()); } try { data.getObject("R1", "XX"); fail("Should have thrown UnknownKeyException unknown key"); } catch (UnknownKeyException e) { assertEquals("Column key (XX) not recognised.", e.getMessage()); } try { data.getObject("XX", "C1"); fail("Should have thrown UnknownKeyException unknown key"); } catch (UnknownKeyException e) { assertEquals("Row key (XX) not recognised.", e.getMessage()); } try { data.getObject("R1", "XX"); fail("Should have thrown UnknownKeyException unknown key"); } catch (UnknownKeyException e) { assertEquals("Column key (XX) not recognised.", e.getMessage()); } } /** * Some checks for the setObject(Object, Comparable, Comparable) method. */ @Test public void testSetObject() { KeyedObjects2D data = new KeyedObjects2D(); data.setObject("Obj1", "R1", "C1"); data.setObject("Obj2", "R2", "C2"); assertEquals("Obj1", data.getObject("R1", "C1")); assertEquals("Obj2", data.getObject("R2", "C2")); assertNull(data.getObject("R1", "C2")); assertNull(data.getObject("R2", "C1")); // confirm overwriting an existing value data.setObject("ABC", "R2", "C2"); assertEquals("ABC", data.getObject("R2", "C2")); // try null keys try { data.setObject("X", null, "C1"); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'rowKey' argument.", e.getMessage()); } try { data.setObject("X", "R1", null); fail("Should have thrown IllegalArgumentException on duplicate key"); } catch (IllegalArgumentException e) { assertEquals("Null 'columnKey' argument.", e.getMessage()); } } /** * Some checks for the removeRow(int) method. */ @Test public void testRemoveRowByIndex() { KeyedObjects2D data = new KeyedObjects2D(); data.setObject("Obj1", "R1", "C1"); data.setObject("Obj2", "R2", "C2"); data.removeRow(0); assertEquals(1, data.getRowCount()); assertEquals("Obj2", data.getObject(0, 1)); // try negative row index try { data.removeRow(-1); fail("Should have thrown IndexOutOfBoundsException on negative index"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } // try row index too high try { data.removeRow(data.getRowCount()); fail("Should have thrown IndexOutOfBoundsException on index out of range"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 1, Size: 1", e.getMessage()); } } /** * Some checks for the removeColumn(int) method. */ @Test public void testRemoveColumnByIndex() { KeyedObjects2D data = new KeyedObjects2D(); data.setObject("Obj1", "R1", "C1"); data.setObject("Obj2", "R2", "C2"); data.removeColumn(0); assertEquals(1, data.getColumnCount()); assertEquals("Obj2", data.getObject(1, 0)); // try negative column index try { data.removeColumn(-1); fail("Should have thrown IndexOutOfBoundsException on negative index"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } // try column index too high try { data.removeColumn(data.getColumnCount()); fail("Should have thrown IndexOutOfBoundsException on index out of range"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 1, Size: 1", e.getMessage()); } } /** * Some checks for the removeRow(Comparable) method. */ @Test public void testRemoveRowByKey() { KeyedObjects2D data = new KeyedObjects2D(); data.setObject("Obj1", "R1", "C1"); data.setObject("Obj2", "R2", "C2"); data.removeRow("R2"); assertEquals(1, data.getRowCount()); assertEquals("Obj1", data.getObject(0, 0)); // try unknown row key try { data.removeRow("XXX"); fail("Should have thrown UnknownKeyException on key that doesn't exist"); } catch (UnknownKeyException e) { assertEquals("Row key (XXX) not recognised.", e.getMessage()); } // try null row key try { data.removeRow(null); fail("Should have thrown IndexOutOfBoundsException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Some checks for the removeColumn(Comparable) method. */ @Test public void testRemoveColumnByKey() { KeyedObjects2D data = new KeyedObjects2D(); data.setObject("Obj1", "R1", "C1"); data.setObject("Obj2", "R2", "C2"); data.removeColumn("C2"); assertEquals(1, data.getColumnCount()); assertEquals("Obj1", data.getObject(0, 0)); // try unknown column key try { data.removeColumn("XXX"); fail("Should have thrown UnknownKeyException on unknown key"); } catch (UnknownKeyException e) { assertEquals("Column key (XXX) not recognised.", e.getMessage()); } // try null column key try { data.removeColumn(null); fail("Should have thrown IllegalArgumentException on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * A simple check for the removeValue() method. */ @Test public void testRemoveValue() { KeyedObjects2D data = new KeyedObjects2D(); data.setObject("Obj1", "R1", "C1"); data.setObject("Obj2", "R2", "C2"); data.removeObject("R2", "C2"); assertEquals(1, data.getRowCount()); assertEquals(1, data.getColumnCount()); assertEquals("Obj1", data.getObject(0, 0)); } }
12,839
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
RangeTypeTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/RangeTypeTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * RangeTypeTests.java * ------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 19-May-2005 : Version 1 (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests for the {@link RangeType} class. */ public class RangeTypeTest { /** * Some checks for the equals() method. */ @Test public void testEquals() { assertEquals(RangeType.FULL, RangeType.FULL); assertEquals(RangeType.NEGATIVE, RangeType.NEGATIVE); assertEquals(RangeType.POSITIVE, RangeType.POSITIVE); assertFalse(RangeType.FULL.equals(RangeType.NEGATIVE)); assertFalse(RangeType.FULL.equals(RangeType.POSITIVE)); assertFalse(RangeType.FULL.equals(null)); assertFalse(RangeType.NEGATIVE.equals(RangeType.FULL)); assertFalse(RangeType.NEGATIVE.equals(RangeType.POSITIVE)); assertFalse(RangeType.NEGATIVE.equals(null)); assertFalse(RangeType.POSITIVE.equals(RangeType.NEGATIVE)); assertFalse(RangeType.POSITIVE.equals(RangeType.FULL)); assertFalse(RangeType.POSITIVE.equals(null)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashCode() { RangeType r1 = RangeType.FULL; RangeType r2 = RangeType.FULL; assertEquals(r1, r2); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { RangeType r1 = RangeType.FULL; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(r1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); RangeType r2 = (RangeType) in.readObject(); in.close(); assertEquals(r1, r2); boolean same = r1 == r2; assertEquals(true, same); } }
3,879
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DomainOrderTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/DomainOrderTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * DomainOrderTests.java * --------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 19-May-2005 : Version 1 (DG); * */ package org.jfree.data; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; /** * Tests for the {@link DomainOrder} class. */ public class DomainOrderTest { /** * Some checks for the equals() method. */ @Test public void testEquals() { assertEquals(DomainOrder.NONE, DomainOrder.NONE); assertEquals(DomainOrder.ASCENDING, DomainOrder.ASCENDING); assertEquals(DomainOrder.DESCENDING, DomainOrder.DESCENDING); assertFalse(DomainOrder.NONE.equals(DomainOrder.ASCENDING)); assertFalse(DomainOrder.NONE.equals(DomainOrder.DESCENDING)); assertFalse(DomainOrder.NONE.equals(null)); assertFalse(DomainOrder.ASCENDING.equals(DomainOrder.NONE)); assertFalse(DomainOrder.ASCENDING.equals(DomainOrder.DESCENDING)); assertFalse(DomainOrder.ASCENDING.equals(null)); assertFalse(DomainOrder.DESCENDING.equals(DomainOrder.NONE)); assertFalse(DomainOrder.DESCENDING.equals(DomainOrder.ASCENDING)); assertFalse(DomainOrder.DESCENDING.equals(null)); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashCode() { DomainOrder d1 = DomainOrder.ASCENDING; DomainOrder d2 = DomainOrder.ASCENDING; assertEquals(d1, d2); int h1 = d1.hashCode(); int h2 = d2.hashCode(); assertEquals(h1, h2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DomainOrder d1 = DomainOrder.ASCENDING; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); DomainOrder d2 = (DomainOrder) in.readObject(); in.close(); assertSame(d1, d2); } }
3,957
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DatasetUtilitiesTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/DatasetUtilitiesTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * DatasetUtilitiesTests.java * -------------------------- * (C) Copyright 2003-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 18-Sep-2003 : Version 1 (DG); * 23-Mar-2004 : Added test for maximumStackedRangeValue() method (DG); * 04-Oct-2004 : Eliminated NumberUtils usage (DG); * 07-Jan-2005 : Updated for method name changes (DG); * 03-Feb-2005 : Added testFindStackedRangeBounds2() method (DG); * 26-Sep-2007 : Added testIsEmptyOrNullXYDataset() method (DG); * 28-Mar-2008 : Added and renamed various tests (DG); * 08-Oct-2008 : New tests to support patch 2131001 and related * changes (DG); * 25-Mar-2009 : Added tests for new iterateToFindRangeBounds() method (DG); * 16-May-2009 : Added * testIterateToFindRangeBounds_MultiValueCategoryDataset() (DG); * 10-Sep-2009 : Added tests for bug 2849731 (DG); * */ package org.jfree.data.general; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link DatasetUtilities} class. */ public class DatasetUtilitiesTest { private static final double EPSILON = 0.0000000001; /** * Some tests to verify that Java does what I think it does! */ @Test public void testJava() { assertTrue(Double.isNaN(Math.min(1.0, Double.NaN))); assertTrue(Double.isNaN(Math.max(1.0, Double.NaN))); } /** * Some tests for the calculatePieDatasetTotal() method. */ @Test public void testCalculatePieDatasetTotal() { DefaultPieDataset d = new DefaultPieDataset(); assertEquals(0.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("A", 1.0); assertEquals(1.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("B", 3.0); assertEquals(4.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); } /** * Some tests for the findDomainBounds() method. */ @Test public void testFindDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that the standard method has 'includeInterval' * defaulting to true. */ @Test public void testFindDomainBounds2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * This test checks that when the 'includeInterval' flag is false, the * bounds come from the regular x-values. */ @Test public void testFindDomainBounds3() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that NaN values are ignored. */ @Test public void testFindDomainBounds_NaN() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, Double.NaN}; double[] x1Start = new double[] {0.9, 1.9, Double.NaN}; double[] x1End = new double[] {1.1, 2.1, Double.NaN}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(2.1, r.getUpperBound(), EPSILON); r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateDomainBounds() method. */ @Test public void testIterateDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the dataset are ignored. */ @Test public void testIterateDomainBounds_NaN() { DefaultXYDataset dataset = new DefaultXYDataset(); double[] x = new double[] {1.0, 2.0, Double.NaN, 3.0}; double[] y = new double[] {9.0, 8.0, 7.0, 6.0}; dataset.addSeries("S1", new double[][] {x, y}); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the IntervalXYDataset are ignored. */ @Test public void testIterateDomainBounds_NaN2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {Double.NaN, 2.0, 3.0}; double[] x1Start = new double[] {0.9, Double.NaN, 2.9}; double[] x1End = new double[] {1.1, Double.NaN, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.iterateDomainBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateDomainBounds(dataset, true); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() for a CategoryDataset method. */ @Test public void testFindRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() method on an XYDataset. */ @Test public void testFindRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * A test for the findRangeBounds(XYDataset) method using * an IntervalXYDataset. */ @Test public void testFindRangeBounds2() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); // what if we don't want the interval? r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ @Test public void testIterateRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ @Test public void testIterateRangeBounds2_CategoryDataset() { // an empty dataset should return a null range DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertNull(r); // a dataset with a single value dataset.addValue(1.23, "R1", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored dataset.addValue(null, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // a Double.NaN should be ignored dataset.addValue(Double.NaN, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method using an * IntervalCategoryDataset. */ @Test public void testIterateRangeBounds3_CategoryDataset() { Number[][] starts = new Double[2][3]; Number[][] ends = new Double[2][3]; starts[0][0] = 1.0; starts[0][1] = 2.0; starts[0][2] = 3.0; starts[1][0] = 11.0; starts[1][1] = 12.0; starts[1][2] = 13.0; ends[0][0] = 4.0; ends[0][1] = 5.0; ends[0][2] = 6.0; ends[1][0] = 16.0; ends[1][1] = 15.0; ends[1][2] = 14.0; DefaultIntervalCategoryDataset d = new DefaultIntervalCategoryDataset( starts, ends); Range r = DatasetUtilities.iterateRangeBounds(d, false); assertEquals(4.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateRangeBounds(d, true); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ @Test public void testIterateRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * Check the range returned when a series contains a null value. */ @Test public void testIterateRangeBounds2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 1.1); s1.add(2.0, null); s1.add(3.0, 3.3); XYSeriesCollection dataset = new XYSeriesCollection(s1); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.1, r.getLowerBound(), EPSILON); assertEquals(3.3, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ @Test public void testIterateRangeBounds3() { // an empty dataset should return a null range XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // a dataset with a single value s1.add(1.0, 1.23); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored s1.add(2.0, null); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // Double.NaN DOESN'T mess things up s1.add(3.0, Double.NaN); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */ @Test public void testIterateRangeBounds4() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); } /** * Some tests for the findMinimumDomainValue() method. */ @Test public void testFindMinimumDomainValue() { XYDataset dataset = createXYDataset1(); Number minimum = DatasetUtilities.findMinimumDomainValue(dataset); assertEquals(1.0, minimum); } /** * Some tests for the findMaximumDomainValue() method. */ @Test public void testFindMaximumDomainValue() { XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumDomainValue(dataset); assertEquals(3.0, maximum); } /** * Some tests for the findMinimumRangeValue() method. */ @Test public void testFindMinimumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number min1 = DatasetUtilities.findMinimumRangeValue(d1); assertEquals(1.0, min1); XYDataset d2 = createXYDataset1(); Number min2 = DatasetUtilities.findMinimumRangeValue(d2); assertEquals(100.0, min2); } /** * Some tests for the findMaximumRangeValue() method. */ @Test public void testFindMaximumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number max1 = DatasetUtilities.findMaximumRangeValue(d1); assertEquals(6.0, max1); XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumRangeValue(dataset); assertEquals(105.0, maximum); } /** * A quick test of the min and max range value methods. */ @Test public void testMinMaxRange() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number min = DatasetUtilities.findMinimumRangeValue(dataset); assertTrue(min.doubleValue() < 100.1); Number max = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(max.doubleValue() > 101.0); } /** * A test to reproduce bug report 803660. */ @Test public void test803660() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number n = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(n.doubleValue() > 101.0); } /** * A simple test for the cumulative range calculation. The sequence of * "cumulative" values are considered to be { 0.0, 10.0, 25.0, 18.0 } so * the range should be 0.0 -> 25.0. */ @Test public void testCumulativeRange1() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(-7.0, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), 0.00000001); assertEquals(25.0, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ @Test public void testCumulativeRange2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-21.4, "Series 1", "Start Value"); dataset.addValue(11.57, "Series 1", "Delta 1"); dataset.addValue(3.51, "Series 1", "Delta 2"); dataset.addValue(-12.36, "Series 1", "Delta 3"); dataset.addValue(3.39, "Series 1", "Delta 4"); dataset.addValue(38.68, "Series 1", "Delta 5"); dataset.addValue(-43.31, "Series 1", "Delta 6"); dataset.addValue(-29.59, "Series 1", "Delta 7"); dataset.addValue(35.30, "Series 1", "Delta 8"); dataset.addValue(5.0, "Series 1", "Delta 9"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(-49.51, range.getLowerBound(), 0.00000001); assertEquals(23.39, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ @Test public void testCumulativeRange3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(15.76, "Product 1", "Labour"); dataset.addValue(8.66, "Product 1", "Administration"); dataset.addValue(4.71, "Product 1", "Marketing"); dataset.addValue(3.51, "Product 1", "Distribution"); dataset.addValue(32.64, "Product 1", "Total Expense"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(65.28, range.getUpperBound(), EPSILON); } /** * Check that the findCumulativeRangeBounds() method ignores Double.NaN * values. */ @Test public void testCumulativeRange_NaN() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(Double.NaN, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(25.0, range.getUpperBound(), EPSILON); } /** * Test the creation of a dataset from an array. */ @Test public void testCreateCategoryDataset1() { String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[3][]; data[0] = new double[] {1.1, 1.2}; data[1] = new double[] {2.1, 2.2}; data[2] = new double[] {3.1, 3.2}; CategoryDataset dataset = DatasetUtilities.createCategoryDataset( rowKeys, columnKeys, data); assertSame(dataset.getRowCount(), 3); assertSame(dataset.getColumnCount(), 2); } /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */ @Test public void testCreateCategoryDataset2() { String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[2][]; data[0] = new double[] {1.1, 1.2, 1.3}; data[1] = new double[] {2.1, 2.2, 2.3}; try { DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); fail("IllegalArgumentException should have been thrown on data not matching length of keys"); } catch (IllegalArgumentException e) { assertEquals("The number of row keys does not match the number of rows in the data array.", e.getMessage()); } } /** * Test for a bug reported in the forum: * * http://www.jfree.org/phpBB2/viewtopic.php?t=7903 */ @Test public void testMaximumStackedRangeValue() { double v1 = 24.3; double v2 = 14.2; double v3 = 33.2; double v4 = 32.4; double v5 = 26.3; double v6 = 22.6; Number answer = Math.max(v1 + v2 + v3, v4 + v5 + v6); DefaultCategoryDataset d = new DefaultCategoryDataset(); d.addValue(v1, "Row 0", "Column 0"); d.addValue(v2, "Row 1", "Column 0"); d.addValue(v3, "Row 2", "Column 0"); d.addValue(v4, "Row 0", "Column 1"); d.addValue(v5, "Row 1", "Column 1"); d.addValue(v6, "Row 2", "Column 1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(d); assertEquals(max, answer); } /** * Some checks for the findStackedRangeBounds() method. */ @Test public void testFindStackedRangeBounds_CategoryDataset1() { CategoryDataset d1 = createCategoryDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(15.0, r.getUpperBound(), EPSILON); d1 = createCategoryDataset2(); r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ @Test public void testFindStackedRangeBounds_CategoryDataset2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.findStackedRangeBounds(dataset); assertNull(r ); dataset.addValue(5.0, "R1", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(3.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(-1.0, "R2", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R3", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds(CategoryDataset, * KeyToGroupMap) method. */ @Test public void testFindStackedRangeBounds_CategoryDataset3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); KeyToGroupMap map = new KeyToGroupMap("Group A"); Range r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertNull(r ); dataset.addValue(1.0, "R1", "C1"); dataset.addValue(2.0, "R2", "C1"); dataset.addValue(3.0, "R3", "C1"); dataset.addValue(4.0, "R4", "C1"); map.mapKeyToGroup("R1", "Group A"); map.mapKeyToGroup("R2", "Group A"); map.mapKeyToGroup("R3", "Group B"); map.mapKeyToGroup("R4", "Group B"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R5", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R6", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ @Test public void testFindStackedRangeBoundsForTableXYDataset1() { TableXYDataset d2 = createTableXYDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d2); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ @Test public void testFindStackedRangeBoundsForTableXYDataset2() { DefaultTableXYDataset d = new DefaultTableXYDataset(); Range r = DatasetUtilities.findStackedRangeBounds(d); assertEquals(r, new Range(0.0, 0.0)); } /** * Tests the stacked range extent calculation. */ @Test public void testStackedRangeWithMap() { CategoryDataset d = createCategoryDataset1(); KeyToGroupMap map = new KeyToGroupMap("G0"); map.mapKeyToGroup("R2", "G1"); Range r = DatasetUtilities.findStackedRangeBounds(d, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(9.0, r.getUpperBound(), EPSILON); } /** * Some checks for the isEmptyOrNull(XYDataset) method. */ @Test public void testIsEmptyOrNullXYDataset() { XYSeriesCollection dataset = null; assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); dataset = new XYSeriesCollection(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); s1.add(1.0, 2.0); assertFalse(DatasetUtilities.isEmptyOrNull(dataset)); s1.clear(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); } /** * Some checks for the limitPieDataset() methods. */ @Test public void testLimitPieDataset() { // check that empty dataset is handled OK DefaultPieDataset d1 = new DefaultPieDataset(); PieDataset d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(0, d2.getItemCount()); // check that minItem limit is observed d1.setValue("Item 1", 1.0); d1.setValue("Item 2", 49.50); d1.setValue("Item 3", 49.50); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(3, d2.getItemCount()); assertEquals("Item 1", d2.getKey(0)); assertEquals("Item 2", d2.getKey(1)); assertEquals("Item 3", d2.getKey(2)); // check that minItem limit is observed d1.setValue("Item 4", 1.0); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05, 2); // and that simple aggregation works assertEquals(3, d2.getItemCount()); assertEquals("Item 2", d2.getKey(0)); assertEquals("Item 3", d2.getKey(1)); assertEquals("Other", d2.getKey(2)); assertEquals(2.0, d2.getValue("Other")); } /** * Some checks for the sampleFunction2D() method. */ @Test public void testSampleFunction2D() { Function2D f = new LineFunction2D(0, 1); XYDataset dataset = DatasetUtilities.sampleFunction2D(f, 0.0, 1.0, 2, "S1"); assertEquals(1, dataset.getSeriesCount()); assertEquals("S1", dataset.getSeriesKey(0)); assertEquals(2, dataset.getItemCount(0)); assertEquals(0.0, dataset.getXValue(0, 0), EPSILON); assertEquals(0.0, dataset.getYValue(0, 0), EPSILON); assertEquals(1.0, dataset.getXValue(0, 1), EPSILON); assertEquals(1.0, dataset.getYValue(0, 1), EPSILON); } /** * A simple check for the findMinimumStackedRangeValue() method. */ @Test public void testFindMinimumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertNull(min); dataset.addValue(1.0, "R1", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ @Test public void testFindMinimumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-1.0, min.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ @Test public void testFindMaximumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertNull(max); dataset.addValue(1.0, "R1", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(1.0, max.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ @Test public void testFindMaximumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset1() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(1.0, "R1", "C0"); result.addValue(1.0, "R2", "C0"); result.addValue(4.0, "R0", "C1"); result.addValue(5.0, "R1", "C1"); result.addValue(6.0, "R2", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset2() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(-2.0, "R1", "C0"); result.addValue(2.0, "R0", "C1"); result.addValue(-1.0, "R1", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private XYDataset createXYDataset1() { XYSeries series1 = new XYSeries("S1"); series1.add(1.0, 100.0); series1.add(2.0, 101.0); series1.add(3.0, 102.0); XYSeries series2 = new XYSeries("S2"); series2.add(1.0, 103.0); series2.add(2.0, null); series2.add(3.0, 105.0); XYSeriesCollection result = new XYSeriesCollection(); result.addSeries(series1); result.addSeries(series2); result.setIntervalWidth(0.0); return result; } /** * Creates a sample dataset for testing purposes. * * @return A sample dataset. */ private TableXYDataset createTableXYDataset1() { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.0); s1.add(2.0, 2.0); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(1.0, -2.0); s2.add(2.0, -1.0); dataset.addSeries(s2); return dataset; } /** * Some checks for the iteratorToFindRangeBounds(XYDataset...) method. */ @Test public void testIterateToFindRangeBounds1_XYDataset() { // null dataset throws IllegalArgumentException try { DatasetUtilities.iterateToFindRangeBounds(null, new ArrayList(), new Range(0.0, 1.0), true); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { assertEquals("Null 'dataset' argument.", e.getMessage()); } // null list throws IllegalArgumentException try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), null, new Range(0.0, 1.0), true); fail("IllegalArgumentException should have been thrown on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'visibleSeriesKeys' argument.", e.getMessage()); } // null range throws IllegalArgumentException try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), new ArrayList(), null, true); fail("IllegalArgumentException should have been thrown on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'xRange' argument.", e.getMessage()); } } /** * Some tests for the iterateToFindRangeBounds() method. */ @Test public void testIterateToFindRangeBounds2_XYDataset() { List<Comparable> visibleSeriesKeys = new ArrayList<Comparable>(); Range xRange = new Range(0.0, 10.0); // empty dataset returns null XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // add an empty series XYSeries s1 = new XYSeries("A"); dataset.addSeries(s1); visibleSeriesKeys.add("A"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a null value s1.add(1.0, null); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a NaN s1.add(2.0, Double.NaN); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a regular value s1.add(3.0, 5.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 5.0), r); // check another regular value s1.add(4.0, 6.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a second series XYSeries s2 = new XYSeries("B"); dataset.addSeries(s2); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); visibleSeriesKeys.add("B"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a value to the second series s2.add(5.0, 15.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); // add a value that isn't in the xRange s2.add(15.0, 150.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, new Range(0.0, 20.0), false); assertEquals(new Range(5.0, 150.0), r); } /** * Some checks for the iterateToFindRangeBounds() method when applied to * a BoxAndWhiskerXYDataset. */ @Test public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset() { DefaultBoxAndWhiskerXYDataset dataset = new DefaultBoxAndWhiskerXYDataset("Series 1"); List<Comparable> visibleSeriesKeys = new ArrayList<Comparable>(); visibleSeriesKeys.add("Series 1"); Range xRange = new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); dataset.add(new Date(50L), new BoxAndWhiskerItem(5.0, 4.9, 2.0, 8.0, 1.0, 9.0, 0.0, 10.0, new ArrayList())); assertEquals(new Range(5.0, 5.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); assertEquals(new Range(1.0, 9.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) * method. */ @Test public void testIterateToFindRangeBounds_StatisticalCategoryDataset() { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); List<Comparable> visibleSeriesKeys = new ArrayList<Comparable>(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); dataset.add(1.0, 0.5, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); assertEquals(new Range(0.5, 1.5), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) method * with a {@link MultiValueCategoryDataset}. */ @Test public void testIterateToFindRangeBounds_MultiValueCategoryDataset() { DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset(); List<Comparable> visibleSeriesKeys = new ArrayList<Comparable>(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); List values = Arrays.asList(1.0); dataset.add(values, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(2.0, 3.0); dataset.add(values, "R1", "C2"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(-1.0, -2.0); dataset.add(values, "R2", "C1"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); visibleSeriesKeys.add("R2"); assertEquals(new Range(-2.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateRangeBounds() method when passed an * IntervalCategoryDataset. */ @Test public void testIterateRangeBounds_IntervalCategoryDataset() { TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); d.addItem(1.0, 2.0, 3.0, "R1", "C1"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateRangeBounds(d)); d = new TestIntervalCategoryDataset(); d.addItem(2.5, 2.0, 3.0, "R1", "C1"); assertEquals(new Range(2.0, 3.0), DatasetUtilities.iterateRangeBounds(d)); d = new TestIntervalCategoryDataset(); d.addItem(4.0, 2.0, 3.0, "R1", "C1"); assertEquals(new Range(2.0, 4.0), DatasetUtilities.iterateRangeBounds(d)); d = new TestIntervalCategoryDataset(); d.addItem(null, 2.0, 3.0, "R1", "C1"); assertEquals(new Range(2.0, 3.0), DatasetUtilities.iterateRangeBounds(d)); // try some nulls d = new TestIntervalCategoryDataset(); d.addItem(null, null, null, "R1", "C1"); assertNull(DatasetUtilities.iterateRangeBounds(d)); d = new TestIntervalCategoryDataset(); d.addItem(1.0, null, null, "R1", "C1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateRangeBounds(d)); d = new TestIntervalCategoryDataset(); d.addItem(null, 1.0, null, "R1", "C1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateRangeBounds(d)); d = new TestIntervalCategoryDataset(); d.addItem(null, null, 1.0, "R1", "C1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateRangeBounds(d)); } /** * A test for bug 2849731. */ @Test public void testBug2849731() { TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); d.addItem(2.5, 2.0, 3.0, "R1", "C1"); d.addItem(4.0, null, null, "R2", "C1"); assertEquals(new Range(2.0, 4.0), DatasetUtilities.iterateRangeBounds(d)); } /** * Another test for bug 2849731. */ @Test public void testBug2849731_2() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, Double.NaN, 1.5, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.0, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(0.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); } /** * Yet another test for bug 2849731. */ @Test public void testBug2849731_3() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, 1.5, Double.NaN, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, Double.NaN, 2.5); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 3.5, Double.NaN); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(3.5, r.getUpperBound(), EPSILON); } /** * Check the findYValue() method with a dataset that is in ascending order * of x-values. */ @Test public void testFindYValue() { XYSeries series = new XYSeries("S1"); XYSeriesCollection dataset = new XYSeriesCollection(series); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 100.0))); series.add(1.0, 5.0); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 0.0))); assertEquals(5.0, DatasetUtilities.findYValue(dataset, 0, 1.0), EPSILON); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 2.0))); series.add(2.0, 10.0); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 0.0))); assertEquals(5.0, DatasetUtilities.findYValue(dataset, 0, 1.0), EPSILON); assertEquals(6.25, DatasetUtilities.findYValue(dataset, 0, 1.25), EPSILON); assertEquals(7.5, DatasetUtilities.findYValue(dataset, 0, 1.5), EPSILON); assertEquals(10.0, DatasetUtilities.findYValue(dataset, 0, 2.0), EPSILON); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 3.0))); } /** * Check the findYValue() method with a dataset that is not sorted. */ @Test public void testFindYValueNonSorted() { XYSeries series = new XYSeries("S1", false); XYSeriesCollection dataset = new XYSeriesCollection(series); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 100.0))); series.add(1.0, 5.0); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 0.0))); assertEquals(5.0, DatasetUtilities.findYValue(dataset, 0, 1.0), EPSILON); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 2.0))); series.add(0.0, 10.0); series.add(4.0, 20.0); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, -0.5))); assertEquals(10.0, DatasetUtilities.findYValue(dataset, 0, 0.0), EPSILON); assertEquals(5.0, DatasetUtilities.findYValue(dataset, 0, 1.0), EPSILON); assertEquals(15.0, DatasetUtilities.findYValue(dataset, 0, 2.0), EPSILON); assertEquals(20.0, DatasetUtilities.findYValue(dataset, 0, 4.0), EPSILON); assertEquals(17.5, DatasetUtilities.findYValue(dataset, 0, 3.0), EPSILON); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 5.0))); } /** * Check the findYValue() method with a dataset that allows duplicate * values. */ @Test public void testFindYValueWithDuplicates() { XYSeries series = new XYSeries("S1", true, true); XYSeriesCollection dataset = new XYSeriesCollection(series); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 100.0))); series.add(1.0, 5.0); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 0.0))); assertEquals(5.0, DatasetUtilities.findYValue(dataset, 0, 1.0), EPSILON); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 2.0))); series.add(1.0, 10.0); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 0.0))); assertEquals(5.0, DatasetUtilities.findYValue(dataset, 0, 1.0), EPSILON); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 2.0))); series.add(2.0, 10.0); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 0.0))); assertEquals(5.0, DatasetUtilities.findYValue(dataset, 0, 1.0), EPSILON); assertEquals(10.0, DatasetUtilities.findYValue(dataset, 0, 1.25), EPSILON); assertEquals(10.0, DatasetUtilities.findYValue(dataset, 0, 1.5), EPSILON); assertEquals(10.0, DatasetUtilities.findYValue(dataset, 0, 2.0), EPSILON); assertTrue(Double.isNaN(DatasetUtilities.findYValue(dataset, 0, 3.0))); } }
54,451
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultKeyedValueDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/DefaultKeyedValueDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------------- * DefaultKeyedValueDatasetTests.java * ---------------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 18-Aug-2003 : Version 1 (DG); * */ package org.jfree.data.general; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Tests for the {@link DefaultKeyedValueDataset} class. */ public class DefaultKeyedValueDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Test", 45.5); DefaultKeyedValueDataset d2 = new DefaultKeyedValueDataset("Test", 45.5); assertEquals(d1, d2); assertEquals(d2, d1); d1 = new DefaultKeyedValueDataset("Test 1", 45.5); d2 = new DefaultKeyedValueDataset("Test 2", 45.5); assertFalse(d1.equals(d2)); d1 = new DefaultKeyedValueDataset("Test", 45.5); d2 = new DefaultKeyedValueDataset("Test", 45.6); assertFalse(d1.equals(d2)); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Test", 45.5); DefaultKeyedValueDataset d2 = (DefaultKeyedValueDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Confirm that the clone is independent of the original. */ @Test public void testCloneIndependence() throws CloneNotSupportedException { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Key", 10.0); DefaultKeyedValueDataset d2 = (DefaultKeyedValueDataset) d1.clone(); assertEquals(d1, d2); d2.updateValue(99.9); assertFalse(d1.equals(d2)); d2.updateValue(10.0); assertEquals(d1, d2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Test", 25.3); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); DefaultKeyedValueDataset d2 = (DefaultKeyedValueDataset) in.readObject(); in.close(); assertEquals(d1, d2); } }
4,473
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultHeatMapDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/DefaultHeatMapDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------- * DefaultHeatMapDatasetTests.java * ------------------------------- * (C) Copyright 2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 28-Jan-2009 : Version 1 (DG); * */ package org.jfree.data.general; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; /** * Somes tests for the {@link DefaultHeatMapDataset} class. * * @since 1.0.13 */ public class DefaultHeatMapDatasetTest implements DatasetChangeListener { /** The last event received. */ private DatasetChangeEvent lastEvent; /** * Records the last event. * * @param event the last event. */ @Override public void datasetChanged(DatasetChangeEvent event) { this.lastEvent = event; } private static final double EPSILON = 0.0000000001; /** * Some general tests. */ @Test public void testGeneral() { DefaultHeatMapDataset d = new DefaultHeatMapDataset(10, 5, 0.0, 9.0, 0.0, 5.0); assertEquals(10, d.getXSampleCount()); assertEquals(5, d.getYSampleCount()); assertEquals(0.0, d.getMinimumXValue(), EPSILON); assertEquals(9.0, d.getMaximumXValue(), EPSILON); assertEquals(0.0, d.getMinimumYValue(), EPSILON); assertEquals(5.0, d.getMaximumYValue(), EPSILON); assertEquals(0.0, d.getZValue(0, 0), EPSILON); d.addChangeListener(this); d.setZValue(0, 0, 1.0, false); assertEquals(1.0, d.getZValue(0, 0), EPSILON); assertNull(this.lastEvent); d.setZValue(1, 2, 2.0); assertEquals(2.0, d.getZValue(1, 2), EPSILON); assertNotNull(this.lastEvent); } /** * Some tests for the equals() method. */ @Test public void testEquals() { DefaultHeatMapDataset d1 = new DefaultHeatMapDataset(5, 10, 1.0, 2.0, 3.0, 4.0); DefaultHeatMapDataset d2 = new DefaultHeatMapDataset(5, 10, 1.0, 2.0, 3.0, 4.0); assertEquals(d1, d2); d1 = new DefaultHeatMapDataset(6, 10, 1.0, 2.0, 3.0, 4.0); assertFalse(d1.equals(d2)); d2 = new DefaultHeatMapDataset(6, 10, 1.0, 2.0, 3.0, 4.0); assertEquals(d1, d2); d1 = new DefaultHeatMapDataset(6, 11, 1.0, 2.0, 3.0, 4.0); assertFalse(d1.equals(d2)); d2 = new DefaultHeatMapDataset(6, 11, 1.0, 2.0, 3.0, 4.0); assertEquals(d1, d2); d1 = new DefaultHeatMapDataset(6, 11, 2.0, 2.0, 3.0, 4.0); assertFalse(d1.equals(d2)); d2 = new DefaultHeatMapDataset(6, 11, 2.0, 2.0, 3.0, 4.0); assertEquals(d1, d2); d1 = new DefaultHeatMapDataset(6, 11, 2.0, 3.0, 3.0, 4.0); assertFalse(d1.equals(d2)); d2 = new DefaultHeatMapDataset(6, 11, 2.0, 3.0, 3.0, 4.0); assertEquals(d1, d2); d1 = new DefaultHeatMapDataset(6, 11, 2.0, 3.0, 4.0, 4.0); assertFalse(d1.equals(d2)); d2 = new DefaultHeatMapDataset(6, 11, 2.0, 3.0, 4.0, 4.0); assertEquals(d1, d2); d1 = new DefaultHeatMapDataset(6, 11, 2.0, 3.0, 4.0, 5.0); assertFalse(d1.equals(d2)); d2 = new DefaultHeatMapDataset(6, 11, 2.0, 3.0, 4.0, 5.0); assertEquals(d1, d2); d1.setZValue(1, 2, 3.0); assertFalse(d1.equals(d2)); d2.setZValue(1, 2, 3.0); assertEquals(d1, d2); d1.setZValue(0, 0, Double.NEGATIVE_INFINITY); assertFalse(d1.equals(d2)); d2.setZValue(0, 0, Double.NEGATIVE_INFINITY); assertEquals(d1, d2); d1.setZValue(0, 1, Double.POSITIVE_INFINITY); assertFalse(d1.equals(d2)); d2.setZValue(0, 1, Double.POSITIVE_INFINITY); assertEquals(d1, d2); d1.setZValue(0, 2, Double.NaN); assertFalse(d1.equals(d2)); d2.setZValue(0, 2, Double.NaN); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultHeatMapDataset d1 = new DefaultHeatMapDataset(2, 3, -1.0, 4.0, -2.0, 5.0); d1.setZValue(0, 0, 10.0); d1.setZValue(0, 1, Double.NEGATIVE_INFINITY); d1.setZValue(0, 2, Double.POSITIVE_INFINITY); d1.setZValue(1, 0, Double.NaN); DefaultHeatMapDataset d2 = (DefaultHeatMapDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // simple check for independence d1.setZValue(0, 0, 11.0); assertFalse(d1.equals(d2)); d2.setZValue(0, 0, 11.0); assertEquals(d1, d2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultHeatMapDataset d1 = new DefaultHeatMapDataset(2, 3, -1.0, 4.0, -2.0, 5.0); d1.setZValue(0, 0, 10.0); d1.setZValue(0, 1, Double.NEGATIVE_INFINITY); d1.setZValue(0, 2, Double.POSITIVE_INFINITY); d1.setZValue(1, 0, Double.NaN); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); DefaultHeatMapDataset d2 = (DefaultHeatMapDataset) in.readObject(); in.close(); assertEquals(d1, d2); } }
7,360
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
TestIntervalCategoryDataset.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/TestIntervalCategoryDataset.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------------- * TestIntervalCategoryDataset.java * -------------------------------- * (C) Copyright 2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 10-Sep-2009 : Version 1, based on DefaultCategoryDataset (DG); * */ package org.jfree.data.general; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.KeyedObjects2D; import org.jfree.data.UnknownKeyException; import org.jfree.data.category.IntervalCategoryDataset; import java.io.Serializable; import java.util.List; /** * A test implementation of the {@link IntervalCategoryDataset} interface. */ public class TestIntervalCategoryDataset extends AbstractDataset implements IntervalCategoryDataset, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -8168173757291644622L; /** A storage structure for the data. */ private KeyedObjects2D data; /** * Creates a new (empty) dataset. */ public TestIntervalCategoryDataset() { this.data = new KeyedObjects2D(); } /** * Returns the number of rows in the table. * * @return The row count. * * @see #getColumnCount() */ @Override public int getRowCount() { return this.data.getRowCount(); } /** * Returns the number of columns in the table. * * @return The column count. * * @see #getRowCount() */ @Override public int getColumnCount() { return this.data.getColumnCount(); } /** * Returns a value from the table. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The value (possibly <code>null</code>). * */ @Override public Number getValue(int row, int column) { IntervalDataItem item = (IntervalDataItem) this.data.getObject(row, column); if (item == null) { return null; } return item.getValue(); } /** * Returns the key for the specified row. * * @param row the row index (zero-based). * * @return The row key. * * @see #getRowIndex(Comparable) * @see #getRowKeys() * @see #getColumnKey(int) */ @Override public Comparable getRowKey(int row) { return this.data.getRowKey(row); } /** * Returns the row index for a given key. * * @param key the row key (<code>null</code> not permitted). * * @return The row index. * * @see #getRowKey(int) */ @Override public int getRowIndex(Comparable key) { // defer null argument check return this.data.getRowIndex(key); } /** * Returns the row keys. * * @return The keys. * * @see #getRowKey(int) */ @Override public List getRowKeys() { return this.data.getRowKeys(); } /** * Returns a column key. * * @param column the column index (zero-based). * * @return The column key. * * @see #getColumnIndex(Comparable) */ @Override public Comparable getColumnKey(int column) { return this.data.getColumnKey(column); } /** * Returns the column index for a given key. * * @param key the column key (<code>null</code> not permitted). * * @return The column index. * * @see #getColumnKey(int) */ @Override public int getColumnIndex(Comparable key) { // defer null argument check return this.data.getColumnIndex(key); } /** * Returns the column keys. * * @return The keys. * * @see #getColumnKey(int) */ @Override public List getColumnKeys() { return this.data.getColumnKeys(); } /** * Returns the value for a pair of keys. * * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @return The value (possibly <code>null</code>). * * @throws UnknownKeyException if either key is not defined in the dataset. * */ @Override public Number getValue(Comparable rowKey, Comparable columnKey) { IntervalDataItem item = (IntervalDataItem) this.data.getObject(rowKey, columnKey); if (item == null) { return null; } return item.getValue(); } /** * Adds a value to the table. Performs the same function as setValue(). * * @param value the value. * @param rowKey the row key. * @param columnKey the column key. * * @see #getValue(Comparable, Comparable) */ public void addItem(Number value, Number lower, Number upper, Comparable rowKey, Comparable columnKey) { IntervalDataItem item = new IntervalDataItem(value, lower, upper); this.data.addObject(item, rowKey, columnKey); fireDatasetChanged(); } /** * Adds a value to the table. * * @param value the value. * @param rowKey the row key. * @param columnKey the column key. * * @see #getValue(Comparable, Comparable) */ public void addItem(double value, double lower, double upper, Comparable rowKey, Comparable columnKey) { addItem(new Double(value), new Double(lower), new Double(upper), rowKey, columnKey); } /** * Adds or updates a value in the table and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param value the value (<code>null</code> permitted). * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @see #getValue(Comparable, Comparable) */ public void setItem(Number value, Number lower, Number upper, Comparable rowKey, Comparable columnKey) { IntervalDataItem item = new IntervalDataItem(value, lower, upper); this.data.addObject(item, rowKey, columnKey); fireDatasetChanged(); } /** * Adds or updates a value in the table and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param value the value. * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @see #getValue(Comparable, Comparable) */ public void setItem(double value, double lower, double upper, Comparable rowKey, Comparable columnKey) { setItem(new Double(value), new Double(lower), new Double(upper), rowKey, columnKey); } /** * Removes a value from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowKey the row key. * @param columnKey the column key. * */ public void removeItem(Comparable rowKey, Comparable columnKey) { this.data.removeObject(rowKey, columnKey); fireDatasetChanged(); } /** * Removes a row from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowIndex the row index. * * @see #removeColumn(int) */ public void removeRow(int rowIndex) { this.data.removeRow(rowIndex); fireDatasetChanged(); } /** * Removes a row from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowKey the row key. * * @see #removeColumn(Comparable) */ public void removeRow(Comparable rowKey) { this.data.removeRow(rowKey); fireDatasetChanged(); } /** * Removes a column from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param columnIndex the column index. * * @see #removeRow(int) */ public void removeColumn(int columnIndex) { this.data.removeColumn(columnIndex); fireDatasetChanged(); } /** * Removes a column from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param columnKey the column key (<code>null</code> not permitted). * * @see #removeRow(Comparable) * * @throws UnknownKeyException if <code>columnKey</code> is not defined * in the dataset. */ public void removeColumn(Comparable columnKey) { this.data.removeColumn(columnKey); fireDatasetChanged(); } /** * Clears all data from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. */ public void clear() { this.data.clear(); fireDatasetChanged(); } /** * Tests this dataset for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof TestIntervalCategoryDataset)) { return false; } TestIntervalCategoryDataset that = (TestIntervalCategoryDataset) obj; if (!getRowKeys().equals(that.getRowKeys())) { return false; } if (!getColumnKeys().equals(that.getColumnKeys())) { return false; } int rowCount = getRowCount(); int colCount = getColumnCount(); for (int r = 0; r < rowCount; r++) { for (int c = 0; c < colCount; c++) { Number v1 = getValue(r, c); Number v2 = that.getValue(r, c); if (v1 == null) { if (v2 != null) { return false; } } else if (!v1.equals(v2)) { return false; } } } return true; } /** * Returns a hash code for the dataset. * * @return A hash code. */ @Override public int hashCode() { return this.data.hashCode(); } /** * Returns a clone of the dataset. * * @return A clone. * * @throws CloneNotSupportedException if there is a problem cloning the * dataset. */ @Override public Object clone() throws CloneNotSupportedException { TestIntervalCategoryDataset clone = (TestIntervalCategoryDataset) super.clone(); clone.data = (KeyedObjects2D) this.data.clone(); return clone; } @Override public Number getStartValue(int series, int category) { IntervalDataItem item = (IntervalDataItem) this.data.getObject(series, category); if (item == null) { return null; } return item.getLowerBound(); } @Override public Number getStartValue(Comparable series, Comparable category) { IntervalDataItem item = (IntervalDataItem) this.data.getObject(series, category); if (item == null) { return null; } return item.getLowerBound(); } @Override public Number getEndValue(int series, int category) { IntervalDataItem item = (IntervalDataItem) this.data.getObject(series, category); if (item == null) { return null; } return item.getUpperBound(); } @Override public Number getEndValue(Comparable series, Comparable category) { IntervalDataItem item = (IntervalDataItem) this.data.getObject(series, category); if (item == null) { return null; } return item.getUpperBound(); } }
13,289
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DatasetGroupTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/DatasetGroupTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * DatasetGroupTests.java * ---------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 14-Jan-2005 : Version 1 (DG); * */ package org.jfree.data.general; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; /** * Tests for the {@link DatasetGroup} class. */ public class DatasetGroupTest { /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DatasetGroup g1 = new DatasetGroup(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(g1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); DatasetGroup g2 = (DatasetGroup) in.readObject(); in.close(); assertEquals(g1, g2); } }
2,627
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultPieDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/DefaultPieDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * DefaultPieDatasetTests.java * --------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 18-Aug-2003 : Version 1 (DG); * 31-Jul-2006 : Added test for new clear() method (DG); * 01-Aug-2006 : Added testGetKey() and testGetIndex() methods (DG); * */ package org.jfree.data.general; import java.io.IOException; import org.junit.Test; import org.jfree.chart.TestUtilities; import org.jfree.data.UnknownKeyException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** * Tests for the {@link org.jfree.data.general.PieDataset} class. */ public class DefaultPieDatasetTest implements DatasetChangeListener { private DatasetChangeEvent lastEvent; /** * Records the last event. * * @param event the last event. */ @Override public void datasetChanged(DatasetChangeEvent event) { this.lastEvent = event; } private static final double EPSILON = 0.00000001; @Test public void testGetValue() { DefaultPieDataset d = new DefaultPieDataset(); d.setValue("A", 5.0); assertEquals(5.0, d.getValue("A").doubleValue(), EPSILON); // fetching the value for a key that does not exist try { d.getValue("KEY_THAT_DOES_NOT_EXIST"); fail("Expected an UnknownKeyException."); } catch (UnknownKeyException e) { // expected in this case } } /** * Some tests for the clear() method. */ @Test public void testClear() { DefaultPieDataset d = new DefaultPieDataset(); d.addChangeListener(this); // no event is generated if the dataset is already empty d.clear(); assertNull(this.lastEvent); d.setValue("A", 1.0); assertEquals(1, d.getItemCount()); this.lastEvent = null; d.clear(); assertNotNull(this.lastEvent); assertEquals(0, d.getItemCount()); } /** * Some checks for the getKey(int) method. */ @Test public void testGetKey() { DefaultPieDataset d = new DefaultPieDataset(); d.setValue("A", 1.0); d.setValue("B", 2.0); assertEquals("A", d.getKey(0)); assertEquals("B", d.getKey(1)); try { d.getKey(-1); fail("IndexOutOfBoundsException should have been thrown on negative key"); } catch (IndexOutOfBoundsException e) { assertEquals("-1", e.getMessage()); } try { d.getKey(2); fail("IndexOutOfBoundsException should have been thrown on key out of range"); } catch (IndexOutOfBoundsException e) { assertEquals("Index: 2, Size: 2", e.getMessage()); } } /** * Some checks for the getIndex() method. */ @Test public void testGetIndex() { DefaultPieDataset d = new DefaultPieDataset(); d.setValue("A", 1.0); d.setValue("B", 2.0); assertEquals(0, d.getIndex("A")); assertEquals(1, d.getIndex("B")); assertEquals(-1, d.getIndex("XX")); try { d.getIndex(null); fail("IllegalArgumentException should have been thrown on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'key' argument.", e.getMessage()); } } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultPieDataset d1 = new DefaultPieDataset(); d1.setValue("V1", new Integer(1)); d1.setValue("V2", null); d1.setValue("V3", new Integer(3)); DefaultPieDataset d2 = (DefaultPieDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultPieDataset d1 = new DefaultPieDataset(); d1.setValue("C1", new Double(234.2)); d1.setValue("C2", null); d1.setValue("C3", new Double(345.9)); d1.setValue("C4", new Double(452.7)); DefaultPieDataset d2 = (DefaultPieDataset) TestUtilities.serialised(d1); assertEquals(d1, d2); } }
5,987
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultKeyedValues2DDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/DefaultKeyedValues2DDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * DefaultKeyedValues2DDatasetTests.java * ------------------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Mar-2003 : Version 1 (DG); * */ package org.jfree.data.general; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Tests for the {@link DefaultKeyedValues2DDataset} class. */ public class DefaultKeyedValues2DDatasetTest { /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultKeyedValues2DDataset d1 = new DefaultKeyedValues2DDataset(); d1.setValue(new Integer(1), "V1", "C1"); d1.setValue(null, "V2", "C1"); d1.setValue(new Integer(3), "V3", "C2"); DefaultKeyedValues2DDataset d2 = (DefaultKeyedValues2DDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultKeyedValues2DDataset d1 = new DefaultKeyedValues2DDataset(); d1.addValue(new Double(234.2), "Row1", "Col1"); d1.addValue(null, "Row1", "Col2"); d1.addValue(new Double(345.9), "Row2", "Col1"); d1.addValue(new Double(452.7), "Row2", "Col2"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); DefaultKeyedValues2DDataset d2 = (DefaultKeyedValues2DDataset) in.readObject(); in.close(); assertEquals(d1, d2); } }
3,605
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultKeyedValuesDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/DefaultKeyedValuesDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------------- * DefaultKeyedValuesDatasetTests.java * ----------------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Mar-2003 : Version 1 (DG); * */ package org.jfree.data.general; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Tests for the {@link DefaultKeyedValuesDataset} class. */ public class DefaultKeyedValuesDatasetTest { /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultKeyedValuesDataset d1 = new DefaultKeyedValuesDataset(); d1.setValue("V1", new Integer(1)); d1.setValue("V2", null); d1.setValue("V3", new Integer(3)); DefaultKeyedValuesDataset d2 = (DefaultKeyedValuesDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultKeyedValuesDataset d1 = new DefaultKeyedValuesDataset(); d1.setValue("C1", new Double(234.2)); d1.setValue("C2", null); d1.setValue("C3", new Double(345.9)); d1.setValue("C4", new Double(452.7)); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); KeyedValuesDataset d2 = (KeyedValuesDataset) in.readObject(); in.close(); assertEquals(d1, d2); } }
3,507
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IntervalDataItem.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/general/IntervalDataItem.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * IntervalDataItem.java * --------------------- * (C) Copyright 2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 10-Sep-2009 : Version 1, based on DefaultCategoryDataset (DG); * */ package org.jfree.data.general; /** * A data holder for a value and an associated range or interval. Used by * the TestIntervalCategoryDataset class. */ public class IntervalDataItem { private Number value; private Number lowerBound; private Number upperBound; public IntervalDataItem(Number value, Number lowerBound, Number upperBound) { this.value = value; this.lowerBound = lowerBound; this.upperBound = upperBound; } public Number getLowerBound() { return lowerBound; } public Number getUpperBound() { return upperBound; } public Number getValue() { return value; } }
2,219
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
YWithXIntervalTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/YWithXIntervalTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * YWithXIntervalTests.java * ------------------------ * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests for the {@link YWithXInterval} class. */ public class YWithXIntervalTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { YWithXInterval i1 = new YWithXInterval(1.0, 0.5, 1.5); YWithXInterval i2 = new YWithXInterval(1.0, 0.5, 1.5); assertEquals(i1, i2); i1 = new YWithXInterval(1.1, 0.5, 1.5); assertFalse(i1.equals(i2)); i2 = new YWithXInterval(1.1, 0.5, 1.5); assertEquals(i1, i2); i1 = new YWithXInterval(1.1, 0.55, 1.5); assertFalse(i1.equals(i2)); i2 = new YWithXInterval(1.1, 0.55, 1.5); assertEquals(i1, i2); i1 = new YWithXInterval(1.1, 0.55, 1.55); assertFalse(i1.equals(i2)); i2 = new YWithXInterval(1.1, 0.55, 1.55); assertEquals(i1, i2); } /** * This class is immutable. */ @Test public void testCloning() throws CloneNotSupportedException { YWithXInterval i1 = new YWithXInterval(1.0, 0.5, 1.5); assertFalse(i1 instanceof Cloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { YWithXInterval i1 = new YWithXInterval(1.0, 0.5, 1.5); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(i1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); YWithXInterval i2 = (YWithXInterval) in.readObject(); in.close(); assertEquals(i1, i2); } }
3,721
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
YIntervalSeriesCollectionTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/YIntervalSeriesCollectionTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------------- * YIntervalSeriesCollectionTests.java * ----------------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * 18-Jan-2008 : Added testRemoveSeries() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link YIntervalSeriesCollection} class. */ public class YIntervalSeriesCollectionTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); YIntervalSeriesCollection c2 = new YIntervalSeriesCollection(); assertEquals(c1, c2); // add a series YIntervalSeries s1 = new YIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); c1.addSeries(s1); assertFalse(c1.equals(c2)); YIntervalSeries s2 = new YIntervalSeries("Series"); s2.add(1.0, 1.1, 1.2, 1.3); c2.addSeries(s2); assertEquals(c1, c2); // add an empty series c1.addSeries(new YIntervalSeries("Empty Series")); assertFalse(c1.equals(c2)); c2.addSeries(new YIntervalSeries("Empty Series")); assertEquals(c1, c2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); c1.addSeries(s1); YIntervalSeriesCollection c2 = (YIntervalSeriesCollection) c1.clone(); assertNotSame(c1, c2); assertSame(c1.getClass(), c2.getClass()); assertEquals(c1, c2); // check independence s1.setDescription("XYZ"); assertFalse(c1.equals(c2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); assertTrue(c1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(c1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); YIntervalSeriesCollection c2 = (YIntervalSeriesCollection) in.readObject(); in.close(); assertEquals(c1, c2); } /** * Some basic checks for the removeSeries() method. */ @Test public void testRemoveSeries() { YIntervalSeriesCollection c = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("s1"); c.addSeries(s1); c.removeSeries(0); assertEquals(0, c.getSeriesCount()); c.addSeries(s1); try { c.removeSeries(-1); fail("IllegalArgumentException should have been thrown on negative key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds.", e.getMessage()); } try { c.removeSeries(1); fail("IllegalArgumentException should have been thrown on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds.", e.getMessage()); } } /** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */ @Test public void test1170825() { YIntervalSeries s1 = new YIntervalSeries("Series1"); YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); dataset.addSeries(s1); try { /* XYSeries s = */ dataset.getSeries(1); fail("Should have thrown an IllegalArgumentException on index out of range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } } }
6,492
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CategoryTableXYDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/CategoryTableXYDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------------- * CategoryTableXYDatasetTests.java * -------------------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 06-Oct-2005 : Version 1 (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; /** * Tests for the {@link CategoryTableXYDataset} class. */ public class CategoryTableXYDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { CategoryTableXYDataset d1 = new CategoryTableXYDataset(); d1.add(1.0, 1.1, "Series 1"); d1.add(2.0, 2.2, "Series 1"); CategoryTableXYDataset d2 = new CategoryTableXYDataset(); d2.add(1.0, 1.1, "Series 1"); d2.add(2.0, 2.2, "Series 1"); assertEquals(d1, d2); assertEquals(d2, d1); d1.add(3.0, 3.3, "Series 1"); assertFalse(d1.equals(d2)); d2.add(3.0, 3.3, "Series 1"); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { CategoryTableXYDataset d1 = new CategoryTableXYDataset(); d1.add(1.0, 1.1, "Series 1"); d1.add(2.0, 2.2, "Series 1"); CategoryTableXYDataset d2 = (CategoryTableXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); d1.add(3.0, 3.3, "Series 1"); assertFalse(d1.equals(d2)); d2.add(3.0, 3.3, "Series 1"); assertEquals(d1, d2); d1.setIntervalPositionFactor(0.33); assertFalse(d1.equals(d2)); d2.setIntervalPositionFactor(0.33); assertEquals(d1, d2); } /** * Another check for cloning - making sure it works for a customised * interval delegate. */ @Test public void testCloning2() throws CloneNotSupportedException { CategoryTableXYDataset d1 = new CategoryTableXYDataset(); d1.add(1.0, 1.1, "Series 1"); d1.add(2.0, 2.2, "Series 1"); d1.setIntervalWidth(1.23); CategoryTableXYDataset d2 = (CategoryTableXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); d1.add(3.0, 3.3, "Series 1"); assertFalse(d1.equals(d2)); d2.add(3.0, 3.3, "Series 1"); assertEquals(d1, d2); d1.setIntervalPositionFactor(0.33); assertFalse(d1.equals(d2)); d2.setIntervalPositionFactor(0.33); assertEquals(d1, d2); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { CategoryTableXYDataset d1 = new CategoryTableXYDataset(); assertTrue(d1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { CategoryTableXYDataset d1 = new CategoryTableXYDataset(); d1.add(1.0, 1.1, "Series 1"); d1.add(2.0, 2.2, "Series 1"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); CategoryTableXYDataset d2 = (CategoryTableXYDataset) in.readObject(); in.close(); assertEquals(d1, d2); } private static final double EPSILON = 0.0000000001; /** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */ @Test public void testAddSeries() { CategoryTableXYDataset d1 = new CategoryTableXYDataset(); d1.setAutoWidth(true); d1.add(3.0, 1.1, "Series 1"); d1.add(7.0, 2.2, "Series 1"); assertEquals(3.0, d1.getXValue(0, 0), EPSILON); assertEquals(7.0, d1.getXValue(0, 1), EPSILON); assertEquals(1.0, d1.getStartXValue(0, 0), EPSILON); assertEquals(5.0, d1.getStartXValue(0, 1), EPSILON); assertEquals(5.0, d1.getEndXValue(0, 0), EPSILON); assertEquals(9.0, d1.getEndXValue(0, 1), EPSILON); // now add some more data d1.add(7.5, 1.1, "Series 2"); d1.add(9.0, 2.2, "Series 2"); assertEquals(3.0, d1.getXValue(1, 0), EPSILON); assertEquals(7.0, d1.getXValue(1, 1), EPSILON); assertEquals(7.5, d1.getXValue(1, 2), EPSILON); assertEquals(9.0, d1.getXValue(1, 3), EPSILON); assertEquals(7.25, d1.getStartXValue(1, 2), EPSILON); assertEquals(8.75, d1.getStartXValue(1, 3), EPSILON); assertEquals(7.75, d1.getEndXValue(1, 2), EPSILON); assertEquals(9.25, d1.getEndXValue(1, 3), EPSILON); // and check the first series too... assertEquals(2.75, d1.getStartXValue(0, 0), EPSILON); assertEquals(6.75, d1.getStartXValue(0, 1), EPSILON); assertEquals(3.25, d1.getEndXValue(0, 0), EPSILON); assertEquals(7.25, d1.getEndXValue(0, 1), EPSILON); } }
7,255
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYBarDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/XYBarDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * XYBarDatasetTests.java * ---------------------- * (C) Copyright 2007, 2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Jan-2007 : Version 1 (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; /** * Some tests for the {@link XYBarDataset} class. */ public class XYBarDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultXYDataset d1 = new DefaultXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; d1.addSeries("S1", data1); DefaultXYDataset d2 = new DefaultXYDataset(); double[] x2 = new double[] {1.0, 2.0, 3.0}; double[] y2 = new double[] {4.0, 5.0, 6.0}; double[][] data2 = new double[][] {x2, y2}; d2.addSeries("S1", data2); XYBarDataset bd1 = new XYBarDataset(d1, 5.0); XYBarDataset bd2 = new XYBarDataset(d2, 5.0); assertEquals(bd1, bd2); assertEquals(bd2, bd1); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultXYDataset d1 = new DefaultXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; d1.addSeries("S1", data1); XYBarDataset bd1 = new XYBarDataset(d1, 5.0); XYBarDataset bd2 = (XYBarDataset) bd1.clone(); assertNotSame(bd1, bd2); assertSame(bd1.getClass(), bd2.getClass()); assertEquals(bd1, bd2); // check independence d1 = (DefaultXYDataset) bd1.getUnderlyingDataset(); d1.addSeries("S2", new double[][] {{1.0}, {2.0}}); assertFalse(bd1.equals(bd2)); DefaultXYDataset d2 = (DefaultXYDataset) bd2.getUnderlyingDataset(); d2.addSeries("S2", new double[][] {{1.0}, {2.0}}); assertEquals(bd1, bd2); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { DefaultXYDataset d1 = new DefaultXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; d1.addSeries("S1", data1); XYBarDataset bd1 = new XYBarDataset(d1, 5.0); assertTrue(bd1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultXYDataset d1 = new DefaultXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; d1.addSeries("S1", data1); XYBarDataset bd1 = new XYBarDataset(d1, 5.0); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(bd1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); XYBarDataset bd2 = (XYBarDataset) in.readObject(); in.close(); assertEquals(bd1, bd2); } }
5,400
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultXYDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/DefaultXYDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * DefaultXYDatasetTests.java * -------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 06-Jul-2006 : Version 1 (DG); * 02-Nov-2006 : Added testAddSeries() method (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for {@link DefaultXYDataset}. */ public class DefaultXYDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultXYDataset d1 = new DefaultXYDataset(); DefaultXYDataset d2 = new DefaultXYDataset(); assertEquals(d1, d2); assertEquals(d2, d1); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; double[] x2 = new double[] {1.0, 2.0, 3.0}; double[] y2 = new double[] {4.0, 5.0, 6.0}; double[][] data2 = new double[][] {x2, y2}; d1.addSeries("S1", data1); assertFalse(d1.equals(d2)); d2.addSeries("S1", data2); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultXYDataset d1 = new DefaultXYDataset(); DefaultXYDataset d2 = (DefaultXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // try a dataset with some content... double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; d1.addSeries("S1", data1); d2 = (DefaultXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // check that the clone doesn't share the same underlying arrays. x1[1] = 2.2; assertFalse(d1.equals(d2)); x1[1] = 2.0; assertEquals(d1, d2); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { DefaultXYDataset d1 = new DefaultXYDataset(); assertTrue(d1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultXYDataset d1 = new DefaultXYDataset(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); DefaultXYDataset d2 = (DefaultXYDataset) in.readObject(); in.close(); assertEquals(d1, d2); // try a dataset with some content... double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; d1.addSeries("S1", data1); buffer = new ByteArrayOutputStream(); out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); d2 = (DefaultXYDataset) in.readObject(); in.close(); assertEquals(d1, d2); } /** * Some checks for the getSeriesKey(int) method. */ @Test public void testGetSeriesKey() { DefaultXYDataset d = createSampleDataset1(); assertEquals("S1", d.getSeriesKey(0)); assertEquals("S2", d.getSeriesKey(1)); // check for series key out of bounds try { /*Comparable k =*/ d.getSeriesKey(-1); fail("IllegalArgumentException should have been thrown on negative key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } try { /*Comparable k =*/ d.getSeriesKey(2); fail("IllegalArgumentException should have been thrown on key out or range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } } /** * Some checks for the indexOf(Comparable) method. */ @Test public void testIndexOf() { DefaultXYDataset d = createSampleDataset1(); assertEquals(0, d.indexOf("S1")); assertEquals(1, d.indexOf("S2")); assertEquals(-1, d.indexOf("Green Eggs and Ham")); assertEquals(-1, d.indexOf(null)); } static final double EPSILON = 0.0000000001; /** * Some tests for the addSeries() method. */ @Test public void testAddSeries() { DefaultXYDataset d = new DefaultXYDataset(); d.addSeries("S1", new double[][] {{1.0}, {2.0}}); assertEquals(1, d.getSeriesCount()); assertEquals("S1", d.getSeriesKey(0)); // check that adding a series will overwrite the old series d.addSeries("S1", new double[][] {{11.0}, {12.0}}); assertEquals(1, d.getSeriesCount()); assertEquals(12.0, d.getYValue(0, 0), EPSILON); // check null key try { d.addSeries(null, new double[][] {{1.0}, {2.0}}); fail("IllegalArgumentException should have been thrown on null key"); } catch (IllegalArgumentException e) { assertEquals("The 'seriesKey' cannot be null.", e.getMessage()); } } /** * Creates a sample dataset for testing. * * @return A sample dataset. */ public DefaultXYDataset createSampleDataset1() { DefaultXYDataset d = new DefaultXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[][] data1 = new double[][] {x1, y1}; d.addSeries("S1", data1); double[] x2 = new double[] {1.0, 2.0, 3.0}; double[] y2 = new double[] {4.0, 5.0, 6.0}; double[][] data2 = new double[][] {x2, y2}; d.addSeries("S2", data2); return d; } }
8,341
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultIntervalXYDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/DefaultIntervalXYDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------------- * DefaultIntervalXYDatasetTests.java * ---------------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Oct-2006 : Version 1 (DG); * 02-Nov-2006 : Added testAddSeries() method (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Some tests for the {@link DefaultIntervalXYDataset} class. */ public class DefaultIntervalXYDatasetTest { /** * Some checks for the getSeriesCount() method. */ @Test public void testGetSeriesCount() { DefaultIntervalXYDataset d = new DefaultIntervalXYDataset(); assertEquals(0, d.getSeriesCount()); d = createSampleDataset1(); assertEquals(2, d.getSeriesCount()); } /** * Some checks for the getSeriesKey(int) method. */ @Test public void testGetSeriesKey() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals("S1", d.getSeriesKey(0)); assertEquals("S2", d.getSeriesKey(1)); // check for series key out of bounds try { /*Comparable k =*/ d.getSeriesKey(-1); fail("IllegalArgumentException should have been thrown on negative key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } try { /*Comparable k =*/ d.getSeriesKey(2); fail("IllegalArgumentException should have been thrown on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } } /** * Some checks for the getItemCount() method. */ @Test public void testGetItemCount() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(3, d.getItemCount(0)); assertEquals(3, d.getItemCount(1)); // try an index out of bounds try { d.getItemCount(2); fail("IllegalArgumentException should have been thrown on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } } private static final double EPSILON = 0.0000000001; /** * Some checks for the getXValue() method. */ @Test public void testGetXValue() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(1.0, d.getXValue(0, 0), EPSILON); assertEquals(2.0, d.getXValue(0, 1), EPSILON); assertEquals(3.0, d.getXValue(0, 2), EPSILON); assertEquals(11.0, d.getXValue(1, 0), EPSILON); assertEquals(12.0, d.getXValue(1, 1), EPSILON); assertEquals(13.0, d.getXValue(1, 2), EPSILON); } /** * Some checks for the getYValue() method. */ @Test public void testGetYValue() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(4.0, d.getYValue(0, 0), EPSILON); assertEquals(5.0, d.getYValue(0, 1), EPSILON); assertEquals(6.0, d.getYValue(0, 2), EPSILON); assertEquals(14.0, d.getYValue(1, 0), EPSILON); assertEquals(15.0, d.getYValue(1, 1), EPSILON); assertEquals(16.0, d.getYValue(1, 2), EPSILON); } /** * Some checks for the getStartXValue() method. */ @Test public void testGetStartXValue() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(0.9, d.getStartXValue(0, 0), EPSILON); assertEquals(1.9, d.getStartXValue(0, 1), EPSILON); assertEquals(2.9, d.getStartXValue(0, 2), EPSILON); assertEquals(10.9, d.getStartXValue(1, 0), EPSILON); assertEquals(11.9, d.getStartXValue(1, 1), EPSILON); assertEquals(12.9, d.getStartXValue(1, 2), EPSILON); } /** * Some checks for the getEndXValue() method. */ @Test public void testGetEndXValue() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(1.1, d.getEndXValue(0, 0), EPSILON); assertEquals(2.1, d.getEndXValue(0, 1), EPSILON); assertEquals(3.1, d.getEndXValue(0, 2), EPSILON); assertEquals(11.1, d.getEndXValue(1, 0), EPSILON); assertEquals(12.1, d.getEndXValue(1, 1), EPSILON); assertEquals(13.1, d.getEndXValue(1, 2), EPSILON); } /** * Some checks for the getStartYValue() method. */ @Test public void testGetStartYValue() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(1.09, d.getStartYValue(0, 0), EPSILON); assertEquals(2.09, d.getStartYValue(0, 1), EPSILON); assertEquals(3.09, d.getStartYValue(0, 2), EPSILON); assertEquals(11.09, d.getStartYValue(1, 0), EPSILON); assertEquals(12.09, d.getStartYValue(1, 1), EPSILON); assertEquals(13.09, d.getStartYValue(1, 2), EPSILON); } /** * Some checks for the getEndYValue() method. */ @Test public void testGetEndYValue() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(1.11, d.getEndYValue(0, 0), EPSILON); assertEquals(2.11, d.getEndYValue(0, 1), EPSILON); assertEquals(3.11, d.getEndYValue(0, 2), EPSILON); assertEquals(11.11, d.getEndYValue(1, 0), EPSILON); assertEquals(12.11, d.getEndYValue(1, 1), EPSILON); assertEquals(13.11, d.getEndYValue(1, 2), EPSILON); } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultIntervalXYDataset d1 = new DefaultIntervalXYDataset(); DefaultIntervalXYDataset d2 = new DefaultIntervalXYDataset(); assertEquals(d1, d2); assertEquals(d2, d1); d1 = createSampleDataset1(); assertFalse(d1.equals(d2)); d2 = createSampleDataset1(); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultIntervalXYDataset d1 = new DefaultIntervalXYDataset(); DefaultIntervalXYDataset d2 = (DefaultIntervalXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // try a dataset with some content... d1 = createSampleDataset1(); d2 = (DefaultIntervalXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Another test for cloning. */ @Test public void testCloning2() throws CloneNotSupportedException { DefaultIntervalXYDataset d1 = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; d1.addSeries("S1", data1); DefaultIntervalXYDataset d2 = (DefaultIntervalXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // check independence x1[0] = 111.1; assertFalse(d1.equals(d2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { DefaultIntervalXYDataset d1 = new DefaultIntervalXYDataset(); assertTrue(d1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultIntervalXYDataset d1 = new DefaultIntervalXYDataset(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); DefaultIntervalXYDataset d2 = (DefaultIntervalXYDataset) in.readObject(); in.close(); assertEquals(d1, d2); // try a dataset with some content... d1 = createSampleDataset1(); buffer = new ByteArrayOutputStream(); out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); d2 = (DefaultIntervalXYDataset) in.readObject(); in.close(); assertEquals(d1, d2); } /** * Some checks for the indexOf(Comparable) method. */ @Test public void testIndexOf() { DefaultIntervalXYDataset d = createSampleDataset1(); assertEquals(0, d.indexOf("S1")); assertEquals(1, d.indexOf("S2")); assertEquals(-1, d.indexOf("Green Eggs and Ham")); assertEquals(-1, d.indexOf(null)); } /** * Some tests for the addSeries() method. */ @Test public void testAddSeries() { DefaultIntervalXYDataset d = new DefaultIntervalXYDataset(); d.addSeries("S1", new double[][] {{1.0}, {0.5}, {1.5}, {2.0}, {2.5}, {1.5}}); assertEquals(1, d.getSeriesCount()); assertEquals("S1", d.getSeriesKey(0)); // check that adding a series will overwrite the old series d.addSeries("S1", new double[][] {{1.1}, {0.6}, {1.6}, {2.1}, {2.6}, {1.6}}); assertEquals(1, d.getSeriesCount()); assertEquals(2.1, d.getYValue(0, 0), EPSILON); // check null key try { d.addSeries(null, new double[][] {{1.1}, {0.6}, {1.6}, {2.1}, {2.6}, {1.6}}); fail("IllegalArgumentException should have been thrown."); } catch (IllegalArgumentException e) { assertEquals("Null 'seriesKey' argument.", e.getMessage()); } } /** * Creates a sample dataset for testing. * * @return A sample dataset. */ public DefaultIntervalXYDataset createSampleDataset1() { DefaultIntervalXYDataset d = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; d.addSeries("S1", data1); double[] x2 = new double[] {11.0, 12.0, 13.0}; double[] x2Start = new double[] {10.9, 11.9, 12.9}; double[] x2End = new double[] {11.1, 12.1, 13.1}; double[] y2 = new double[] {14.0, 15.0, 16.0}; double[] y2Start = new double[] {11.09, 12.09, 13.09}; double[] y2End = new double[] {11.11, 12.11, 13.11}; double[][] data2 = new double[][] {x2, x2Start, x2End, y2, y2Start, y2End}; d.addSeries("S2", data2); return d; } }
13,507
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MatrixSeriesTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/MatrixSeriesTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * MatrixSeriesTests.java * ---------------------- * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 21-May-2004 : Version 1 (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Tests for the {@link MatrixSeries} class. */ public class MatrixSeriesTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { MatrixSeries m1 = new MatrixSeries("Test", 8, 3); m1.update(0, 0, 11.0); m1.update(7, 2, 22.0); MatrixSeries m2 = new MatrixSeries("Test", 8, 3); m2.update(0, 0, 11.0); m2.update(7, 2, 22.0); assertEquals(m1, m2); assertEquals(m2, m1); m1 = new MatrixSeries("Test 2", 8, 3); assertFalse(m1.equals(m2)); m2 = new MatrixSeries("Test 2", 8, 3); assertEquals(m1, m2); m1 = new MatrixSeries("Test 2", 10, 3); assertFalse(m1.equals(m2)); m2 = new MatrixSeries("Test 2", 10, 3); assertEquals(m1, m2); m1 = new MatrixSeries("Test 2", 10, 5); assertFalse(m1.equals(m2)); m2 = new MatrixSeries("Test 2", 10, 5); assertEquals(m1, m2); m1.update(0, 0, 99); assertFalse(m1.equals(m2)); m2.update(0, 0, 99); assertEquals(m1, m2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { MatrixSeries m1 = new MatrixSeries("Test", 8, 3); m1.update(0, 0, 11.0); m1.update(7, 2, 22.0); MatrixSeries m2 = (MatrixSeries) m1.clone(); assertNotSame(m1, m2); assertSame(m1.getClass(), m2.getClass()); assertEquals(m1, m2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { MatrixSeries m1 = new MatrixSeries("Test", 8, 3); m1.update(0, 0, 11.0); m1.update(7, 2, 22.0); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(m1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); MatrixSeries m2 = (MatrixSeries) in.readObject(); in.close(); assertEquals(m1, m2); } /** * Tests the getItemColumn() method. */ @Test public void testGetItemColumn() { MatrixSeries m = new MatrixSeries("Test", 3, 2); assertEquals(0, m.getItemColumn(0)); assertEquals(1, m.getItemColumn(1)); assertEquals(0, m.getItemColumn(2)); assertEquals(1, m.getItemColumn(3)); assertEquals(0, m.getItemColumn(4)); assertEquals(1, m.getItemColumn(5)); } /** * Tests the getItemRow() method. */ @Test public void testGetItemRow() { MatrixSeries m = new MatrixSeries("Test", 3, 2); assertEquals(0, m.getItemRow(0)); assertEquals(0, m.getItemRow(1)); assertEquals(1, m.getItemRow(2)); assertEquals(1, m.getItemRow(3)); assertEquals(2, m.getItemRow(4)); assertEquals(2, m.getItemRow(5)); } /** * Tests the getItem() method. */ @Test public void testGetItem() { MatrixSeries m = new MatrixSeries("Test", 3, 2); m.update(0, 0, 0.0); m.update(0, 1, 1.0); m.update(1, 0, 2.0); m.update(1, 1, 3.0); m.update(2, 0, 4.0); m.update(2, 1, 5.0); assertEquals(0.0, m.getItem(0).doubleValue(), 0.001); assertEquals(1.0, m.getItem(1).doubleValue(), 0.001); assertEquals(2.0, m.getItem(2).doubleValue(), 0.001); assertEquals(3.0, m.getItem(3).doubleValue(), 0.001); assertEquals(4.0, m.getItem(4).doubleValue(), 0.001); assertEquals(5.0, m.getItem(5).doubleValue(), 0.001); } }
5,849
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
YIntervalSeriesTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/YIntervalSeriesTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * YIntervalSeriesTests.java * ------------------------- * (C) Copyright 2006, 2007, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1, based on XYSeriesTests (DG); * 27-Nov-2007 : Added testClear() method (DG); * */ package org.jfree.data.xy; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; /** * Tests for the {@link YIntervalSeries} class. */ public class YIntervalSeriesTest implements SeriesChangeListener { SeriesChangeEvent lastEvent; /** * Records the last event. * * @param event the event. */ @Override public void seriesChanged(SeriesChangeEvent event) { this.lastEvent = event; } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { YIntervalSeries s1 = new YIntervalSeries("s1"); YIntervalSeries s2 = new YIntervalSeries("s1"); assertEquals(s1, s2); // seriesKey s1 = new YIntervalSeries("s2"); assertFalse(s1.equals(s2)); s2 = new YIntervalSeries("s2"); assertEquals(s1, s2); // autoSort s1 = new YIntervalSeries("s2", false, true); assertFalse(s1.equals(s2)); s2 = new YIntervalSeries("s2", false, true); assertEquals(s1, s2); // allowDuplicateValues s1 = new YIntervalSeries("s2", false, false); assertFalse(s1.equals(s2)); s2 = new YIntervalSeries("s2", false, false); assertEquals(s1, s2); // add a value s1.add(1.0, 0.5, 1.5, 2.0); assertFalse(s1.equals(s2)); s2.add(1.0, 0.5, 1.5, 2.0); assertEquals(s2, s1); // add another value s1.add(2.0, 0.5, 1.5, 2.0); assertFalse(s1.equals(s2)); s2.add(2.0, 0.5, 1.5, 2.0); assertEquals(s2, s1); // remove a value s1.remove(1.0); assertFalse(s1.equals(s2)); s2.remove(1.0); assertEquals(s2, s1); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { YIntervalSeries s1 = new YIntervalSeries("s1"); s1.add(1.0, 0.5, 1.5, 2.0); YIntervalSeries s2 = (YIntervalSeries) s1.clone(); assertNotSame(s1, s2); assertSame(s1.getClass(), s2.getClass()); assertEquals(s1, s2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { YIntervalSeries s1 = new YIntervalSeries("s1"); s1.add(1.0, 0.5, 1.5, 2.0); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); YIntervalSeries s2 = (YIntervalSeries) in.readObject(); in.close(); assertEquals(s1, s2); } /** * Simple test for the indexOf() method. */ @Test public void testIndexOf() { YIntervalSeries s1 = new YIntervalSeries("Series 1"); s1.add(1.0, 1.0, 1.0, 2.0); s1.add(2.0, 2.0, 2.0, 3.0); s1.add(3.0, 3.0, 3.0, 4.0); assertEquals(0, s1.indexOf(1.0)); } /** * A check for the indexOf() method for an unsorted series. */ @Test public void testIndexOf2() { YIntervalSeries s1 = new YIntervalSeries("Series 1", false, true); s1.add(1.0, 1.0, 1.0, 2.0); s1.add(3.0, 3.0, 3.0, 3.0); s1.add(2.0, 2.0, 2.0, 2.0); assertEquals(0, s1.indexOf(1.0)); assertEquals(1, s1.indexOf(3.0)); assertEquals(2, s1.indexOf(2.0)); } /** * Simple test for the remove() method. */ @Test public void testRemove() { YIntervalSeries s1 = new YIntervalSeries("Series 1"); s1.add(1.0, 1.0, 1.0, 2.0); s1.add(2.0, 2.0, 2.0, 2.0); s1.add(3.0, 3.0, 3.0, 3.0); assertEquals(3, s1.getItemCount()); s1.remove(2.0); assertEquals(3.0, s1.getX(1)); s1.remove(1.0); assertEquals(3.0, s1.getX(0)); } private static final double EPSILON = 0.0000000001; /** * When items are added with duplicate x-values, we expect them to remain * in the order they were added. */ @Test public void testAdditionOfDuplicateXValues() { YIntervalSeries s1 = new YIntervalSeries("Series 1"); s1.add(1.0, 1.0, 1.0, 1.0); s1.add(2.0, 2.0, 2.0, 2.0); s1.add(2.0, 3.0, 3.0, 3.0); s1.add(2.0, 4.0, 4.0, 4.0); s1.add(3.0, 5.0, 5.0, 5.0); assertEquals(1.0, s1.getYValue(0), EPSILON); assertEquals(2.0, s1.getYValue(1), EPSILON); assertEquals(3.0, s1.getYValue(2), EPSILON); assertEquals(4.0, s1.getYValue(3), EPSILON); assertEquals(5.0, s1.getYValue(4), EPSILON); } /** * Some checks for the add() method for an UNSORTED series. */ @Test public void testAdd() { YIntervalSeries series = new YIntervalSeries("Series", false, true); series.add(5.0, 5.50, 5.50, 5.50); series.add(5.1, 5.51, 5.51, 5.51); series.add(6.0, 6.6, 6.6, 6.6); series.add(3.0, 3.3, 3.3, 3.3); series.add(4.0, 4.4, 4.4, 4.4); series.add(2.0, 2.2, 2.2, 2.2); series.add(1.0, 1.1, 1.1, 1.1); assertEquals(5.5, series.getYValue(0), EPSILON); assertEquals(5.51, series.getYValue(1), EPSILON); assertEquals(6.6, series.getYValue(2), EPSILON); assertEquals(3.3, series.getYValue(3), EPSILON); assertEquals(4.4, series.getYValue(4), EPSILON); assertEquals(2.2, series.getYValue(5), EPSILON); assertEquals(1.1, series.getYValue(6), EPSILON); } /** * A simple check that the maximumItemCount attribute is working. */ @Test public void testSetMaximumItemCount() { YIntervalSeries s1 = new YIntervalSeries("S1"); assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount()); s1.setMaximumItemCount(2); assertEquals(2, s1.getMaximumItemCount()); s1.add(1.0, 1.1, 1.1, 1.1); s1.add(2.0, 2.2, 2.2, 2.2); s1.add(3.0, 3.3, 3.3, 3.3); assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON); assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON); } /** * Check that the maximum item count can be applied retrospectively. */ @Test public void testSetMaximumItemCount2() { YIntervalSeries s1 = new YIntervalSeries("S1"); s1.add(1.0, 1.1, 1.1, 1.1); s1.add(2.0, 2.2, 2.2, 2.2); s1.add(3.0, 3.3, 3.3, 3.3); s1.setMaximumItemCount(2); assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON); assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON); } /** * Some checks for the clear() method. */ @Test public void testClear() { YIntervalSeries s1 = new YIntervalSeries("S1"); s1.addChangeListener(this); s1.clear(); assertNull(this.lastEvent); assertTrue(s1.isEmpty()); s1.add(1.0, 2.0, 3.0, 4.0); assertFalse(s1.isEmpty()); s1.clear(); assertNotNull(this.lastEvent); assertTrue(s1.isEmpty()); } }
9,490
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYDataItemTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/XYDataItemTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * XYDataItemTests.java * -------------------- * (C) Copyright 2003-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Dec-2003 : Version 1 (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Tests for the {@link XYDataItem} class. */ public class XYDataItemTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { XYDataItem i1 = new XYDataItem(1.0, 1.1); XYDataItem i2 = new XYDataItem(1.0, 1.1); assertEquals(i1, i2); assertEquals(i2, i1); i1.setY(new Double(9.9)); assertFalse(i1.equals(i2)); i2.setY(new Double(9.9)); assertEquals(i1, i2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYDataItem i1 = new XYDataItem(1.0, 1.1); XYDataItem i2 = (XYDataItem) i1.clone(); assertNotSame(i1, i2); assertSame(i1.getClass(), i2.getClass()); assertEquals(i1, i2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { XYDataItem i1 = new XYDataItem(1.0, 1.1); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(i1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); XYDataItem i2 = (XYDataItem) in.readObject(); in.close(); assertEquals(i1, i2); } }
3,522
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYIntervalTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/XYIntervalTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * XYIntervalTests.java * -------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests for the {@link XYInterval} class. */ public class XYIntervalTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { XYInterval i1 = new XYInterval(1.0, 2.0, 3.0, 2.5, 3.5); XYInterval i2 = new XYInterval(1.0, 2.0, 3.0, 2.5, 3.5); assertEquals(i1, i2); i1 = new XYInterval(1.1, 2.0, 3.0, 2.5, 3.5); assertFalse(i1.equals(i2)); i2 = new XYInterval(1.1, 2.0, 3.0, 2.5, 3.5); assertEquals(i1, i2); i1 = new XYInterval(1.1, 2.2, 3.0, 2.5, 3.5); assertFalse(i1.equals(i2)); i2 = new XYInterval(1.1, 2.2, 3.0, 2.5, 3.5); assertEquals(i1, i2); i1 = new XYInterval(1.1, 2.2, 3.3, 2.5, 3.5); assertFalse(i1.equals(i2)); i2 = new XYInterval(1.1, 2.2, 3.3, 2.5, 3.5); assertEquals(i1, i2); i1 = new XYInterval(1.1, 2.2, 3.3, 2.6, 3.5); assertFalse(i1.equals(i2)); i2 = new XYInterval(1.1, 2.2, 3.3, 2.6, 3.5); assertEquals(i1, i2); i1 = new XYInterval(1.1, 2.2, 3.3, 2.6, 3.6); assertFalse(i1.equals(i2)); i2 = new XYInterval(1.1, 2.2, 3.3, 2.6, 3.6); assertEquals(i1, i2); } /** * This class is immutable. */ @Test public void testCloning() throws CloneNotSupportedException { XYInterval i1 = new XYInterval(1.0, 2.0, 3.0, 2.5, 3.5); assertFalse(i1 instanceof Cloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { XYInterval i1 = new XYInterval(1.0, 2.0, 3.0, 2.5, 3.5); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(i1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); XYInterval i2 = (XYInterval) in.readObject(); in.close(); assertEquals(i1, i2); } }
4,081
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OHLCDataItemTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/OHLCDataItemTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * OHLCDataItemTests.java * ---------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 29-Apr-2005 : Version 1 (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Date; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests for the {@link OHLCDataItem} class. */ public class OHLCDataItemTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { OHLCDataItem i1 = new OHLCDataItem( new Date(1L), 1.0, 2.0, 3.0, 4.0, 5.0 ); OHLCDataItem i2 = new OHLCDataItem( new Date(1L), 1.0, 2.0, 3.0, 4.0, 5.0 ); assertEquals(i1, i2); assertEquals(i2, i1); } /** * Instances of this class are immutable - cloning not required. */ @Test public void testCloning() throws CloneNotSupportedException { OHLCDataItem i1 = new OHLCDataItem( new Date(1L), 1.0, 2.0, 3.0, 4.0, 5.0 ); assertFalse(i1 instanceof Cloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { OHLCDataItem i1 = new OHLCDataItem( new Date(1L), 1.0, 2.0, 3.0, 4.0, 5.0 ); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(i1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); OHLCDataItem i2 = (OHLCDataItem) in.readObject(); in.close(); assertEquals(i1, i2); } }
3,479
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultXYZDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/DefaultXYZDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * DefaultXYZDatasetTests.java * --------------------------- * (C) Copyright 2006-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 12-Jul-2006 : Version 1 (DG); * 02-Nov-2006 : Added testAddSeries() method (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for {@link DefaultXYZDataset}. */ public class DefaultXYZDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultXYZDataset d1 = new DefaultXYZDataset(); DefaultXYZDataset d2 = new DefaultXYZDataset(); assertEquals(d1, d2); assertEquals(d2, d1); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] z1 = new double[] {7.0, 8.0, 9.0}; double[][] data1 = new double[][] {x1, y1, z1}; double[] x2 = new double[] {1.0, 2.0, 3.0}; double[] y2 = new double[] {4.0, 5.0, 6.0}; double[] z2 = new double[] {7.0, 8.0, 9.0}; double[][] data2 = new double[][] {x2, y2, z2}; d1.addSeries("S1", data1); assertFalse(d1.equals(d2)); d2.addSeries("S1", data2); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultXYZDataset d1 = new DefaultXYZDataset(); DefaultXYZDataset d2 = (DefaultXYZDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // try a dataset with some content... double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] z1 = new double[] {7.0, 8.0, 9.0}; double[][] data1 = new double[][] {x1, y1, z1}; d1.addSeries("S1", data1); d2 = (DefaultXYZDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // check that the clone doesn't share the same underlying arrays. x1[1] = 2.2; assertFalse(d1.equals(d2)); x1[1] = 2.0; assertEquals(d1, d2); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { DefaultXYZDataset d1 = new DefaultXYZDataset(); assertTrue(d1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultXYZDataset d1 = new DefaultXYZDataset(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); DefaultXYZDataset d2 = (DefaultXYZDataset) in.readObject(); in.close(); assertEquals(d1, d2); // try a dataset with some content... double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] z1 = new double[] {7.0, 8.0, 9.0}; double[][] data1 = new double[][] {x1, y1, z1}; d1.addSeries("S1", data1); buffer = new ByteArrayOutputStream(); out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); d2 = (DefaultXYZDataset) in.readObject(); in.close(); assertEquals(d1, d2); } /** * Some checks for the getSeriesKey(int) method. */ @Test public void testGetSeriesKey() { DefaultXYZDataset d = createSampleDataset1(); assertEquals("S1", d.getSeriesKey(0)); assertEquals("S2", d.getSeriesKey(1)); // check for series key out of bounds try { /*Comparable k =*/ d.getSeriesKey(-1); fail("IllegalArgumentException should have been thrown on negative key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } try { /*Comparable k =*/ d.getSeriesKey(2); fail("IllegalArgumentException should have been thrown on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } } /** * Some checks for the indexOf(Comparable) method. */ @Test public void testIndexOf() { DefaultXYZDataset d = createSampleDataset1(); assertEquals(0, d.indexOf("S1")); assertEquals(1, d.indexOf("S2")); assertEquals(-1, d.indexOf("Green Eggs and Ham")); assertEquals(-1, d.indexOf(null)); } static final double EPSILON = 0.0000000001; /** * Some tests for the addSeries() method. */ @Test public void testAddSeries() { DefaultXYZDataset d = new DefaultXYZDataset(); d.addSeries("S1", new double[][] {{1.0}, {2.0}, {3.0}}); assertEquals(1, d.getSeriesCount()); assertEquals("S1", d.getSeriesKey(0)); // check that adding a series will overwrite the old series d.addSeries("S1", new double[][] {{11.0}, {12.0}, {13.0}}); assertEquals(1, d.getSeriesCount()); assertEquals(12.0, d.getYValue(0, 0), EPSILON); // check null key try { d.addSeries(null, new double[][] {{1.0}, {2.0}, {3.0}}); fail("IllegalArgumentException should have been thrown on null key"); } catch (IllegalArgumentException e) { assertEquals("Null 'seriesKey' argument.", e.getMessage()); } } /** * Creates a sample dataset for testing. * * @return A sample dataset. */ public DefaultXYZDataset createSampleDataset1() { DefaultXYZDataset d = new DefaultXYZDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] z1 = new double[] {7.0, 8.0, 9.0}; double[][] data1 = new double[][] {x1, y1, z1}; d.addSeries("S1", data1); double[] x2 = new double[] {1.0, 2.0, 3.0}; double[] y2 = new double[] {4.0, 5.0, 6.0}; double[] z2 = new double[] {7.0, 8.0, 9.0}; double[][] data2 = new double[][] {x2, y2, z2}; d.addSeries("S2", data2); return d; } }
8,689
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IntervalXYDelegateTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/IntervalXYDelegateTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * IntervalXYDelegateTests.java * ---------------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 21-Feb-2005 : Version 1 (DG); * 06-Oct-2005 : Updated for testEquals() for method name change (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Some checks for the {@link IntervalXYDelegate} class. */ public class IntervalXYDelegateTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { XYSeries s1 = new XYSeries("Series"); s1.add(1.2, 3.4); XYSeriesCollection c1 = new XYSeriesCollection(); c1.addSeries(s1); IntervalXYDelegate d1 = new IntervalXYDelegate(c1); XYSeries s2 = new XYSeries("Series"); XYSeriesCollection c2 = new XYSeriesCollection(); s2.add(1.2, 3.4); c2.addSeries(s2); IntervalXYDelegate d2 = new IntervalXYDelegate(c2); assertEquals(d1, d2); assertEquals(d2, d1); d1.setAutoWidth(false); assertFalse(d1.equals(d2)); d2.setAutoWidth(false); assertEquals(d1, d2); d1.setIntervalPositionFactor(0.123); assertFalse(d1.equals(d2)); d2.setIntervalPositionFactor(0.123); assertEquals(d1, d2); d1.setFixedIntervalWidth(1.23); assertFalse(d1.equals(d2)); d2.setFixedIntervalWidth(1.23); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XYSeries s1 = new XYSeries("Series"); s1.add(1.2, 3.4); XYSeriesCollection c1 = new XYSeriesCollection(); c1.addSeries(s1); IntervalXYDelegate d1 = new IntervalXYDelegate(c1); IntervalXYDelegate d2 = (IntervalXYDelegate) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { XYSeries s1 = new XYSeries("Series"); s1.add(1.2, 3.4); XYSeriesCollection c1 = new XYSeriesCollection(); c1.addSeries(s1); IntervalXYDelegate d1 = new IntervalXYDelegate(c1); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); IntervalXYDelegate d2 = (IntervalXYDelegate) in.readObject(); in.close(); assertEquals(d1, d2); } }
4,619
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYCoordinateTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/XYCoordinateTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * XYCoordinateTests.java * ---------------------- * (C) Copyright 2007, 2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 30-Jan-2007 : Version 1 (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests for the {@link XYCoordinate} class. */ public class XYCoordinateTest { /** * Test that the equals() method distinguishes all fields. */ @Test public void testEquals() { // default instances XYCoordinate v1 = new XYCoordinate(1.0, 2.0); XYCoordinate v2 = new XYCoordinate(1.0, 2.0); assertEquals(v1, v2); assertEquals(v2, v1); v1 = new XYCoordinate(1.1, 2.0); assertFalse(v1.equals(v2)); v2 = new XYCoordinate(1.1, 2.0); assertEquals(v1, v2); v1 = new XYCoordinate(1.1, 2.2); assertFalse(v1.equals(v2)); v2 = new XYCoordinate(1.1, 2.2); assertEquals(v1, v2); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { XYCoordinate v1 = new XYCoordinate(1.0, 2.0); XYCoordinate v2 = new XYCoordinate(1.0, 2.0); assertEquals(v1, v2); int h1 = v1.hashCode(); int h2 = v2.hashCode(); assertEquals(h1, h2); } /** * Immutable class is not cloneable. */ @Test public void testCloning() throws CloneNotSupportedException { XYCoordinate v1 = new XYCoordinate(1.0, 2.0); assertFalse(v1 instanceof Cloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { XYCoordinate v1 = new XYCoordinate(1.0, 2.0); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(v1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); XYCoordinate v2 = (XYCoordinate) in.readObject(); in.close(); assertEquals(v1, v2); } }
3,901
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XIntervalSeriesCollectionTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/XIntervalSeriesCollectionTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------------- * XIntervalSeriesCollectionTests.java * ----------------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * 18-Jan-2008 : Added testRemoveSeries() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link XIntervalSeriesCollection} class. */ public class XIntervalSeriesCollectionTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { XIntervalSeriesCollection c1 = new XIntervalSeriesCollection(); XIntervalSeriesCollection c2 = new XIntervalSeriesCollection(); assertEquals(c1, c2); // add a series XIntervalSeries s1 = new XIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); c1.addSeries(s1); assertFalse(c1.equals(c2)); XIntervalSeries s2 = new XIntervalSeries("Series"); s2.add(1.0, 1.1, 1.2, 1.3); c2.addSeries(s2); assertEquals(c1, c2); // add an empty series c1.addSeries(new XIntervalSeries("Empty Series")); assertFalse(c1.equals(c2)); c2.addSeries(new XIntervalSeries("Empty Series")); assertEquals(c1, c2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { XIntervalSeriesCollection c1 = new XIntervalSeriesCollection(); XIntervalSeries s1 = new XIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); c1.addSeries(s1); XIntervalSeriesCollection c2 = (XIntervalSeriesCollection) c1.clone(); assertNotSame(c1, c2); assertSame(c1.getClass(), c2.getClass()); assertEquals(c1, c2); // check independence s1.setDescription("XYZ"); assertFalse(c1.equals(c2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { XIntervalSeriesCollection c1 = new XIntervalSeriesCollection(); assertTrue(c1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { XIntervalSeriesCollection c1 = new XIntervalSeriesCollection(); XIntervalSeries s1 = new XIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(c1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); XIntervalSeriesCollection c2 = (XIntervalSeriesCollection) in.readObject(); in.close(); assertEquals(c1, c2); } /** * Some basic checks for the removeSeries() method. */ @Test public void testRemoveSeries() { XIntervalSeriesCollection c = new XIntervalSeriesCollection(); XIntervalSeries s1 = new XIntervalSeries("s1"); c.addSeries(s1); c.removeSeries(0); assertEquals(0, c.getSeriesCount()); c.addSeries(s1); try { c.removeSeries(-1); fail("IllegalArgumentException should have been thrown on negative key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds.", e.getMessage()); } try { c.removeSeries(1); fail("IllegalArgumentException should have been thrown on key out of range key"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds.", e.getMessage()); } } /** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */ @Test public void test1170825() { XIntervalSeries s1 = new XIntervalSeries("Series1"); XIntervalSeriesCollection dataset = new XIntervalSeriesCollection(); dataset.addSeries(s1); try { /* XYSeries s = */ dataset.getSeries(1); fail("Should have thrown an IllegalArgumentException on index out of bounds"); } catch (IllegalArgumentException e) { assertEquals("Series index out of bounds", e.getMessage()); } } }
6,497
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultWindDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/DefaultWindDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * DefaultWindDatasetTests.java * ---------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 12-Jul-2006 : Version 1 (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.time.Day; import org.jfree.data.time.RegularTimePeriod; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for {@link DefaultWindDataset}. */ public class DefaultWindDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultWindDataset d1 = new DefaultWindDataset(); DefaultWindDataset d2 = new DefaultWindDataset(); assertEquals(d1, d2); assertEquals(d2, d1); d1 = createSampleDataset1(); assertFalse(d1.equals(d2)); d2 = createSampleDataset1(); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultWindDataset d1 = new DefaultWindDataset(); DefaultWindDataset d2 = (DefaultWindDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); // try a dataset with some content... d1 = createSampleDataset1(); d2 = (DefaultWindDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { DefaultWindDataset d1 = new DefaultWindDataset(); assertTrue(d1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultWindDataset d1 = new DefaultWindDataset(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); DefaultWindDataset d2 = (DefaultWindDataset) in.readObject(); in.close(); assertEquals(d1, d2); // try a dataset with some content... d1 = createSampleDataset1(); buffer = new ByteArrayOutputStream(); out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); d2 = (DefaultWindDataset) in.readObject(); in.close(); assertEquals(d1, d2); } /** * Some checks for the getSeriesKey(int) method. */ @Test public void testGetSeriesKey() { DefaultWindDataset d = createSampleDataset1(); assertEquals("Series 1", d.getSeriesKey(0)); assertEquals("Series 2", d.getSeriesKey(1)); // check for series key out of bounds try { /*Comparable k =*/ d.getSeriesKey(-1); fail("IllegalArgumentException should have been thrown on negative key"); } catch (IllegalArgumentException e) { assertEquals("Invalid series index: -1", e.getMessage()); } try { /*Comparable k =*/ d.getSeriesKey(2); fail("IllegalArgumentException should have been thrown on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Invalid series index: 2", e.getMessage()); } } /** * Some checks for the indexOf(Comparable) method. */ @Test public void testIndexOf() { DefaultWindDataset d = createSampleDataset1(); assertEquals(0, d.indexOf("Series 1")); assertEquals(1, d.indexOf("Series 2")); assertEquals(-1, d.indexOf("Green Eggs and Ham")); assertEquals(-1, d.indexOf(null)); } /** * Creates a sample dataset for testing. * * @return A sample dataset. */ public DefaultWindDataset createSampleDataset1() { Day t = new Day(1, 4, 2006); Object[] item1 = createItem(t, 3, 7); Object[] item2 = createItem(t.next(), 4, 8); Object[] item3 = createItem(t.next(), 5, 9); Object[][] series1 = new Object[][] {item1, item2, item3}; Object[] item1b = createItem(t, 6, 10); Object[] item2b = createItem(t.next(), 7, 11); Object[] item3b = createItem(t.next(), 8, 12); Object[][] series2 = new Object[][] {item1b, item2b, item3b}; Object[][][] data = new Object[][][] {series1, series2}; return new DefaultWindDataset(data); } /** * Creates an array representing one item in a series. * * @param t the time period. * @param dir the wind direction. * @param force the wind force. * * @return An array containing the specified items. */ private Object[] createItem(RegularTimePeriod t, int dir, int force) { return new Object[] {t.getMiddleMillisecond(), dir, force}; } }
7,217
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultTableXYDatasetTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/DefaultTableXYDatasetTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------- * DefaultTableXYDatasetTests.java * ------------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Dec-2003 : Version 1 (DG); * 06-Oct-2005 : Added test for new data updating interval width (DG); * 08-Mar-2007 : Added testGetSeries() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for the {@link DefaultTableXYDataset} class. */ public class DefaultTableXYDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.1); s1.add(2.0, 2.2); d1.addSeries(s1); DefaultTableXYDataset d2 = new DefaultTableXYDataset(); XYSeries s2 = new XYSeries("Series 1", true, false); s2.add(1.0, 1.1); s2.add(2.0, 2.2); d2.addSeries(s2); assertEquals(d1, d2); assertEquals(d2, d1); s1.add(3.0, 3.3); assertFalse(d1.equals(d2)); s2.add(3.0, 3.3); assertEquals(d1, d2); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.1); s1.add(2.0, 2.2); d1.addSeries(s1); DefaultTableXYDataset d2 = (DefaultTableXYDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); s1.add(3.0, 3.3); assertFalse(d1.equals(d2)); } /** * Verify that this class implements {@link PublicCloneable}. */ @Test public void testPublicCloneable() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); assertTrue(d1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.1); s1.add(2.0, 2.2); d1.addSeries(s1); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); DefaultTableXYDataset d2 = (DefaultTableXYDataset) in.readObject(); in.close(); assertEquals(d1, d2); } private static final double EPSILON = 0.0000000001; /** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */ @Test public void testAddSeries() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); d1.setAutoWidth(true); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(3.0, 1.1); s1.add(7.0, 2.2); d1.addSeries(s1); assertEquals(3.0, d1.getXValue(0, 0), EPSILON); assertEquals(7.0, d1.getXValue(0, 1), EPSILON); assertEquals(1.0, d1.getStartXValue(0, 0), EPSILON); assertEquals(5.0, d1.getStartXValue(0, 1), EPSILON); assertEquals(5.0, d1.getEndXValue(0, 0), EPSILON); assertEquals(9.0, d1.getEndXValue(0, 1), EPSILON); // now add another series XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(7.5, 1.1); s2.add(9.0, 2.2); d1.addSeries(s2); assertEquals(3.0, d1.getXValue(1, 0), EPSILON); assertEquals(7.0, d1.getXValue(1, 1), EPSILON); assertEquals(7.5, d1.getXValue(1, 2), EPSILON); assertEquals(9.0, d1.getXValue(1, 3), EPSILON); assertEquals(7.25, d1.getStartXValue(1, 2), EPSILON); assertEquals(8.75, d1.getStartXValue(1, 3), EPSILON); assertEquals(7.75, d1.getEndXValue(1, 2), EPSILON); assertEquals(9.25, d1.getEndXValue(1, 3), EPSILON); // and check the first series too... assertEquals(2.75, d1.getStartXValue(0, 0), EPSILON); assertEquals(6.75, d1.getStartXValue(0, 1), EPSILON); assertEquals(3.25, d1.getEndXValue(0, 0), EPSILON); assertEquals(7.25, d1.getEndXValue(0, 1), EPSILON); } /** * Some basic checks for the getSeries() method. */ @Test public void testGetSeries() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); d1.addSeries(s1); assertEquals("Series 1", d1.getSeries(0).getKey()); try { d1.getSeries(-1); fail("IllegalArgumentException should have been thrown on negative key"); } catch (IllegalArgumentException e) { assertEquals("Index outside valid range.", e.getMessage()); } try { d1.getSeries(1); fail("IllegalArgumentException should have been thrown on key out of range"); } catch (IllegalArgumentException e) { assertEquals("Index outside valid range.", e.getMessage()); } } }
7,511
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XIntervalDataItemTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/XIntervalDataItemTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * XIntervalDataItemTests.java * --------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * */ package org.jfree.data.xy; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; /** * Tests for the {@link XIntervalDataItem} class. */ public class XIntervalDataItemTest { private static final double EPSILON = 0.00000000001; /** * Some checks for the constructor. */ @Test public void testConstructor1() { XIntervalDataItem item1 = new XIntervalDataItem(1.0, 2.0, 3.0, 4.0); assertEquals(1.0, item1.getX()); assertEquals(2.0, item1.getXLowValue(), EPSILON); assertEquals(3.0, item1.getXHighValue(), EPSILON); assertEquals(4.0, item1.getYValue(), EPSILON); } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { XIntervalDataItem item1 = new XIntervalDataItem(1.0, 2.0, 3.0, 4.0); XIntervalDataItem item2 = new XIntervalDataItem(1.0, 2.0, 3.0, 4.0); assertEquals(item1, item2); assertEquals(item2, item1); // x item1 = new XIntervalDataItem(1.1, 2.0, 3.0, 4.0); assertFalse(item1.equals(item2)); item2 = new XIntervalDataItem(1.1, 2.0, 3.0, 4.0); assertEquals(item1, item2); // xLow item1 = new XIntervalDataItem(1.1, 2.2, 3.0, 4.0); assertFalse(item1.equals(item2)); item2 = new XIntervalDataItem(1.1, 2.2, 3.0, 4.0); assertEquals(item1, item2); // xHigh item1 = new XIntervalDataItem(1.1, 2.2, 3.3, 4.0); assertFalse(item1.equals(item2)); item2 = new XIntervalDataItem(1.1, 2.2, 3.3, 4.0); assertEquals(item1, item2); // y item1 = new XIntervalDataItem(1.1, 2.2, 3.3, 4.4); assertFalse(item1.equals(item2)); item2 = new XIntervalDataItem(1.1, 2.2, 3.3, 4.4); assertEquals(item1, item2); } /** * Some checks for the clone() method. */ @Test public void testCloning() throws CloneNotSupportedException { XIntervalDataItem item1 = new XIntervalDataItem(1.0, 2.0, 3.0, 4.0); XIntervalDataItem item2 = (XIntervalDataItem) item1.clone(); assertNotSame(item1, item2); assertSame(item1.getClass(), item2.getClass()); assertEquals(item1, item2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { XIntervalDataItem item1 = new XIntervalDataItem(1.0, 2.0, 3.0, 4.0); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(item1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); XIntervalDataItem item2 = (XIntervalDataItem) in.readObject(); in.close(); assertEquals(item1, item2); } }
4,888
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
VectorSeriesTest.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/test/java/org/jfree/data/xy/VectorSeriesTest.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * VectorSeriesTests.java * ---------------------- * (C) Copyright 2007, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 30-Jan-2007 : Version 1, based on XYSeriesTests (DG); * 24-May-2007 : Updated for modified method names (DG); * 27-Nov-2007 : Added testClear() method (DG); * */ package org.jfree.data.xy; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; /** * Tests for the {@link VectorSeries} class. */ public class VectorSeriesTest implements SeriesChangeListener { SeriesChangeEvent lastEvent; /** * Records the last event. * * @param event the event. */ @Override public void seriesChanged(SeriesChangeEvent event) { this.lastEvent = event; } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { VectorSeries s1 = new VectorSeries("s1"); VectorSeries s2 = new VectorSeries("s1"); assertEquals(s1, s2); // seriesKey s1 = new VectorSeries("s2"); assertFalse(s1.equals(s2)); s2 = new VectorSeries("s2"); assertEquals(s1, s2); // autoSort s1 = new VectorSeries("s2", true, true); assertFalse(s1.equals(s2)); s2 = new VectorSeries("s2", true, true); assertEquals(s1, s2); // allowDuplicateValues s1 = new VectorSeries("s2", false, false); assertFalse(s1.equals(s2)); s2 = new VectorSeries("s2", false, false); assertEquals(s1, s2); // add a value s1.add(1.0, 0.5, 1.5, 2.0); assertFalse(s1.equals(s2)); s2.add(1.0, 0.5, 1.5, 2.0); assertEquals(s2, s1); // add another value s1.add(2.0, 0.5, 1.5, 2.0); assertFalse(s1.equals(s2)); s2.add(2.0, 0.5, 1.5, 2.0); assertEquals(s2, s1); // remove a value s1.remove(new XYCoordinate(1.0, 0.5)); assertFalse(s1.equals(s2)); s2.remove(new XYCoordinate(1.0, 0.5)); assertEquals(s2, s1); } /** * Confirm that cloning works. */ @Test public void testCloning() throws CloneNotSupportedException { VectorSeries s1 = new VectorSeries("s1"); s1.add(1.0, 0.5, 1.5, 2.0); VectorSeries s2 = (VectorSeries) s1.clone(); assertNotSame(s1, s2); assertSame(s1.getClass(), s2.getClass()); assertEquals(s1, s2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { VectorSeries s1 = new VectorSeries("s1"); s1.add(1.0, 0.5, 1.5, 2.0); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); VectorSeries s2 = (VectorSeries) in.readObject(); in.close(); assertEquals(s1, s2); } /** * Simple test for the indexOf() method. */ @Test public void testIndexOf() { VectorSeries s1 = new VectorSeries("Series 1"); s1.add(1.0, 1.0, 1.0, 2.0); s1.add(2.0, 2.0, 2.0, 3.0); s1.add(3.0, 3.0, 3.0, 4.0); assertEquals(0, s1.indexOf(new XYCoordinate(1.0, 1.0))); } /** * A check for the indexOf() method for an unsorted series. */ @Test public void testIndexOf2() { VectorSeries s1 = new VectorSeries("Series 1"); s1.add(1.0, 1.0, 1.0, 2.0); s1.add(3.0, 3.0, 3.0, 3.0); s1.add(2.0, 2.0, 2.0, 2.0); assertEquals(0, s1.indexOf(new XYCoordinate(1.0, 1.0))); assertEquals(1, s1.indexOf(new XYCoordinate(3.0, 3.0))); assertEquals(2, s1.indexOf(new XYCoordinate(2.0, 2.0))); } /** * Simple test for the remove() method. */ @Test public void testRemove() { VectorSeries s1 = new VectorSeries("Series 1"); s1.add(1.0, 1.0, 1.0, 2.0); s1.add(3.0, 3.0, 3.0, 3.0); s1.add(2.0, 2.0, 2.0, 2.0); assertEquals(3, s1.getItemCount()); s1.remove(new XYCoordinate(2.0, 2.0)); assertEquals(3.0, s1.getXValue(1), EPSILON); s1.remove(new XYCoordinate(1.0, 1.0)); assertEquals(3.0, s1.getXValue(0), EPSILON); } private static final double EPSILON = 0.0000000001; /** * When items are added with duplicate x-values, we expect them to remain * in the order they were added. */ @Test public void testAdditionOfDuplicateXValues() { VectorSeries s1 = new VectorSeries("Series 1"); s1.add(1.0, 1.0, 1.0, 1.0); s1.add(2.0, 2.0, 2.0, 2.0); s1.add(2.0, 2.0, 3.0, 3.0); s1.add(2.0, 3.0, 4.0, 4.0); s1.add(3.0, 5.0, 5.0, 5.0); assertEquals(1.0, s1.getVectorXValue(0), EPSILON); assertEquals(2.0, s1.getVectorXValue(1), EPSILON); assertEquals(3.0, s1.getVectorXValue(2), EPSILON); assertEquals(4.0, s1.getVectorXValue(3), EPSILON); assertEquals(5.0, s1.getVectorXValue(4), EPSILON); } /** * Some checks for the add() method for an UNSORTED series. */ @Test public void testAdd() { VectorSeries series = new VectorSeries("Series", false, true); series.add(5.0, 5.50, 5.50, 5.50); series.add(5.1, 5.51, 5.51, 5.51); series.add(6.0, 6.6, 6.6, 6.6); series.add(3.0, 3.3, 3.3, 3.3); series.add(4.0, 4.4, 4.4, 4.4); series.add(2.0, 2.2, 2.2, 2.2); series.add(1.0, 1.1, 1.1, 1.1); assertEquals(5.5, series.getVectorXValue(0), EPSILON); assertEquals(5.51, series.getVectorXValue(1), EPSILON); assertEquals(6.6, series.getVectorXValue(2), EPSILON); assertEquals(3.3, series.getVectorXValue(3), EPSILON); assertEquals(4.4, series.getVectorXValue(4), EPSILON); assertEquals(2.2, series.getVectorXValue(5), EPSILON); assertEquals(1.1, series.getVectorXValue(6), EPSILON); } /** * A simple check that the maximumItemCount attribute is working. */ @Test public void testSetMaximumItemCount() { VectorSeries s1 = new VectorSeries("S1"); assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount()); s1.setMaximumItemCount(2); assertEquals(2, s1.getMaximumItemCount()); s1.add(1.0, 1.1, 1.1, 1.1); s1.add(2.0, 2.2, 2.2, 2.2); s1.add(3.0, 3.3, 3.3, 3.3); assertEquals(2.0, s1.getXValue(0), EPSILON); assertEquals(3.0, s1.getXValue(1), EPSILON); } /** * Check that the maximum item count can be applied retrospectively. */ @Test public void testSetMaximumItemCount2() { VectorSeries s1 = new VectorSeries("S1"); s1.add(1.0, 1.1, 1.1, 1.1); s1.add(2.0, 2.2, 2.2, 2.2); s1.add(3.0, 3.3, 3.3, 3.3); s1.setMaximumItemCount(2); assertEquals(2.0, s1.getXValue(0), EPSILON); assertEquals(3.0, s1.getXValue(1), EPSILON); } /** * Some checks for the clear() method. */ @Test public void testClear() { VectorSeries s1 = new VectorSeries("S1"); s1.addChangeListener(this); s1.clear(); assertNull(this.lastEvent); assertTrue(s1.isEmpty()); s1.add(1.0, 2.0, 3.0, 4.0); assertFalse(s1.isEmpty()); s1.clear(); assertNotNull(this.lastEvent); assertTrue(s1.isEmpty()); } }
9,650
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z