language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
Java
|
public class GitHubClient {
//github api url
private static final String API_URL = "https://api.github.com";
//sort the github repos by stars in desc order
static final String DEFAULT_SORT = "stars";
static final String DEFAULT_ORDER = "desc";
//Search result github response
static public class SearchResult {
@SerializedName("total_count")
int totalCount;
@SerializedName("incomplete_results")
boolean incompleteResults;
@SerializedName("items")
List<Repo> repos;
}
//Github repo information
static public class Repo {
public int id;
public String name;
public Owner owner;
@SerializedName("html_url")
public String htmlUrl;
public String description;
@SerializedName("stargazers_count")
public int starsGazers;
@SerializedName("watchers")
public int watchers;
public int forks;
public static class Owner {
String login;
@SerializedName("avatar_url")
public String avatarUrl;
}
}
//Retorfit github interface
interface GitHub {
@GET("/search/repositories?per_page=10")
SearchResult searchRepos(@Query("q") String query,
@Query("sort") String sortBy,
@Query("order") String order,
@Query("page") int start);
}
/**
* Get github client.
*
* @return Github retrofit interface
*/
public static GitHub getClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.setLogLevel(RestAdapter.LogLevel.BASIC)
.build();
return restAdapter.create(GitHub.class);
}
}
|
Java
|
static public class SearchResult {
@SerializedName("total_count")
int totalCount;
@SerializedName("incomplete_results")
boolean incompleteResults;
@SerializedName("items")
List<Repo> repos;
}
|
Java
|
static public class Repo {
public int id;
public String name;
public Owner owner;
@SerializedName("html_url")
public String htmlUrl;
public String description;
@SerializedName("stargazers_count")
public int starsGazers;
@SerializedName("watchers")
public int watchers;
public int forks;
public static class Owner {
String login;
@SerializedName("avatar_url")
public String avatarUrl;
}
}
|
Java
|
@SuppressWarnings("WeakerAccess")
public class ParquetTableMetadataUtils {
static final List<CollectableColumnStatisticsKind> PARQUET_COLUMN_STATISTICS =
ImmutableList.of(
ColumnStatisticsKind.MAX_VALUE,
ColumnStatisticsKind.MIN_VALUE,
ColumnStatisticsKind.NULLS_COUNT);
private ParquetTableMetadataUtils() {
throw new IllegalStateException("Utility class");
}
/**
* Creates new map based on specified {@code columnStatistics} with added statistics
* for implicit and partition (dir) columns.
*
* @param columnsStatistics map of column statistics to expand
* @param columns list of all columns including implicit or partition ones
* @param partitionValues list of partition values
* @param optionManager option manager
* @param location location of metadata part
* @param supportsFileImplicitColumns whether implicit columns are supported
* @return map with added statistics for implicit and partition (dir) columns
*/
public static Map<SchemaPath, ColumnStatistics> addImplicitColumnsStatistics(
Map<SchemaPath, ColumnStatistics> columnsStatistics, List<SchemaPath> columns,
List<String> partitionValues, OptionManager optionManager, Path location, boolean supportsFileImplicitColumns) {
ColumnExplorer columnExplorer = new ColumnExplorer(optionManager, columns);
Map<String, String> implicitColValues = columnExplorer.populateImplicitColumns(
location, partitionValues, supportsFileImplicitColumns);
columnsStatistics = new HashMap<>(columnsStatistics);
for (Map.Entry<String, String> partitionValue : implicitColValues.entrySet()) {
columnsStatistics.put(SchemaPath.getCompoundPath(partitionValue.getKey()),
StatisticsProvider.getConstantColumnStatistics(partitionValue.getValue(), TypeProtos.MinorType.VARCHAR));
}
return columnsStatistics;
}
/**
* Returns list of {@link RowGroupMetadata} received by converting parquet row groups metadata
* taken from the specified tableMetadata.
* Assigns index to row groups based on their position in files metadata.
* For empty / fake row groups assigns '-1' index.
*
* @param tableMetadata the source of row groups to be converted
* @return list of {@link RowGroupMetadata}
*/
public static Multimap<Path, RowGroupMetadata> getRowGroupsMetadata(MetadataBase.ParquetTableMetadataBase tableMetadata) {
Multimap<Path, RowGroupMetadata> rowGroups = LinkedListMultimap.create();
for (MetadataBase.ParquetFileMetadata file : tableMetadata.getFiles()) {
int index = 0;
for (MetadataBase.RowGroupMetadata rowGroupMetadata : file.getRowGroups()) {
int newIndex;
if (rowGroupMetadata.isEmpty()) {
Preconditions.checkState(file.getRowGroups().size() == 1, "Only one empty / fake row group is allowed per file");
newIndex = -1;
} else {
newIndex = index++;
}
Path filePath = Path.getPathWithoutSchemeAndAuthority(file.getPath());
rowGroups.put(filePath, getRowGroupMetadata(tableMetadata, rowGroupMetadata, newIndex, filePath));
}
}
return rowGroups;
}
/**
* Returns {@link RowGroupMetadata} instance converted from specified parquet {@code rowGroupMetadata}.
*
* @param tableMetadata table metadata which contains row group metadata to convert
* @param rowGroupMetadata row group metadata to convert
* @param rgIndexInFile index of current row group within the file
* @param location location of file with current row group
* @return {@link RowGroupMetadata} instance converted from specified parquet {@code rowGroupMetadata}
*/
public static RowGroupMetadata getRowGroupMetadata(MetadataBase.ParquetTableMetadataBase tableMetadata,
MetadataBase.RowGroupMetadata rowGroupMetadata, int rgIndexInFile, Path location) {
Map<SchemaPath, ColumnStatistics> columnsStatistics = getRowGroupColumnStatistics(tableMetadata, rowGroupMetadata);
List<StatisticsHolder> rowGroupStatistics = new ArrayList<>();
rowGroupStatistics.add(new StatisticsHolder<>(rowGroupMetadata.getRowCount(), TableStatisticsKind.ROW_COUNT));
rowGroupStatistics.add(new StatisticsHolder<>(rowGroupMetadata.getStart(), new BaseStatisticsKind(ExactStatisticsConstants.START, true)));
rowGroupStatistics.add(new StatisticsHolder<>(rowGroupMetadata.getLength(), new BaseStatisticsKind(ExactStatisticsConstants.LENGTH, true)));
Map<SchemaPath, TypeProtos.MajorType> columns = getRowGroupFields(tableMetadata, rowGroupMetadata);
Map<SchemaPath, TypeProtos.MajorType> intermediateColumns = getIntermediateFields(tableMetadata, rowGroupMetadata);
TupleMetadata schema = new TupleSchema();
columns.forEach(
(schemaPath, majorType) -> SchemaPathUtils.addColumnMetadata(schema, schemaPath, majorType, intermediateColumns)
);
MetadataInfo metadataInfo = MetadataInfo.builder().type(MetadataType.ROW_GROUP).build();
return RowGroupMetadata.builder()
.tableInfo(TableInfo.UNKNOWN_TABLE_INFO)
.metadataInfo(metadataInfo)
.schema(schema)
.columnsStatistics(columnsStatistics)
.metadataStatistics(rowGroupStatistics)
.hostAffinity(rowGroupMetadata.getHostAffinity())
.rowGroupIndex(rgIndexInFile)
.path(location)
.build();
}
/**
* Returns {@link FileMetadata} instance received by merging specified {@link RowGroupMetadata} list.
*
* @param rowGroups collection of {@link RowGroupMetadata} to be merged
* @return {@link FileMetadata} instance
*/
public static FileMetadata getFileMetadata(Collection<RowGroupMetadata> rowGroups) {
if (rowGroups.isEmpty()) {
return null;
}
List<StatisticsHolder> fileStatistics = new ArrayList<>();
fileStatistics.add(new StatisticsHolder<>(TableStatisticsKind.ROW_COUNT.mergeStatistics(rowGroups), TableStatisticsKind.ROW_COUNT));
RowGroupMetadata rowGroupMetadata = rowGroups.iterator().next();
TupleMetadata schema = rowGroupMetadata.getSchema();
Set<SchemaPath> columns = rowGroupMetadata.getColumnsStatistics().keySet();
MetadataInfo metadataInfo = MetadataInfo.builder().type(MetadataType.FILE).build();
return FileMetadata.builder()
.tableInfo(rowGroupMetadata.getTableInfo())
.metadataInfo(metadataInfo)
.path(rowGroupMetadata.getPath())
.schema(schema)
.columnsStatistics(TableMetadataUtils.mergeColumnsStatistics(rowGroups, columns, PARQUET_COLUMN_STATISTICS))
.metadataStatistics(fileStatistics)
.build();
}
/**
* Returns {@link PartitionMetadata} instance received by merging specified {@link FileMetadata} list.
*
* @param partitionColumn partition column
* @param files list of files to be merged
* @return {@link PartitionMetadata} instance
*/
public static PartitionMetadata getPartitionMetadata(SchemaPath partitionColumn, List<FileMetadata> files) {
Set<Path> locations = new HashSet<>();
Set<SchemaPath> columns = new HashSet<>();
for (FileMetadata file : files) {
columns.addAll(file.getColumnsStatistics().keySet());
locations.add(file.getPath());
}
FileMetadata fileMetadata = files.iterator().next();
MetadataInfo metadataInfo = MetadataInfo.builder().type(MetadataType.PARTITION).build();
return PartitionMetadata.builder()
.tableInfo(fileMetadata.getTableInfo())
.metadataInfo(metadataInfo)
.column(partitionColumn)
.schema(fileMetadata.getSchema())
.columnsStatistics(TableMetadataUtils.mergeColumnsStatistics(files, columns, PARQUET_COLUMN_STATISTICS))
.metadataStatistics(Collections.singletonList(new StatisticsHolder<>(TableStatisticsKind.ROW_COUNT.mergeStatistics(files), TableStatisticsKind.ROW_COUNT)))
.partitionValues(Collections.emptyList())
.locations(locations)
.build();
}
/**
* Converts specified {@link MetadataBase.RowGroupMetadata} into the map of {@link ColumnStatistics}
* instances with column names as keys.
*
* @param tableMetadata the source of column types
* @param rowGroupMetadata metadata to convert
* @return map with converted row group metadata
*/
public static Map<SchemaPath, ColumnStatistics> getRowGroupColumnStatistics(
MetadataBase.ParquetTableMetadataBase tableMetadata, MetadataBase.RowGroupMetadata rowGroupMetadata) {
Map<SchemaPath, ColumnStatistics> columnsStatistics = new HashMap<>();
for (MetadataBase.ColumnMetadata column : rowGroupMetadata.getColumns()) {
SchemaPath colPath = SchemaPath.getCompoundPath(column.getName());
Long nulls = column.getNulls();
if (!column.isNumNullsSet() || nulls == null) {
nulls = Statistic.NO_COLUMN_STATS;
}
PrimitiveType.PrimitiveTypeName primitiveType = getPrimitiveTypeName(tableMetadata, column);
OriginalType originalType = getOriginalType(tableMetadata, column);
TypeProtos.MinorType type = ParquetReaderUtility.getMinorType(primitiveType, originalType);
List<StatisticsHolder> statistics = new ArrayList<>();
statistics.add(new StatisticsHolder<>(getValue(column.getMinValue(), primitiveType, originalType), ColumnStatisticsKind.MIN_VALUE));
statistics.add(new StatisticsHolder<>(getValue(column.getMaxValue(), primitiveType, originalType), ColumnStatisticsKind.MAX_VALUE));
statistics.add(new StatisticsHolder<>(nulls, ColumnStatisticsKind.NULLS_COUNT));
columnsStatistics.put(colPath, new ColumnStatistics<>(statistics, type));
}
return columnsStatistics;
}
/**
* Returns the non-interesting column's metadata
* @param parquetTableMetadata the source of column metadata for non-interesting column's statistics
* @return returns non-interesting columns metadata
*/
public static NonInterestingColumnsMetadata getNonInterestingColumnsMeta(MetadataBase.ParquetTableMetadataBase parquetTableMetadata) {
Map<SchemaPath, ColumnStatistics> columnsStatistics = new HashMap<>();
if (parquetTableMetadata instanceof Metadata_V4.ParquetTableMetadata_v4) {
Map<Metadata_V4.ColumnTypeMetadata_v4.Key, Metadata_V4.ColumnTypeMetadata_v4> columnTypeInfoMap =
((Metadata_V4.ParquetTableMetadata_v4) parquetTableMetadata).getColumnTypeInfoMap();
if (columnTypeInfoMap == null) {
return new NonInterestingColumnsMetadata(columnsStatistics);
} // in some cases for runtime pruning
for (Metadata_V4.ColumnTypeMetadata_v4 columnTypeMetadata : columnTypeInfoMap.values()) {
if (!columnTypeMetadata.isInteresting) {
SchemaPath schemaPath = SchemaPath.getCompoundPath(columnTypeMetadata.name);
List<StatisticsHolder> statistics = new ArrayList<>();
statistics.add(new StatisticsHolder<>(Statistic.NO_COLUMN_STATS, ColumnStatisticsKind.NULLS_COUNT));
PrimitiveType.PrimitiveTypeName primitiveType = columnTypeMetadata.primitiveType;
OriginalType originalType = columnTypeMetadata.originalType;
TypeProtos.MinorType type = ParquetReaderUtility.getMinorType(primitiveType, originalType);
columnsStatistics.put(schemaPath, new ColumnStatistics<>(statistics, type));
}
}
return new NonInterestingColumnsMetadata(columnsStatistics);
}
return new NonInterestingColumnsMetadata(columnsStatistics);
}
/**
* Handles passed value considering its type and specified {@code primitiveType} with {@code originalType}.
*
* @param value value to handle
* @param primitiveType primitive type of the column whose value should be handled
* @param originalType original type of the column whose value should be handled
* @return handled value
*/
public static Object getValue(Object value, PrimitiveType.PrimitiveTypeName primitiveType, OriginalType originalType) {
if (value != null) {
switch (primitiveType) {
case BOOLEAN:
return Boolean.parseBoolean(value.toString());
case INT32:
if (originalType == OriginalType.DATE) {
return convertToDrillDateValue(getInt(value));
} else if (originalType == OriginalType.DECIMAL) {
return BigInteger.valueOf(getInt(value));
}
return getInt(value);
case INT64:
if (originalType == OriginalType.DECIMAL) {
return BigInteger.valueOf(getLong(value));
} else {
return getLong(value);
}
case FLOAT:
return getFloat(value);
case DOUBLE:
return getDouble(value);
case INT96:
return new String(getBytes(value));
case BINARY:
case FIXED_LEN_BYTE_ARRAY:
if (originalType == OriginalType.DECIMAL) {
return new BigInteger(getBytes(value));
} else if (originalType == OriginalType.INTERVAL) {
return getBytes(value);
} else {
return new String(getBytes(value));
}
}
}
return null;
}
private static byte[] getBytes(Object value) {
if (value instanceof Binary) {
return ((Binary) value).getBytes();
} else if (value instanceof byte[]) {
return (byte[]) value;
} else if (value instanceof String) { // value is obtained from metadata cache v2+
return ((String) value).getBytes();
} else if (value instanceof Map) { // value is obtained from metadata cache v1
String bytesString = (String) ((Map) value).get("bytes");
if (bytesString != null) {
return bytesString.getBytes();
}
} else if (value instanceof Long) {
return Longs.toByteArray((Long) value);
} else if (value instanceof Integer) {
return Longs.toByteArray((Integer) value);
} else if (value instanceof Float) {
return BigDecimal.valueOf((Float) value).unscaledValue().toByteArray();
} else if (value instanceof Double) {
return BigDecimal.valueOf((Double) value).unscaledValue().toByteArray();
}
throw new UnsupportedOperationException(String.format("Cannot obtain bytes using value %s", value));
}
private static Integer getInt(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
return Integer.parseInt(value.toString());
} else if (value instanceof byte[]) {
return new BigInteger((byte[]) value).intValue();
} else if (value instanceof Binary) {
return new BigInteger(((Binary) value).getBytes()).intValue();
}
throw new UnsupportedOperationException(String.format("Cannot obtain Integer using value %s", value));
}
private static Long getLong(Object value) {
if (value instanceof Number) {
return ((Number) value).longValue();
} else if (value instanceof String) {
return Long.parseLong(value.toString());
} else if (value instanceof byte[]) {
return new BigInteger((byte[]) value).longValue();
} else if (value instanceof Binary) {
return new BigInteger(((Binary) value).getBytes()).longValue();
}
throw new UnsupportedOperationException(String.format("Cannot obtain Integer using value %s", value));
}
private static Float getFloat(Object value) {
if (value instanceof Number) {
return ((Number) value).floatValue();
} else if (value instanceof String) {
return Float.parseFloat(value.toString());
}
// TODO: allow conversion form bytes only when actual type of data is known (to obtain scale)
/* else if (value instanceof byte[]) {
return new BigInteger((byte[]) value).floatValue();
} else if (value instanceof Binary) {
return new BigInteger(((Binary) value).getBytes()).floatValue();
}*/
throw new UnsupportedOperationException(String.format("Cannot obtain Integer using value %s", value));
}
private static Double getDouble(Object value) {
if (value instanceof Number) {
return ((Number) value).doubleValue();
} else if (value instanceof String) {
return Double.parseDouble(value.toString());
}
// TODO: allow conversion form bytes only when actual type of data is known (to obtain scale)
/* else if (value instanceof byte[]) {
return new BigInteger((byte[]) value).doubleValue();
} else if (value instanceof Binary) {
return new BigInteger(((Binary) value).getBytes()).doubleValue();
}*/
throw new UnsupportedOperationException(String.format("Cannot obtain Integer using value %s", value));
}
private static long convertToDrillDateValue(int dateValue) {
return dateValue * (long) DateTimeConstants.MILLIS_PER_DAY;
}
/**
* Returns map of column names with their drill types for specified {@code file}.
*
* @param parquetTableMetadata the source of primitive and original column types
* @param file file whose columns should be discovered
* @return map of column names with their drill types
*/
public static Map<SchemaPath, TypeProtos.MajorType> getFileFields(
MetadataBase.ParquetTableMetadataBase parquetTableMetadata, MetadataBase.ParquetFileMetadata file) {
// does not resolve types considering all row groups, just takes type from the first row group.
return getRowGroupFields(parquetTableMetadata, file.getRowGroups().iterator().next());
}
/**
* Returns map of column names with their drill types for specified {@code rowGroup}.
*
* @param parquetTableMetadata the source of primitive and original column types
* @param rowGroup row group whose columns should be discovered
* @return map of column names with their drill types
*/
public static Map<SchemaPath, TypeProtos.MajorType> getRowGroupFields(
MetadataBase.ParquetTableMetadataBase parquetTableMetadata, MetadataBase.RowGroupMetadata rowGroup) {
Map<SchemaPath, TypeProtos.MajorType> columns = new LinkedHashMap<>();
if (new MetadataVersion(parquetTableMetadata.getMetadataVersion()).compareTo(new MetadataVersion(4, 0)) > 0
&& !((Metadata_V4.ParquetTableMetadata_v4) parquetTableMetadata).isAllColumnsInteresting()) {
// adds non-interesting fields from table metadata
for (MetadataBase.ColumnTypeMetadata columnTypeMetadata : parquetTableMetadata.getColumnTypeInfoList()) {
Metadata_V4.ColumnTypeMetadata_v4 metadata = (Metadata_V4.ColumnTypeMetadata_v4) columnTypeMetadata;
if (!metadata.isInteresting) {
TypeProtos.MajorType columnType = getColumnType(metadata.name, metadata.primitiveType, metadata.originalType, parquetTableMetadata);
SchemaPath columnPath = SchemaPath.getCompoundPath(metadata.name);
putType(columns, columnPath, columnType);
}
}
}
for (MetadataBase.ColumnMetadata column : rowGroup.getColumns()) {
TypeProtos.MajorType columnType = getColumnType(parquetTableMetadata, column);
SchemaPath columnPath = SchemaPath.getCompoundPath(column.getName());
putType(columns, columnPath, columnType);
}
return columns;
}
private static TypeProtos.MajorType getColumnType(
MetadataBase.ParquetTableMetadataBase parquetTableMetadata,MetadataBase.ColumnMetadata column) {
PrimitiveType.PrimitiveTypeName primitiveType = getPrimitiveTypeName(parquetTableMetadata, column);
OriginalType originalType = getOriginalType(parquetTableMetadata, column);
String[] name = column.getName();
return getColumnType(name, primitiveType, originalType, parquetTableMetadata);
}
private static TypeProtos.MajorType getColumnType(String[] name,
PrimitiveType.PrimitiveTypeName primitiveType, OriginalType originalType,
MetadataBase.ParquetTableMetadataBase parquetTableMetadata) {
int precision = 0;
int scale = 0;
int definitionLevel = 1;
int repetitionLevel = 0;
MetadataVersion metadataVersion = new MetadataVersion(parquetTableMetadata.getMetadataVersion());
// only ColumnTypeMetadata_v3 and ColumnTypeMetadata_v4 store information about scale, precision, repetition level and definition level
if (parquetTableMetadata.hasColumnMetadata() && (metadataVersion.compareTo(new MetadataVersion(3, 0)) >= 0)) {
scale = parquetTableMetadata.getScale(name);
precision = parquetTableMetadata.getPrecision(name);
repetitionLevel = parquetTableMetadata.getRepetitionLevel(name);
definitionLevel = parquetTableMetadata.getDefinitionLevel(name);
}
TypeProtos.DataMode mode;
if (repetitionLevel >= 1) {
mode = TypeProtos.DataMode.REPEATED;
} else if (repetitionLevel == 0 && definitionLevel == 0) {
mode = TypeProtos.DataMode.REQUIRED;
} else {
mode = TypeProtos.DataMode.OPTIONAL;
}
return TypeProtos.MajorType.newBuilder(ParquetReaderUtility.getType(primitiveType, originalType, precision, scale))
.setMode(mode)
.build();
}
/**
* Returns map of column names with their Drill types for every {@code NameSegment} in {@code SchemaPath}
* in specified {@code rowGroup}. The type for a {@code SchemaPath} can be {@code null} in case when
* it is not possible to determine its type. Actually, as of now this hierarchy is of interest solely
* because there is a need to account for {@link org.apache.drill.common.types.TypeProtos.MinorType#DICT}
* to make sure filters used on {@code DICT}'s values (get by key) are not pruned out before actual filtering
* happens.
*
* @param parquetTableMetadata the source of column types
* @param rowGroup row group whose columns should be discovered
* @return map of column names with their drill types
*/
public static Map<SchemaPath, TypeProtos.MajorType> getIntermediateFields(
MetadataBase.ParquetTableMetadataBase parquetTableMetadata, MetadataBase.RowGroupMetadata rowGroup) {
Map<SchemaPath, TypeProtos.MajorType> columns = new LinkedHashMap<>();
MetadataVersion metadataVersion = new MetadataVersion(parquetTableMetadata.getMetadataVersion());
boolean hasParentTypes = parquetTableMetadata.hasColumnMetadata()
&& metadataVersion.compareTo(new MetadataVersion(4, 1)) >= 0;
if (!hasParentTypes) {
return Collections.emptyMap();
}
for (MetadataBase.ColumnMetadata column : rowGroup.getColumns()) {
Metadata_V4.ColumnTypeMetadata_v4 columnTypeMetadata =
((Metadata_V4.ParquetTableMetadata_v4) parquetTableMetadata).getColumnTypeInfo(column.getName());
List<OriginalType> parentTypes = columnTypeMetadata.parentTypes;
List<TypeProtos.MajorType> drillTypes = ParquetReaderUtility.getComplexTypes(parentTypes);
for (int i = 0; i < drillTypes.size(); i++) {
SchemaPath columnPath = SchemaPath.getCompoundPath(i + 1, column.getName());
TypeProtos.MajorType drillType = drillTypes.get(i);
putType(columns, columnPath, drillType);
}
}
return columns;
}
/**
* Returns {@link OriginalType} type for the specified column.
*
* @param parquetTableMetadata the source of column type
* @param column column whose {@link OriginalType} should be returned
* @return {@link OriginalType} type for the specified column
*/
public static OriginalType getOriginalType(MetadataBase.ParquetTableMetadataBase parquetTableMetadata, MetadataBase.ColumnMetadata column) {
OriginalType originalType = column.getOriginalType();
// for the case of parquet metadata v1 version, type information isn't stored in parquetTableMetadata, but in ColumnMetadata
if (originalType == null) {
originalType = parquetTableMetadata.getOriginalType(column.getName());
}
return originalType;
}
/**
* Returns {@link PrimitiveType.PrimitiveTypeName} type for the specified column.
*
* @param parquetTableMetadata the source of column type
* @param column column whose {@link PrimitiveType.PrimitiveTypeName} should be returned
* @return {@link PrimitiveType.PrimitiveTypeName} type for the specified column
*/
public static PrimitiveType.PrimitiveTypeName getPrimitiveTypeName(MetadataBase.ParquetTableMetadataBase parquetTableMetadata, MetadataBase.ColumnMetadata column) {
PrimitiveType.PrimitiveTypeName primitiveType = column.getPrimitiveType();
// for the case of parquet metadata v1 version, type information isn't stored in parquetTableMetadata, but in ColumnMetadata
if (primitiveType == null) {
primitiveType = parquetTableMetadata.getPrimitiveType(column.getName());
}
return primitiveType;
}
/**
* Returns map of column names with their drill types for specified {@code parquetTableMetadata}
* with resolved types for the case of schema evolution.
*
* @param parquetTableMetadata table metadata whose columns should be discovered
* @return map of column names with their drill types
*/
static Map<SchemaPath, TypeProtos.MajorType> resolveFields(MetadataBase.ParquetTableMetadataBase parquetTableMetadata) {
Map<SchemaPath, TypeProtos.MajorType> columns = new LinkedHashMap<>();
for (MetadataBase.ParquetFileMetadata file : parquetTableMetadata.getFiles()) {
// row groups in the file have the same schema, so using the first one
Map<SchemaPath, TypeProtos.MajorType> fileColumns = getFileFields(parquetTableMetadata, file);
fileColumns.forEach((columnPath, type) -> putType(columns, columnPath, type));
}
return columns;
}
static Map<SchemaPath, TypeProtos.MajorType> resolveIntermediateFields(MetadataBase.ParquetTableMetadataBase parquetTableMetadata) {
Map<SchemaPath, TypeProtos.MajorType> columns = new LinkedHashMap<>();
for (MetadataBase.ParquetFileMetadata file : parquetTableMetadata.getFiles()) {
// row groups in the file have the same schema, so using the first one
Map<SchemaPath, TypeProtos.MajorType> fileColumns = getIntermediateFields(parquetTableMetadata, file.getRowGroups().iterator().next());
fileColumns.forEach((columnPath, type) -> putType(columns, columnPath, type));
}
return columns;
}
private static void putType(Map<SchemaPath, TypeProtos.MajorType> columns, SchemaPath columnPath, TypeProtos.MajorType type) {
TypeProtos.MajorType majorType = columns.get(columnPath);
if (majorType == null) {
columns.put(columnPath, type);
} else if (!majorType.equals(type)) {
TypeProtos.MinorType leastRestrictiveType = TypeCastRules.getLeastRestrictiveType(Arrays.asList(majorType.getMinorType(), type.getMinorType()));
if (leastRestrictiveType != majorType.getMinorType()) {
columns.put(columnPath, type);
}
}
}
/**
* Returns map with schema path and {@link ColumnStatistics} obtained from specified {@link DrillStatsTable}
* for all columns from specified {@link BaseTableMetadata}.
*
* @param schema source of column names
* @param statistics source of column statistics
* @return map with schema path and {@link ColumnStatistics}
*/
public static Map<SchemaPath, ColumnStatistics> getColumnStatistics(TupleMetadata schema, DrillStatsTable statistics) {
List<SchemaPath> schemaPaths = SchemaUtil.getSchemaPaths(schema);
return schemaPaths.stream()
.collect(
Collectors.toMap(
Function.identity(),
schemaPath -> new ColumnStatistics<>(
DrillStatsTable.getEstimatedColumnStats(statistics, schemaPath),
SchemaPathUtils.getColumnMetadata(schemaPath, schema).type())));
}
}
|
Java
|
public class ApplicationAgent implements ApplicationAgentApi {
private static final String TAG = "ldcp-api";
private String host;
private int port;
private LdcpServer server;
private BlobFactory factory;
private ExtensionToolbox toolbox;
private Log logger;
/**
* Constructor.
*
* @param host host of the LDCP server running on the registrar
* @param port port of the LDCP server running on the registrar
*/
public static ApplicationAgentApi create(String host,
int port) {
return new ApplicationAgent(
host,
port,
new BaseExtensionToolbox(),
new BaseBlobFactory().enableVolatile(1000000),
new NullLogger());
}
/**
* Constructor.
*
* @param host host of the LDCP server running on the registrar
* @param port port of the LDCP server running on the registrar
* @param factory Blob factory
*/
public static ApplicationAgentApi create(String host,
int port,
BlobFactory factory) {
return new ApplicationAgent(
host,
port,
new BaseExtensionToolbox(),
factory,
new NullLogger());
}
/**
* Constructor.
*
* @param host host of the LDCP server running on the registrar
* @param port port of the LDCP server running on the registrar
* @param toolbox Blocks and Eids factory
* @param factory Blob factory
*/
public static ApplicationAgentApi create(String host,
int port,
ExtensionToolbox toolbox,
BlobFactory factory) {
return new ApplicationAgent(
host,
port,
toolbox,
factory,
new NullLogger());
}
/**
* Constructor.
*
* @param host host of the LDCP server running on the registrar
* @param port port of the LDCP server running on the registrar
* @param toolbox Blocks and Eids factory
* @param factory Blob factory
* @param logger logging service
*/
public static ApplicationAgentApi create(String host,
int port,
ExtensionToolbox toolbox,
BlobFactory factory,
Log logger) {
return new ApplicationAgent(
host,
port,
toolbox,
factory,
logger);
}
private ApplicationAgent(String host,
int port,
ExtensionToolbox toolbox,
BlobFactory factory,
Log logger) {
this.host = host;
this.port = port;
this.toolbox = toolbox;
this.factory = factory;
this.logger = logger;
}
private boolean startServer(ActiveRegistrationCallback cb) {
if (server != null) {
return false;
}
server = new LdcpServer();
server.start(0, toolbox, factory, logger,
Router.create()
.POST(ApiPaths.DaemonToClientLdcpPathVersion1.DELIVER.path,
(req, res) -> cb.recv(req.bundle)
.doOnComplete(() ->
res.setCode(ResponseMessage.ResponseCode.OK))
.doOnError(e ->
res.setCode(ResponseMessage.ResponseCode.ERROR))));
return true;
}
private boolean stopServer() {
if (server == null) {
return false;
}
server.stop();
return true;
}
@Override
public Single<Boolean> isRegistered(String sink) {
return LdcpRequest.GET(ApiPaths.ClientToDaemonLdcpPathVersion1.ISREGISTERED.path)
.setHeader("sink", sink)
.send(host, port, toolbox, factory, logger)
.map(res -> res.code == ResponseMessage.ResponseCode.OK);
}
@Override
public Single<String> register(String sink) {
return register(sink, null);
}
@Override
public Single<String> register(String sink, ActiveRegistrationCallback cb) {
if (startServer(cb)) {
return LdcpRequest.POST(ApiPaths.ClientToDaemonLdcpPathVersion1.REGISTER.path)
.setHeader("sink", sink)
.setHeader("active", cb == null ? "false" : "true")
.setHeader("active-host", "127.0.0.1")
.setHeader("active-port", "" + server.getPort())
.send(host, port, toolbox, factory, logger)
.flatMap(res -> {
if (res.code == ResponseMessage.ResponseCode.ERROR) {
return Single.error(new RegistrarException(res.body));
}
if (res.fields.get("cookie") == null) {
return Single.error(new RegistrarException("no cookie received"));
}
return Single.just(res.fields.get("cookie"));
});
} else {
return Single.error(new RegistrationAlreadyActive());
}
}
@Override
public Single<Boolean> unregister(String sink, String cookie) {
return LdcpRequest.POST(ApiPaths.ClientToDaemonLdcpPathVersion1.UNREGISTER.path)
.setHeader("sink", sink)
.setHeader("cookie", cookie)
.send(host, port, toolbox, factory, logger)
.map(res -> res.code == ResponseMessage.ResponseCode.OK);
}
@Override
public Set<BundleId> checkInbox(String sink, String cookie) {
return null;
}
@Override
public Single<Bundle> get(String sink, String cookie, BundleId bundleId) {
return LdcpRequest.GET(ApiPaths.ClientToDaemonLdcpPathVersion1.GETBUNDLE.path)
.setHeader("sink", sink)
.setHeader("cookie", cookie)
.setHeader("bundle-id", bundleId.getBidString())
.send(host, port, toolbox, factory, logger)
.flatMap(res -> {
if (res.code == ResponseMessage.ResponseCode.ERROR) {
return Single.error(new RegistrarException());
}
if (res.bundle == null) {
return Single.error(new RegistrarException());
}
return Single.just(res.bundle);
});
}
@Override
public Single<Bundle> fetch(String sink, String cookie, BundleId bundleId) {
return LdcpRequest.GET(ApiPaths.ClientToDaemonLdcpPathVersion1.FETCHBUNDLE.path)
.setHeader("sink", sink)
.setHeader("cookie", cookie)
.setHeader("bundle-id", bundleId.getBidString())
.send(host, port, toolbox, factory, logger)
.flatMap(res -> {
if (res.code == ResponseMessage.ResponseCode.ERROR) {
return Single.error(new RegistrarException());
}
if (res.bundle == null) {
return Single.error(new RegistrarException());
}
return Single.just(res.bundle);
});
}
@Override
public Single<Boolean> send(String sink, String cookie, Bundle bundle) {
return LdcpRequest.POST(ApiPaths.ClientToDaemonLdcpPathVersion1.DISPATCH.path)
.setHeader("sink", sink)
.setHeader("cookie", cookie)
.setBundle(bundle)
.send(host, port, toolbox, factory, logger)
.map(res -> res.code == ResponseMessage.ResponseCode.OK);
}
@Override
public Single<Boolean> send(Bundle bundle) {
return LdcpRequest.POST(ApiPaths.ClientToDaemonLdcpPathVersion1.DISPATCH.path)
.setBundle(bundle)
.send(host, port, toolbox, factory, logger)
.map(res -> res.code == ResponseMessage.ResponseCode.OK);
}
@Override
public Single<Boolean> reAttach(String sink, String cookie, ActiveRegistrationCallback cb) {
if (startServer(cb)) {
return LdcpRequest.POST(ApiPaths.ClientToDaemonLdcpPathVersion1.UPDATE.path)
.setHeader("sink", sink)
.setHeader("cookie", cookie)
.setHeader("active", "true")
.setHeader("active-host", "127.0.0.1")
.setHeader("active-port", "" + server.getPort())
.send(host, port, toolbox, factory, logger)
.flatMap(res -> {
if (res.code == ResponseMessage.ResponseCode.ERROR) {
return Single.error(new RegistrarException(res.body));
}
return Single.just(true);
});
} else {
return Single.error(new RegistrationAlreadyActive());
}
}
@Override
public Single<Boolean> setPassive(String sink, String cookie) {
stopServer();
return LdcpRequest.POST(ApiPaths.ClientToDaemonLdcpPathVersion1.UPDATE.path)
.setHeader("active", "false")
.setHeader("sink", sink)
.setHeader("cookie", cookie)
.send(host, port, toolbox, factory, logger)
.flatMap(res -> {
if (res.code == ResponseMessage.ResponseCode.ERROR) {
return Single.error(new RegistrarException(res.body));
}
return Single.just(true);
});
}
}
|
Java
|
public class HbIrUserGroupAccessControlEntryDAO implements
IrUserGroupAccessControlEntryDAO
{
/** eclipse generated id */
private static final long serialVersionUID = -6233995403157802235L;
/** helper for persistence operations */
private final HbCrudDAO<IrUserGroupAccessControlEntry> hbCrudDAO;
/**
* Default Constructor
*/
public HbIrUserGroupAccessControlEntryDAO() {
hbCrudDAO = new HbCrudDAO<IrUserGroupAccessControlEntry>(IrUserGroupAccessControlEntry.class);
}
/**
* Set the session factory.
*
* @param sessionFactory
*/
public void setSessionFactory(SessionFactory sessionFactory)
{
hbCrudDAO.setSessionFactory(sessionFactory);
}
/**
* Get a count of the user access cotnrol entries.
*
* @see edu.ur.dao.CountableDAO#getCount()
*/
public Long getCount() {
return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("irUserGroupAccessEntryCount"));
}
/**
* Get all user access control entries.
*
* @see edu.ur.dao.CrudDAO#getAll()
*/
@SuppressWarnings("unchecked")
public List getAll() {
return hbCrudDAO.getAll();
}
/**
* Get the user access control entry by id.
*
* @see edu.ur.dao.CrudDAO#getById(java.lang.Long, boolean)
*/
public IrUserGroupAccessControlEntry getById(Long id, boolean lock) {
return hbCrudDAO.getById(id, lock);
}
/**
* Make the user access control entry persistent.
*
* @see edu.ur.dao.CrudDAO#makePersistent(java.lang.Object)
*/
public void makePersistent(IrUserGroupAccessControlEntry entity) {
hbCrudDAO.makePersistent(entity);
}
/**
* Make the user access control entry transient.
*
* @see edu.ur.dao.CrudDAO#makeTransient(java.lang.Object)
*/
public void makeTransient(IrUserGroupAccessControlEntry entity) {
hbCrudDAO.makeTransient(entity);
}
/**
* Determine if the user group has the permission for the specified class type
*
* @see edu.ur.ir.security.IrUserGroupAccessControlEntryDAO#getUserGroupPermissionCountForClassType(edu.ur.ir.user.IrUserGroup, edu.ur.ir.security.IrClassTypePermission, edu.ur.ir.security.IrClassType)
*/
public Long getUserGroupPermissionCountForClassType(IrUserGroup userGroup,
IrClassTypePermission classTypePermission, IrClassType classType) {
Long[] ids = new Long[] {classType.getId(),
classTypePermission.getId(),
userGroup.getId() };
Long count = (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("permissionCountForClassType",
ids));
return count;
}
/**
* Determine if the user group has the permission for the specified object
* and class type.
*
* @see edu.ur.ir.security.IrUserGroupAccessControlEntryDAO#getUserGroupPermissionCountForClassTypeObject(edu.ur.ir.user.IrUserGroup, edu.ur.ir.security.IrClassTypePermission, edu.ur.ir.security.IrClassType, java.lang.Long)
*/
public Long getUserGroupPermissionCountForClassTypeObject(
IrUserGroup userGroup, IrClassTypePermission classTypePermission,
IrClassType classType, Long objectId) {
Long[] ids = new Long[] {classType.getId(),
classTypePermission.getId(),
userGroup.getId(),
objectId};
Long count = (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("permissionCountForClassTypeObject",
ids));
return count;
}
}
|
Java
|
public class DeleteOperationImpl extends AbstractOperation<AbstractOperationTask> {
/**
* (Boolean) If true then the entities are only marked as deleted; otherwise they are physically deleted.
*/
public static final String PARAM_MARK_AS_DELETED = DeleteOperationImpl.class.getName() + ".markOnly";
private boolean allowRemoval = false;
@Override
public void setProperties(Map<String, String> params)
{
super.setProperties(params);
allowRemoval = !Boolean.parseBoolean(parameters.getOrDefault(PARAM_MARK_AS_DELETED, "true"));
}
@Override
protected AbstractOperationTask createTask()
{
return new AbstractOperationTask() {
@Override
protected Boolean doWork(String[] keys, CachedRowSet rowset) throws CoalescePersistorException
{
CoalesceEntity[] entities = source.getEntity(keys);
for (CoalesceEntity entity : entities)
{
entity.markAsDeleted();
}
return saveWork(allowRemoval, entities);
}
};
}
}
|
Java
|
public class steg extends Frame implements ActionListener
{
static String path;
static String path1;
FileDialog fd,fd1;
public Image img=null;
public Image img1=null;
public Image img3=null;
static steg f;
int index=0;
int max;
int bytes[]=new int[10000];
int binary[]=new int[2450000];
int maxbinary,maxbinary1,maxbinary2,ivalue;
String msg;
String filename,filename1;
int flag=0;
public int pixels[]=new int[350000];
public int pixels1[]=new int[350000];
static int width,height,padding;
static int index1=0,ch,i=0,l=0,r,g,b,r1,g1,b1;
int p[]=new int[2000000];
int p1[]=new int[2000000];
int p2[]=new int[2000000];
int p3[]=new int[2000000];
int pix[]=new int[350000];
int pix1[]=new int[350000];
int blue[]=new int[300];
int green[]=new int[300];
int red[]=new int[300];
int maxp;
int maxp1;
TextArea ta=new TextArea(10,100);
MenuBar mb=new MenuBar();
Menu m1=new Menu("File ");
MenuItem mi1=new MenuItem("Open");
MenuItem mi2=new MenuItem("OpenTextFile");
MenuItem mi3=new MenuItem("Save");
MenuItem mi4=new MenuItem("Decrypt");
MenuItem mi5=new MenuItem("Reset");
MenuItem mi6=new MenuItem("Exit");
steg()
{
setMenuBar(mb);
m1.add(mi1);
mi1.setEnabled(false);
m1.add(mi2);
m1.add(mi3);
mi3.setEnabled(false);
m1.add(mi4);
m1.add(mi5);
m1.add(mi6);
mb.add(m1);
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);
setLayout(new BorderLayout( ));
add(ta,BorderLayout.SOUTH);
addWindowListener(new WindowAdapter()
{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
// It is the main function
public static void main(String args[])
{
f=new steg();
f.setSize(800,800);
f.setTitle("STEGANOGRAPHY ");
f.show();
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
// It opens the Bitmap image file
if(s.equals("Open"))
{
msg="Encrypted Image";
flag=0;
fd=new FileDialog(f,"Opening Files......");
fd.show();
path=fd.getDirectory()+fd.getFile();
if(path!=null)
{
mi1.setEnabled(false);
mi3.setEnabled(true);
openimagefile(path,11);
repaint();
}
}
// It opens the text file
else if(s.equals("OpenTextFile"))
{
fd1=new FileDialog(f,"Opening Files......");
fd1.show();
path1=fd1.getDirectory()+fd1.getFile();
if(path1!=null)
{
mi1.setEnabled(true);
mi2.setEnabled(false);
opentextfile(path1);
ta.setEditable(false);
}
}
// It saves the image file which contains the encrypted data
else if(s.equals("Save"))
{
flag=0;
FileDialog fd2=new FileDialog(f,"save file",FileDialog.SAVE);
fd2.show();
try
{
if(fd2.getFile()!=null)
{
filename=fd2.getDirectory()+fd2.getFile();
mi3.setEnabled(false);
FileOutputStream fout=new FileOutputStream(filename);
DataOutputStream d=new DataOutputStream(fout);
i=0;
while(i<maxp)
{
d.write(p1[i]);
i++;
}
fout.close();
repaint();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
// It gets the data from the image and decrypts it using IDEA //algorithm
else if(s.equals("Decrypt"))
{
ta.setText(" ");
FileDialog fd3=new FileDialog(f,"OPEN file");
fd3.show();
msg="Decrypted Image";
System.out.println("Go"+fd3.getFile());
try
{
if(fd3.getFile()!=null)
{
filename1=fd3.getDirectory()+fd3.getFile();
i=0;
FileInputStream fis1 = new FileInputStream(filename1);
DataInputStream dis=new DataInputStream(fis1);
while((ch=dis.readUnsignedByte())!=-1)
{
p2[i]=ch;
p3[i]=ch;
i++;
System.out.println("GOO*********"+ch);
}
}
}
catch(Exception e)
{
maxp1=i;
switch(p2[28])
{
case 24:
{
init241();
break;
} //case 24 ends
} // switchp[28] ends
} //catch() ends
img3=createImage(new MemoryImageSource(width,height,pixels,0,width));
img=createImage(new MemoryImageSource(width,height,pixels,0,width));
flag=1;
repaint();
}
else if(s.equals("Reset"))
{
img=null;
img1=null;
img3=null;
mi2.setEnabled(true);
mi1.setEnabled(false);
mi3.setEnabled(false);
repaint();
}
// It exits the program
else if(s.equals("Exit"))
{
System.exit(0);
}
}
// It reads the encrypted data from the image
public void init241()
{
width= p2[21]<<24 | p2[20]<<16 | p2[19]<<8 | p2[18];
height= p2[25]<<24 | p2[24]<<16 | p2[23]<<8 | p2[22];
int extra=(width*3)%4;
if(extra!=0)
padding=4-extra;
int x,z=54;
l=0;
int j=0;
i=0;
for(int q=0;q<height;q++)
{
x=0;
while(x<width)
{
b=p2[z]&0xff;
binary[j++]=b&0x01;
g=p2[z+1]&0xff;
binary[j++]=g&0x01;
r=p2[z+2]&0xff;
binary[j++]=r&0x01;
pix[l]= 255<<24 | r<<16 | g<<8 | b;
z=z+3;
x++;
l++;
}
z=z+padding;
}
int k;
x=0;
stringcon();
for(i=l-width;i>=0;i=i-width)
{
for(k=0;k<width;k++)
{
pixels[x]=pix[i+k];
// pixels1[x]=pix[i+k];
x++;
}
}
}
// It converts the data obtained from the image into binary data
public void stringcon()
{
int i,j,k;
int temp[]=new int[8];
int a[]=new int[32];
i=0;
j=0;
for(i=0;i<10000;i++)
bytes[i]=0;
i=0;
maxbinary1=0;
for(i=0;i<24;i++)
a[i]=binary[i];
for(i=0;i<24;i++)
maxbinary1+=a[i]*Math.pow(2,23-i);
maxbinary2=maxbinary1*8;
ivalue=0;
for(i=24,j=0;i<32;i++,j++)
{
a[j]=binary[i];
ivalue+=a[j]*Math.pow(2,7-j);
}
if(ivalue==73)
{
i=32;
while(i<maxbinary2)
{
for(k=0;k<=7;k++)
temp[k]=binary[i++];
for(k=0;k<=7;k++)
bytes[j]+=temp[k]*Math.pow(2,7-k);
j++;
}
String s=JOptionPane.showInputDialog(this,"Enter key with 16 letters");
char ch[]=new char[s.length()];
ch=s.toCharArray();
try
{
FileOutputStream f=new FileOutputStream("key1.txt");
for(i=0;i<ch.length;i++)
f.write(ch[i]);
f.close();
FileOutputStream fout=new FileOutputStream("enc1.txt");
DataOutputStream d=new DataOutputStream(fout);
i=8;
while(i<(maxbinary1))
{
d.write(bytes[i]);
i++;
}
fout.close();
}
catch(Exception e)
{
System.out.println(e);
}
ideaalgo b=new ideaalgo();
b.procedure();
b.decryption("enc1.txt");
try
{
BufferedReader d;
StringBuffer sb=new StringBuffer();
d=new BufferedReader(new FileReader("dec.txt"));
String line;
while((line=d.readLine())!=null)
sb.append(line+"\n");
ta.setText(sb.toString());
d.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
// It opens the text file and converts the data into cipher text
public void opentextfile(String path1)
{
FileInputStream fin,fin1;
int i,j=0;
String s=JOptionPane.showInputDialog(this,"Enter key with 16 letters");
char ch[]=new char[s.length()];
ch=s.toCharArray();
try
{
FileOutputStream f=new FileOutputStream("key1.txt");
for(i=0;i<ch.length;i++)
f.write(ch[i]);
f.close();
ideaalgo a=new ideaalgo(path1);
a.procedure();
a.encrypt();
BufferedReader d;
StringBuffer sb=new StringBuffer();
d=new BufferedReader(new FileReader(path1));
String line;
while((line=d.readLine())!=null)
sb.append(line+"\n");
ta.setText(sb.toString());
d.close();
fin=new FileInputStream("enc.txt");
do
{
i=fin.read();
if(i!=-1)
{
bytes[j++]=i;
}
} while(i!=-1);
max=j;
fin.close();
binarycon();
}
catch(Exception e)
{
System.out.println(e);
}
}
// It converts the encrypted data into binary data
public void binarycon()
{
int i,j,k,t;
int temp[]=new int[10];
int m=0;
for(i=0;i<600000;i++)
binary[i]=0;
int b[]=new int[32];
int dum;
dum=max;
i=0;
while(dum!=0)
{
b[i]=dum%2;
i=i+1;
dum/=2;
}
j=24-i;
for(k=j,t=i-1;k<(i+j);k++,t--)
binary[k]=b[t];
dum=73;
i=0;
while(dum!=0)
{
b[i]=dum%2;
i=i+1;
dum/=2;
}
j=32-i;
for(k=j,t=i-1;k<32;k++,t--)
binary[k]= b[t];
m=32;
for( i=0 ; i < max ; i++)
{
j=0;
while( bytes[i]!= 0 )
{
temp[j++]=bytes[i]%2;
bytes[i]=bytes[i]/2;
}
for( k=0;k<8-j ; k++)
binary[m++]=0;
for(k=j-1; k >=0 ; k--)
binary[m++]=temp[k];
}
maxbinary=m;
}
public void paint(Graphics g)
{
g.drawString ("Original Image",180,70);
if(msg!=null)
g.drawString (msg,550,50);
if(img!=null)
g.drawImage(img,20,80,this);
if(img1!=null&&flag!=1)
g.drawImage(img1,400,80,this);
if(img3!=null&&flag!=0)
g.drawImage(img3,400,80,this);
}
// It opens the image file and hides the data in images
public void openimagefile(String fn,int sno)
{
try
{
i=0;
FileInputStream fis = new FileInputStream(fn);
DataInputStream dis=new DataInputStream(fis);
while((ch=dis.readUnsignedByte())!=-1)
{
p[i]=ch;
p1[i]=ch;
i++;
}
fis.close();
dis.close();
}
catch(Exception e)
{
maxp=i;
switch(p[28])
{
case 24:
{
init24();
break;
} //case 24 ends
} // switchp[28] ends
} //catch() ends
img=createImage(new MemoryImageSource(width,height,pixels,0,width));
img1=createImage(new MemoryImageSource(width,height,pixels1,0,width));
} //openfile ends
// It hides the binary data in the least significant bit of the image
public void init24()
{
width= p[21]<<24 | p[20]<<16 | p[19]<<8 | p[18];
height= p[25]<<24 | p[24]<<16 | p[23]<<8 | p[22];
int extra=(width*3)%4;
if(extra!=0)
padding=4-extra;
int x,z=54;
l=0;
int j=0;
for(int q=0;q<height;q++)
{
x=0;
while(x<width)
{
b=p[z]&0xff;
if(j<maxbinary)
{
if(binary[j]!=0)
{
p1[z]=p[z]&0xff|binary[j++];
b1=p1[z]&0xff;
}
else
{
p1[z]=p[z]&0xff & (binary[j++]|0xfe);
b1=p1[z]&0xff;
}
}
else
b1=p[z]&0xff;
g=p[z+1]&0xff;
if(j<maxbinary)
{
if(binary[j]!=0)
{
p1[z+1]=p[z+1]&0xff|binary[j++];
g1=p[z+1]&0xff;
}
else
{
p1[z+1]=p[z+1]&0xff & (binary[j++]|0xfe);
g1=p1[z+1]&0xff;
}
}
else
g1=p[z]&0xff;
r=p[z+2]&0xff;
if(j<maxbinary)
{
if(binary[j]!=0)
{
p1[z+2]=p[z+2]&0xfe|binary[j++];
r1=p[z+2]&0xff;
}
else
{
p1[z+2]=p[z+2]&0xff & (binary[j++]|0xfe);
r1=p1[z+2]&0xff;
}
}
else
r1=p[z]&0xff;
z=z+3;
pix[l]= 255<<24 | r<<16 | g<<8 | b;
pix1[l]= 255<<24 | r1<<16 | g1<<8 | b1;
l++;
x++;
}
z=z+padding;
}
int k;
x=0;
for(i=l-width;i>=0;i=i-width) //l=WIDTH * height
{
for(k=0;k<width;k++)
{
pixels[x]=pix[i+k];
pixels1[x]=pix[i+k];
x++;
}
}
}
}
|
Java
|
class ideaalgo
{
FileInputStream fin,fkey,fenc1;
DataOutputStream fdec,fenc;
int step1,step2,step3,step4,step5,step6,step7,step8,step9,step10,step11,step12,step13,step14;
int t;
int index=0,j1,i1,i,mark,k1,k2,k;
int iz[]=new int[52];
int size;
byte buf[],keybuf[];
int ft,ft1,nl,np=0,p;
int x[]=new int[5];
int z[]=new int[52];
byte buf1[];
String file2,file3,file4;
ideaalgo()
{
file2="key1.txt";
}
ideaalgo(String file1)
{
file2="key1.txt";
file3="enc.txt";
file4="dec.txt";
try
{
fin=new FileInputStream(file1);
fenc1=new FileInputStream(file3);
fenc=new DataOutputStream(new FileOutputStream(file3));
}
catch(Exception e)
{
System.out.println(e);
}
}
// It generates 52 keys which is used to encrypt the data
void procedure()
{
try
{
fkey=new FileInputStream(file2);
}
catch(Exception e)
{
System.out.println(e);
}
keybuf= new byte[16];
try
{
fkey.read(keybuf);
z= new int[52];
j1=0;
i1=0;
for(i=0;i<52;i++)
z[i]=0;
while( i1<8)
{
if((j1+1)%2==0)
{
z[i1]|=keybuf[j1]; // dividing 64 bit cypher block into four 16 bit registers
i1++;
}
else
{
z[i1]=keybuf[j1];
z[i1]<<=8;
}
j1++;
}
i=0;
for(j1=1;j1<=5;j1++)
{
i++;
z[i+7]=((z[i]<<9)&0xfe00)|((z[i+1]>>7)&0x1ff);
z[i+8]=((z[i+1]<<9)&0xfe00)|((z[i+2]>>7)&0x1ff);
z[i+9]=((z[i+2]<<9)&0xfe00)|((z[i+3]>>7)&0x1ff);
z[i+10]=((z[i+3]<<9)&0xfe00)|((z[i+4]>>7)&0x1ff);
z[i+11]=((z[i+4]<<9)&0xfe00)|((z[i+5]>>7)&0x1ff);
z[i+12]=((z[i+5]<<9)&0xfe00)|((z[i+6]>>7)&0x1ff);
z[i+13]=((z[i+6]<<9)&0xfe00)|((z[i-1]>>7)&0x1ff);
z[i+14]=((z[i-1]<<9)&0xfe00)|((z[i]>>7)&0x1ff);
i=i+7;
}
i1=41;
z[48]=((z[i1]<<9)&0xfe00)|((z[i1+1]>>7)&0x1ff);
z[49]=((z[i1+1]<<9)&0xfe00)|((z[i1+2]>>7)&0x1ff);
z[50]=((z[i1+2]<<9)&0xfe00)|((z[i1+3]>>7)&0x1ff);
z[51]=((z[i1+3]<<9)&0xfe00)|((z[i1+4]>>7)&0x1ff);
}
catch(Exception e)
{
System.out.println(e);
}
}
// This function encrypts the data using 52 keys and place the //o/p in a file
void encrypt()
{
try
{
size=fin.available();
p=size%8;
if(p!=0)
np=8-p;
size+=np;
if(p==0)
nl=size/8;
else
nl=size/8+1;
buf=new byte[8];
buf1=new byte[size+10];
fin.read(buf1);
int enc[]=new int[size];
mark=-8;
k2=0;
for(k=0;k<nl;k++)
{
mark+=8;
for(int k1=0;k1<8;k1++)
buf[k1]=buf1[mark+k1];
i=0;
for(i=0;i<4;i++)
x[i]=0;
j1=0;i1=0;
while( i1<=3)
{
if((j1+1)%2==0)
{
x[i1]|=buf[j1]; // dividing 64 bit cipher block into four 16 bit registers
i1++;
}
else
{
x[i1]=buf[j1];
x[i1]<<=8;
}
j1++;
}
// 7 rounds and 14 steps
for(i=0 ; i <48 ; )
{
step1=mul(x[0],z[i+0]);
step2=(x[1]+z[i+1])%65536;
step3=(x[2]+z[i+2])%65536;
step4=mul(x[3],z[i+3]);
step5=step1^step3;
step6=step2^step4;
step7=mul(step5,z[i+4]);
step8=(step6+step7)%65536;
step9=mul(step8,z[i+5]);
step10=(step7+step9)%65536;
step11=step1^step9;
step12=step3^step9;
step13=step2^step10;
step14=step4^step10;
x[0]=step11;
x[1]=step13;
x[2]=step12;
x[3]=step14;
i=i+6;
}
x[0]=mul(x[0],z[48]);
x[1]=(x[1]+z[49])%65536;
x[2]=(x[2]+z[50])%65536;
x[3]=mul(x[3],z[51]);
for(int t=0;t<4;t++)
{
ft1 =x[t]&255;
ft=x[t]>>8;
fenc.write((char)ft);
fenc.write((char)ft1);
}
}
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
// This function decrypts the data which in text file by using 52 keys
void decryption(String file)
{
try
{
fdec=new DataOutputStream(new FileOutputStream("dec.txt"));
fenc1=new FileInputStream(file);
}
catch(Exception e)
{
System.out.println(e);
}
try
{
size=fenc1.available();
np=0;
p=size%8;
if(p!=0)
np=8-p;
size+=np;
if(p==0)
nl=size/8;
else
nl=size/8+1;
buf1=new byte[size+10];
buf=new byte[8];
fenc1.read(buf1);
mark=-8;
int arr[]=new int [8];
for(k1=0;k1<nl;k1++)
{
mark+=8;
for(int k2=0;k2<8;k2++)
buf[k2]=buf1[mark+k2];
for(int k2=0;k2<8;k2++)
{
arr[k2]=0;
if(buf[k2]>=0)
arr[k2]=buf[k2];
else
arr[k2]=buf[k2]+256;
}
j1=0;i1=0;
while( i1<=3)
{
if((j1+1)%2==0)
{
x[i1]|=arr[j1]; // dividing 64 bit cypher block into four 16 bit registers
i1++;
}
else
{
x[i1]=arr[j1];
x[i1]<<=8;
}
j1++;
}
for(int t=0;t<4;t++)
{
ft1 =x[t]&255;
ft=x[t]>>8;
}
step1=mul( x[0] , minverse( z[48] ));
step2=( x[1] + ainverse( z[49] )) % 65536;
step3=( x[2] + ainverse( z[50] )) % 65536;
step4=mul( x[3] , minverse( z[51] ));
step5=step1^step3;
step6=step2^step4;
step7=mul(step5,z[46]);
step8=(step6+step7)%65536;
step9=mul(step8,z[47]);
step10=(step7+step9)%65536;
step11=step1^step9;
step12=step3^step9;
step13=step2^step10;
step14=step4^step10;
x[0]=step11;
x[1]=step12;
x[2]=step13;
x[3]=step14;
// 2nd round
int j2=40;
for(j1=1;j1<=7;j1++)
{
step1=mul( x[0] , minverse( z[j2+2] ));
step2=( x[1] + ainverse( z[j2+4] )) % 65536;
step3=( x[2] + ainverse( z[j2+3] )) % 65536;
t=step2;
step2=step3;
step3=t;
step4=mul( x[3] , minverse( z[j2+5] ));
step5=step1^step3;
step6=step2^step4;
step7=mul(step5,z[j2+0]);
step8=(step6+step7)%65536;
step9=mul(step8,z[j2+1]);
step10=(step7+step9)%65536;
step11=step1^step9;
step12=step3^step9;
step13=step2^step10;
step14=step4^step10;
x[0]=step11;
x[1]=step12;
x[2]=step13;
x[3]=step14;
j2=j2-6;
}
x[0]=mul(x[0],minverse(z[0]));
x[1]=(x[1]+ainverse(z[2]))%65536;
x[2]=(x[2]+ainverse(z[1]))%65536;
x[3]=mul(x[3],minverse(z[3]));
t=x[1];
x[1]=x[2];
x[2]=t;
for(int t=0;t<4;t++)
{
ft1 =x[t]&255;
ft=x[t]>>8;
fdec.write((char)ft);
fdec.write((char)ft1);
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
// It multiplies two numbers and returns (a*b)%65537
int mul( int a , int b)
{
double c,d;
if (a==0)
c=65536;
if(b==0)
d=65536;
c=(double)a;
d=(double)b;
a= (int)((c*d)%65537);
return a;
}
// It returns the multiplicative inverse modulo 65537 of z
int minverse(int z)
{
int to,t1;
int q,y;
if(z<=1)
return z;
t1=0x10001/z;
y=0x10001%z;
if(y==1)
return (0xffff&(1-t1));
to=1;
do
{
q=z/y;
z=z%y;
to+=q*t1;
if(z==1)
return to;
q=y/z;
y=y%z;
t1+=q*to;
}while(y!=1);
return (0xffff&(1-t1));
}
// It return the additive inverse of z
int ainverse(int z)
{
return (65536-z);
}
}
|
Java
|
public class PhraseSpecTest extends SimpleNLG4Test {
public PhraseSpecTest(String name) {
super(name);
}
/**
* Test SPhraseSpec
*/
@Test
public void testSPhraseSpec() {
// simple test of methods
SPhraseSpec c1 = (SPhraseSpec) phraseFactory.createClause();
c1.setVerb("give");
c1.setSubject("John");
c1.setObject("an apple");
c1.setIndirectObject("Mary");
c1.setFeature(Feature.TENSE, Tense.PAST);
c1.setFeature(Feature.NEGATED, true);
// check getXXX methods
Assert.assertEquals("give", getBaseForm(c1.getVerb()));
Assert.assertEquals("John", getBaseForm(c1.getSubject()));
Assert.assertEquals("an apple", getBaseForm(c1.getObject()));
Assert.assertEquals("Mary", getBaseForm(c1.getIndirectObject()));
Assert.assertEquals("John did not give Mary an apple", this.realiser //$NON-NLS-1$
.realise(c1).getRealisation());
// test modifier placement
SPhraseSpec c2 = (SPhraseSpec) phraseFactory.createClause();
c2.setVerb("see");
c2.setSubject("the man");
c2.setObject("me");
c2.addModifier("fortunately");
c2.addModifier("quickly");
c2.addModifier("in the park");
// try setting tense directly as a feature
c2.setFeature(Feature.TENSE, Tense.PAST);
Assert.assertEquals("fortunately the man quickly saw me in the park", this.realiser //$NON-NLS-1$
.realise(c2).getRealisation());
}
// get string for head of constituent
private String getBaseForm(NLGElement constituent) {
if (constituent == null)
return null;
else if (constituent instanceof StringElement)
return constituent.getRealisation();
else if (constituent instanceof WordElement)
return ((WordElement)constituent).getBaseForm();
else if (constituent instanceof InflectedWordElement)
return getBaseForm(((InflectedWordElement)constituent).getBaseWord());
else if (constituent instanceof PhraseElement)
return getBaseForm(((PhraseElement)constituent).getHead());
else
return null;
}
}
|
Java
|
@Component
public class GenericRestExternalTranslatorConfigDtoMapper extends AbstractExternalTranslatorConfigDtoMapper<ExternalTranslatorGenericRestConfigEntity, ExternalTranslatorGenericRestConfigDto> {
@Override
public boolean support(ExternalTranslatorConfigType configType) {
return configType == ExternalTranslatorConfigType.EXTERNAL_GENERIC_REST;
}
@Override
public ExternalTranslatorGenericRestConfigDto mapToDto(ExternalTranslatorGenericRestConfigEntity config) {
return fillDtoBuilder(ExternalTranslatorGenericRestConfigDto.builder(), config)
.method(config.getMethod())
.url(config.getUrl())
.queryHeaders(config.getQueryHeaders())
.queryParameters(config.getQueryParameters())
.bodyTemplate(config.getBodyTemplate().orElse(null))
.queryExtractor(config.getQueryExtractor())
.build();
}
@Override
public ExternalTranslatorGenericRestConfigEntity mapFromDto(ExternalTranslatorGenericRestConfigDto dto) {
return fillFromDto(dto, new ExternalTranslatorGenericRestConfigEntity(dto.getLabel(), dto.getLinkUrl(), dto.getMethod(), dto.getUrl(), dto.getQueryExtractor()));
}
@Override
public ExternalTranslatorGenericRestConfigEntity fillFromDto(ExternalTranslatorGenericRestConfigDto dto, ExternalTranslatorGenericRestConfigEntity entity) {
return fillEntity(entity, dto)
.setMethod(dto.getMethod())
.setUrl(dto.getUrl())
.setQueryHeaders(dto.getQueryHeaders())
.setQueryParameters(dto.getQueryParameters())
.setBodyTemplate(dto.getBodyTemplate())
.setQueryExtractor(dto.getQueryExtractor());
}
}
|
Java
|
@Interceptor
@FaultToleranceBinding
@Priority(Interceptor.Priority.PLATFORM_AFTER + 10)
public class FaultToleranceInterceptor {
private final Bean<?> interceptedBean;
private final FaultToleranceOperationProvider operationProvider;
private final StrategyCache cache;
private final FallbackHandlerProvider fallbackHandlerProvider;
private final MetricsProvider metricsProvider;
private final ExecutorService asyncExecutor;
private final EventLoop eventLoop;
private final Timer timer;
private final RequestContextController requestContextController;
private final CircuitBreakerMaintenanceImpl cbMaintenance;
private final SpecCompatibility specCompatibility;
@Inject
public FaultToleranceInterceptor(
@Intercepted Bean<?> interceptedBean,
FaultToleranceOperationProvider operationProvider,
StrategyCache cache,
FallbackHandlerProvider fallbackHandlerProvider,
MetricsProvider metricsProvider,
ExecutorHolder executorHolder,
RequestContextIntegration requestContextIntegration,
CircuitBreakerMaintenanceImpl cbMaintenance,
SpecCompatibility specCompatibility) {
this.interceptedBean = interceptedBean;
this.operationProvider = operationProvider;
this.cache = cache;
this.fallbackHandlerProvider = fallbackHandlerProvider;
this.metricsProvider = metricsProvider;
asyncExecutor = executorHolder.getAsyncExecutor();
eventLoop = executorHolder.getEventLoop();
timer = executorHolder.getTimer();
requestContextController = requestContextIntegration.get();
this.cbMaintenance = cbMaintenance;
this.specCompatibility = specCompatibility;
}
@AroundInvoke
public Object interceptCommand(InvocationContext interceptionContext) throws Exception {
Method method = interceptionContext.getMethod();
Class<?> beanClass = interceptedBean != null ? interceptedBean.getBeanClass() : method.getDeclaringClass();
InterceptionPoint point = new InterceptionPoint(beanClass, interceptionContext);
FaultToleranceOperation operation = operationProvider.get(beanClass, method);
if (specCompatibility.isOperationTrulyAsynchronous(operation)) {
return asyncFlow(operation, interceptionContext, point);
} else if (specCompatibility.isOperationPseudoAsynchronous(operation)) {
return futureFlow(operation, interceptionContext, point);
} else {
return syncFlow(operation, interceptionContext, point);
}
}
private Object asyncFlow(FaultToleranceOperation operation, InvocationContext interceptionContext,
InterceptionPoint point) {
FaultToleranceStrategy<Object> strategy = cache.getStrategy(point, () -> prepareAsyncStrategy(operation, point));
io.smallrye.faulttolerance.core.InvocationContext<Object> ctx = invocationContext(interceptionContext);
try {
return strategy.apply(ctx);
} catch (Exception e) {
return AsyncTypes.get(operation.getReturnType()).fromCompletionStage(failedStage(e));
}
}
private <T> T syncFlow(FaultToleranceOperation operation, InvocationContext interceptionContext, InterceptionPoint point)
throws Exception {
FaultToleranceStrategy<T> strategy = cache.getStrategy(point, () -> prepareSyncStrategy(operation, point));
io.smallrye.faulttolerance.core.InvocationContext<T> ctx = invocationContext(interceptionContext);
return strategy.apply(ctx);
}
private <T> Future<T> futureFlow(FaultToleranceOperation operation, InvocationContext interceptionContext,
InterceptionPoint point) throws Exception {
FaultToleranceStrategy<Future<T>> strategy = cache.getStrategy(point, () -> prepareFutureStrategy(operation, point));
io.smallrye.faulttolerance.core.InvocationContext<Future<T>> ctx = invocationContext(interceptionContext);
return strategy.apply(ctx);
}
@SuppressWarnings("unchecked")
private <T> io.smallrye.faulttolerance.core.InvocationContext<T> invocationContext(InvocationContext interceptionContext) {
io.smallrye.faulttolerance.core.InvocationContext<T> result = new io.smallrye.faulttolerance.core.InvocationContext<>(
() -> (T) interceptionContext.proceed());
result.set(InvocationContext.class, interceptionContext);
return result;
}
private FaultToleranceStrategy<Object> prepareAsyncStrategy(FaultToleranceOperation operation, InterceptionPoint point) {
// FaultToleranceStrategy expects that the input type and output type are the same, which
// isn't true for the conversion strategies used below (even though the entire chain does
// retain the type, the conversions are only intermediate)
// that's why we use raw types here, to work around this design choice
FaultToleranceStrategy result = invocation();
result = new AsyncTypesConversion.ToCompletionStage(result, AsyncTypes.get(operation.getReturnType()));
result = prepareComplectionStageChain((FaultToleranceStrategy<CompletionStage<Object>>) result, operation, point);
result = new AsyncTypesConversion.FromCompletionStage(result, AsyncTypes.get(operation.getReturnType()));
return result;
}
private <T> FaultToleranceStrategy<CompletionStage<T>> prepareComplectionStageChain(
FaultToleranceStrategy<CompletionStage<T>> invocation, FaultToleranceOperation operation, InterceptionPoint point) {
FaultToleranceStrategy<CompletionStage<T>> result = invocation;
result = new RequestScopeActivator<>(result, requestContextController);
Executor executor = operation.isThreadOffloadRequired() ? asyncExecutor : DirectExecutor.INSTANCE;
result = new CompletionStageExecution<>(result, executor);
if (operation.hasBulkhead()) {
int size = operation.getBulkhead().value();
int queueSize = operation.getBulkhead().waitingTaskQueue();
result = new CompletionStageThreadPoolBulkhead<>(result, "Bulkhead[" + point + "]",
size, queueSize);
}
if (operation.hasTimeout()) {
long timeoutMs = getTimeInMs(operation.getTimeout().value(), operation.getTimeout().unit());
result = new CompletionStageTimeout<>(result, "Timeout[" + point + "]",
timeoutMs,
new TimerTimeoutWatcher(timer));
}
if (operation.hasCircuitBreaker()) {
long delayInMillis = getTimeInMs(operation.getCircuitBreaker().delay(), operation.getCircuitBreaker().delayUnit());
result = new CompletionStageCircuitBreaker<>(result, "CircuitBreaker[" + point + "]",
getSetOfThrowables(operation.getCircuitBreaker().failOn()),
getSetOfThrowables(operation.getCircuitBreaker().skipOn()),
delayInMillis,
operation.getCircuitBreaker().requestVolumeThreshold(),
operation.getCircuitBreaker().failureRatio(),
operation.getCircuitBreaker().successThreshold(),
new SystemStopwatch());
String cbName = operation.hasCircuitBreakerName()
? operation.getCircuitBreakerName().value()
: UUID.randomUUID().toString();
cbMaintenance.register(cbName, (CircuitBreaker<?>) result);
}
if (operation.hasRetry()) {
long maxDurationMs = getTimeInMs(operation.getRetry().maxDuration(), operation.getRetry().durationUnit());
Supplier<BackOff> backoff = prepareRetryBackoff(operation);
result = new CompletionStageRetry<>(result,
"Retry[" + point + "]",
getSetOfThrowables(operation.getRetry().retryOn()),
getSetOfThrowables(operation.getRetry().abortOn()),
operation.getRetry().maxRetries(),
maxDurationMs,
() -> new TimerDelay(backoff.get(), timer),
new SystemStopwatch());
}
if (operation.hasFallback()) {
result = new CompletionStageFallback<>(
result,
"Fallback[" + point + "]",
prepareFallbackFunction(point, operation),
getSetOfThrowables(operation.getFallback().applyOn()),
getSetOfThrowables(operation.getFallback().skipOn()));
}
if (metricsProvider.isEnabled()) {
result = new CompletionStageMetricsCollector<>(result, getMetricsRecorder(operation, point));
}
if (!operation.isThreadOffloadRequired()) {
result = new RememberEventLoop<>(result, eventLoop);
}
return result;
}
private <T> FaultToleranceStrategy<T> prepareSyncStrategy(FaultToleranceOperation operation, InterceptionPoint point) {
FaultToleranceStrategy<T> result = invocation();
if (operation.hasBulkhead()) {
result = new SemaphoreBulkhead<>(result,
"Bulkhead[" + point + "]",
operation.getBulkhead().value());
}
if (operation.hasTimeout()) {
long timeoutMs = getTimeInMs(operation.getTimeout().value(), operation.getTimeout().unit());
result = new Timeout<>(result, "Timeout[" + point + "]",
timeoutMs,
new TimerTimeoutWatcher(timer));
}
if (operation.hasCircuitBreaker()) {
long delayInMillis = getTimeInMs(operation.getCircuitBreaker().delay(), operation.getCircuitBreaker().delayUnit());
result = new CircuitBreaker<>(result, "CircuitBreaker[" + point + "]",
getSetOfThrowables(operation.getCircuitBreaker().failOn()),
getSetOfThrowables(operation.getCircuitBreaker().skipOn()),
delayInMillis,
operation.getCircuitBreaker().requestVolumeThreshold(),
operation.getCircuitBreaker().failureRatio(),
operation.getCircuitBreaker().successThreshold(),
new SystemStopwatch());
String cbName = operation.hasCircuitBreakerName()
? operation.getCircuitBreakerName().value()
: UUID.randomUUID().toString();
cbMaintenance.register(cbName, (CircuitBreaker<?>) result);
}
if (operation.hasRetry()) {
long maxDurationMs = getTimeInMs(operation.getRetry().maxDuration(), operation.getRetry().durationUnit());
Supplier<BackOff> backoff = prepareRetryBackoff(operation);
result = new Retry<>(result,
"Retry[" + point + "]",
getSetOfThrowables(operation.getRetry().retryOn()),
getSetOfThrowables(operation.getRetry().abortOn()),
operation.getRetry().maxRetries(),
maxDurationMs,
() -> new ThreadSleepDelay(backoff.get()),
new SystemStopwatch());
}
if (operation.hasFallback()) {
result = new Fallback<>(
result,
"Fallback[" + point + "]",
prepareFallbackFunction(point, operation),
getSetOfThrowables(operation.getFallback().applyOn()),
getSetOfThrowables(operation.getFallback().skipOn()));
}
if (metricsProvider.isEnabled()) {
result = new MetricsCollector<>(result, getMetricsRecorder(operation, point), false);
}
return result;
}
private <T> FaultToleranceStrategy<Future<T>> prepareFutureStrategy(FaultToleranceOperation operation,
InterceptionPoint point) {
FaultToleranceStrategy<Future<T>> result = invocation();
result = new RequestScopeActivator<>(result, requestContextController);
if (operation.hasBulkhead()) {
int size = operation.getBulkhead().value();
int queueSize = operation.getBulkhead().waitingTaskQueue();
result = new FutureThreadPoolBulkhead<>(result, "Bulkhead[" + point + "]",
size, queueSize);
}
if (operation.hasTimeout()) {
long timeoutMs = getTimeInMs(operation.getTimeout().value(), operation.getTimeout().unit());
Timeout<Future<T>> timeout = new Timeout<>(result, "Timeout[" + point + "]",
timeoutMs,
new TimerTimeoutWatcher(timer));
result = new AsyncTimeout<>(timeout, asyncExecutor);
}
if (operation.hasCircuitBreaker()) {
long delayInMillis = getTimeInMs(operation.getCircuitBreaker().delay(), operation.getCircuitBreaker().delayUnit());
result = new CircuitBreaker<>(result, "CircuitBreaker[" + point + "]",
getSetOfThrowables(operation.getCircuitBreaker().failOn()),
getSetOfThrowables(operation.getCircuitBreaker().skipOn()),
delayInMillis,
operation.getCircuitBreaker().requestVolumeThreshold(),
operation.getCircuitBreaker().failureRatio(),
operation.getCircuitBreaker().successThreshold(),
new SystemStopwatch());
String cbName = operation.hasCircuitBreakerName()
? operation.getCircuitBreakerName().value()
: UUID.randomUUID().toString();
cbMaintenance.register(cbName, (CircuitBreaker<?>) result);
}
if (operation.hasRetry()) {
long maxDurationMs = getTimeInMs(operation.getRetry().maxDuration(), operation.getRetry().durationUnit());
Supplier<BackOff> backoff = prepareRetryBackoff(operation);
result = new Retry<>(result,
"Retry[" + point + "]",
getSetOfThrowables(operation.getRetry().retryOn()),
getSetOfThrowables(operation.getRetry().abortOn()),
operation.getRetry().maxRetries(),
maxDurationMs,
() -> new ThreadSleepDelay(backoff.get()),
new SystemStopwatch());
}
if (operation.hasFallback()) {
result = new Fallback<>(result,
"Fallback[" + point + "]",
prepareFallbackFunction(point, operation),
getSetOfThrowables(operation.getFallback().applyOn()),
getSetOfThrowables(operation.getFallback().skipOn()));
}
if (metricsProvider.isEnabled()) {
result = new MetricsCollector<>(result, getMetricsRecorder(operation, point), true);
}
result = new FutureExecution<>(result, asyncExecutor);
return result;
}
private Supplier<BackOff> prepareRetryBackoff(FaultToleranceOperation operation) {
long delayMs = getTimeInMs(operation.getRetry().delay(), operation.getRetry().delayUnit());
long jitterMs = getTimeInMs(operation.getRetry().jitter(), operation.getRetry().jitterDelayUnit());
Jitter jitter = jitterMs == 0 ? Jitter.ZERO : new RandomJitter(jitterMs);
if (operation.hasExponentialBackoff()) {
int factor = operation.getExponentialBackoff().factor();
long maxDelay = getTimeInMs(operation.getExponentialBackoff().maxDelay(),
operation.getExponentialBackoff().maxDelayUnit());
return () -> new ExponentialBackOff(delayMs, factor, jitter, maxDelay);
} else if (operation.hasFibonacciBackoff()) {
long maxDelay = getTimeInMs(operation.getFibonacciBackoff().maxDelay(),
operation.getFibonacciBackoff().maxDelayUnit());
return () -> new FibonacciBackOff(delayMs, jitter, maxDelay);
} else if (operation.hasCustomBackoff()) {
Class<? extends CustomBackoffStrategy> strategy = operation.getCustomBackoff().value();
return () -> {
CustomBackoffStrategy instance;
try {
instance = strategy.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw sneakyThrow(e);
}
instance.init(delayMs);
return new CustomBackOff(instance::nextDelayInMillis);
};
} else {
return () -> new ConstantBackOff(delayMs, jitter);
}
}
private <V> FallbackFunction<V> prepareFallbackFunction(InterceptionPoint point, FaultToleranceOperation operation) {
Method fallbackMethod = null;
Class<? extends FallbackHandler<?>> fallback = operation.getFallback().value();
String fallbackMethodName = operation.getFallback().fallbackMethod();
if (fallback.equals(org.eclipse.microprofile.faulttolerance.Fallback.DEFAULT.class) && !"".equals(fallbackMethodName)) {
try {
Method method = point.method();
fallbackMethod = SecurityActions.getDeclaredMethod(point.beanClass(), method.getDeclaringClass(),
fallbackMethodName, method.getGenericParameterTypes());
if (fallbackMethod == null) {
throw new FaultToleranceException("Could not obtain fallback method " + fallbackMethodName);
}
SecurityActions.setAccessible(fallbackMethod);
} catch (PrivilegedActionException e) {
throw new FaultToleranceException("Could not obtain fallback method", e);
}
}
Class<?> returnType = operation.getReturnType();
FallbackFunction<V> fallbackFunction;
Method fallbackMethodFinal = fallbackMethod;
if (fallbackMethod != null) {
boolean isDefault = fallbackMethodFinal.isDefault();
fallbackFunction = ctx -> {
InvocationContext interceptionContext = ctx.invocationContext.get(InvocationContext.class);
ExecutionContextWithInvocationContext executionContext = new ExecutionContextWithInvocationContext(
interceptionContext);
try {
V result;
if (isDefault) {
// Workaround for default methods (used e.g. in MP Rest Client)
//noinspection unchecked
result = (V) DefaultMethodFallbackProvider.getFallback(fallbackMethodFinal, executionContext);
} else {
//noinspection unchecked
result = (V) fallbackMethodFinal.invoke(interceptionContext.getTarget(),
interceptionContext.getParameters());
}
result = AsyncTypes.toCompletionStageIfRequired(result, returnType);
return result;
} catch (Throwable e) {
if (e instanceof InvocationTargetException) {
e = e.getCause();
}
if (e instanceof Exception) {
throw (Exception) e;
}
throw new FaultToleranceException("Error during fallback method invocation", e);
}
};
} else {
FallbackHandler<V> fallbackHandler = fallbackHandlerProvider.get(operation);
if (fallbackHandler != null) {
fallbackFunction = ctx -> {
InvocationContext interceptionContext = ctx.invocationContext.get(InvocationContext.class);
ExecutionContextWithInvocationContext executionContext = new ExecutionContextWithInvocationContext(
interceptionContext);
executionContext.setFailure(ctx.failure);
V result = fallbackHandler.handle(executionContext);
result = AsyncTypes.toCompletionStageIfRequired(result, returnType);
return result;
};
} else {
throw new FaultToleranceException("Could not obtain fallback handler for " + point);
}
}
if (specCompatibility.isOperationTrulyAsynchronous(operation) && operation.isThreadOffloadRequired()) {
fallbackFunction = new AsyncFallbackFunction(fallbackFunction, asyncExecutor);
}
return fallbackFunction;
}
private long getTimeInMs(long time, ChronoUnit unit) {
return Duration.of(time, unit).toMillis();
}
private SetOfThrowables getSetOfThrowables(Class<? extends Throwable>[] throwableClasses) {
if (throwableClasses == null) {
return SetOfThrowables.EMPTY;
}
return SetOfThrowables.create(Arrays.asList(throwableClasses));
}
private MetricsRecorder getMetricsRecorder(FaultToleranceOperation operation, InterceptionPoint point) {
return cache.getMetrics(point, () -> metricsProvider.create(operation));
}
}
|
Java
|
public abstract class BooleanFormula {
public abstract boolean presentIn(Instance instance);
public abstract SddFormula toTerm();
public abstract boolean isLiteral();
public abstract int size();
public boolean makesRedundant(BooleanFormula o){
return false;
}
public abstract String getName();
public abstract BooleanFormula convertToTermRepresentation(String string);
public abstract String convertToString();
public abstract boolean containsVar(int f);
public abstract long[] getParents();
protected double probabilityInData = -1;
protected double lastKLD = -1;
public void setProbabilityInData(double probabilityInData) {
this.probabilityInData=probabilityInData;
}
public double getProbabilityInData() {
return probabilityInData;
}
public void setLastKLD(double lastKLD) {
this.lastKLD=lastKLD;
}
public double getLastKLD() {
return lastKLD;
}
}
|
Java
|
public class GetPermissionsByAdElementIdQueryTest extends AbstractUserQueryTest<IdQueryParameters, GetPermissionsByAdElementIdQuery<IdQueryParameters>> {
@Mock
private PermissionDao permissionDaoMock;
@Test
public void testQueryExecution() {
// Prepare the query parameters
Guid adElementGuid = Guid.newGuid();
when(getQueryParameters().getId()).thenReturn(adElementGuid);
// Create expected result
Permission expected = new Permission();
expected.setAdElementId(adElementGuid);
// Mock the Daos
when(permissionDaoMock.getAllForAdElement
(adElementGuid, getQuery().getEngineSessionSeqId(), getQueryParameters().isFiltered())).
thenReturn(Collections.singletonList(expected));
getQuery().executeQueryCommand();
// Assert the query's results
@SuppressWarnings("unchecked")
List<Permission> actual = getQuery().getQueryReturnValue().getReturnValue();
assertEquals(1, actual.size(), "Wrong number of returned permissions");
assertEquals(expected, actual.get(0), "Wrong returned permissions");
}
}
|
Java
|
public class TwoLevelMorphologicParserCache implements MorphologicParserCache {
private boolean built = false;
private int l2MaxSize;
private final MorphologicParserCache l1Cache;
private int l2Size;
private Map<String, List<MorphemeContainer>> l2Cache;
/**
* See documentation of <code>TwoLevelMorphologicParserCache</code>
*
* @param l2MaxSize Max size of cache level 2
* @param l1Cache L1 cache to use
*/
public TwoLevelMorphologicParserCache(int l2MaxSize, MorphologicParserCache l1Cache) {
this.l2MaxSize = l2MaxSize;
this.l1Cache = l1Cache;
this.l2Cache = new HashMap<String, List<MorphemeContainer>>(l2MaxSize);
this.l2Size = 0;
}
@Override
public List<MorphemeContainer> get(String input) {
final List<MorphemeContainer> morphemeContainers = l2Cache.get(input);
if (morphemeContainers != null) {
return morphemeContainers;
} else {
return l1Cache.get(input);
}
}
@Override
public void put(String input, List<MorphemeContainer> morphemeContainers) {
//noinspection SynchronizeOnNonFinalField
synchronized (l2Cache) {
// l2Cache should not be changed during put operation.
// remember : there can be multiple threads accessing this instance of TwoLevelMorphologicParserCache
l2Cache.put(input, morphemeContainers == null ? Collections.<MorphemeContainer>emptyList() : morphemeContainers);
l2Size++;
}
if (l2Size >= l2MaxSize) {
//noinspection SynchronizeOnNonFinalField
synchronized (l2Cache) {
// l2Cache should not be changed during bulk insert to l1Cache operation
l1Cache.putAll(l2Cache);
// TODO: weird code! lock is on l2Cache, but it is reinitialized!
// shouldn't the lock be on 'this' ?
l2Cache = new HashMap<String, List<MorphemeContainer>>(l2MaxSize);
l2Size = 0;
}
}
}
@Override
public void putAll(Map<String, List<MorphemeContainer>> map) {
if (l2Size + map.size() >= l2MaxSize) {
//noinspection SynchronizeOnNonFinalField
synchronized (l2Cache) {
l1Cache.putAll(l2Cache);
l1Cache.putAll(map);
// TODO: weird code! lock is on l2Cache, but it is reinitialized!
// shouldn't the lock be on 'this' ?
l2Cache = new HashMap<String, List<MorphemeContainer>>(l2MaxSize);
l2Size = 0;
}
} else {
//noinspection SynchronizeOnNonFinalField
synchronized (l2Cache) {
l2Cache.putAll(map);
l2Size += map.size();
}
}
}
@Override
public void build(MorphologicParser parser) {
// cannot build self, since it is online.
// but l1Cache might need building
if(l1Cache.isNotBuilt())
l1Cache.build(parser);
built = true;
}
@Override
public boolean isNotBuilt() {
return !this.built;
}
}
|
Java
|
public class ClientHandler extends Thread {
private static final String CMD_PUBLIC_MESSAGE = "msg";
private static final String CMD_PRIVATE_MESSAGE = "privmsg";
private static final String CMD_MSG_OK = "msgok";
private static final String CMD_HELP = "help";
private static final String CMD_LOGIN = "login";
private static final String CMD_LOGIN_OK = "loginok";
private static final String CMD_USERS = "users";
private static final String CMD_JOKE = "joke";
private static final String ERR_NOT_SUPPORTED = "cmderr command not supported";
private static final String ERR_USERNAME_TAKEN = "loginerr username already in use";
private static final String ERR_INCORRECT_USERNAME = "loginerr incorrect username format";
private static final String ERR_INCORRECT_RECIPIENT = "msgerr incorrect recipient";
private static final String ERR_UNAUTHORIZED = "msgerr unauthorized";
private final Socket socket;
private final Server server;
private boolean needToRun = true;
private final BufferedReader inFromClient;
private final PrintWriter outToClient;
private String username;
// This flag will be set to true once the user logs in with a valid username
private boolean loggedIn = false;
// Incremented by 1 for each user
private static int userCounter = 1;
/**
* ClientHandler constructor
*
* @param clientSocket Socket for this particular client
* @param server The main server class which manages all the connections
*/
public ClientHandler(Socket clientSocket, Server server) {
this.socket = clientSocket;
this.server = server;
this.inFromClient = this.createInputStreamReader();
this.outToClient = this.createOutputStreamWriter();
this.username = this.generateUniqueUsername();
}
/**
* Generate a unique username
*
* @return a unique username
*/
private String generateUniqueUsername() {
String username = "user" + (userCounter++);
// Make sure the generated username does not collide with any of the other users
while (!this.server.isUsernameAvailable(username)) {
username = "user" + (userCounter++);
}
return username;
}
/**
* Create buffered input stream reader for the socket
*
* @return The input stream reader or null on error
*/
private BufferedReader createInputStreamReader() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
} catch (IOException e) {
Server.log("Could not setup the input stream: " + e.getMessage());
}
return reader;
}
/**
* Create writer which can be used to send data to the client (to the socket)
*
* @return The output-stream writer or null on error
*/
private PrintWriter createOutputStreamWriter() {
PrintWriter writer = null;
try {
writer = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
Server.log("Could not setup the output stream: " + e.getMessage());
}
return writer;
}
/**
* Handle the conversation according to the protocol
*/
public void run() {
while (this.needToRun) {
Message message = this.readClientMessage();
if (message != null) {
Server.log(this.getId() + ": " + message);
switch (message.getCommand()) {
case CMD_PUBLIC_MESSAGE:
this.handlePublicMessage(message.getArguments());
break;
case CMD_PRIVATE_MESSAGE:
this.forwardPrivateMessage(message);
break;
case CMD_HELP:
this.send("supported msg privmsg login users joke help");
break;
case CMD_LOGIN:
this.handleLogin(message.getArguments());
break;
case CMD_USERS:
this.send(CMD_USERS + " " + this.server.getActiveUsernames());
break;
case CMD_JOKE:
this.send(CMD_JOKE + " " + Jokes.getRandomJoke());
break;
default:
this.send(ERR_NOT_SUPPORTED);
}
} else {
Server.log("Error while reading client input, probably socket is closed, exiting...");
this.needToRun = false;
}
}
Server.log("Done processing client");
this.closeSocket();
this.server.removeClientHandler(this);
}
/**
* Try to log in with the given username. Send response to the client.
*
* @param username The username to use for this client
*/
private void handleLogin(String username) {
if (isAlphaNumeric(username)) {
if (this.server.isUsernameAvailable(username)) {
this.username = username;
this.loggedIn = true;
this.send(CMD_LOGIN_OK);
} else {
this.send(ERR_USERNAME_TAKEN);
}
} else {
this.send(ERR_INCORRECT_USERNAME);
}
}
/**
* Check if the given string contains only alphanumeric characters
* Function taken from: https://www.techiedelight.com/check-string-contains-alphanumeric-characters-java/
*
* @param s The string to check
* @return True if the string contains alphanumerics only, false if it contains any other characters
*/
public static boolean isAlphaNumeric(String s) {
return s != null && s.matches("^[a-zA-Z0-9]*$");
}
/**
* Forward the message to all other clients, except this one who sent it.
* Send also a response to the sender, according to the protocol.
*
* @param message The message to forward
*/
private void handlePublicMessage(String message) {
String forwardedMessage = CMD_PUBLIC_MESSAGE + " " + this.username + " " + message;
int recipientCount = this.server.forwardToAllClientsExcept(forwardedMessage, this);
this.send(CMD_MSG_OK + " " + recipientCount);
}
/**
* Forward a private message to necessary recipient
*
* @param m The received message
*/
private void forwardPrivateMessage(Message m) {
if (!this.isLoggedIn()) {
this.send(ERR_UNAUTHORIZED);
return;
}
// Split the arguments into recipient and message
String arguments = m.getArguments();
if (arguments != null) {
String[] parts = arguments.split(" ", 2);
if (parts.length == 2) {
String recipient = parts[0];
String message = CMD_PRIVATE_MESSAGE + " " + recipient + " " + parts[1];
if (this.server.forwardPrivateMessage(recipient, message)) {
this.send(CMD_MSG_OK + " 1");
} else {
this.send(ERR_INCORRECT_RECIPIENT);
}
} else {
this.send(ERR_NOT_SUPPORTED);
}
} else {
this.send(ERR_NOT_SUPPORTED);
}
}
/**
* Return true if this client has logged in with a proper username
*
* @return True if logged in, false if not
*/
public boolean isLoggedIn() {
return this.loggedIn;
}
/**
* Read one message from the client (from the socket)
*
* @return The message or null on error
*/
private Message readClientMessage() {
String receivedInputLine = null;
try {
receivedInputLine = this.inFromClient.readLine();
} catch (IOException e) {
Server.log("Error while reading the socket input: " + e.getMessage());
}
return Message.createFromInput(receivedInputLine);
}
/**
* Send a message to the client. Newline appended automatically
*
* @param message The message to send
*/
public void send(String message) {
this.outToClient.println(message);
}
/**
* Close socket connection for this client
*/
private void closeSocket() {
Server.log("Closing client socket...");
try {
this.socket.close();
} catch (IOException e) {
Server.log("Error while closing a client socket: " + e.getMessage());
}
Server.log("Client socket closed");
}
/**
* Check if this client has the provided username
*
* @param username The username to check
* @return true if this client has the given username, false if it doesn't
*/
public boolean hasUsername(String username) {
return this.username.equals(username);
}
/**
* Return the username of the current user
*
* @return The username for this client
*/
public String getUsername() {
return this.username;
}
}
|
Java
|
@RunWith(Parameterized.class)
@DBUnit(url = "jdbc:h2:mem:test", driver = "org.h2.Driver", user = "sa", password = "sa")
public class ParameterizedTest {
private int given;
private int expected;
@Rule public final DBUnitRule dbUnitRule = DBUnitRule.instance();
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[] {0, 0}, new Object[] {1, 1}, new Object[] {2, 2});
}
public ParameterizedTest(int given, int expected) {
this.given = given;
this.expected = expected;
}
@Test
public void shouldJustRunMoreThanOneTime() {
Assertions.assertThat(given).isEqualTo(expected);
}
}
|
Java
|
@SuppressWarnings("unused")
public class ProcessorHelper {
private final static Logger logger = LoggerFactory
.getLogger(ProcessorHelper.class);
@SuppressWarnings("null")
public static OkHttpClient configureClient(final OkHttpClient client) {
final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(final X509Certificate[] chain,
final String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(final X509Certificate[] chain,
final String authType) throws CertificateException {
}
} };
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, certs, new SecureRandom());
} catch (final java.security.GeneralSecurityException ex) {
}
try {
final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(final String hostname,
final SSLSession session) {
return true;
}
};
client.setHostnameVerifier(hostnameVerifier);
client.setSslSocketFactory(ctx.getSocketFactory());
} catch (final Exception e) {
}
return client;
}
public static OkHttpClient createClient() {
final OkHttpClient client = new OkHttpClient();
return configureClient(client);
}
@SuppressWarnings("rawtypes")
public static Callback createCallback(final String url) {
return new Callback() {
@Override
public void onFailure(Call call, Throwable t) {
logger.info(t.getMessage());
}
@Override
public void onResponse(Call call, Response response) {
logger.info("URL : " + url + "\tStatus : "+ response.body());
}
};
}
public static WebHookService createWebHookService(final String url) {
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url) // On AVD
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(WebHookService.class);
// final OkHttpClient client = ProcessorHelper.createClient();
// final Retrofit restAdapter = new Retrofit.Builder().baseUrl(url).build();
// return restAdapter.create(WebHookService.class);
}
}
|
Java
|
public class KafkaNotificationMetaData implements PluginMetaData {
private static final String PLUGIN_PROPERTIES = "cn.qingmg.graylog-plugin-kafka-notification/graylog-plugin.properties";
@Override
public String getUniqueId() {
return "cn.qingmg.graylog.plugin.kafka.notification.KafkaNotificationPlugin";
}
@Override
public String getName() {
return "KafkaNotification";
}
@Override
public String getAuthor() {
return "青木恭 <[email protected]>";
}
@Override
public URI getURL() {
return URI.create("https://github.com/https://github.com/qingmg/graylog-plugin-kafka-notification.git");
}
@Override
public Version getVersion() {
return Version.fromPluginProperties(getClass(), PLUGIN_PROPERTIES, "version", Version.from(0, 0, 0, "unknown"));
}
@Override
public String getDescription() {
// TODO Insert correct plugin description
return "Description of KafkaNotification plugin";
}
@Override
public Version getRequiredVersion() {
return Version.fromPluginProperties(getClass(), PLUGIN_PROPERTIES, "graylog.version", Version.from(0, 0, 0, "unknown"));
}
@Override
public Set<ServerStatus.Capability> getRequiredCapabilities() {
return Collections.emptySet();
}
}
|
Java
|
public class SshServerTest extends BaseTest {
@Test
public void stopMethodShouldBeIdempotent() throws Exception {
SshServer sshd = new SshServer();
sshd.stop();
sshd.stop();
sshd.stop();
}
@Test
public void testExecutorShutdownFalse() throws Exception {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
SshServer sshd = createTestServer();
sshd.setScheduledExecutorService(executorService);
sshd.start();
sshd.stop();
assertFalse(executorService.isShutdown());
executorService.shutdownNow();
}
@Test
public void testExecutorShutdownTrue() throws Exception {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
SshServer sshd = createTestServer();
sshd.setScheduledExecutorService(executorService, true);
sshd.start();
sshd.stop();
assertTrue(executorService.isShutdown());
}
@Test
public void testDynamicPort() throws Exception {
SshServer sshd = createTestServer();
sshd.setHost("localhost");
sshd.start();
assertNotEquals(0, sshd.getPort());
sshd.stop();
}
private SshServer createTestServer() {
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
sshd.setShellFactory(new EchoShellFactory());
sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
return sshd;
}
}
|
Java
|
public class CallStack {
/**
* The call stack.
*/
private ArrayList<Procedure> stack = new ArrayList<>();
/**
* Checks if the specified procedure exists in the call stack.
*
* @param proc the procedure definition
*
* @return true if the procedure exists in the call stack, or
* false otherwise
*/
public boolean contains(Procedure proc) {
return stack.contains(proc);
}
/**
* Returns the current height of the call stack.
*
* @return the current height of the call stack
*/
public int height() {
return stack.size();
}
/**
* Returns the bottom procedure in the stack, i.e. the first
* procedure in the call chain.
*
* @return the bottom procedure in the stack, or
* null if the stack is empty
*/
public Procedure bottom() {
return (stack.size() > 0) ? (Procedure) stack.get(0) : null;
}
/**
* Returns the top procedure in the stack, i.e. the last
* procedure in the call chain.
*
* @return the top procedure in the stack, or
* null if the stack is empty
*/
public Procedure top() {
return (stack.size() > 0) ? (Procedure) stack.get(stack.size() - 1) : null;
}
/**
* Returns all procedures on the stack in an array.
*
* @return an array with all the procedures on the stack
*/
public Procedure[] toArray() {
Procedure[] res = new Procedure[stack.size()];
stack.toArray(res);
return res;
}
/**
* Adds a new last entry to the call stack.
*
* @param proc the procedure being called
* @param bindings the bindings used
*/
void push(Procedure proc, Bindings bindings) {
stack.add(proc);
}
/**
* Removes the last entry in the call stack.
*/
void pop() {
if (stack.size() > 0) {
stack.remove(stack.size() - 1);
}
}
}
|
Java
|
abstract public class Pool<T> {
public final int max;
private final Array<T> freeObjects;
/** Creates a pool with an initial capacity of 16 and no maximum. */
public Pool () {
this(16, Integer.MAX_VALUE);
}
/** Creates a pool with the specified initial capacity and no maximum. */
public Pool (int initialCapacity) {
this(initialCapacity, Integer.MAX_VALUE);
}
/** @param max The maximum number of free objects to store in this pool. */
public Pool (int initialCapacity, int max) {
freeObjects = new Array(false, initialCapacity);
this.max = max;
}
abstract protected T newObject ();
/** Returns an object from this pool. The object may be new (from {@link #newObject()}) or reused (previously
* {@link #free(Object) freed}). */
public T obtain () {
return freeObjects.size == 0 ? newObject() : freeObjects.pop();
}
/** Puts the specified object in the pool, making it eligible to be returned by {@link #obtain()}. If the pool already contains
* {@link #max} free objects, the specified object is ignored. */
public void free (T object) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
if (freeObjects.size < max) freeObjects.add(object);
}
/** Puts the specified objects in the pool.
* @see #free(Object) */
public void free (Array<T> objects) {
for (int i = 0, n = Math.min(objects.size, max - freeObjects.size); i < n; i++)
freeObjects.add(objects.get(i));
}
/** Removes all free objects from this pool. */
public void clear () {
freeObjects.clear();
}
}
|
Java
|
public class Bounds {
public static Bounds EMPTY_BOUNDS = new Bounds(0, 0, 0, 0);
private static final Cache cache = new Cache();
public static Bounds create(int x, int y, int wid, int ht) {
int hashCode = 13 * (31 * (31 * x + y) + wid) + ht;
Object cached = cache.get(hashCode);
if (cached != null) {
Bounds bds = (Bounds) cached;
if (bds.x == x && bds.y == y && bds.wid == wid && bds.ht == ht) return bds;
}
Bounds ret = new Bounds(x, y, wid, ht);
cache.put(hashCode, ret);
return ret;
}
public static Bounds create(java.awt.Rectangle rect) {
return create(rect.x, rect.y, rect.width, rect.height);
}
public static Bounds create(Location pt) {
return create(pt.getX(), pt.getY(), 1, 1);
}
private final int x;
private final int y;
private final int wid;
private final int ht;
private Bounds(int x, int y, int wid, int ht) {
this.x = x;
this.y = y;
this.wid = wid;
this.ht = ht;
if (wid < 0) { x += wid / 2; wid = 0; }
if (ht < 0) { y += ht / 2; ht = 0; }
}
@Override
public boolean equals(Object other_obj) {
if (!(other_obj instanceof Bounds)) return false;
Bounds other = (Bounds) other_obj;
return x == other.x && y == other.y
&& wid == other.wid && ht == other.ht;
}
@Override
public int hashCode() {
int ret = 31 * x + y;
ret = 31 * ret + wid;
ret = 31 * ret + ht;
return ret;
}
@Override
public String toString() {
return "(" + x + "," + y + "): " + wid + "x" + ht;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return wid;
}
public int getHeight() {
return ht;
}
public Rectangle toRectangle() {
return new Rectangle(x, y, wid, ht);
}
public boolean contains(Location p) {
return contains(p.getX(), p.getY(), 0);
}
public boolean contains(Location p, int allowedError) {
return contains(p.getX(), p.getY(), allowedError);
}
public boolean contains(int px, int py) {
return contains(px, py, 0);
}
public boolean contains(int px, int py, int allowedError) {
return px >= x - allowedError && px < x + wid + allowedError
&& py >= y - allowedError && py < y + ht + allowedError;
}
public boolean contains(int x, int y, int wid, int ht) {
int oth_x = (wid <= 0 ? x : x + wid - 1);
int oth_y = (ht <= 0 ? y : y + ht - 1);
return contains(x, y) && contains(oth_x, oth_y);
}
public boolean contains(Bounds bd) {
return contains(bd.x, bd.y, bd.wid, bd.ht);
}
public boolean borderContains(Location p, int fudge) {
return borderContains(p.getX(), p.getY(), fudge);
}
public boolean borderContains(int px, int py, int fudge) {
int x1 = x + wid - 1;
int y1 = y + ht - 1;
if (Math.abs(px - x) <= fudge || Math.abs(px - x1) <= fudge) {
// maybe on east or west border?
return y - fudge >= py && py <= y1 + fudge;
}
if (Math.abs(py - y) <= fudge || Math.abs(py - y1) <= fudge) {
// maybe on north or south border?
return x - fudge >= px && px <= x1 + fudge;
}
return false;
}
public Bounds add(Location p) {
return add(p.getX(), p.getY());
}
public Bounds add(int x, int y) {
if (this == EMPTY_BOUNDS) return Bounds.create(x, y, 1, 1);
if (contains(x, y)) return this;
int new_x = this.x;
int new_wid = this.wid;
int new_y = this.y;
int new_ht = this.ht;
if (x < this.x) {
new_x = x;
new_wid = (this.x + this.wid) - x;
} else if (x >= this.x + this.wid) {
new_x = this.x;
new_wid = x - this.x + 1;
}
if (y < this.y) {
new_y = y;
new_ht = (this.y + this.ht) - y;
} else if (y >= this.y + this.ht) {
new_y = this.y;
new_ht = y - this.y + 1;
}
return create(new_x, new_y, new_wid, new_ht);
}
public Bounds add(int x, int y, int wid, int ht) {
if (this == EMPTY_BOUNDS) return Bounds.create(x, y, wid, ht);
int retX = Math.min(x, this.x);
int retY = Math.min(y, this.y);
int retWidth = Math.max(x + wid, this.x + this.wid) - retX;
int retHeight = Math.max(y + ht, this.y + this.ht) - retY;
if (retX == this.x && retY == this.y && retWidth == this.wid && retHeight == this.ht) {
return this;
} else {
return Bounds.create(retX, retY, retWidth, retHeight);
}
}
public Bounds add(Bounds bd) {
if (this == EMPTY_BOUNDS) return bd;
if (bd == EMPTY_BOUNDS) return this;
int retX = Math.min(bd.x, this.x);
int retY = Math.min(bd.y, this.y);
int retWidth = Math.max(bd.x + bd.wid, this.x + this.wid) - retX;
int retHeight = Math.max(bd.y + bd.ht, this.y + this.ht) - retY;
if (retX == this.x && retY == this.y && retWidth == this.wid && retHeight == this.ht) {
return this;
} else if (retX == bd.x && retY == bd.y && retWidth == bd.wid && retHeight == bd.ht) {
return bd;
} else {
return Bounds.create(retX, retY, retWidth, retHeight);
}
}
public Bounds expand(int d) { // d pixels in each direction
if (this == EMPTY_BOUNDS) return this;
if (d == 0) return this;
return create(x - d, y - d, wid + 2 * d, ht + 2 * d);
}
public Bounds translate(int dx, int dy) {
if (this == EMPTY_BOUNDS) return this;
if (dx == 0 && dy == 0) return this;
return create(x + dx, y + dy, wid, ht);
}
// rotates this around (xc,yc) assuming that this is facing in the
// from direction and the returned bounds should face in the to direction.
public Bounds rotate(Direction from, Direction to, int xc, int yc) {
int degrees = to.toDegrees() - from.toDegrees();
while (degrees >= 360) degrees -= 360;
while (degrees < 0) degrees += 360;
int dx = x - xc;
int dy = y - yc;
if (degrees == 90) {
return create(xc + dy, yc - dx - wid, ht, wid);
} else if (degrees == 180) {
return create(xc - dx - wid, yc - dy - ht, wid, ht);
} else if (degrees == 270) {
return create(xc - dy - ht, yc + dx, ht, wid);
} else {
return this;
}
}
public Bounds intersect(Bounds other) {
int x0 = this.x;
int y0 = this.y;
int x1 = x0 + this.wid;
int y1 = y0 + this.ht;
int x2 = other.x;
int y2 = other.y;
int x3 = x2 + other.wid;
int y3 = y2 + other.ht;
if (x2 > x0) x0 = x2;
if (y2 > y0) y0 = y2;
if (x3 < x1) x1 = x3;
if (y3 < y1) y1 = y3;
if (x1 < x0 || y1 < y0) {
return EMPTY_BOUNDS;
} else {
return create(x0, y0, x1 - x0, y1 - y0);
}
}
}
|
Java
|
public class LogServiceImpl implements LogService {
/**
* Creates a message.
* @param level the log level
* @param msg the message
* @param exception the thrown exception
* @return the computed message
*/
private String computeLogMessage(int level, String msg, Throwable exception) {
String message = null;
switch (level) {
case LogService.LOG_DEBUG:
message = "[DEBUG] " + msg;
break;
case LogService.LOG_ERROR:
message = "[ERROR] " + msg;
break;
case LogService.LOG_INFO:
message = "[INFO] " + msg;
break;
case LogService.LOG_WARNING:
message = "[WARNING] " + msg;
break;
default:
break;
}
if (exception != null) {
message = message + " : " + exception.getMessage();
}
return message;
}
/**
* Logs a message.
* @param arg0 the log level
* @param arg1 the message
* @see org.osgi.service.log.LogService#log(int, java.lang.String)
*/
public void log(int arg0, String arg1) {
System.err.println(computeLogMessage(arg0, arg1, null));
}
/**
* Logs a message.
* @param arg0 the log level
* @param arg1 the message
* @param arg2 the thrown exception
* @see org.osgi.service.log.LogService#log(int, java.lang.String)
*/
public void log(int arg0, String arg1, Throwable arg2) {
System.err.println(computeLogMessage(arg0, arg1, arg2));
}
/**
* Logs a message.
* @param arg0 the service reference
* @param arg1 the log level
* @param arg2 the message
* @see org.osgi.service.log.LogService#log(ServiceReference, int, String)
*/
public void log(ServiceReference arg0, int arg1, String arg2) {
System.err.println(computeLogMessage(arg1, arg2, null));
}
/**
* Logs a message.
* @param arg0 the service reference
* @param arg1 the log level
* @param arg2 the message
* @param arg3 the thrown exception
* @see org.osgi.service.log.LogService#log(ServiceReference, int, String, Throwable)
*/
public void log(ServiceReference arg0, int arg1, String arg2, Throwable arg3) {
System.err.println(computeLogMessage(arg1, arg2, arg3));
}
}
|
Java
|
@RunWith(DataProviderRunner.class)
public abstract class ChannelFactoryTestBase {
static final EndPoint SERVER_ADDRESS =
new LocalEndPoint(ChannelFactoryTestBase.class.getSimpleName() + "-server");
private static final int TIMEOUT_MILLIS = 500;
DefaultEventLoopGroup serverGroup;
DefaultEventLoopGroup clientGroup;
@Mock InternalDriverContext context;
@Mock DriverConfig driverConfig;
@Mock DriverExecutionProfile defaultProfile;
@Mock NettyOptions nettyOptions;
@Mock ProtocolVersionRegistry protocolVersionRegistry;
@Mock EventBus eventBus;
@Mock Compressor<ByteBuf> compressor;
// The server's I/O thread will store the last received request here, and block until the test
// thread retrieves it. This assumes readOutboundFrame() is called for each actual request, else
// the test will hang forever.
private final Exchanger<Frame> requestFrameExchanger = new Exchanger<>();
// The channel that accepts incoming connections on the server
private LocalServerChannel serverAcceptChannel;
// The channel to send responses to the last open connection
private volatile LocalChannel serverResponseChannel;
@Before
public void setup() throws InterruptedException {
MockitoAnnotations.initMocks(this);
serverGroup = new DefaultEventLoopGroup(1);
clientGroup = new DefaultEventLoopGroup(1);
when(context.getConfig()).thenReturn(driverConfig);
when(driverConfig.getDefaultProfile()).thenReturn(defaultProfile);
when(defaultProfile.isDefined(DefaultDriverOption.AUTH_PROVIDER_CLASS)).thenReturn(false);
when(defaultProfile.getDuration(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT))
.thenReturn(Duration.ofMillis(TIMEOUT_MILLIS));
when(defaultProfile.getDuration(DefaultDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT))
.thenReturn(Duration.ofMillis(TIMEOUT_MILLIS));
when(defaultProfile.getInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS)).thenReturn(1);
when(defaultProfile.getDuration(DefaultDriverOption.HEARTBEAT_INTERVAL))
.thenReturn(Duration.ofSeconds(30));
when(defaultProfile.getDuration(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT))
.thenReturn(Duration.ofSeconds(5));
when(context.getProtocolVersionRegistry()).thenReturn(protocolVersionRegistry);
when(context.getNettyOptions()).thenReturn(nettyOptions);
when(nettyOptions.ioEventLoopGroup()).thenReturn(clientGroup);
when(nettyOptions.channelClass()).thenAnswer((Answer<Object>) i -> LocalChannel.class);
when(nettyOptions.allocator()).thenReturn(ByteBufAllocator.DEFAULT);
when(context.getFrameCodec())
.thenReturn(
FrameCodec.defaultClient(
new ByteBufPrimitiveCodec(ByteBufAllocator.DEFAULT), Compressor.none()));
when(context.getSslHandlerFactory()).thenReturn(Optional.empty());
when(context.getEventBus()).thenReturn(eventBus);
when(context.getWriteCoalescer()).thenReturn(new PassThroughWriteCoalescer(null));
when(context.getCompressor()).thenReturn(compressor);
// Start local server
ServerBootstrap serverBootstrap =
new ServerBootstrap()
.group(serverGroup)
.channel(LocalServerChannel.class)
.localAddress(SERVER_ADDRESS.resolve())
.childHandler(new ServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind().sync();
serverAcceptChannel = (LocalServerChannel) channelFuture.sync().channel();
}
// Sets up the pipeline for our local server
private class ServerInitializer extends ChannelInitializer<LocalChannel> {
@Override
protected void initChannel(LocalChannel ch) throws Exception {
// Install a single handler that stores received requests, so that the test can check what
// the client sent
ch.pipeline()
.addLast(
new ChannelInboundHandlerAdapter() {
@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
requestFrameExchanger.exchange((Frame) msg);
}
});
// Store the channel so that the test can send responses back to the client
serverResponseChannel = ch;
}
}
protected Frame readOutboundFrame() {
try {
return requestFrameExchanger.exchange(null, TIMEOUT_MILLIS, MILLISECONDS);
} catch (InterruptedException e) {
fail("unexpected interruption while waiting for outbound frame", e);
} catch (TimeoutException e) {
fail("Timed out reading outbound frame");
}
return null; // never reached
}
protected void writeInboundFrame(Frame requestFrame, Message response) {
writeInboundFrame(requestFrame, response, requestFrame.protocolVersion);
}
private void writeInboundFrame(Frame requestFrame, Message response, int protocolVersion) {
serverResponseChannel.writeAndFlush(
Frame.forResponse(
protocolVersion,
requestFrame.streamId,
null,
Frame.NO_PAYLOAD,
Collections.emptyList(),
response));
}
/**
* Simulate the sequence of roundtrips to initialize a simple channel without authentication or
* keyspace (avoids repeating it in subclasses).
*/
protected void completeSimpleChannelInit() {
Frame requestFrame = readOutboundFrame();
assertThat(requestFrame.message).isInstanceOf(Options.class);
writeInboundFrame(requestFrame, TestResponses.supportedResponse("mock_key", "mock_value"));
requestFrame = readOutboundFrame();
assertThat(requestFrame.message).isInstanceOf(Startup.class);
writeInboundFrame(requestFrame, new Ready());
requestFrame = readOutboundFrame();
writeInboundFrame(requestFrame, TestResponses.clusterNameResponse("mockClusterName"));
}
ChannelFactory newChannelFactory() {
return new TestChannelFactory(context);
}
// A simplified channel factory to use in the tests.
// It only installs high-level handlers on the pipeline, not the frame codecs. So we'll receive
// Frame objects on the server side, which is simpler to test.
private static class TestChannelFactory extends ChannelFactory {
private TestChannelFactory(InternalDriverContext internalDriverContext) {
super(internalDriverContext);
}
@Override
ChannelInitializer<Channel> initializer(
EndPoint endPoint,
ProtocolVersion protocolVersion,
DriverChannelOptions options,
NodeMetricUpdater nodeMetricUpdater,
CompletableFuture<DriverChannel> resultFuture) {
return new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
try {
DriverExecutionProfile defaultProfile = context.getConfig().getDefaultProfile();
long setKeyspaceTimeoutMillis =
defaultProfile
.getDuration(DefaultDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT)
.toMillis();
int maxRequestsPerConnection =
defaultProfile.getInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS);
InFlightHandler inFlightHandler =
new InFlightHandler(
protocolVersion,
new StreamIdGenerator(maxRequestsPerConnection),
Integer.MAX_VALUE,
setKeyspaceTimeoutMillis,
channel.newPromise(),
null,
"test");
HeartbeatHandler heartbeatHandler = new HeartbeatHandler(defaultProfile);
ProtocolInitHandler initHandler =
new ProtocolInitHandler(
context,
protocolVersion,
getClusterName(),
endPoint,
options,
heartbeatHandler,
productType == null);
channel.pipeline().addLast("inflight", inFlightHandler).addLast("init", initHandler);
} catch (Throwable t) {
resultFuture.completeExceptionally(t);
}
}
};
}
}
@After
public void tearDown() throws InterruptedException {
serverAcceptChannel.close();
serverGroup
.shutdownGracefully(TIMEOUT_MILLIS, TIMEOUT_MILLIS * 2, TimeUnit.MILLISECONDS)
.sync();
clientGroup
.shutdownGracefully(TIMEOUT_MILLIS, TIMEOUT_MILLIS * 2, TimeUnit.MILLISECONDS)
.sync();
}
}
|
Java
|
private class ServerInitializer extends ChannelInitializer<LocalChannel> {
@Override
protected void initChannel(LocalChannel ch) throws Exception {
// Install a single handler that stores received requests, so that the test can check what
// the client sent
ch.pipeline()
.addLast(
new ChannelInboundHandlerAdapter() {
@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
requestFrameExchanger.exchange((Frame) msg);
}
});
// Store the channel so that the test can send responses back to the client
serverResponseChannel = ch;
}
}
|
Java
|
private static class TestChannelFactory extends ChannelFactory {
private TestChannelFactory(InternalDriverContext internalDriverContext) {
super(internalDriverContext);
}
@Override
ChannelInitializer<Channel> initializer(
EndPoint endPoint,
ProtocolVersion protocolVersion,
DriverChannelOptions options,
NodeMetricUpdater nodeMetricUpdater,
CompletableFuture<DriverChannel> resultFuture) {
return new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
try {
DriverExecutionProfile defaultProfile = context.getConfig().getDefaultProfile();
long setKeyspaceTimeoutMillis =
defaultProfile
.getDuration(DefaultDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT)
.toMillis();
int maxRequestsPerConnection =
defaultProfile.getInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS);
InFlightHandler inFlightHandler =
new InFlightHandler(
protocolVersion,
new StreamIdGenerator(maxRequestsPerConnection),
Integer.MAX_VALUE,
setKeyspaceTimeoutMillis,
channel.newPromise(),
null,
"test");
HeartbeatHandler heartbeatHandler = new HeartbeatHandler(defaultProfile);
ProtocolInitHandler initHandler =
new ProtocolInitHandler(
context,
protocolVersion,
getClusterName(),
endPoint,
options,
heartbeatHandler,
productType == null);
channel.pipeline().addLast("inflight", inFlightHandler).addLast("init", initHandler);
} catch (Throwable t) {
resultFuture.completeExceptionally(t);
}
}
};
}
}
|
Java
|
public class WorkItemState {
private static final Map<String, WorkItemState> ourAllStates = new HashMap<>();
public static final WorkItemState ACTIVE = register("Active");
public static final WorkItemState RESOLVED = register("Resolved");
public static final WorkItemState CLOSED = register("Closed");
@NonNls @NotNull private final String myName;
private WorkItemState(@NonNls @NotNull String name) {
myName = name;
}
@NotNull
public String getName() {
return myName;
}
@NotNull
public static WorkItemState from(@NotNull String stateName) {
return register(stateName);
}
@NotNull
private static synchronized WorkItemState register(@NotNull String stateName) {
WorkItemState result = ourAllStates.get(stateName);
if (result == null) {
result = new WorkItemState(stateName);
ourAllStates.put(stateName, result);
}
return result;
}
@Override
public String toString() {
return myName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof WorkItemState)) return false;
WorkItemState state = (WorkItemState)o;
return myName.equals(state.myName);
}
@Override
public int hashCode() {
return myName.hashCode();
}
}
|
Java
|
public class AddPart_Controller implements Initializable {
Stage stage;
Parent scene;
@FXML
private RadioButton InhousePartRadio;
@FXML
private RadioButton OutsourcedPartRadio;
@FXML
private TextField AddPartId;
@FXML
private TextField AddPartName;
@FXML
private TextField AddInventory;
@FXML
private TextField AddPrice;
@FXML
private TextField MinQty;
@FXML
private TextField MaxQty;
@FXML
private TextField CompNameMachID;
@FXML
private Label LabelCompanyName;
private int partCounter = Inventory.partIncrement();
private boolean IsInHouse;
/**
*
* @param event onMouseClick
* @param switchPath The FXML file that will be opened
* @throws IOException to catch read/write errors
*/
private void changeScreen(ActionEvent event, String switchPath) throws IOException {
Parent parent = FXMLLoader.load(getClass().getResource(switchPath));
Scene scene = new Scene(parent);
Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
}
/**
* Selects whether the part being
* added is Inhouse or Outsourced
*
* @param event onMouseClick
*/
public void SetInOut(ActionEvent event) {
if(InhousePartRadio.isSelected()) {
CompNameMachID.setPromptText("Machine ID");
CompNameMachID.clear();
LabelCompanyName.setText("Machine ID");
}
if(OutsourcedPartRadio.isSelected()) {
IsInHouse = false;
CompNameMachID.clear();
CompNameMachID.setPromptText("Company Name");
LabelCompanyName.setText("Company Name");
}
}
/**
* Saves new part to Part list
* This method includes part
* validation. Checking that
* the name is not empty and stock
* value is within max and min values.
* Min is also checked to be under max.
*
* @param event onMouseClick
* @throws IOException to catch read/write errors
*/
@FXML
void onActionSavePart(ActionEvent event) throws IOException {
String name = AddPartName.getText();
int stock = Integer.parseInt(AddInventory.getText());
double price = Double.parseDouble(AddPrice.getText());
int max = Integer.parseInt(MaxQty.getText());
int min = Integer.parseInt(MinQty.getText());
try {
if(min > max){
Alert maxAlert = new Alert(Alert.AlertType.ERROR);
maxAlert.setTitle("ERROR");
maxAlert.setContentText("Minimum stock quantity must not exceed maximum allowable quantity.");
maxAlert.showAndWait();
return;
}
if(stock < min){
Alert minAlert = new Alert(Alert.AlertType.ERROR);
minAlert.setTitle("ERROR");
minAlert.setContentText("Minimum stock quantity must not exceed current inventory quantity.");
minAlert.showAndWait();
return;
}
if(stock > max){
Alert minAlert = new Alert(Alert.AlertType.ERROR);
minAlert.setTitle("ERROR");
minAlert.setContentText("Current inventory quantity must not exceed maximum allowable quantity.");
minAlert.showAndWait();
return;
}
if (AddPartName.getText() == null || AddPartName.getText().trim().isEmpty()){
Alert nameAlert = new Alert(Alert.AlertType.ERROR);
nameAlert.setTitle("ERROR");
nameAlert.setContentText("Part name cannot be empty.");
nameAlert.showAndWait();
return;
}
if(AddPrice.getText() == null || AddPrice.getText() == ""){
Alert minAlert = new Alert(Alert.AlertType.ERROR);
minAlert.setTitle("ERROR");
minAlert.setContentText("Price field cannot be empty.");
minAlert.showAndWait();
return;
}
if(MaxQty.getText() == null || MaxQty.getText() == ""){
Alert minAlert = new Alert(Alert.AlertType.ERROR);
minAlert.setTitle("ERROR");
minAlert.setContentText("Max fields cannot be empty.");
minAlert.showAndWait();
return;
}
if(MinQty.getText() == null || MinQty.getText() == ""){
Alert minAlert = new Alert(Alert.AlertType.ERROR);
minAlert.setTitle("ERROR");
minAlert.setContentText("Min fields cannot be empty.");
minAlert.showAndWait();
return;
}
else{
if (IsInHouse){
int machineId = Integer.parseInt(CompNameMachID.getText());
InhousePart InHousePart = new InhousePart(partCounter, name, price, stock, min, max, machineId);
Inventory.addPart(InHousePart);
}
else{
String companyName = CompNameMachID.getText();
OutsourcedPart OutsourcedPart = new OutsourcedPart(partCounter, name, price, stock, min, max, companyName);
Inventory.addPart(OutsourcedPart);
}
}
}
/**
* Validates all fields are filled in correctly
*/
catch (NumberFormatException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("ERROR");
alert.setContentText("Missing value(s) in required field(s).");
alert.showAndWait();
return;
}
changeScreen(event, "MainForm.fxml");
}
/**
* Changes screen back to
* the main form.
*
* @param event onMouseClick
* @throws IOException to catch read/write errors
*/
@FXML
void onActionDisplayMainForm(ActionEvent event) throws IOException {
/**
* To confirm user will leave Add Part screen
* and return to the Main Form
*/
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure you wish to exit?");
Optional<ButtonType> result = alert.showAndWait();
if(result.isPresent() && result.get() == ButtonType.OK){
partCounter = Inventory.partDecrement();
changeScreen(event, "MainForm.fxml");
}
}
/**
* When Add Part screen is opened
* by the program.
*
* @param url location of resources
* @param rb list of resources
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
AddPartId.setText(Integer.toString(partCounter));
}
}
|
Java
|
public class JSimpleDBNamespaceHandler extends NamespaceHandlerSupport {
public static final String JSIMPLEDB_NAMESPACE_URI = "http://jsimpledb.googlecode.com/schema/jsimpledb";
public static final String JSIMPLEDB_TAG = "jsimpledb";
public static final String SCAN_CLASSES_TAG = "scan-classes";
public static final String SCAN_FIELD_TYPES_TAG = "scan-field-types";
@Override
public void init() {
this.registerBeanDefinitionParser(JSIMPLEDB_TAG, new JSimpleDBBeanDefinitionParser());
this.registerBeanDefinitionParser(SCAN_CLASSES_TAG, new ScanClassesBeanDefinitionParser());
this.registerBeanDefinitionParser(SCAN_FIELD_TYPES_TAG, new ScanFieldTypesBeanDefinitionParser());
}
}
|
Java
|
public final class CompressionCodecs {
private CompressionCodecs() {
} //prevent external instantiation
/**
* Codec implementing the <a href="https://tools.ietf.org/html/rfc7518">JWA</a> standard
* <a href="https://en.wikipedia.org/wiki/DEFLATE">deflate</a> compression algorithm
*/
public static final CompressionCodec DEFLATE =
Classes.newInstance("io.jsonwebtoken.impl.compression.DeflateCompressionCodec");
/**
* Codec implementing the <a href="https://en.wikipedia.org/wiki/Gzip">gzip</a> compression algorithm.
* <h3>Compatibility Warning</h3>
* <p><b>This is not a standard JWA compression algorithm</b>. Be sure to use this only when you are confident
* that all parties accessing the token support the gzip algorithm.</p>
* <p>If you're concerned about compatibility, the {@link #DEFLATE DEFLATE} code is JWA standards-compliant.</p>
*/
public static final CompressionCodec GZIP =
Classes.newInstance("io.jsonwebtoken.impl.compression.GzipCompressionCodec");
}
|
Java
|
public class HttpsURLConnectionImpl
extends javax.net.ssl.HttpsURLConnection {
private final DelegateHttpsURLConnection delegate;
HttpsURLConnectionImpl(URL u, Handler handler) throws IOException {
this(u, null, handler);
}
static URL checkURL(URL u) throws IOException {
if (u != null) {
if (u.toExternalForm().indexOf('\n') > -1) {
throw new MalformedURLException("Illegal character in URL");
}
}
return u;
}
HttpsURLConnectionImpl(URL u, Proxy p, Handler handler) throws IOException {
super(checkURL(u));
delegate = new DelegateHttpsURLConnection(url, p, handler, this);
}
/**
* Create a new HttpClient object, bypassing the cache of
* HTTP client objects/connections.
*
* @param url the URL being accessed
*/
protected void setNewClient(URL url) throws IOException {
delegate.setNewClient(url, false);
}
/**
* Obtain a HttpClient object. Use the cached copy if specified.
*
* @param url the URL being accessed
* @param useCache whether the cached connection should be used
* if present
*/
protected void setNewClient(URL url, boolean useCache)
throws IOException {
delegate.setNewClient(url, useCache);
}
/**
* Create a new HttpClient object, set up so that it uses
* per-instance proxying to the given HTTP proxy. This
* bypasses the cache of HTTP client objects/connections.
*
* @param url the URL being accessed
* @param proxyHost the proxy host to use
* @param proxyPort the proxy port to use
*/
protected void setProxiedClient(URL url, String proxyHost, int proxyPort)
throws IOException {
delegate.setProxiedClient(url, proxyHost, proxyPort);
}
/**
* Obtain a HttpClient object, set up so that it uses per-instance
* proxying to the given HTTP proxy. Use the cached copy of HTTP
* client objects/connections if specified.
*
* @param url the URL being accessed
* @param proxyHost the proxy host to use
* @param proxyPort the proxy port to use
* @param useCache whether the cached connection should be used
* if present
*/
protected void setProxiedClient(URL url, String proxyHost, int proxyPort,
boolean useCache) throws IOException {
delegate.setProxiedClient(url, proxyHost, proxyPort, useCache);
}
/**
* Implements the HTTP protocol handler's "connect" method,
* establishing an SSL connection to the server as necessary.
*/
public void connect() throws IOException {
delegate.connect();
}
/**
* Used by subclass to access "connected" variable. Since we are
* delegating the actual implementation to "delegate", we need to
* delegate the access of "connected" as well.
*/
protected boolean isConnected() {
return delegate.isConnected();
}
/**
* Used by subclass to access "connected" variable. Since we are
* delegating the actual implementation to "delegate", we need to
* delegate the access of "connected" as well.
*/
protected void setConnected(boolean conn) {
delegate.setConnected(conn);
}
/**
* Returns the cipher suite in use on this connection.
*/
public String getCipherSuite() {
return delegate.getCipherSuite();
}
/**
* Returns the certificate chain the client sent to the
* server, or null if the client did not authenticate.
*/
public java.security.cert.Certificate []
getLocalCertificates() {
return delegate.getLocalCertificates();
}
/**
* Returns the server's certificate chain, or throws
* SSLPeerUnverified Exception if
* the server did not authenticate.
*/
public java.security.cert.Certificate []
getServerCertificates() throws SSLPeerUnverifiedException {
return delegate.getServerCertificates();
}
/**
* Returns the principal with which the server authenticated itself,
* or throw a SSLPeerUnverifiedException if the server did not authenticate.
*/
public Principal getPeerPrincipal()
throws SSLPeerUnverifiedException
{
return delegate.getPeerPrincipal();
}
/**
* Returns the principal the client sent to the
* server, or null if the client did not authenticate.
*/
public Principal getLocalPrincipal()
{
return delegate.getLocalPrincipal();
}
/*
* Allowable input/output sequences:
* [interpreted as POST/PUT]
* - get output, [write output,] get input, [read input]
* - get output, [write output]
* [interpreted as GET]
* - get input, [read input]
* Disallowed:
* - get input, [read input,] get output, [write output]
*/
public OutputStream getOutputStream() throws IOException {
return delegate.getOutputStream();
}
public InputStream getInputStream() throws IOException {
return delegate.getInputStream();
}
public InputStream getErrorStream() {
return delegate.getErrorStream();
}
/**
* Disconnect from the server.
*/
public void disconnect() {
delegate.disconnect();
}
public boolean usingProxy() {
return delegate.usingProxy();
}
/**
* Returns an unmodifiable Map of the header fields.
* The Map keys are Strings that represent the
* response-header field names. Each Map value is an
* unmodifiable List of Strings that represents
* the corresponding field values.
*
* @return a Map of header fields
* @since 1.4
*/
public Map<String,List<String>> getHeaderFields() {
return delegate.getHeaderFields();
}
/**
* Gets a header field by name. Returns null if not known.
* @param name the name of the header field
*/
public String getHeaderField(String name) {
return delegate.getHeaderField(name);
}
/**
* Gets a header field by index. Returns null if not known.
* @param n the index of the header field
*/
public String getHeaderField(int n) {
return delegate.getHeaderField(n);
}
/**
* Gets a header field by index. Returns null if not known.
* @param n the index of the header field
*/
public String getHeaderFieldKey(int n) {
return delegate.getHeaderFieldKey(n);
}
/**
* Sets request property. If a property with the key already
* exists, overwrite its value with the new value.
* @param value the value to be set
*/
public void setRequestProperty(String key, String value) {
delegate.setRequestProperty(key, value);
}
/**
* Adds a general request property specified by a
* key-value pair. This method will not overwrite
* existing values associated with the same key.
*
* @param key the keyword by which the request is known
* (e.g., "<code>accept</code>").
* @param value the value associated with it.
* @see #getRequestProperties(java.lang.String)
* @since 1.4
*/
public void addRequestProperty(String key, String value) {
delegate.addRequestProperty(key, value);
}
/**
* Overwrite super class method
*/
public int getResponseCode() throws IOException {
return delegate.getResponseCode();
}
public String getRequestProperty(String key) {
return delegate.getRequestProperty(key);
}
/**
* Returns an unmodifiable Map of general request
* properties for this connection. The Map keys
* are Strings that represent the request-header
* field names. Each Map value is a unmodifiable List
* of Strings that represents the corresponding
* field values.
*
* @return a Map of the general request properties for this connection.
* @throws IllegalStateException if already connected
* @since 1.4
*/
public Map<String,List<String>> getRequestProperties() {
return delegate.getRequestProperties();
}
/*
* We support JDK 1.2.x so we can't count on these from JDK 1.3.
* We override and supply our own version.
*/
public void setInstanceFollowRedirects(boolean shouldFollow) {
delegate.setInstanceFollowRedirects(shouldFollow);
}
public boolean getInstanceFollowRedirects() {
return delegate.getInstanceFollowRedirects();
}
public void setRequestMethod(String method) throws ProtocolException {
delegate.setRequestMethod(method);
}
public String getRequestMethod() {
return delegate.getRequestMethod();
}
public String getResponseMessage() throws IOException {
return delegate.getResponseMessage();
}
public long getHeaderFieldDate(String name, long Default) {
return delegate.getHeaderFieldDate(name, Default);
}
public Permission getPermission() throws IOException {
return delegate.getPermission();
}
public URL getURL() {
return delegate.getURL();
}
public int getContentLength() {
return delegate.getContentLength();
}
public long getContentLengthLong() {
return delegate.getContentLengthLong();
}
public String getContentType() {
return delegate.getContentType();
}
public String getContentEncoding() {
return delegate.getContentEncoding();
}
public long getExpiration() {
return delegate.getExpiration();
}
public long getDate() {
return delegate.getDate();
}
public long getLastModified() {
return delegate.getLastModified();
}
public int getHeaderFieldInt(String name, int Default) {
return delegate.getHeaderFieldInt(name, Default);
}
public long getHeaderFieldLong(String name, long Default) {
return delegate.getHeaderFieldLong(name, Default);
}
public Object getContent() throws IOException {
return delegate.getContent();
}
@SuppressWarnings("rawtypes")
public Object getContent(Class[] classes) throws IOException {
return delegate.getContent(classes);
}
public String toString() {
return delegate.toString();
}
public void setDoInput(boolean doinput) {
delegate.setDoInput(doinput);
}
public boolean getDoInput() {
return delegate.getDoInput();
}
public void setDoOutput(boolean dooutput) {
delegate.setDoOutput(dooutput);
}
public boolean getDoOutput() {
return delegate.getDoOutput();
}
public void setAllowUserInteraction(boolean allowuserinteraction) {
delegate.setAllowUserInteraction(allowuserinteraction);
}
public boolean getAllowUserInteraction() {
return delegate.getAllowUserInteraction();
}
public void setUseCaches(boolean usecaches) {
delegate.setUseCaches(usecaches);
}
public boolean getUseCaches() {
return delegate.getUseCaches();
}
public void setIfModifiedSince(long ifmodifiedsince) {
delegate.setIfModifiedSince(ifmodifiedsince);
}
public long getIfModifiedSince() {
return delegate.getIfModifiedSince();
}
public boolean getDefaultUseCaches() {
return delegate.getDefaultUseCaches();
}
public void setDefaultUseCaches(boolean defaultusecaches) {
delegate.setDefaultUseCaches(defaultusecaches);
}
/*
* finalize (dispose) the delegated object. Otherwise
* sun.net.www.protocol.http.HttpURLConnection's finalize()
* would have to be made public.
*/
@SuppressWarnings("deprecation")
protected void finalize() throws Throwable {
delegate.dispose();
}
public boolean equals(Object obj) {
return this == obj || ((obj instanceof HttpsURLConnectionImpl) &&
delegate.equals(((HttpsURLConnectionImpl)obj).delegate));
}
public int hashCode() {
return delegate.hashCode();
}
public void setConnectTimeout(int timeout) {
delegate.setConnectTimeout(timeout);
}
public int getConnectTimeout() {
return delegate.getConnectTimeout();
}
public void setReadTimeout(int timeout) {
delegate.setReadTimeout(timeout);
}
public int getReadTimeout() {
return delegate.getReadTimeout();
}
public void setFixedLengthStreamingMode (int contentLength) {
delegate.setFixedLengthStreamingMode(contentLength);
}
public void setFixedLengthStreamingMode(long contentLength) {
delegate.setFixedLengthStreamingMode(contentLength);
}
public void setChunkedStreamingMode (int chunklen) {
delegate.setChunkedStreamingMode(chunklen);
}
@Override
public void setAuthenticator(Authenticator auth) {
delegate.setAuthenticator(auth);
}
@Override
public Optional<SSLSession> getSSLSession() {
return Optional.ofNullable(delegate.getSSLSession());
}
}
|
Java
|
public class HDFSZoneValidator implements ConfigValidator<ServiceSpec> {
static final String NAME_POD_TYPE = "name";
static final String JOURNAL_POD_TYPE = "journal";
static final String DATA_POD_TYPE = "data";
@Override
public Collection<ConfigValidationError> validate(Optional<ServiceSpec> oldConfig, ServiceSpec newConfig) {
return ZoneValidator.validate(oldConfig, newConfig, NAME_POD_TYPE, JOURNAL_POD_TYPE, DATA_POD_TYPE);
}
}
|
Java
|
public class TrendReportHeightValidatorTest extends AbstractValidatorTest {
/**
* Test some valid encodings.
*/
@Test
public void testValidEncodings() {
assertThatInputIsValid("50");
assertThatInputIsValid("51");
assertThatInputIsValid("52");
assertThatInputIsValid("5000");
}
/**
* Test some invalid encodings.
*/
@Test
public void testInvalidEncodings() {
assertThatInputIsInvalid("NIX");
assertThatInputIsInvalid("-1");
assertThatInputIsInvalid("49");
}
@Override
protected Validator createValidator() {
return new TrendReportHeightValidator();
}
}
|
Java
|
public class LocalAndRemoteFileTreeFrame extends JFrame
{
/** local file tree */
private static DragTree ltree;
/** close/exit menu item */
private JMenuItem prefClose;
/**
*
* Displays the remote and local file managers in the
* same frame.
* @param mysettings jemboss properties
*
*/
public LocalAndRemoteFileTreeFrame(final JembossParams mysettings)
throws JembossSoapException
{
super("File Manager");
try
{
final JPanel remotePanel = new JPanel(new BorderLayout());
final RemoteFileTreePanel rtree =
new RemoteFileTreePanel(mysettings,false);
ltree = new DragTree(new File(mysettings.getUserHome()),
this, mysettings);
// ltree = new DragTree(new File(System.getProperty("user.home")),
// this, mysettings);
final JPanel localPanel = new JPanel(new BorderLayout());
localPanel.add(new LocalTreeToolBar(mysettings),
BorderLayout.NORTH);
JScrollPane localTree = new JScrollPane(ltree);
final JSplitPane treePane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
localPanel,remotePanel);
JMenuBar menuBar = new JMenuBar();
JMenu prefMenu = new JMenu("File");
prefMenu.setMnemonic(KeyEvent.VK_F);
final Dimension panelSize = new Dimension(210, 270);
JRadioButtonMenuItem prefV = new JRadioButtonMenuItem("Vertical Split");
prefMenu.add(prefV);
prefV.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
treePane.remove(remotePanel);
treePane.remove(localPanel);
treePane.setOrientation(JSplitPane.VERTICAL_SPLIT);
treePane.setTopComponent(localPanel);
treePane.setBottomComponent(remotePanel);
// rtree.setPreferredSize(panelSize);
// ltree.setPreferredSize(panelSize);
remotePanel.setPreferredSize(panelSize);
localPanel.setPreferredSize(panelSize);
pack();
treePane.setDividerLocation(0.5);
}
});
prefV.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(prefV);
JRadioButtonMenuItem prefH = new JRadioButtonMenuItem("Horizontal Split");
prefMenu.add(prefH);
prefH.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
treePane.remove(remotePanel);
treePane.remove(localPanel);
treePane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
treePane.setLeftComponent(localPanel);
treePane.setRightComponent(remotePanel);
// rtree.setPreferredSize(panelSize);
// ltree.setPreferredSize(panelSize);
remotePanel.setPreferredSize(panelSize);
localPanel.setPreferredSize(panelSize);
pack();
treePane.setDividerLocation(0.5);
}
});
group.add(prefH);
// close / exit
prefClose = new JMenuItem("Close");
prefClose.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_E, ActionEvent.CTRL_MASK));
prefClose.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setVisible(false);
}
});
prefMenu.addSeparator();
prefMenu.add(prefClose);
menuBar.add(prefMenu);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
JMenuItem fmh = new JMenuItem("About File Manager");
fmh.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
ClassLoader cl = this.getClass().getClassLoader();
try
{
URL inURL = cl.getResource("resources/filemgr.html");
new Browser(inURL,"resources/filemgr.html");
}
catch (MalformedURLException mex)
{
System.out.println("Didn't find resources/filemgr.html");
}
catch (IOException iex)
{
System.out.println("Didn't find resources/filemgr.html");
}
}
});
helpMenu.add(fmh);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
rtree.setPreferredSize(panelSize);
localTree.setPreferredSize(panelSize);
localPanel.add(localTree,BorderLayout.CENTER);
remotePanel.add(rtree,BorderLayout.CENTER);
// local panel menu
JComboBox rootSelect = rtree.getRootSelect();
JPanel lbar = new JPanel(new BorderLayout());
Dimension d = new Dimension((int)lbar.getPreferredSize().getWidth(),
(int)rootSelect.getMinimumSize().getHeight());
lbar.add(new JLabel(" LOCAL"),BorderLayout.WEST);
lbar.setPreferredSize(d);
localPanel.add(lbar,BorderLayout.SOUTH);
// remote panel menu
JPanel rbar = new JPanel(new BorderLayout());
rbar.add(new JLabel(" REMOTE "),BorderLayout.WEST);
rbar.add(rootSelect,BorderLayout.EAST);
rbar.setPreferredSize(d);
remotePanel.add(rbar,BorderLayout.SOUTH);
// treePane.setOneTouchExpandable(true);
getContentPane().add(treePane);
pack();
}
catch(JembossSoapException jse)
{
throw new JembossSoapException();
}
}
/**
*
* Set the closing menu item to exit (for standalone
* file manager)
*
*/
public void setExit()
{
prefClose.setText("Exit");
prefClose.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_E, ActionEvent.CTRL_MASK));
prefClose.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
/**
*
* Returns the local file tree
* @return local file tree
*
*/
public static DragTree getLocalDragTree()
{
return ltree;
}
}
|
Java
|
public class WaterFallChartTest extends ChartTest {
@Before
public void setUp() {
}
@Test
public void de_serialize() throws IOException {
// 범례
//
ChartLegend legend = new ChartLegend();
ChartAxis xAxis = new ChartAxis(true, "test", true, null, null, null);
ChartAxis yAxis = new ChartAxis(true, null, true, null, null, null);
WaterFallChart chart = new WaterFallChart(colorByMeasureForSection(), null, legend, null, fontLargerSize(), null, null,
70,
new WaterFallChart.BarColor("#COLOR1", "#COLOR2"),
new WaterFallChart.GuideLine("#COLOR", "THIN"),
xAxis, yAxis);
System.out.println(chart.toString());
String chartStr = GlobalObjectMapper.getDefaultMapper().writeValueAsString(chart);
System.out.println(chartStr);
Chart deSerialized = GlobalObjectMapper.getDefaultMapper().readValue(chartStr, Chart.class);
System.out.println("Result : " + deSerialized.toString());
}
@Test
public void deserialize() throws IOException {
String chartSpec = "{\n" +
" \"type\" : \"waterfall\",\n" +
" \"size\" : {\n" +
" \"size\" : 80,\n" +
" \"auto\" : true\n" +
" },\n" +
" \"label\" : {\n" +
" \"shows\" : [ {\n" +
" \"mode\" : \"column\",\n" +
" \"mark\" : \"HORIZONTAL\"\n" +
" }, {\n" +
" \"mode\" : \"row\",\n" +
" \"mark\" : \"VERTICAL\"\n" +
" }, {\n" +
" \"mode\" : \"aggregation\"\n" +
" } ],\n" +
" \"auto\" : true\n" +
" },\n" +
" \"series\" : {\n" +
" \"align\" : \"HORIZONTAL\"\n" +
" \"view\" : \"ALL\"\n" +
" \"position\" : [0, 100]\n" +
" }\n" +
"}";
Chart chart = GlobalObjectMapper.readValue(chartSpec, Chart.class);
System.out.println("ToString Result - \n" + ToStringBuilder.reflectionToString(chart, ToStringStyle.MULTI_LINE_STYLE));
}
}
|
Java
|
public class StargateManager implements ITickEventHandler {
private final HintProviderServer server;
private final HashMap<Integer, ArrayList<StargateConnection>> connections;
/**
* Default constructor
*
* @param server
* The hint server
*/
public StargateManager(HintProviderServer server) {
this.server = server;
this.connections = new HashMap<Integer, ArrayList<StargateConnection>>();
LCRuntime.runtime.ticks().register(this);
}
/**
* Get a Stargate address for a tile
*
* @param tile
* The tile
* @return The address
*/
public StargateAddress getStargateAddress(TileStargateBase tile) {
return server.universeMgr.findAddress(tile.getWorldObj().provider.dimensionId, new ChunkPos(tile));
}
/**
* Open a connection from a Stargate
*
* @param tile
* The source tile
* @param address
* The destination address
* @param connectTimeout
* The time to wait before giving up on connecting
* @param establishedTimeout
* The time to wait before force-closing the Stargate
* @return The connection
*/
public StargateConnection openConnection(TileStargateBase tile, StargateAddress address, int connectTimeout,
int establishedTimeout) {
StargateRecord what = server.universeMgr.findRecord(address);
if (what == null) {
LCLog.debug("No such address found: " + address);
return null;
}
StargateConnectionType type = (what.server != null) ? StargateConnectionType.SERVERTOSERVER
: StargateConnectionType.LOCAL;
StargateConnection connection = new StargateConnection(type, tile, what, connectTimeout, establishedTimeout);
synchronized (connections) {
if (!connections.containsKey(tile.getWorldObj().provider.dimensionId))
connections.put(tile.getWorldObj().provider.dimensionId, new ArrayList<StargateConnection>());
connections.get(tile.getWorldObj().provider.dimensionId).add(connection);
}
connection.openConnection();
return connection;
}
/**
* Close all connections in a dimension
*
* @param dimensionId
* The dimension
*/
public void closeConnectionsIn(int dimensionId) {
LCLog.info("Closing connections in dimension %s.", dimensionId);
ArrayList<StargateConnection> dc = null;
synchronized (connections) {
dc = connections.remove(dimensionId);
}
if (dc != null) {
Iterator<StargateConnection> iter = dc.iterator();
while (iter.hasNext())
iter.next().deleteConnection();
}
}
/**
* Close all connections active in the game
*
* @param now
* Force the close - don't wait for idle to arrive
*/
public void closeAllConnections(boolean now) {
synchronized (connections) {
Iterator<Integer> dimensions = connections.keySet().iterator();
while (dimensions.hasNext()) {
int dimension = dimensions.next();
ArrayList<StargateConnection> dc = connections.get(dimension);
Iterator<StargateConnection> iter = dc.iterator();
while (iter.hasNext())
iter.next().deleteConnection();
dimensions.remove();
}
}
}
@Override
public void think(Side what) {
if (what == Side.SERVER) {
synchronized (connections) {
Iterator<Integer> dimensions = connections.keySet().iterator();
while (dimensions.hasNext()) {
int dimension = dimensions.next();
ArrayList<StargateConnection> dc = connections.get(dimension);
Iterator<StargateConnection> iter = dc.iterator();
while (iter.hasNext()) {
StargateConnection conn = iter.next();
conn.think();
if (conn.dead) {
LCLog.debug("Removing dead connection %s.", conn);
iter.remove();
}
}
}
}
}
}
}
|
Java
|
public /*abstract*/ class BidiClassifier {
/**
* This object can be used for any purpose by the caller to pass
* information to the BidiClassifier methods, and by the BidiClassifier
* methods themselves.<br>
* For instance, this object can be used to save a reference to
* a previous custom BidiClassifier while setting a new one, so as to
* allow chaining between them.
* @stable ICU 3.8
*/
protected Object context;
/**
* @param context Context for this classifier instance.
* May be null.
* @stable ICU 3.8
*/
public BidiClassifier(Object context) {
this.context = context;
}
/**
* Sets classifier context, which can be used either by a caller or
* callee for various purposes.
*
* @param context Context for this classifier instance.
* May be null.
* @stable ICU 3.8
*/
public void setContext(Object context) {
this.context = context;
}
/**
* Returns the current classifier context.
* @stable ICU 3.8
*/
public Object getContext() {
return this.context;
}
/**
* Gets customized Bidi class for the code point <code>c</code>.
* <p>
* Default implementation, to be overridden.
*
* @param c Code point to be classified.
* @return An integer representing directional property / Bidi class for the
* given code point <code>c</code>, or Bidi.CLASS_DEFAULT=UCharacter.getIntPropertyMaxValue(UProperty.BIDI_CLASS)+1
* to signify that there is no need to override the standard Bidi class for
* the given code point.
* @see Bidi#CLASS_DEFAULT
* @stable ICU 3.8
*/
public int classify(int c) {
return Bidi.CLASS_DEFAULT;
}
}
|
Java
|
public class PDListAttributeObject extends PDStandardAttributeObject
{
/**
* standard attribute owner: List
*/
public static final String OWNER_LIST = "List";
protected static final String LIST_NUMBERING = "ListNumbering";
/**
* ListNumbering: Circle: Open circular bullet
*/
public static final String LIST_NUMBERING_CIRCLE = "Circle";
/**
* ListNumbering: Decimal: Decimal arabic numerals (1–9, 10–99, …)
*/
public static final String LIST_NUMBERING_DECIMAL = "Decimal";
/**
* ListNumbering: Disc: Solid circular bullet
*/
public static final String LIST_NUMBERING_DISC = "Disc";
/**
* ListNumbering: LowerAlpha: Lowercase letters (a, b, c, …)
*/
public static final String LIST_NUMBERING_LOWER_ALPHA = "LowerAlpha";
/**
* ListNumbering: LowerRoman: Lowercase roman numerals (i, ii, iii, iv, …)
*/
public static final String LIST_NUMBERING_LOWER_ROMAN = "LowerRoman";
/**
* ListNumbering: None: No autonumbering; Lbl elements (if present) contain arbitrary text
* not subject to any numbering scheme
*/
public static final String LIST_NUMBERING_NONE = "None";
/**
* ListNumbering: Square: Solid square bullet
*/
public static final String LIST_NUMBERING_SQUARE = "Square";
/**
* ListNumbering: UpperAlpha: Uppercase letters (A, B, C, …)
*/
public static final String LIST_NUMBERING_UPPER_ALPHA = "UpperAlpha";
/**
* ListNumbering: UpperRoman: Uppercase roman numerals (I, II, III, IV, …)
*/
public static final String LIST_NUMBERING_UPPER_ROMAN = "UpperRoman";
/**
* Default constructor.
*/
public PDListAttributeObject()
{
this.setOwner(OWNER_LIST);
}
/**
* Creates a new List attribute object with a given dictionary.
*
* @param dictionary the dictionary
*/
public PDListAttributeObject(COSDictionary dictionary)
{
super(dictionary);
}
/**
* Gets the list numbering (ListNumbering). The default value is
* {@link #LIST_NUMBERING_NONE}.
*
* @return the list numbering
*/
public String getListNumbering()
{
return this.getName(LIST_NUMBERING, LIST_NUMBERING_NONE);
}
/**
* Sets the list numbering (ListNumbering). The value shall be one of the
* following:
* <ul>
* <li>{@link #LIST_NUMBERING_NONE},</li>
* <li>{@link #LIST_NUMBERING_DISC},</li>
* <li>{@link #LIST_NUMBERING_CIRCLE},</li>
* <li>{@link #LIST_NUMBERING_SQUARE},</li>
* <li>{@link #LIST_NUMBERING_DECIMAL},</li>
* <li>{@link #LIST_NUMBERING_UPPER_ROMAN},</li>
* <li>{@link #LIST_NUMBERING_LOWER_ROMAN},</li>
* <li>{@link #LIST_NUMBERING_UPPER_ALPHA},</li>
* <li>{@link #LIST_NUMBERING_LOWER_ALPHA}.</li>
* </ul>
*
* @param listNumbering the list numbering
*/
public void setListNumbering(String listNumbering)
{
this.setName(LIST_NUMBERING, listNumbering);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder().append(super.toString());
if (this.isSpecified(LIST_NUMBERING))
{
sb.append(", ListNumbering=").append(this.getListNumbering());
}
return sb.toString();
}
}
|
Java
|
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
// The sub types that extend the SpeechletRequest class.
@JsonSubTypes({
@Type(value = PlainTextOutputSpeech.class),
@Type(value = SsmlOutputSpeech.class)
})
public abstract class OutputSpeech {
private String id;
/**
* Returns the identifier assigned to this speech.
*
* @return the identifier
*/
public String getId() {
return id;
}
/**
* Sets the identifier assigned to this speech.
*
* @param id
* the identifier to set
*/
public void setId(final String id) {
this.id = id;
}
}
|
Java
|
public class EraseOperationTest extends FHIRServerTestBase {
private static final String LONG_REASON =
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
public static final boolean DEBUG = false;
/**
* used when processing Erase on all Resources
*/
private static class SubmitResourceAndErase implements Callable<Integer> {
private EraseOperationTest test;
private String resourceType;
SubmitResourceAndErase(EraseOperationTest test, String resourceType) {
this.test = test;
this.resourceType = resourceType;
}
@Override
public Integer call() throws Exception {
String logicalId = test.generateCompleteMockResource(resourceType);
test.eraseResource(resourceType, logicalId, false, "message");
test.checkResourceNoLongerExists(resourceType, logicalId);
if (DEBUG) {
System.out.println("Done testing erase on " + resourceType + "/" + logicalId + "'");
}
return 1;
}
}
/**
* @return a map of String(resource type), String(logical-id)
*/
private Set<String> generateResourcesForAllTypes() throws Exception {
Set<String> results = new HashSet<>();
for (Class<? extends Resource> flz : ModelSupport.getResourceTypes(false)) {
results.add(flz.getSimpleName());
}
return results;
}
/**
* generates a mock resource for the fhir-operation-erase test.
* @param resourceType
* @return the logical id
* @throws Exception
*/
public String generateMockResource(String resourceType) throws Exception {
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/" + resourceType + "-1.json"))) {
Resource r = FHIRParser.parser(Format.JSON).parse(example);
WebTarget target = getWebTarget();
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
try (Response response = target.path(resourceType).request().post(entity, Response.class)) {
assertResponse(response, Response.Status.CREATED.getStatusCode());
String id = getLocationLogicalId(response);
try (Response responseGet = target.path(resourceType + "/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get()) {
assertResponse(responseGet, Response.Status.OK.getStatusCode());
}
return id;
}
}
}
/**
* generates a mock resource for the fhir-operation-erase test.
* @param resourceType
* @return the logical id
* @throws Exception
*/
public String generateCompleteMockResource(String resourceType) throws Exception {
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/complete-mock/" + resourceType + "-1.json"))) {
Resource r = FHIRParser.parser(Format.JSON).parse(example);
WebTarget target = getWebTarget();
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path(resourceType).request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
String id = getLocationLogicalId(response);
response = target.path(resourceType + "/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
return id;
}
}
/**
* erases the given resource
* @param resourceType
* @param logicalId
* @param error do you expect an error?
* @param msg the error message
*/
private void eraseResource(String resourceType, String logicalId, boolean error, String msg) {
eraseResource(resourceType, logicalId, error, msg, true, true, null);
}
/**
*
* erases the given resource
* @param resourceType
* @param logicalId
* @param error do you expect an error?
* @param msg the error message
* @param patient should include patientId?
*/
private void eraseResource(String resourceType, String logicalId, boolean error, String msg, boolean patient) {
eraseResource(resourceType, logicalId, error, msg, patient, true, null);
}
/**
* erases the given resource
* @param resourceType
* @param logicalId
* @param error do you expect an error?
* @param msg the error message
* @param patient should include patientId?
* @param reason should include the reason?
*/
private void eraseResource(String resourceType, String logicalId, boolean error, String msg, boolean patient, boolean reason) {
eraseResource(resourceType, logicalId, error, msg, patient, reason, null);
}
/**
* erases the given resource
* @param resourceType
* @param logicalId
* @param error do you expect an error?
* @param msg the error message
* @param patient should include patientId?
* @param reason should include the reason?
* @param reasonMsg the string to provide
*/
private void eraseResource(String resourceType, String logicalId, boolean error, String msg, boolean patient, boolean reason, String reasonMsg) {
Entity<Parameters> entity = Entity.entity(generateParameters(patient, reason, reasonMsg, Optional.empty()), FHIRMediaType.APPLICATION_FHIR_JSON);
Response r = getWebTarget()
.path("/" + resourceType + "/" + logicalId + "/$erase")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
if (error) {
assertEquals(r.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} else {
assertEquals(r.getStatus(), Response.Status.OK.getStatusCode());
}
}
/**
* erases the given resource's version
*
* @param resourceType
* @param logicalId
* @param version - the version to be deleted
* @param error do you expect an error?
* @param msg the error message
* @param patient should include patientId?
* @param reason should include the reason?
* @param reasonMsg the string to provide
*/
private void eraseResourceByVersion(String resourceType, String logicalId, Integer version, boolean error, String msg, boolean patient, boolean reason, String reasonMsg) {
Entity<Parameters> entity = Entity.entity(generateParameters(patient, reason, reasonMsg, Optional.of(version)), FHIRMediaType.APPLICATION_FHIR_JSON);
Response r = getWebTarget()
.path("/" + resourceType + "/" + logicalId + "/$erase")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
if (error) {
assertEquals(r.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} else {
assertEquals(r.getStatus(), Response.Status.OK.getStatusCode());
}
}
/**
* runs with query parameters
* @param resourceType
* @param logicalId
*/
private void eraseResourceWithQueryParameters(String resourceType, String logicalId) {
Entity<String> entity = Entity.entity("{\"resourceType\": \"Parameters\"}",
FHIRMediaType.APPLICATION_FHIR_JSON);
WebTarget target = getWebTarget();
target = target.path("/" + resourceType + "/" + logicalId + "/$erase")
.queryParam("patient", "1-2-3-4")
.queryParam("reason", "patient erasure");
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertEquals(r.getStatus(), Status.BAD_REQUEST.getStatusCode());
r = getWebTarget().path("/" + resourceType + "/" + logicalId)
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get(Response.class);
assertEquals(r.getStatus(), Status.OK.getStatusCode());
}
/**
* generate parameters object
* @param patient indicating that the patient parameter should be included
* @param reason should include the reason?
* @param reasonMsg the string to provide
* @param version the version that is to be erased
* @return
*/
public Parameters generateParameters(boolean patient, boolean reason, String reasonMsg, Optional<Integer> version) {
List<Parameter> parameters = new ArrayList<>();
if (patient) {
parameters.add(Parameter.builder().name(string("patient")).value(string("Patient/1-2-3-4")).build());
}
if (reason) {
if (reasonMsg == null) {
parameters.add(Parameter.builder().name(string("reason")).value(string("Patient has requested an erase")).build());
} else {
parameters.add(Parameter.builder().name(string("reason")).value(string(reasonMsg)).build());
}
}
if (version != null && version.isPresent()) {
parameters.add(Parameter.builder().name(string("version")).value(com.ibm.fhir.model.type.Integer.of(version.get())).build());
}
Parameters.Builder builder = Parameters.builder();
builder.id(UUID.randomUUID().toString());
builder.parameter(parameters);
return builder.build();
}
public Parameters generateParameters(boolean patient, boolean reason, String reasonMsg, int version) {
List<Parameter> parameters = new ArrayList<>();
if (patient) {
parameters.add(Parameter.builder().name(string("patient")).value(string("Patient/1-2-3-4")).build());
}
if (reason) {
if (reasonMsg == null) {
parameters.add(Parameter.builder().name(string("reason")).value(string("Patient has requested an erase")).build());
} else {
parameters.add(Parameter.builder().name(string("reason")).value(string(reasonMsg)).build());
}
}
Parameters.Builder builder = Parameters.builder();
builder.id(UUID.randomUUID().toString());
builder.parameter(parameters);
return builder.build();
}
/**
* checks that the resource no longer exists
* @param resourceType
* @param logicalId
*/
private void checkResourceNoLongerExists(String resourceType, String logicalId) {
WebTarget target = getWebTarget();
target = target.path("/" + resourceType + "/" + logicalId);
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get(Response.class);
assertEquals(r.getStatus(), Status.NOT_FOUND.getStatusCode());
r = getWebTarget().path("/" + resourceType)
.queryParam("_id", logicalId)
.queryParam("_tag", "6aAf1ugE47")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get();
Bundle bundle = r.readEntity(Bundle.class);
assertNotNull(bundle);
assertTrue(bundle.getEntry().isEmpty());
assertNotNull(bundle.getTotal().getValue());
assertEquals((int) bundle.getTotal().getValue(), 0);
}
/**
* checks that the resource exists
* @param resourceType
* @param logicalId
*/
private void checkResourceExists(String resourceType, String logicalId) {
WebTarget target = getWebTarget();
target = target.path("/" + resourceType + "/" + logicalId);
try (Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get(Response.class)) {
assertEquals(r.getStatus(), Status.OK.getStatusCode());
}
if ("Patient".equals(resourceType)) {
try (Response r = getWebTarget().path("/" + resourceType)
.queryParam("_id", logicalId)
.queryParam("_tag", "6aAf1ugE47")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get()) {
Bundle bundle = r.readEntity(Bundle.class);
assertNotNull(bundle);
assertFalse(bundle.getEntry().isEmpty());
assertEquals(bundle.getEntry().size(), 1);
}
} else {
// must be structure definition
try (Response r = getWebTarget().path("/" + resourceType)
.queryParam("_id", logicalId)
.queryParam("kind", "resource")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get()) {
Bundle bundle = r.readEntity(Bundle.class);
assertNotNull(bundle);
assertFalse(bundle.getEntry().isEmpty());
assertEquals(bundle.getEntry().size(), 1);
}
}
}
/**
* checks the resource is Deleted, not erased
* @param resourceType
* @param logicalId
*/
private void checkResourceDeletedNotErased(String resourceType, String logicalId) {
WebTarget target = getWebTarget();
target = target.path("/" + resourceType + "/" + logicalId);
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get(Response.class);
assertEquals(r.getStatus(), Status.GONE.getStatusCode());
}
/**
* checks that the resource history does not exist
* @param resourceType
* @param logicalId
* @param version
*/
private void checkResourceHistoryDoesNotExist(String resourceType, String logicalId, Integer version) {
WebTarget target = getWebTarget();
target = target.path("/" + resourceType + "/" + logicalId + "/_history/" + version);
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get(Response.class);
assertEquals(r.getStatus(), Status.NOT_FOUND.getStatusCode());
}
/**
* checks that the resource history exists
* @param resourceType
* @param logicalId
* @param version
* @param status
*/
private void checkResourceHistoryExists(String resourceType, String logicalId, Integer version, Status status) {
WebTarget target = getWebTarget();
target = target.path("/" + resourceType + "/" + logicalId + "/_history/" + version);
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.get(Response.class);
assertEquals(r.getStatus(), status.getStatusCode());
}
/**
* verifies a bundle
* @param r
*/
private void verifyBundle(Response r) {
Bundle bundle = r.readEntity(Bundle.class);
assertNotNull(bundle);
assertFalse(bundle.getEntry().isEmpty());
for(Bundle.Entry entry : bundle.getEntry()){
Bundle.Entry.Response response = entry.getResponse();
assertEquals(response.getStatus().getValue(), "" + Status.OK.getStatusCode());
}
}
/**
* Acceptance Criteria 1/2: Resource Exists, not Deleted and No Audit
*
* GIVEN Patient Resource (ID1)
* AND Resource latest is not deleted
* AND Audit is disabled
* WHEN the ID1 is $erase
* THEN Patient Resource is no longer searchable
* AND READ does not return GONE
* AND READ does not return the resource
* AND READ does returns not found
* AND READ does not return a Resource
* AND No Audit Record created
* @throws IOException
* @throws FHIRParserException
*/
@Test
public void testEraseWhenResourceExists() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
eraseResource("Patient", id, false, "message");
checkResourceNoLongerExists("Patient", id);
}
@Test
public void testEraseWhenResourceExistsWithLogicalId() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
List<Parameter> parameters = new ArrayList<>();
parameters.add(Parameter.builder().name(string("patient")).value(string("Patient/1-2-3-4")).build());
parameters.add(Parameter.builder().name(string("reason")).value(string("Patient has requested an erase")).build());
parameters.add(Parameter.builder().name(string("id")).value(string(id)).build());
Parameters.Builder builder = Parameters.builder();
builder.id(UUID.randomUUID().toString());
builder.parameter(parameters);
Entity<Parameters> entity = Entity.entity(builder.build(), FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = getWebTarget()
.path("/Patient/$erase")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
checkResourceNoLongerExists("Patient", id);
}
@Test
public void testEraseWhenResourceExistsWithLogicalIdUsingVersion1() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
List<Parameter> parameters = new ArrayList<>();
parameters.add(Parameter.builder().name(string("patient")).value(string("Patient/1-2-3-4")).build());
parameters.add(Parameter.builder().name(string("reason")).value(string("Patient has requested an erase")).build());
parameters.add(Parameter.builder().name(string("id")).value(string(id)).build());
parameters.add(Parameter.builder().name(string("version")).value(com.ibm.fhir.model.type.Integer.of(1)).build());
Parameters.Builder builder = Parameters.builder();
builder.id(UUID.randomUUID().toString());
builder.parameter(parameters);
Entity<Parameters> entity = Entity.entity(builder.build(), FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = getWebTarget()
.path("/Patient/$erase")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
checkResourceNoLongerExists("Patient", id);
}
@Test
public void testEraseWhenResourceExistsWithLogicalIdUsingVersion1MultipleVersions() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
// Version 2 (Update)
r = response.readEntity(Patient.class);
entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
response = target.path("Patient/" + id).request().put(entity, Response.class);
}
List<Parameter> parameters = new ArrayList<>();
parameters.add(Parameter.builder().name(string("patient")).value(string("Patient/1-2-3-4")).build());
parameters.add(Parameter.builder().name(string("reason")).value(string("Patient has requested an erase")).build());
parameters.add(Parameter.builder().name(string("id")).value(string(id)).build());
parameters.add(Parameter.builder().name(string("version")).value(com.ibm.fhir.model.type.Integer.of(1)).build());
Parameters.Builder builder = Parameters.builder();
builder.id(UUID.randomUUID().toString());
builder.parameter(parameters);
Entity<Parameters> entity = Entity.entity(builder.build(), FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = getWebTarget()
.path("/Patient/$erase")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
checkResourceExists("Patient", id);
}
@Test
public void testEraseWhenResourceExistsWithLogicalIdUsingVersion2MultipleVersionsBad() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
// Version 2 (Update)
r = response.readEntity(Patient.class);
entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
response = target.path("Patient/" + id).request().put(entity, Response.class);
}
List<Parameter> parameters = new ArrayList<>();
parameters.add(Parameter.builder().name(string("patient")).value(string("Patient/1-2-3-4")).build());
parameters.add(Parameter.builder().name(string("reason")).value(string("Patient has requested an erase")).build());
parameters.add(Parameter.builder().name(string("id")).value(string(id)).build());
parameters.add(Parameter.builder().name(string("version")).value(com.ibm.fhir.model.type.Integer.of(2)).build());
Parameters.Builder builder = Parameters.builder();
builder.id(UUID.randomUUID().toString());
builder.parameter(parameters);
Entity<Parameters> entity = Entity.entity(builder.build(), FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = getWebTarget()
.path("/Patient/$erase")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
checkResourceExists("Patient", id);
}
@Test
public void testEraseWhenResourceExistsByVersionUsingVersion1() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
eraseResourceByVersion("Patient", id, 1, false, "message", true, true, "message");
checkResourceNoLongerExists("Patient", id);
}
@Test
public void testEraseWhenResourceExistsByVersionUsingVersion1WithMultipleVersions() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
// Version 2 (Update)
r = response.readEntity(Patient.class);
entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
response = target.path("Patient/" + id).request().put(entity, Response.class);
}
eraseResourceByVersion("Patient", id, 1, false, "message", true, true, "message");
checkResourceExists("Patient", id);
checkResourceHistoryDoesNotExist("Patient", id, 1);
checkResourceHistoryExists("Patient", id, 2, Status.OK);
}
/**
* Acceptance Criteria 3/4: Resource Exists, latest is Deleted
* GIVEN Patient Resource (ID2)
* AND Resource latest is deleted
* WHEN the ID1 is $erase
* THEN Patient Resource is no longer searchable
* AND READ does not return GONE
* AND READ does not return the resource
* AND READ does returns not found
* AND READ does not return a Resource
* @throws FHIRParserException
* @throws IOException
*/
@Test
public void testEraseWhenResourceExistsLatestDeleted() throws FHIRParserException, IOException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
eraseResource("Patient", id, false, "message");
checkResourceNoLongerExists("Patient", id);
}
@Test
public void testEraseWhenResourceVersionDelete() throws FHIRParserException, IOException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
eraseResourceByVersion("Patient", id, 1, false, "message", true, true, "message");
checkResourceNoLongerExists("Patient", id);
}
@Test
public void testEraseWhenResourceExistsLatestDeletedWithVersion() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
// Version 2 (Deleted)
response = target.path("Patient/" + id).request().delete();
}
eraseResourceByVersion("Patient", id, 1, false, "message", true, true, "message");
checkResourceDeletedNotErased("Patient", id);
checkResourceHistoryDoesNotExist("Patient", id, 1);
checkResourceHistoryExists("Patient", id, 2, Status.GONE);
}
/**
* Acceptance Criteria 5/6: Resource Exists, latest not Deleted
*
* GIVEN Patient Resource v1
* AND Resource v2 is created
* AND Resource v3 is deleted
* AND Resource latest is not deleted
* WHEN the $erase is called on the resource
* THEN Patient Resource is no longer searchable
* AND READ does not return GONE
* AND READ does not return the resource
* AND READ does returns not found
* AND READ does not return a Resource
* AND no History is accessible
* @throws FHIRParserException
* @throws IOException
*/
@Test
public void testEraseWhenResourceExistsWithMultipleVersionsWithOneDeleted() throws FHIRParserException, IOException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
// Version 2 (delete)
response = target.path("Patient/" + id).request().delete();
// Version 3 (Update)
Collection<Extension> exts = Arrays.asList(
Extension.builder()
.url("dummy")
.value(string("Version: " + 3))
.build());
r = r.toBuilder()
.meta(r.getMeta().toBuilder()
.id(id)
.build())
.id(id)
.extension(Extension.builder()
.url("http://ibm.com/fhir/test")
.extension(exts)
.build())
.build();
entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
response = target.path("Patient/" + id).request().put(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
}
// Version 4, 5 (Update)
Patient.Builder builder = r.toBuilder();
for (int i = 4; i <= 6; i++) {
r = builder.build();
Collection<Extension> exts = Arrays.asList(
Extension.builder()
.url("dummy")
.value(string("Version: " + i))
.build());
r = r.toBuilder()
.meta(r.getMeta().toBuilder()
.id(id)
.build())
.id(id)
.extension(Extension.builder()
.url("http://ibm.com/fhir/test")
.extension(exts)
.build())
.build();
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient/" + id).request().put(entity, Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
eraseResource("Patient", id, false, "message", true, true, "message");
checkResourceNoLongerExists("Patient", id);
}
/**
* Acceptance Criteria 7b - Run From a Transaction Bundle - One Bad, One Good, Fails
* Given a Resource is created
* AND another Resource that does not exist
* AND a Transaction Bundle is created to Post
* AND one BAD, one good Bundle.Entry
* When the $erase operation is run
* Then result is the resource is no resources are deleted
* AND the Response Bundle indicates failure
* @throws Exception
*/
@Test
public void testAsTransactionBundle() throws Exception {
String patientId1 = generateMockResource("Patient");
String patientId2 = "1-2-3-4-5-BAD";
List<Bundle.Entry> entries = new ArrayList<>();
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId1 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId2 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
Bundle bundle = Bundle.builder()
.type(BundleType.TRANSACTION)
.entry(entries)
.build();
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
WebTarget target = getWebTarget();
Response r = target.path("/")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertResponse(r, Status.BAD_REQUEST.getStatusCode());
OperationOutcome responseOutcome = r.readEntity(OperationOutcome.class);
assertNotNull(responseOutcome);
}
/**
* Acceptance Criteria 7a - Run From a Batch Bundle - One Bad, One Good, Fails
* Given a Resource is created
* AND another Resource that does not exist
* AND a Batch Bundle is created to Post
* AND one BAD, one good Bundle.Entry
* When the $erase operation is run
* Then result is the good resource is deleted
* AND the Response Bundle indicates failure with the bad resource
* @throws Exception
*/
@Test
public void testAsBatchBundle() throws Exception {
String patientId1 = generateMockResource("Patient");
String patientId2 = "1-2-3-4-5-BaD";
List<Bundle.Entry> entries = new ArrayList<>();
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId1 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId2 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
Bundle bundle = Bundle.builder()
.type(BundleType.BATCH)
.entry(entries)
.build();
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
WebTarget target = getWebTarget();
target = target.path("/");
try (Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class)) {
assertResponse(r, Status.OK.getStatusCode());
Bundle responseBundle = r.readEntity(Bundle.class);
int countFail = 0;
int countSuccess = 0;
int countUnknown = 0;
for(Bundle.Entry entry : responseBundle.getEntry()) {
Bundle.Entry.Response response = entry.getResponse();
if ("404".equals(response.getStatus().getValue())) {
// this should be hit when there is a
countFail++;
} else if ("200".equals(response.getStatus().getValue())) {
countSuccess++;
} else {
countUnknown++;
}
}
assertEquals(countFail, 1);
assertEquals(countSuccess, 1);
assertEquals(countUnknown, 0);
}
}
/**
* Acceptance Criteria 8b - Run From a Transaction Bundle - All Good
* Given a Resource is created
* AND another Resource that exists
* AND a Transaction Bundle is created to Post
* AND all good Bundle.Entry
* When the $erase operation is run
* Then result is the resource is all Resources are deleted
* AND the Response Bundle indicates success
* @throws Exception
*/
@Test
public void testAsTransactionBundleGood() throws Exception {
String patientId1 = generateMockResource("Patient");
String patientId2 = generateMockResource("Patient");
List<Bundle.Entry> entries = new ArrayList<>();
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId1 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId2 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
Bundle bundle = Bundle.builder()
.type(BundleType.TRANSACTION)
.entry(entries)
.build();
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
WebTarget target = getWebTarget();
target = target.path("/");
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertResponse(r, Status.OK.getStatusCode());
verifyBundle(r);
}
/**
* Acceptance Criteria 8a - Run From a Batch Bundle - All Good
* Given a Resource is created
* AND another Resource that exists
* AND a batch Bundle is created to Post
* AND all good Bundle.Entry
* When the $erase operation is run
* Then result is the resource is all Resources are deleted
* AND the Response Bundle indicates success
* @throws Exception
*/
@Test
public void testAsBatchBundleGood() throws Exception {
String patientId1 = generateMockResource("Patient");
String patientId2 = generateMockResource("Patient");
List<Bundle.Entry> entries = new ArrayList<>();
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId1 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
entries.add(Bundle.Entry.builder()
.request(Request.builder()
.method(HTTPVerb.POST)
.url(Uri.of("Patient/" + patientId2 + "/$erase"))
.build())
.resource(generateParameters(true, true, "Need to Remove the file", null))
.build());
Bundle bundle = Bundle.builder()
.type(BundleType.BATCH)
.entry(entries)
.build();
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
WebTarget target = getWebTarget();
target = target.path("/");
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertResponse(r, Status.OK.getStatusCode());
verifyBundle(r);
}
/**
* Acceptance Criteria 10 - $erase is not authorized for the given tenant's users
* Given the Resource ID exists
* And Tenant is configured to disallow FHIRUsers
* When the $erase operation is run
* Then result is forbidden
* @throws IOException
* @throws FHIRParserException
*/
@Test
public void testForbiddenResourceExists() throws IOException, FHIRParserException {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient")
.request()
.header("X-FHIR-TENANT-ID", "tenant1")
.header("X-FHIR-DSID", "profile")
.post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = getWebTarget()
.path("Patient/" + id)
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "tenant1")
.header("X-FHIR-DSID", "profile")
.get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
Entity<Parameters> entity = Entity.entity(generateParameters(true, true, null, null),
FHIRMediaType.APPLICATION_FHIR_JSON);
target = target.path("/Patient/" + id + "/$erase");
Response response = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "tenant1")
.header("X-FHIR-DSID", "profile")
.post(entity, Response.class);
assertEquals(response.getStatus(), Status.FORBIDDEN.getStatusCode());
response = getWebTarget()
.path("Patient/" + id)
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "tenant1")
.header("X-FHIR-DSID", "profile")
.get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
/**
* Acceptance Criteria 11 - $erase is not authorized for the given tenant's users
* Given the Resource ID does not exist
* And Tenant is configured to disallow FHIRUsers
* When the $erase operation is run
* Then result is forbidden
*/
@Test
public void testForbiddenResourceDoesNotExists() {
Response r = getWebTarget()
.path("/Patient/1-2-3-4-5-BAD/$erase")
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "tenant1")
.header("X-FHIR-DSID", "study1")
.get(Response.class);
assertEquals(r.getStatus(), Status.FORBIDDEN.getStatusCode());
OperationOutcome outcome = r.readEntity(OperationOutcome.class);
assertEquals(outcome.getIssue().get(0).getCode().getValue(), "forbidden");
}
/**
* Acceptance Criteria 12 - $erase fails as a bad request when resource doesn't exist
* Given the Resource ID does not Exist (UUID Generate + '-bad'
* When the $erase operation is run
* Then result is bad request
*/
@Test
public void testEraseWhenResourceDoesNotExist() {
String resourceType = "Patient";
String logicalId = "1-2-3-4-5-BAD";
Entity<Parameters> entity = Entity.entity(generateParameters(true, true, null, null),
FHIRMediaType.APPLICATION_FHIR_JSON);
WebTarget target = getWebTarget();
target = target.path("/" + resourceType + "/" + logicalId + "/$erase");
Response r = target.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.post(entity, Response.class);
assertEquals(r.getStatus(), Status.NOT_FOUND.getStatusCode());
}
/**
* Acceptance Criteria 13 - $erase a deleted resource
* Given the Resource ID exist (UUID Generate)
* AND the last version of the Resource is deleted
* When the $erase operation is run
* Then result is each version of the Resource is deleted
* AND the resource is not found
* @throws Exception
*/
@Test
public void testEraseWhenLastResourceVersionDeleted() throws Exception {
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
r = response.readEntity(Patient.class);
}
loadLargeBundle(r, id);
// Delete the latest version of the resource
Response response = target
.path("Patient/" + id)
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.delete(Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
eraseResource("Patient", id, false, "Deleting per Patient Request");
checkResourceNoLongerExists("Patient", id);
}
public void loadLargeBundle(Patient r, String id) {
WebTarget target = getWebTarget();
// 1001 is delete block size (+1)
Patient.Builder builder = r.toBuilder();
// Originally this made 1000 Bundle.Entry - I chose to use a 100 for IT.
for (int j = 1; j <= 10; j++) {
List<Bundle.Entry> entries = new ArrayList<>();
Bundle.Builder bundleBuilder = Bundle.builder();
for (int i = 1; i <= 10; i++) {
r = builder.build();
Collection<Extension> exts = Arrays.asList(
Extension.builder()
.url("dummy")
.value(string("Version: " + (j * i)))
.build());
Patient tmp = r.toBuilder()
.meta(r.getMeta().toBuilder()
.id(id)
.build())
.id(id)
.extension(Extension.builder()
.url("http://ibm.com/fhir/test")
.extension(exts)
.build())
.build();
Bundle.Entry.Request request = Bundle.Entry.Request.builder()
.url(Uri.uri("Patient/" + id))
.method(HTTPVerb.PUT)
.build();
Bundle.Entry entry = Bundle.Entry.builder()
.request(request)
.resource(tmp)
.build();
entries.add(entry);
}
Bundle bundle = bundleBuilder
.type(BundleType.BATCH)
.entry(entries)
.build();
Entity<Resource> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("/").request().post(entity, Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
}
}
/**
* Acceptance Criteria 14 - All Resources work with $erase
* Given for each Resource type a version of the Resource is created as empty
* When for each the $erase operation is run
* Then result is each version of the Resource is deleted
* AND the resource is not found
* @throws Exception
*/
@Test
public void testEraseOnAllResources() throws Exception {
System.out.println("testEraseOnAllResources is long running... and just started");
Set<String> allResourcesById = generateResourcesForAllTypes();
assertFalse(allResourcesById.isEmpty());
List<SubmitResourceAndErase> callables = new ArrayList<>();
ThreadPoolExecutor exec = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
try {
for(String entry: allResourcesById) {
callables.add(new SubmitResourceAndErase(this, entry));
}
exec.invokeAll(callables);
} catch (Exception e) {
System.out.println();
e.printStackTrace();
fail();
}
System.out.println("Finished long running test");
}
/**
* Acceptance Criteria 15 - No Patient Parameter Outside of Compartment
* Given a Resource is created
* and the Resource is outside the Patient Compartment
* When for each the $erase operation is run
* Then result is the resource is deleted
* AND the resource is not found upon a search
* @throws Exception
*/
@Test
public void testEraseWithoutPatientIdOutsideOfPatientCompartment() throws Exception {
String resourceType = "StructureDefinition";
String logicalId = generateMockResource(resourceType);
eraseResource(resourceType, logicalId, false, null, false);
checkResourceNoLongerExists(resourceType, logicalId);
}
/**
* Acceptance Criteria 16 - No Patient Parameter Inside of Compartment
* Given a Resource is created
* and the Resource is inside the Patient Compartment
* and the parameters object does not include patient
* When for each the $erase operation is run
* Then result is the resource is NOT deleted
* AND the resource is found upon a search
* @throws Exception
*/
@Test
public void testEraseWithoutPatientIdInsideOfPatientCompartment() throws Exception {
String resourceType = "Patient";
String logicalId = generateMockResource(resourceType);
eraseResource(resourceType, logicalId, true, null, false);
checkResourceExists(resourceType, logicalId);
}
/**
* Acceptance Criteria 16 - No Reason
* Given a Resource is created
* When for each the $erase operation is run
* Then result is the resource is NOT deleted
* AND the resource is found upon a search
* AND there is a bad request response/status code
* @throws Exception
*/
@Test
public void testEraseWithoutReason() throws Exception {
String resourceType = "StructureDefinition";
String logicalId = generateMockResource(resourceType);
eraseResource(resourceType, logicalId, true, "No Reason Given", false, false);
checkResourceExists(resourceType, logicalId);
}
/**
* Acceptance Criteria 17 - Too Long a Reason
* Given a Resource is created
* When for each the $erase operation is run
* AND the reason is 1001 characters
* Then result is the resource is NOT deleted
* AND the resource is found upon a search
* AND there is a bad request response/status code
* @throws Exception
*/
@Test
public void testEraseWithTooLongAReason() throws Exception {
String resourceType = "StructureDefinition";
String logicalId = generateMockResource(resourceType);
eraseResource(resourceType, logicalId, true, "No Reason Given", false, true, LONG_REASON);
checkResourceExists(resourceType, logicalId);
}
/**
* Acceptance Criteria 18 - Empty Parameters Object
* Given a Resource is created
* When the $erase operation is run
* AND the empty parameters object is run
* AND the query parameters are added to the URL
* Then the result is rejected
* AND result is the resource is not deleted
* @throws Exception
*/
@Test
public void testEmptyParametersObject() throws Exception {
String resourceType = "StructureDefinition";
String logicalId = generateMockResource(resourceType);
eraseResourceWithQueryParameters(resourceType, logicalId);
checkResourceExists(resourceType, logicalId);
}
/**
* Acceptance Criteria 9 - Lots of Versions of the Same Resource which hit a timeout
* Given the Resource ID exists
* And there are at least 1000 versions of the Same Resource
* When the $erase operation is run
* AND result is a partial erase
* And the $erase operation is looped to completion
* Then
* The resource does not exist
* @throws IOException
* @throws FHIRParserException
*/
@Test(timeOut = 1200000, enabled = false) // 20 Minutes
public void testTooManyVersionsForOneErase() throws IOException, FHIRParserException {
// Timeout of 120s / 200ms per version = 600 resources in the time frame
// Timeout of 120s / 5ms per version = 24000 resources in the time frame
// Adding 24K versions of the single resource
// Trial Runs:
// 1 - Created 3500 in 600 seconds = 171ms per resource
// 2 - Created 3501 in 601 seconds = 172ms per resource
WebTarget target = getWebTarget();
String id = null;
Patient r = null;
try (Reader example = ExamplesUtil.resourceReader(("json/ibm/fhir-operation-erase/Patient-1.json"))) {
r = FHIRParser.parser(Format.JSON).parse(example);
Entity<Resource> entity = Entity.entity(r, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
id = getLocationLogicalId(response);
response = target.path("Patient/" + id).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
loadExtraLargeBundle(r, id);
// Delete the latest version of the resource
Response response = target
.path("Patient/" + id)
.request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", "default")
.header("X-FHIR-DSID", "default")
.delete(Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
eraseResource("Patient", id, false, "Deleting per Patient Request");
checkResourceNoLongerExists("Patient", id);
}
public void loadExtraLargeBundle(Patient r, String id) {
WebTarget target = getWebTarget();
Patient.Builder builder = r.toBuilder();
for (int j = 2; j <= 350000; j++) {
List<Bundle.Entry> entries = new ArrayList<>();
Bundle.Builder bundleBuilder = Bundle.builder();
for (int i = 1; i <= 100; i++, j++) {
r = builder.build();
Collection<Extension> exts = Arrays.asList(
Extension.builder()
.url("dummy")
.value(string("Version: " + j))
.build());
Patient tmp = r.toBuilder()
.meta(r.getMeta().toBuilder()
.id(id)
.build())
.id(id)
.extension(Extension.builder()
.url("http://ibm.com/fhir/test")
.extension(exts)
.build())
.build();
Bundle.Entry.Request request = Bundle.Entry.Request.builder()
.url(Uri.uri("Patient/" + id))
.method(HTTPVerb.PUT)
.build();
Bundle.Entry entry = Bundle.Entry.builder()
.request(request)
.resource(tmp)
.build();
entries.add(entry);
}
Bundle bundle = bundleBuilder
.type(BundleType.BATCH)
.entry(entries)
.build();
Entity<Resource> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("/").request().post(entity, Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
}
}
/**
* used to generate a VERY large test data set.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
EraseOperationTest test = new EraseOperationTest();
test.setUp();
test.testTooManyVersionsForOneErase();
}
}
|
Java
|
private static class SubmitResourceAndErase implements Callable<Integer> {
private EraseOperationTest test;
private String resourceType;
SubmitResourceAndErase(EraseOperationTest test, String resourceType) {
this.test = test;
this.resourceType = resourceType;
}
@Override
public Integer call() throws Exception {
String logicalId = test.generateCompleteMockResource(resourceType);
test.eraseResource(resourceType, logicalId, false, "message");
test.checkResourceNoLongerExists(resourceType, logicalId);
if (DEBUG) {
System.out.println("Done testing erase on " + resourceType + "/" + logicalId + "'");
}
return 1;
}
}
|
Java
|
public class CaptchaTraderService implements ImageCaptchaService {
private static final Logger logger = LoggerFactory
.getLogger(CaptchaTraderService.class);
private static final String APP_KEY = "2acc44805ec208cc4d6b00c75a414996";
/**
* The current application key to be used
*/
private String currentApplicationKey = CaptchaTraderService.APP_KEY;
/**
* The CaptchaTrader.com API object
*/
private CaptchaTrader api;
@Override
public int authenticate(String username, String password)
throws AuthenticationCaptchaServiceException {
api = new CaptchaTrader(currentApplicationKey, username, password);
logger.debug("Authenticating into CaptchaTrader");
try {
// this will validate the account
return (int) Math.ceil(((double) api.getCredits()) / 10);
} catch (IOException | CaptchaTraderException e) {
throw new AuthenticationCaptchaServiceException(e);
}
}
@Override
public void solve(ImageCaptcha captcha)
throws UnsolvableCaptchaServiceException {
try {
logger.debug("Resolving CAPTCHA {}", captcha.getImageURI());
final ResolvedCaptcha resolved = api.submit(captcha.getImageURI());
captcha.setAnswer(resolved.getAnswer());
captcha.setAttachment(resolved);
logger.debug("CAPTCHA solved, answer is \"{}\"",
resolved.getAnswer());
} catch (IOException | CaptchaTraderException e) {
throw new UnsolvableCaptchaServiceException(e);
}
}
@Override
public void valid(ImageCaptcha captcha)
throws InvalidCaptchaServiceException {
final Object attachment = captcha.getAttachment();
if (attachment instanceof ResolvedCaptcha) {
try {
logger.debug("Notifying server that CAPTCHA {} is valid",
captcha);
((ResolvedCaptcha) attachment).valid();
} catch (CaptchaTraderException | IOException e) {
throw new InvalidCaptchaServiceException(e);
}
} else {
throw new InvalidCaptchaServiceException();
}
}
@Override
public void invalid(ImageCaptcha captcha)
throws InvalidCaptchaServiceException {
final Object attachment = captcha.getAttachment();
if (attachment instanceof ResolvedCaptcha) {
try {
logger.debug("Notifying server that CAPTCHA {} is invalid",
captcha);
((ResolvedCaptcha) attachment).invalid();
} catch (CaptchaTraderException | IOException e) {
throw new InvalidCaptchaServiceException(e);
}
} else {
throw new InvalidCaptchaServiceException();
}
}
/**
* Sets the CaptchaTrader API key. Each application should provide a key,
* otherwise the default "HttpChannel" key will be used.
*
* @param key
* the application key
*/
public void setApplicationKey(String key) {
if (key == null)
key = APP_KEY;
logger.debug("Setting new application key as {}", key);
currentApplicationKey = key;
}
}
|
Java
|
public class CustomersData implements Serializable {
// data:查询成功[{ custid:1,name:“王美丽”,tel:“13015201136”,
// pic:“http://xxx/xx”,count:5,unfinished:3 }]
private Integer custid;
private String name;
private String tel;
private String pic;
private Integer count;
private Integer unfinished;
public Integer getCustid() {
return custid;
}
public void setCustid(Integer custid) {
this.custid = custid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getUnfinished() {
return unfinished;
}
public void setUnfinished(Integer unfinished) {
this.unfinished = unfinished;
}
}
|
Java
|
public class Helper {
public static final ExplicitHibernateTypeSource TO_ONE_ATTRIBUTE_TYPE_SOURCE = new ExplicitHibernateTypeSource() {
@Override
public String getName() {
return null;
}
@Override
public Map<String, String> getParameters() {
return null;
}
};
public static InheritanceType interpretInheritanceType(EntityElement entityElement) {
if ( JaxbSubclassElement.class.isInstance( entityElement ) ) {
return InheritanceType.SINGLE_TABLE;
}
else if ( JaxbJoinedSubclassElement.class.isInstance( entityElement ) ) {
return InheritanceType.JOINED;
}
else if ( JaxbUnionSubclassElement.class.isInstance( entityElement ) ) {
return InheritanceType.TABLE_PER_CLASS;
}
else {
return InheritanceType.NO_INHERITANCE;
}
}
/**
* Given a user-specified description of how to perform custom SQL, build the {@link CustomSQL} representation.
*
* @param customSqlElement User-specified description of how to perform custom SQL
*
* @return The {@link CustomSQL} representation
*/
public static CustomSQL buildCustomSql(CustomSqlElement customSqlElement) {
if ( customSqlElement == null ) {
return null;
}
final ExecuteUpdateResultCheckStyle checkStyle = customSqlElement.getCheck() == null
? customSqlElement.isCallable()
? ExecuteUpdateResultCheckStyle.NONE
: ExecuteUpdateResultCheckStyle.COUNT
: ExecuteUpdateResultCheckStyle.fromExternalName( customSqlElement.getCheck().value() );
return new CustomSQL( customSqlElement.getValue(), customSqlElement.isCallable(), checkStyle );
}
/**
* Given the user-specified entity mapping, determine the appropriate entity name
*
* @param entityElement The user-specified entity mapping
* @param unqualifiedClassPackage The package to use for unqualified class names
*
* @return The appropriate entity name
*/
public static String determineEntityName(EntityElement entityElement, String unqualifiedClassPackage) {
return entityElement.getEntityName() != null
? entityElement.getEntityName()
: qualifyIfNeeded( entityElement.getName(), unqualifiedClassPackage );
}
/**
* Qualify a (supposed class) name with the unqualified-class package name if it is not already qualified
*
* @param name The name
* @param unqualifiedClassPackage The unqualified-class package name
*
* @return {@code null} if the incoming name was {@code null}; or the qualified name.
*/
public static String qualifyIfNeeded(String name, String unqualifiedClassPackage) {
if ( name == null ) {
return null;
}
if ( name.indexOf( '.' ) < 0 && unqualifiedClassPackage != null ) {
return unqualifiedClassPackage + '.' + name;
}
return name;
}
public static String getPropertyAccessorName(String access, boolean isEmbedded, String defaultAccess) {
return getStringValue( access, isEmbedded ? "embedded" : defaultAccess );
}
public static MetaAttributeContext extractMetaAttributeContext(
List<JaxbMetaElement> metaElementList,
boolean onlyInheritable,
MetaAttributeContext parentContext) {
final MetaAttributeContext subContext = new MetaAttributeContext( parentContext );
for ( JaxbMetaElement metaElement : metaElementList ) {
if ( onlyInheritable & !metaElement.isInherit() ) {
continue;
}
final String name = metaElement.getAttribute();
final MetaAttribute inheritedMetaAttribute = parentContext.getMetaAttribute( name );
MetaAttribute metaAttribute = subContext.getLocalMetaAttribute( name );
if ( metaAttribute == null || metaAttribute == inheritedMetaAttribute ) {
metaAttribute = new MetaAttribute( name );
subContext.add( metaAttribute );
}
metaAttribute.addValue( metaElement.getValue() );
}
return subContext;
}
public static String getStringValue(String value, String defaultValue) {
return value == null ? defaultValue : value;
}
public static int getIntValue(String value, int defaultValue) {
return value == null ? defaultValue : Integer.parseInt( value );
}
public static long getLongValue(String value, long defaultValue) {
return value == null ? defaultValue : Long.parseLong( value );
}
public static boolean getBooleanValue(Boolean value, boolean defaultValue) {
return value == null ? defaultValue : value;
}
public static Iterable<CascadeStyle> interpretCascadeStyles(String cascades, LocalBindingContext bindingContext) {
final Set<CascadeStyle> cascadeStyles = new HashSet<CascadeStyle>();
if ( StringHelper.isEmpty( cascades ) ) {
cascades = bindingContext.getMappingDefaults().getCascadeStyle();
}
for ( String cascade : StringHelper.split( ",", cascades ) ) {
cascadeStyles.add( CascadeStyle.getCascadeStyle( cascade ) );
}
return cascadeStyles;
}
public static Map<String, String> extractParameters(List<JaxbParamElement> xmlParamElements) {
if ( xmlParamElements == null || xmlParamElements.isEmpty() ) {
return null;
}
final HashMap<String,String> params = new HashMap<String, String>();
for ( JaxbParamElement paramElement : xmlParamElements ) {
params.put( paramElement.getName(), paramElement.getValue() );
}
return params;
}
public static Iterable<MetaAttributeSource> buildMetaAttributeSources(List<JaxbMetaElement> metaElements) {
ArrayList<MetaAttributeSource> result = new ArrayList<MetaAttributeSource>();
if ( metaElements == null || metaElements.isEmpty() ) {
// do nothing
}
else {
for ( final JaxbMetaElement metaElement : metaElements ) {
result.add(
new MetaAttributeSource() {
@Override
public String getName() {
return metaElement.getAttribute();
}
@Override
public String getValue() {
return metaElement.getValue();
}
@Override
public boolean isInheritable() {
return metaElement.isInherit();
}
}
);
}
}
return result;
}
public static Schema.Name determineDatabaseSchemaName(
String explicitSchemaName,
String explicitCatalogName,
LocalBindingContext bindingContext) {
return new Schema.Name(
resolveIdentifier(
explicitSchemaName,
bindingContext.getMappingDefaults().getSchemaName(),
bindingContext.isGloballyQuotedIdentifiers()
),
resolveIdentifier(
explicitCatalogName,
bindingContext.getMappingDefaults().getCatalogName(),
bindingContext.isGloballyQuotedIdentifiers()
)
);
}
public static Identifier resolveIdentifier(String explicitName, String defaultName, boolean globalQuoting) {
String name = StringHelper.isNotEmpty( explicitName ) ? explicitName : defaultName;
if ( globalQuoting ) {
name = StringHelper.quote( name );
}
return Identifier.toIdentifier( name );
}
public static class ValueSourcesAdapter {
public String getContainingTableName() {
return null;
}
public boolean isIncludedInInsertByDefault() {
return false;
}
public boolean isIncludedInUpdateByDefault() {
return false;
}
public String getColumnAttribute() {
return null;
}
public String getFormulaAttribute() {
return null;
}
public List getColumnOrFormulaElements() {
return null;
}
public boolean isForceNotNull() {
return false;
}
}
public static List<RelationalValueSource> buildValueSources(
ValueSourcesAdapter valueSourcesAdapter,
LocalBindingContext bindingContext) {
List<RelationalValueSource> result = new ArrayList<RelationalValueSource>();
if ( StringHelper.isNotEmpty( valueSourcesAdapter.getColumnAttribute() ) ) {
if ( valueSourcesAdapter.getColumnOrFormulaElements() != null
&& ! valueSourcesAdapter.getColumnOrFormulaElements().isEmpty() ) {
throw new org.hibernate.metamodel.source.MappingException(
"column/formula attribute may not be used together with <column>/<formula> subelement",
bindingContext.getOrigin()
);
}
if ( StringHelper.isNotEmpty( valueSourcesAdapter.getFormulaAttribute() ) ) {
throw new org.hibernate.metamodel.source.MappingException(
"column and formula attributes may not be used together",
bindingContext.getOrigin()
);
}
result.add(
new ColumnAttributeSourceImpl(
valueSourcesAdapter.getContainingTableName(),
valueSourcesAdapter.getColumnAttribute(),
valueSourcesAdapter.isIncludedInInsertByDefault(),
valueSourcesAdapter.isIncludedInUpdateByDefault(),
valueSourcesAdapter.isForceNotNull()
)
);
}
else if ( StringHelper.isNotEmpty( valueSourcesAdapter.getFormulaAttribute() ) ) {
if ( valueSourcesAdapter.getColumnOrFormulaElements() != null
&& ! valueSourcesAdapter.getColumnOrFormulaElements().isEmpty() ) {
throw new org.hibernate.metamodel.source.MappingException(
"column/formula attribute may not be used together with <column>/<formula> subelement",
bindingContext.getOrigin()
);
}
// column/formula attribute combo checked already
result.add(
new FormulaImpl(
valueSourcesAdapter.getContainingTableName(),
valueSourcesAdapter.getFormulaAttribute()
)
);
}
else if ( valueSourcesAdapter.getColumnOrFormulaElements() != null
&& ! valueSourcesAdapter.getColumnOrFormulaElements().isEmpty() ) {
for ( Object columnOrFormulaElement : valueSourcesAdapter.getColumnOrFormulaElements() ) {
if ( JaxbColumnElement.class.isInstance( columnOrFormulaElement ) ) {
result.add(
new ColumnSourceImpl(
valueSourcesAdapter.getContainingTableName(),
(JaxbColumnElement) columnOrFormulaElement,
valueSourcesAdapter.isIncludedInInsertByDefault(),
valueSourcesAdapter.isIncludedInUpdateByDefault(),
valueSourcesAdapter.isForceNotNull()
)
);
}
else {
result.add(
new FormulaImpl(
valueSourcesAdapter.getContainingTableName(),
(String) columnOrFormulaElement
)
);
}
}
}
return result;
}
// todo : remove this once the state objects are cleaned up
public static Class classForName(String className, ServiceRegistry serviceRegistry) {
ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
try {
return classLoaderService.classForName( className );
}
catch ( ClassLoadingException e ) {
throw new MappingException( "Could not find class: " + className );
}
}
}
|
Java
|
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonTypeName("ManagedImage")
@Fluent
public final class ImageTemplateManagedImageDistributor extends ImageTemplateDistributor {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ImageTemplateManagedImageDistributor.class);
/*
* Resource Id of the Managed Disk Image
*/
@JsonProperty(value = "imageId", required = true)
private String imageId;
/*
* Azure location for the image, should match if image already exists
*/
@JsonProperty(value = "location", required = true)
private String location;
/**
* Get the imageId property: Resource Id of the Managed Disk Image.
*
* @return the imageId value.
*/
public String imageId() {
return this.imageId;
}
/**
* Set the imageId property: Resource Id of the Managed Disk Image.
*
* @param imageId the imageId value to set.
* @return the ImageTemplateManagedImageDistributor object itself.
*/
public ImageTemplateManagedImageDistributor withImageId(String imageId) {
this.imageId = imageId;
return this;
}
/**
* Get the location property: Azure location for the image, should match if image already exists.
*
* @return the location value.
*/
public String location() {
return this.location;
}
/**
* Set the location property: Azure location for the image, should match if image already exists.
*
* @param location the location value to set.
* @return the ImageTemplateManagedImageDistributor object itself.
*/
public ImageTemplateManagedImageDistributor withLocation(String location) {
this.location = location;
return this;
}
/** {@inheritDoc} */
@Override
public ImageTemplateManagedImageDistributor withRunOutputName(String runOutputName) {
super.withRunOutputName(runOutputName);
return this;
}
/** {@inheritDoc} */
@Override
public ImageTemplateManagedImageDistributor withArtifactTags(Map<String, String> artifactTags) {
super.withArtifactTags(artifactTags);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
@Override
public void validate() {
super.validate();
if (imageId() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property imageId in model ImageTemplateManagedImageDistributor"));
}
if (location() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property location in model ImageTemplateManagedImageDistributor"));
}
}
}
|
Java
|
public class Util {
public interface Comparable {
/**
* Returns 0 if this and c are equal, >0 if this is greater than c,
* or <0 if this is less than c.
*/
int compareTo(Comparable c);
}
public interface Comparer {
/**
* Returns 0 if a and b are equal, >0 if a is greater than b,
* or <0 if a is less than b.
*/
int compare(Object a, Object b);
}
public static interface BindingsToNodesMap {
public org.eclipse.jdt.internal.compiler.ast.ASTNode get(Binding binding);
}
private static final char ARGUMENTS_DELIMITER = '#';
private static final String EMPTY_ARGUMENT = " "; //$NON-NLS-1$
private static char[][] JAVA_LIKE_EXTENSIONS;
private static final char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$
private static final char[] BYTE = "byte".toCharArray(); //$NON-NLS-1$
private static final char[] CHAR = "char".toCharArray(); //$NON-NLS-1$
private static final char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$
private static final char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$
private static final char[] INT = "int".toCharArray(); //$NON-NLS-1$
private static final char[] LONG = "long".toCharArray(); //$NON-NLS-1$
private static final char[] SHORT = "short".toCharArray(); //$NON-NLS-1$
private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$
private static final char[] INIT = "<init>".toCharArray(); //$NON-NLS-1$
private static final String TASK_PRIORITIES_PROBLEM = "TASK_PRIORITIES_PB"; //$NON-NLS-1$
private static List fgRepeatedMessages= new ArrayList(5);
private Util() {
// cannot be instantiated
}
/**
* Returns a new array adding the second array at the end of first array.
* It answers null if the first and second are null.
* If the first array is null or if it is empty, then a new array is created with second.
* If the second array is null, then the first array is returned.
* <br>
* <br>
* For example:
* <ol>
* <li><pre>
* first = null
* second = "a"
* => result = {"a"}
* </pre>
* <li><pre>
* first = {"a"}
* second = null
* => result = {"a"}
* </pre>
* </li>
* <li><pre>
* first = {"a"}
* second = {"b"}
* => result = {"a", "b"}
* </pre>
* </li>
* </ol>
*
* @param first the first array to concatenate
* @param second the array to add at the end of the first array
* @return a new array adding the second array at the end of first array, or null if the two arrays are null.
*/
public static final String[] arrayConcat(String[] first, String second) {
if (second == null)
return first;
if (first == null)
return new String[] {second};
int length = first.length;
if (first.length == 0) {
return new String[] {second};
}
String[] result = new String[length + 1];
System.arraycopy(first, 0, result, 0, length);
result[length] = second;
return result;
}
/**
* Checks the type signature in String sig,
* starting at start and ending before end (end is not included).
* Returns the index of the character immediately after the signature if valid,
* or -1 if not valid.
*/
private static int checkTypeSignature(String sig, int start, int end, boolean allowVoid) {
if (start >= end) return -1;
int i = start;
char c = sig.charAt(i++);
int nestingDepth = 0;
while (c == '[') {
++nestingDepth;
if (i >= end) return -1;
c = sig.charAt(i++);
}
switch (c) {
case 'B':
case 'C':
case 'D':
case 'F':
case 'I':
case 'J':
case 'S':
case 'Z':
break;
case 'V':
if (!allowVoid) return -1;
// array of void is not allowed
if (nestingDepth != 0) return -1;
break;
case 'L':
int semicolon = sig.indexOf(';', i);
// Must have at least one character between L and ;
if (semicolon <= i || semicolon >= end) return -1;
i = semicolon + 1;
break;
default:
return -1;
}
return i;
}
/**
* Combines two hash codes to make a new one.
*/
public static int combineHashCodes(int hashCode1, int hashCode2) {
return hashCode1 * 17 + hashCode2;
}
/**
* Compares two byte arrays.
* Returns <0 if a byte in a is less than the corresponding byte in b, or if a is shorter, or if a is null.
* Returns >0 if a byte in a is greater than the corresponding byte in b, or if a is longer, or if b is null.
* Returns 0 if they are equal or both null.
*/
public static int compare(byte[] a, byte[] b) {
if (a == b)
return 0;
if (a == null)
return -1;
if (b == null)
return 1;
int len = Math.min(a.length, b.length);
for (int i = 0; i < len; ++i) {
int diff = a[i] - b[i];
if (diff != 0)
return diff;
}
if (a.length > len)
return 1;
if (b.length > len)
return -1;
return 0;
}
/**
* Compares two strings lexicographically.
* The comparison is based on the Unicode value of each character in
* the strings.
*
* @return the value <code>0</code> if the str1 is equal to str2;
* a value less than <code>0</code> if str1
* is lexicographically less than str2;
* and a value greater than <code>0</code> if str1 is
* lexicographically greater than str2.
*/
public static int compare(char[] str1, char[] str2) {
int len1= str1.length;
int len2= str2.length;
int n= Math.min(len1, len2);
int i= 0;
while (n-- != 0) {
char c1= str1[i];
char c2= str2[i++];
if (c1 != c2) {
return c1 - c2;
}
}
return len1 - len2;
}
/**
* Concatenate a String[] compound name to a continuous char[].
*/
public static char[] concatCompoundNameToCharArray(String[] compoundName) {
if (compoundName == null) return null;
int length = compoundName.length;
if (length == 0) return new char[0];
int size = 0;
for (int i=0; i<length; i++) {
size += compoundName[i].length();
}
char[] compoundChars = new char[size+length-1];
int pos = 0;
for (int i=0; i<length; i++) {
String name = compoundName[i];
if (i > 0) compoundChars[pos++] = '.';
int nameLength = name.length();
name.getChars(0, nameLength, compoundChars, pos);
pos += nameLength;
}
return compoundChars;
}
public static String concatenateName(String name1, String name2, char separator) {
StringBuffer buf= new StringBuffer();
if (name1 != null && name1.length() > 0) {
buf.append(name1);
}
if (name2 != null && name2.length() > 0) {
if (buf.length() > 0) {
buf.append(separator);
}
buf.append(name2);
}
return buf.toString();
}
/**
* Returns the concatenation of the given array parts using the given separator between each part.
* <br>
* <br>
* For example:<br>
* <ol>
* <li><pre>
* array = {"a", "b"}
* separator = '.'
* => result = "a.b"
* </pre>
* </li>
* <li><pre>
* array = {}
* separator = '.'
* => result = ""
* </pre></li>
* </ol>
*
* @param array the given array
* @param separator the given separator
* @return the concatenation of the given array parts using the given separator between each part
*/
public static final String concatWith(String[] array, char separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0, length = array.length; i < length; i++) {
buffer.append(array[i]);
if (i < length - 1)
buffer.append(separator);
}
return buffer.toString();
}
/**
* Returns the concatenation of the given array parts using the given separator between each
* part and appending the given name at the end.
* <br>
* <br>
* For example:<br>
* <ol>
* <li><pre>
* name = "c"
* array = { "a", "b" }
* separator = '.'
* => result = "a.b.c"
* </pre>
* </li>
* <li><pre>
* name = null
* array = { "a", "b" }
* separator = '.'
* => result = "a.b"
* </pre></li>
* <li><pre>
* name = " c"
* array = null
* separator = '.'
* => result = "c"
* </pre></li>
* </ol>
*
* @param array the given array
* @param name the given name
* @param separator the given separator
* @return the concatenation of the given array parts using the given separator between each
* part and appending the given name at the end
*/
public static final String concatWith(
String[] array,
String name,
char separator) {
if (array == null || array.length == 0) return name;
if (name == null || name.length() == 0) return concatWith(array, separator);
StringBuffer buffer = new StringBuffer();
for (int i = 0, length = array.length; i < length; i++) {
buffer.append(array[i]);
buffer.append(separator);
}
buffer.append(name);
return buffer.toString();
}
/**
* Converts a type signature from the IBinaryType representation to the DC representation.
*/
public static String convertTypeSignature(char[] sig, int start, int length) {
return new String(sig, start, length).replace('/', '.');
}
/*
* Returns the default java extension (".java").
* To be used when the extension is not known.
*/
public static String defaultJavaExtension() {
return SuffixConstants.SUFFIX_STRING_java;
}
/**
* Apply the given edit on the given string and return the updated string.
* Return the given string if anything wrong happen while applying the edit.
*
* @param original the given string
* @param edit the given edit
*
* @return the updated string
*/
public final static String editedString(String original, TextEdit edit) {
if (edit == null) {
return original;
}
SimpleDocument document = new SimpleDocument(original);
try {
edit.apply(document, TextEdit.NONE);
return document.get();
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
return original;
}
/**
* Returns true iff str.toLowerCase().endsWith(end.toLowerCase())
* implementation is not creating extra strings.
*/
public final static boolean endsWithIgnoreCase(String str, String end) {
int strLength = str == null ? 0 : str.length();
int endLength = end == null ? 0 : end.length();
// return false if the string is smaller than the end.
if(endLength > strLength)
return false;
// return false if any character of the end are
// not the same in lower case.
for(int i = 1 ; i <= endLength; i++){
if(ScannerHelper.toLowerCase(end.charAt(endLength - i)) != ScannerHelper.toLowerCase(str.charAt(strLength - i)))
return false;
}
return true;
}
/**
* Compares two arrays using equals() on the elements.
* Neither can be null. Only the first len elements are compared.
* Return false if either array is shorter than len.
*/
public static boolean equalArrays(Object[] a, Object[] b, int len) {
if (a == b) return true;
if (a.length < len || b.length < len) return false;
for (int i = 0; i < len; ++i) {
if (a[i] == null) {
if (b[i] != null) return false;
} else {
if (!a[i].equals(b[i])) return false;
}
}
return true;
}
/**
* Compares two arrays using equals() on the elements.
* Either or both arrays may be null.
* Returns true if both are null.
* Returns false if only one is null.
* If both are arrays, returns true iff they have the same length and
* all elements are equal.
*/
public static boolean equalArraysOrNull(int[] a, int[] b) {
if (a == b)
return true;
if (a == null || b == null)
return false;
int len = a.length;
if (len != b.length)
return false;
for (int i = 0; i < len; ++i) {
if (a[i] != b[i])
return false;
}
return true;
}
/**
* Compares two arrays using equals() on the elements.
* Either or both arrays may be null.
* Returns true if both are null.
* Returns false if only one is null.
* If both are arrays, returns true iff they have the same length and
* all elements compare true with equals.
*/
public static boolean equalArraysOrNull(Object[] a, Object[] b) {
if (a == b) return true;
if (a == null || b == null) return false;
int len = a.length;
if (len != b.length) return false;
// walk array from end to beginning as this optimizes package name cases
// where the first part is always the same (e.g. org.eclipse.jdt)
for (int i = len-1; i >= 0; i--) {
if (a[i] == null) {
if (b[i] != null) return false;
} else {
if (!a[i].equals(b[i])) return false;
}
}
return true;
}
/**
* Compares two arrays using equals() on the elements.
* The arrays are first sorted.
* Either or both arrays may be null.
* Returns true if both are null.
* Returns false if only one is null.
* If both are arrays, returns true iff they have the same length and
* iff, after sorting both arrays, all elements compare true with equals.
* The original arrays are left untouched.
*/
public static boolean equalArraysOrNullSortFirst(Comparable[] a, Comparable[] b) {
if (a == b) return true;
if (a == null || b == null) return false;
int len = a.length;
if (len != b.length) return false;
if (len >= 2) { // only need to sort if more than two items
a = sortCopy(a);
b = sortCopy(b);
}
for (int i = 0; i < len; ++i) {
if (!a[i].equals(b[i])) return false;
}
return true;
}
/**
* Compares two String arrays using equals() on the elements.
* The arrays are first sorted.
* Either or both arrays may be null.
* Returns true if both are null.
* Returns false if only one is null.
* If both are arrays, returns true iff they have the same length and
* iff, after sorting both arrays, all elements compare true with equals.
* The original arrays are left untouched.
*/
public static boolean equalArraysOrNullSortFirst(String[] a, String[] b) {
if (a == b) return true;
if (a == null || b == null) return false;
int len = a.length;
if (len != b.length) return false;
if (len >= 2) { // only need to sort if more than two items
a = sortCopy(a);
b = sortCopy(b);
}
for (int i = 0; i < len; ++i) {
if (!a[i].equals(b[i])) return false;
}
return true;
}
/**
* Compares two objects using equals().
* Either or both array may be null.
* Returns true if both are null.
* Returns false if only one is null.
* Otherwise, return the result of comparing with equals().
*/
public static boolean equalOrNull(Object a, Object b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return a.equals(b);
}
/*
* Returns whether the given file name equals to the given string ignoring the java like extension
* of the file name.
* Returns false if it is not a java like file name.
*/
public static boolean equalsIgnoreJavaLikeExtension(String fileName, String string) {
int fileNameLength = fileName.length();
int stringLength = string.length();
if (fileNameLength < stringLength) return false;
for (int i = 0; i < stringLength; i ++) {
if (fileName.charAt(i) != string.charAt(i)) {
return false;
}
}
char[][] javaLikeExtensions = getJavaLikeExtensions();
suffixes: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
char[] suffix = javaLikeExtensions[i];
int extensionStart = stringLength+1;
if (extensionStart + suffix.length != fileNameLength) continue;
if (fileName.charAt(stringLength) != '.') continue;
for (int j = extensionStart; j < fileNameLength; j++) {
if (fileName.charAt(j) != suffix[j-extensionStart])
continue suffixes;
}
return true;
}
return false;
}
/**
* Given a qualified name, extract the last component.
* If the input is not qualified, the same string is answered.
*/
public static String extractLastName(String qualifiedName) {
int i = qualifiedName.lastIndexOf('.');
if (i == -1) return qualifiedName;
return qualifiedName.substring(i+1);
}
/**
* Extracts the parameter types from a method signature.
*/
public static String[] extractParameterTypes(char[] sig) {
int count = getParameterCount(sig);
String[] result = new String[count];
if (count == 0)
return result;
int i = CharOperation.indexOf('(', sig) + 1;
count = 0;
int len = sig.length;
int start = i;
for (;;) {
if (i == len)
break;
char c = sig[i];
if (c == ')')
break;
if (c == '[') {
++i;
} else
if (c == 'L') {
i = CharOperation.indexOf(';', sig, i + 1) + 1;
Assert.isTrue(i != 0);
result[count++] = convertTypeSignature(sig, start, i - start);
start = i;
} else {
++i;
result[count++] = convertTypeSignature(sig, start, i - start);
start = i;
}
}
return result;
}
/**
* Extracts the return type from a method signature.
*/
public static String extractReturnType(String sig) {
int i = sig.lastIndexOf(')');
Assert.isTrue(i != -1);
return sig.substring(i+1);
}
private static IFile findFirstClassFile(IFolder folder) {
try {
IResource[] members = folder.members();
for (int i = 0, max = members.length; i < max; i++) {
IResource member = members[i];
if (member.getType() == IResource.FOLDER) {
return findFirstClassFile((IFolder)member);
} else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(member.getName())) {
return (IFile) member;
}
}
} catch (CoreException e) {
// ignore
}
return null;
}
/**
* Finds the first line separator used by the given text.
*
* @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>,
* or <code>null</code> if none found
*/
public static String findLineSeparator(char[] text) {
// find the first line separator
int length = text.length;
if (length > 0) {
char nextChar = text[0];
for (int i = 0; i < length; i++) {
char currentChar = nextChar;
nextChar = i < length-1 ? text[i+1] : ' ';
switch (currentChar) {
case '\n': return "\n"; //$NON-NLS-1$
case '\r': return nextChar == '\n' ? "\r\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
// not found
return null;
}
public static IClassFileAttribute getAttribute(IClassFileReader classFileReader, char[] attributeName) {
IClassFileAttribute[] attributes = classFileReader.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
public static IClassFileAttribute getAttribute(ICodeAttribute codeAttribute, char[] attributeName) {
IClassFileAttribute[] attributes = codeAttribute.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
public static IClassFileAttribute getAttribute(IFieldInfo fieldInfo, char[] attributeName) {
IClassFileAttribute[] attributes = fieldInfo.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
public static IClassFileAttribute getAttribute(IMethodInfo methodInfo, char[] attributeName) {
IClassFileAttribute[] attributes = methodInfo.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
private static IClassFile getClassFile(char[] fileName) {
int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
int pkgEnd = CharOperation.lastIndexOf('/', fileName); // pkgEnd is exclusive
if (pkgEnd == -1)
pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
if (jarSeparator != -1 && pkgEnd < jarSeparator) // if in a jar and no slash, it is a default package -> pkgEnd should be equal to jarSeparator
pkgEnd = jarSeparator;
if (pkgEnd == -1)
return null;
IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
if (pkg == null) return null;
int start;
return pkg.getClassFile(new String(fileName, start = pkgEnd + 1, fileName.length - start));
}
private static ICompilationUnit getCompilationUnit(char[] fileName, WorkingCopyOwner workingCopyOwner) {
char[] slashSeparatedFileName = CharOperation.replaceOnCopy(fileName, File.separatorChar, '/');
int pkgEnd = CharOperation.lastIndexOf('/', slashSeparatedFileName); // pkgEnd is exclusive
if (pkgEnd == -1)
return null;
IPackageFragment pkg = getPackageFragment(slashSeparatedFileName, pkgEnd, -1/*no jar separator for .java files*/);
if (pkg == null) return null;
int start;
ICompilationUnit cu = pkg.getCompilationUnit(new String(slashSeparatedFileName, start = pkgEnd+1, slashSeparatedFileName.length - start));
if (workingCopyOwner != null) {
ICompilationUnit workingCopy = cu.findWorkingCopy(workingCopyOwner);
if (workingCopy != null)
return workingCopy;
}
return cu;
}
/**
* Returns the registered Java like extensions.
*/
public static char[][] getJavaLikeExtensions() {
if (JAVA_LIKE_EXTENSIONS == null) {
IContentType javaContentType = Platform.getContentTypeManager().getContentType(JavaCore.JAVA_SOURCE_CONTENT_TYPE);
HashSet fileExtensions = new HashSet();
// content types derived from java content type should be included (https://bugs.eclipse.org/bugs/show_bug.cgi?id=121715)
IContentType[] contentTypes = Platform.getContentTypeManager().getAllContentTypes();
for (int i = 0, length = contentTypes.length; i < length; i++) {
if (contentTypes[i].isKindOf(javaContentType)) { // note that javaContentType.isKindOf(javaContentType) == true
String[] fileExtension = contentTypes[i].getFileSpecs(IContentType.FILE_EXTENSION_SPEC);
for (int j = 0, length2 = fileExtension.length; j < length2; j++) {
fileExtensions.add(fileExtension[j]);
}
}
}
int length = fileExtensions.size();
// note that file extensions contains "java" as it is defined in JDT Core's plugin.xml
char[][] extensions = new char[length][];
extensions[0] = SuffixConstants.EXTENSION_java.toCharArray(); // ensure that "java" is first
int index = 1;
Iterator iterator = fileExtensions.iterator();
while (iterator.hasNext()) {
String fileExtension = (String) iterator.next();
if (SuffixConstants.EXTENSION_java.equals(fileExtension))
continue;
extensions[index++] = fileExtension.toCharArray();
}
JAVA_LIKE_EXTENSIONS = extensions;
}
return JAVA_LIKE_EXTENSIONS;
}
/**
* Get the jdk level of this root.
* The value can be:
* <ul>
* <li>major<<16 + minor : see predefined constants on ClassFileConstants </li>
* <li><code>0</null> if the root is a source package fragment root or if a Java model exception occured</li>
* </ul>
* Returns the jdk level
*/
public static long getJdkLevel(Object targetLibrary) {
try {
ClassFileReader reader = null;
if (targetLibrary instanceof IFolder) {
IFile classFile = findFirstClassFile((IFolder) targetLibrary); // only internal classfolders are allowed
if (classFile != null)
reader = Util.newClassFileReader(classFile);
} else {
// root is a jar file or a zip file
ZipFile jar = null;
try {
IPath path = null;
if (targetLibrary instanceof IResource) {
path = ((IResource)targetLibrary).getFullPath();
} else if (targetLibrary instanceof File){
File f = (File) targetLibrary;
if (!f.isDirectory()) {
path = new Path(((File)targetLibrary).getPath());
}
}
if (path != null) {
jar = JavaModelManager.getJavaModelManager().getZipFile(path);
for (Enumeration e= jar.entries(); e.hasMoreElements();) {
ZipEntry member= (ZipEntry) e.nextElement();
String entryName= member.getName();
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entryName)) {
reader = ClassFileReader.read(jar, entryName);
break;
}
}
}
} catch (CoreException e) {
// ignore
} finally {
JavaModelManager.getJavaModelManager().closeZipFile(jar);
}
}
if (reader != null) {
return reader.getVersion();
}
} catch (CoreException e) {
// ignore
} catch(ClassFormatException e) {
// ignore
} catch(IOException e) {
// ignore
}
return 0;
}
/**
* Returns the substring of the given file name, ending at the start of a
* Java like extension. The entire file name is returned if it doesn't end
* with a Java like extension.
*/
public static String getNameWithoutJavaLikeExtension(String fileName) {
int index = indexOfJavaLikeExtension(fileName);
if (index == -1)
return fileName;
return fileName.substring(0, index);
}
/**
* Returns the line separator found in the given text.
* If it is null, or not found return the line delimiter for the given project.
* If the project is null, returns the line separator for the workspace.
* If still null, return the system line separator.
*/
public static String getLineSeparator(String text, IJavaProject project) {
String lineSeparator = null;
// line delimiter in given text
if (text != null && text.length() != 0) {
lineSeparator = findLineSeparator(text.toCharArray());
if (lineSeparator != null)
return lineSeparator;
}
if (Platform.isRunning()) {
// line delimiter in project preference
IScopeContext[] scopeContext;
if (project != null) {
scopeContext= new IScopeContext[] { new ProjectScope(project.getProject()) };
lineSeparator= Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
if (lineSeparator != null)
return lineSeparator;
}
// line delimiter in workspace preference
scopeContext= new IScopeContext[] { InstanceScope.INSTANCE };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
if (lineSeparator != null)
return lineSeparator;
}
// system line delimiter
return org.eclipse.jdt.internal.compiler.util.Util.LINE_SEPARATOR;
}
/**
* Returns the line separator used by the given buffer.
* Uses the given text if none found.
*
* @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>
*/
private static String getLineSeparator(char[] text, char[] buffer) {
// search in this buffer's contents first
String lineSeparator = findLineSeparator(buffer);
if (lineSeparator == null) {
// search in the given text
lineSeparator = findLineSeparator(text);
if (lineSeparator == null) {
// default to system line separator
return getLineSeparator((String) null, (IJavaProject) null);
}
}
return lineSeparator;
}
private static IPackageFragment getPackageFragment(char[] fileName, int pkgEnd, int jarSeparator) {
if (jarSeparator != -1) {
String jarMemento = new String(fileName, 0, jarSeparator);
PackageFragmentRoot root = (PackageFragmentRoot) JavaCore.create(jarMemento);
if (pkgEnd == jarSeparator)
return root.getPackageFragment(CharOperation.NO_STRINGS);
char[] pkgName = CharOperation.subarray(fileName, jarSeparator+1, pkgEnd);
char[][] compoundName = CharOperation.splitOn('/', pkgName);
return root.getPackageFragment(CharOperation.toStrings(compoundName));
} else {
Path path = new Path(new String(fileName, 0, pkgEnd));
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IContainer folder = path.segmentCount() == 1 ? workspaceRoot.getProject(path.lastSegment()) : (IContainer) workspaceRoot.getFolder(path);
IJavaElement element = JavaCore.create(folder);
if (element == null) return null;
switch (element.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
return (IPackageFragment) element;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return ((PackageFragmentRoot) element).getPackageFragment(CharOperation.NO_STRINGS);
case IJavaElement.JAVA_PROJECT:
PackageFragmentRoot root = (PackageFragmentRoot) ((IJavaProject) element).getPackageFragmentRoot(folder);
if (root == null) return null;
return root.getPackageFragment(CharOperation.NO_STRINGS);
}
return null;
}
}
/**
* Returns the number of parameter types in a method signature.
*/
public static int getParameterCount(char[] sig) {
int i = CharOperation.indexOf('(', sig) + 1;
Assert.isTrue(i != 0);
int count = 0;
int len = sig.length;
for (;;) {
if (i == len)
break;
char c = sig[i];
if (c == ')')
break;
if (c == '[') {
++i;
} else
if (c == 'L') {
++count;
i = CharOperation.indexOf(';', sig, i + 1) + 1;
Assert.isTrue(i != 0);
} else {
++count;
++i;
}
}
return count;
}
/**
* Put all the arguments in one String.
*/
public static String getProblemArgumentsForMarker(String[] arguments){
StringBuffer args = new StringBuffer(10);
args.append(arguments.length);
args.append(':');
for (int j = 0; j < arguments.length; j++) {
if(j != 0)
args.append(ARGUMENTS_DELIMITER);
if(arguments[j].length() == 0) {
args.append(EMPTY_ARGUMENT);
} else {
encodeArgument(arguments[j], args);
}
}
return args.toString();
}
/**
* Encode the argument by doubling the '#' if present into the argument value.
*
* <p>This stores the encoded argument into the given buffer.</p>
*
* @param argument the given argument
* @param buffer the buffer in which the encoded argument is stored
*/
private static void encodeArgument(String argument, StringBuffer buffer) {
for (int i = 0, max = argument.length(); i < max; i++) {
char charAt = argument.charAt(i);
switch(charAt) {
case ARGUMENTS_DELIMITER :
buffer.append(ARGUMENTS_DELIMITER).append(ARGUMENTS_DELIMITER);
break;
default:
buffer.append(charAt);
}
}
}
/**
* Separate all the arguments of a String made by getProblemArgumentsForMarker
*/
public static String[] getProblemArgumentsFromMarker(String argumentsString){
if (argumentsString == null) {
return null;
}
int index = argumentsString.indexOf(':');
if(index == -1)
return null;
int length = argumentsString.length();
int numberOfArg = 0;
try{
numberOfArg = Integer.parseInt(argumentsString.substring(0 , index));
} catch (NumberFormatException e) {
return null;
}
argumentsString = argumentsString.substring(index + 1, length);
return decodeArgumentString(numberOfArg, argumentsString);
}
private static String[] decodeArgumentString(int length, String argumentsString) {
// decode the argumentString knowing that '#' is doubled if part of the argument value
if (length == 0) {
if (argumentsString.length() != 0) {
return null;
}
return CharOperation.NO_STRINGS;
}
String[] result = new String[length];
int count = 0;
StringBuffer buffer = new StringBuffer();
for (int i = 0, max = argumentsString.length(); i < max; i++) {
char current = argumentsString.charAt(i);
switch(current) {
case ARGUMENTS_DELIMITER :
/* check the next character. If this is also ARGUMENTS_DELIMITER then only put one into the
* decoded argument and proceed with the next character
*/
if ((i + 1) == max) {
return null;
}
char next = argumentsString.charAt(i + 1);
if (next == ARGUMENTS_DELIMITER) {
buffer.append(ARGUMENTS_DELIMITER);
i++; // proceed with the next character
} else {
// this means the current argument is over
String currentArgumentContents = String.valueOf(buffer);
if (EMPTY_ARGUMENT.equals(currentArgumentContents)) {
currentArgumentContents = org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING;
}
result[count++] = currentArgumentContents;
if (count > length) {
// too many elements - ill-formed
return null;
}
buffer.delete(0, buffer.length());
}
break;
default :
buffer.append(current);
}
}
// process last argument
String currentArgumentContents = String.valueOf(buffer);
if (EMPTY_ARGUMENT.equals(currentArgumentContents)) {
currentArgumentContents = org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING;
}
result[count++] = currentArgumentContents;
if (count > length) {
// too many elements - ill-formed
return null;
}
buffer.delete(0, buffer.length());
return result;
}
/**
* Returns the given file's contents as a byte array.
*/
public static byte[] getResourceContentsAsByteArray(IFile file) throws JavaModelException {
InputStream stream= null;
try {
stream = file.getContents(true);
} catch (CoreException e) {
throw new JavaModelException(e);
}
try {
return org.eclipse.jdt.internal.compiler.util.Util.getInputStreamAsByteArray(stream, -1);
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
} finally {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
}
/**
* Returns the given file's contents as a character array.
*/
public static char[] getResourceContentsAsCharArray(IFile file) throws JavaModelException {
// Get encoding from file
String encoding;
try {
encoding = file.getCharset();
} catch(CoreException ce) {
// do not use any encoding
encoding = null;
}
return getResourceContentsAsCharArray(file, encoding);
}
public static char[] getResourceContentsAsCharArray(IFile file, String encoding) throws JavaModelException {
// Get file length
// workaround https://bugs.eclipse.org/bugs/show_bug.cgi?id=130736 by using java.io.File if possible
IPath location = file.getLocation();
long length;
if (location == null) {
// non local file
try {
URI locationURI = file.getLocationURI();
if (locationURI == null)
throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Messages.bind(Messages.file_notFound, file.getFullPath().toString())));
length = EFS.getStore(locationURI).fetchInfo().getLength();
} catch (CoreException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST);
}
} else {
// local file
length = location.toFile().length();
}
// Get resource contents
InputStream stream= null;
try {
stream = file.getContents(true);
} catch (CoreException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST);
}
try {
return org.eclipse.jdt.internal.compiler.util.Util.getInputStreamAsCharArray(stream, (int) length, encoding);
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
} finally {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
}
/*
* Returns the signature of the given type.
*/
public static String getSignature(Type type) {
StringBuffer buffer = new StringBuffer();
getFullyQualifiedName(type, buffer);
return Signature.createTypeSignature(buffer.toString(), false/*not resolved in source*/);
}
/*
* Returns the source attachment property for this package fragment root's path
*/
public static String getSourceAttachmentProperty(IPath path) throws JavaModelException {
Map rootPathToAttachments = JavaModelManager.getJavaModelManager().rootPathToAttachments;
String property = (String) rootPathToAttachments.get(path);
if (property == null) {
try {
property = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(getSourceAttachmentPropertyName(path));
if (property == null) {
rootPathToAttachments.put(path, PackageFragmentRoot.NO_SOURCE_ATTACHMENT);
return null;
}
rootPathToAttachments.put(path, property);
return property;
} catch (CoreException e) {
throw new JavaModelException(e);
}
} else if (property.equals(PackageFragmentRoot.NO_SOURCE_ATTACHMENT)) {
return null;
} else
return property;
}
private static QualifiedName getSourceAttachmentPropertyName(IPath path) {
return new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + path.toOSString()); //$NON-NLS-1$
}
public static void setSourceAttachmentProperty(IPath path, String property) {
if (property == null) {
JavaModelManager.getJavaModelManager().rootPathToAttachments.put(path, PackageFragmentRoot.NO_SOURCE_ATTACHMENT);
} else {
JavaModelManager.getJavaModelManager().rootPathToAttachments.put(path, property);
}
try {
ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(getSourceAttachmentPropertyName(path), property);
} catch (CoreException e) {
e.printStackTrace();
}
}
/*
* Returns the declaring type signature of the element represented by the given binding key.
* Returns the signature of the element if it is a type.
*
* @return the declaring type signature
*/
public static String getDeclaringTypeSignature(String key) {
KeyToSignature keyToSignature = new KeyToSignature(key, KeyToSignature.DECLARING_TYPE);
keyToSignature.parse();
return keyToSignature.signature.toString();
}
/*
* Appends to the given buffer the fully qualified name (as it appears in the source) of the given type
*/
private static void getFullyQualifiedName(Type type, StringBuffer buffer) {
switch (type.getNodeType()) {
case ASTNode.ARRAY_TYPE:
ArrayType arrayType = (ArrayType) type;
getFullyQualifiedName(arrayType.getElementType(), buffer);
for (int i = 0, length = arrayType.getDimensions(); i < length; i++) {
buffer.append('[');
buffer.append(']');
}
break;
case ASTNode.PARAMETERIZED_TYPE:
ParameterizedType parameterizedType = (ParameterizedType) type;
getFullyQualifiedName(parameterizedType.getType(), buffer);
buffer.append('<');
Iterator iterator = parameterizedType.typeArguments().iterator();
boolean isFirst = true;
while (iterator.hasNext()) {
if (!isFirst)
buffer.append(',');
else
isFirst = false;
Type typeArgument = (Type) iterator.next();
getFullyQualifiedName(typeArgument, buffer);
}
buffer.append('>');
break;
case ASTNode.PRIMITIVE_TYPE:
buffer.append(((PrimitiveType) type).getPrimitiveTypeCode().toString());
break;
case ASTNode.QUALIFIED_TYPE:
buffer.append(((QualifiedType) type).getName().getFullyQualifiedName());
break;
case ASTNode.SIMPLE_TYPE:
buffer.append(((SimpleType) type).getName().getFullyQualifiedName());
break;
case ASTNode.WILDCARD_TYPE:
buffer.append('?');
WildcardType wildcardType = (WildcardType) type;
Type bound = wildcardType.getBound();
if (bound == null) return;
if (wildcardType.isUpperBound()) {
buffer.append(" extends "); //$NON-NLS-1$
} else {
buffer.append(" super "); //$NON-NLS-1$
}
getFullyQualifiedName(bound, buffer);
break;
}
}
/**
* Returns a trimmed version the simples names returned by Signature.
*/
public static String[] getTrimmedSimpleNames(String name) {
String[] result = Signature.getSimpleNames(name);
for (int i = 0, length = result.length; i < length; i++) {
result[i] = result[i].trim();
}
return result;
}
/**
* Return the java element corresponding to the given compiler binding.
*/
public static JavaElement getUnresolvedJavaElement(FieldBinding binding, WorkingCopyOwner workingCopyOwner, BindingsToNodesMap bindingsToNodes) {
if (binding.declaringClass == null) return null; // array length
JavaElement unresolvedJavaElement = getUnresolvedJavaElement(binding.declaringClass, workingCopyOwner, bindingsToNodes);
if (unresolvedJavaElement == null || unresolvedJavaElement.getElementType() != IJavaElement.TYPE) {
return null;
}
return (JavaElement) ((IType) unresolvedJavaElement).getField(String.valueOf(binding.name));
}
/**
* Returns the IInitializer that contains the given local variable in the given type
*/
public static JavaElement getUnresolvedJavaElement(int localSourceStart, int localSourceEnd, JavaElement type) {
try {
if (!(type instanceof IType))
return null;
IInitializer[] initializers = ((IType) type).getInitializers();
for (int i = 0; i < initializers.length; i++) {
IInitializer initializer = initializers[i];
ISourceRange sourceRange = initializer.getSourceRange();
if (sourceRange != null) {
int initializerStart = sourceRange.getOffset();
int initializerEnd = initializerStart + sourceRange.getLength();
if (initializerStart <= localSourceStart && localSourceEnd <= initializerEnd) {
return (JavaElement) initializer;
}
}
}
return null;
} catch (JavaModelException e) {
return null;
}
}
/**
* Return the java element corresponding to the given compiler binding.
*/
public static JavaElement getUnresolvedJavaElement(MethodBinding methodBinding, WorkingCopyOwner workingCopyOwner, BindingsToNodesMap bindingsToNodes) {
JavaElement unresolvedJavaElement = getUnresolvedJavaElement(methodBinding.declaringClass, workingCopyOwner, bindingsToNodes);
if (unresolvedJavaElement == null || unresolvedJavaElement.getElementType() != IJavaElement.TYPE) {
return null;
}
IType declaringType = (IType) unresolvedJavaElement;
org.eclipse.jdt.internal.compiler.ast.ASTNode node = bindingsToNodes == null ? null : bindingsToNodes.get(methodBinding);
if (node != null && !declaringType.isBinary()) {
if (node instanceof AnnotationMethodDeclaration) {
// node is an AnnotationMethodDeclaration
AnnotationMethodDeclaration typeMemberDeclaration = (AnnotationMethodDeclaration) node;
return (JavaElement) declaringType.getMethod(String.valueOf(typeMemberDeclaration.selector), CharOperation.NO_STRINGS); // annotation type members don't have parameters
} else {
// node is an MethodDeclaration
MethodDeclaration methodDeclaration = (MethodDeclaration) node;
Argument[] arguments = methodDeclaration.arguments;
String[] parameterSignatures;
if (arguments != null) {
parameterSignatures = new String[arguments.length];
for (int i = 0; i < arguments.length; i++) {
Argument argument = arguments[i];
TypeReference typeReference = argument.type;
int arrayDim = typeReference.dimensions();
String typeSig =
Signature.createTypeSignature(
CharOperation.concatWith(
typeReference.getTypeName(), '.'), false);
if (arrayDim > 0) {
typeSig = Signature.createArraySignature(typeSig, arrayDim);
}
parameterSignatures[i] = typeSig;
}
} else {
parameterSignatures = CharOperation.NO_STRINGS;
}
return (JavaElement) declaringType.getMethod(String.valueOf(methodDeclaration.selector), parameterSignatures);
}
} else {
// case of method not in the created AST, or a binary method
org.eclipse.jdt.internal.compiler.lookup.MethodBinding original = methodBinding.original();
String selector = original.isConstructor() ? declaringType.getElementName() : new String(original.selector);
boolean isBinary = declaringType.isBinary();
ReferenceBinding enclosingType = original.declaringClass.enclosingType();
boolean isInnerBinaryTypeConstructor = isBinary && original.isConstructor() && enclosingType != null;
TypeBinding[] parameters = original.parameters;
int length = parameters == null ? 0 : parameters.length;
int declaringIndex = isInnerBinaryTypeConstructor ? 1 : 0;
String[] parameterSignatures = new String[declaringIndex + length];
if (isInnerBinaryTypeConstructor)
parameterSignatures[0] = new String(enclosingType.genericTypeSignature()).replace('/', '.');
for (int i = 0; i < length; i++) {
char[] signature = parameters[i].genericTypeSignature();
if (isBinary) {
signature = CharOperation.replaceOnCopy(signature, '/', '.');
} else {
signature = toUnresolvedTypeSignature(signature);
}
parameterSignatures[declaringIndex + i] = new String(signature);
}
IMethod result = declaringType.getMethod(selector, parameterSignatures);
if (isBinary)
return (JavaElement) result;
if (result.exists()) // if perfect match (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=249567 )
return (JavaElement) result;
IMethod[] methods = null;
try {
methods = declaringType.getMethods();
} catch (JavaModelException e) {
// declaring type doesn't exist
return null;
}
IMethod[] candidates = Member.findMethods(result, methods);
if (candidates == null || candidates.length == 0)
return null;
return (JavaElement) candidates[0];
}
}
/**
* Return the java element corresponding to the given compiler binding.
*/
public static JavaElement getUnresolvedJavaElement(TypeBinding typeBinding, WorkingCopyOwner workingCopyOwner, BindingsToNodesMap bindingsToNodes) {
if (typeBinding == null)
return null;
switch (typeBinding.kind()) {
case Binding.ARRAY_TYPE :
typeBinding = ((org.eclipse.jdt.internal.compiler.lookup.ArrayBinding) typeBinding).leafComponentType();
return getUnresolvedJavaElement(typeBinding, workingCopyOwner, bindingsToNodes);
case Binding.BASE_TYPE :
case Binding.WILDCARD_TYPE :
case Binding.INTERSECTION_TYPE:
return null;
default :
if (typeBinding.isCapture())
return null;
}
ReferenceBinding referenceBinding;
if (typeBinding.isParameterizedType() || typeBinding.isRawType())
referenceBinding = (ReferenceBinding) typeBinding.erasure();
else
referenceBinding = (ReferenceBinding) typeBinding;
char[] fileName = referenceBinding.getFileName();
if (referenceBinding.isLocalType() || referenceBinding.isAnonymousType()) {
// local or anonymous type
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(fileName)) {
int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
int pkgEnd = CharOperation.lastIndexOf('/', fileName); // pkgEnd is exclusive
if (pkgEnd == -1)
pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
if (jarSeparator != -1 && pkgEnd < jarSeparator) // if in a jar and no slash, it is a default package -> pkgEnd should be equal to jarSeparator
pkgEnd = jarSeparator;
if (pkgEnd == -1)
return null;
IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
char[] constantPoolName = referenceBinding.constantPoolName();
if (constantPoolName == null) {
ClassFile classFile = (ClassFile) getClassFile(fileName);
return classFile == null ? null : (JavaElement) classFile.getType();
}
pkgEnd = CharOperation.lastIndexOf('/', constantPoolName);
char[] classFileName = CharOperation.subarray(constantPoolName, pkgEnd+1, constantPoolName.length);
ClassFile classFile = (ClassFile) pkg.getClassFile(new String(classFileName) + SuffixConstants.SUFFIX_STRING_class);
return (JavaElement) classFile.getType();
}
ICompilationUnit cu = getCompilationUnit(fileName, workingCopyOwner);
if (cu == null) return null;
// must use getElementAt(...) as there is no back pointer to the defining method (scope is null after resolution has ended)
try {
int sourceStart = ((org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding) referenceBinding).sourceStart;
return (JavaElement) cu.getElementAt(sourceStart);
} catch (JavaModelException e) {
// does not exist
return null;
}
} else if (referenceBinding.isTypeVariable()) {
// type parameter
final String typeVariableName = new String(referenceBinding.sourceName());
org.eclipse.jdt.internal.compiler.lookup.Binding declaringElement = ((org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding) referenceBinding).declaringElement;
if (declaringElement instanceof MethodBinding) {
IMethod declaringMethod = (IMethod) getUnresolvedJavaElement((MethodBinding) declaringElement, workingCopyOwner, bindingsToNodes);
return (JavaElement) declaringMethod.getTypeParameter(typeVariableName);
} else {
IType declaringType = (IType) getUnresolvedJavaElement((TypeBinding) declaringElement, workingCopyOwner, bindingsToNodes);
return (JavaElement) declaringType.getTypeParameter(typeVariableName);
}
} else {
if (fileName == null) return null; // case of a WilCardBinding that doesn't have a corresponding Java element
// member or top level type
TypeBinding declaringTypeBinding = typeBinding.enclosingType();
if (declaringTypeBinding == null) {
// top level type
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(fileName)) {
ClassFile classFile = (ClassFile) getClassFile(fileName);
if (classFile == null) return null;
return (JavaElement) classFile.getType();
}
ICompilationUnit cu = getCompilationUnit(fileName, workingCopyOwner);
if (cu == null) return null;
return (JavaElement) cu.getType(new String(referenceBinding.sourceName()));
} else {
// member type
IType declaringType = (IType) getUnresolvedJavaElement(declaringTypeBinding, workingCopyOwner, bindingsToNodes);
if (declaringType == null) return null;
return (JavaElement) declaringType.getType(new String(referenceBinding.sourceName()));
}
}
}
/*
* Returns the index of the most specific argument paths which is strictly enclosing the path to check
*/
public static int indexOfEnclosingPath(IPath checkedPath, IPath[] paths, int pathCount) {
int bestMatch = -1, bestLength = -1;
for (int i = 0; i < pathCount; i++){
if (paths[i].equals(checkedPath)) continue;
if (paths[i].isPrefixOf(checkedPath)) {
int currentLength = paths[i].segmentCount();
if (currentLength > bestLength) {
bestLength = currentLength;
bestMatch = i;
}
}
}
return bestMatch;
}
/*
* Returns the index of the Java like extension of the given file name
* or -1 if it doesn't end with a known Java like extension.
* Note this is the index of the '.' even if it is not considered part of the extension.
*/
public static int indexOfJavaLikeExtension(String fileName) {
int fileNameLength = fileName.length();
char[][] javaLikeExtensions = getJavaLikeExtensions();
extensions: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
char[] extension = javaLikeExtensions[i];
int extensionLength = extension.length;
int extensionStart = fileNameLength - extensionLength;
int dotIndex = extensionStart - 1;
if (dotIndex < 0) continue;
if (fileName.charAt(dotIndex) != '.') continue;
for (int j = 0; j < extensionLength; j++) {
if (fileName.charAt(extensionStart + j) != extension[j])
continue extensions;
}
return dotIndex;
}
return -1;
}
/*
* Returns the index of the first argument paths which is equal to the path to check
*/
public static int indexOfMatchingPath(IPath checkedPath, IPath[] paths, int pathCount) {
for (int i = 0; i < pathCount; i++){
if (paths[i].equals(checkedPath)) return i;
}
return -1;
}
/*
* Returns the index of the first argument paths which is strictly nested inside the path to check
*/
public static int indexOfNestedPath(IPath checkedPath, IPath[] paths, int pathCount) {
for (int i = 0; i < pathCount; i++){
if (checkedPath.equals(paths[i])) continue;
if (checkedPath.isPrefixOf(paths[i])) return i;
}
return -1;
}
/**
* Returns whether the local file system supports accessing and modifying
* the given attribute.
*/
protected static boolean isAttributeSupported(int attribute) {
return (EFS.getLocalFileSystem().attributes() & attribute) != 0;
}
/**
* Returns whether the given resource is read-only or not.
* @param resource
* @return <code>true</code> if the resource is read-only, <code>false</code> if it is not or
* if the file system does not support the read-only attribute.
*/
public static boolean isReadOnly(IResource resource) {
if (isReadOnlySupported()) {
ResourceAttributes resourceAttributes = resource.getResourceAttributes();
if (resourceAttributes == null) return false; // not supported on this platform for this resource
return resourceAttributes.isReadOnly();
}
return false;
}
/**
* Returns whether the local file system supports accessing and modifying
* the read only flag.
*/
public static boolean isReadOnlySupported() {
return isAttributeSupported(EFS.ATTRIBUTE_READ_ONLY);
}
/*
* Returns whether the given java element is exluded from its root's classpath.
* It doesn't check whether the root itself is on the classpath or not
*/
public static final boolean isExcluded(IJavaElement element) {
int elementType = element.getElementType();
switch (elementType) {
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return false;
case IJavaElement.PACKAGE_FRAGMENT:
PackageFragmentRoot root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
IResource resource = ((PackageFragment) element).resource();
return resource != null && isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars());
case IJavaElement.COMPILATION_UNIT:
root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
resource = element.getResource();
if (resource == null)
return false;
if (isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars()))
return true;
return isExcluded(element.getParent());
default:
IJavaElement cu = element.getAncestor(IJavaElement.COMPILATION_UNIT);
return cu != null && isExcluded(cu);
}
}
/*
* Returns whether the given resource path matches one of the inclusion/exclusion
* patterns.
* NOTE: should not be asked directly using pkg root pathes
* @see IClasspathEntry#getInclusionPatterns
* @see IClasspathEntry#getExclusionPatterns
*/
public final static boolean isExcluded(IPath resourcePath, char[][] inclusionPatterns, char[][] exclusionPatterns, boolean isFolderPath) {
if (inclusionPatterns == null && exclusionPatterns == null) return false;
return org.eclipse.jdt.internal.compiler.util.Util.isExcluded(resourcePath.toString().toCharArray(), inclusionPatterns, exclusionPatterns, isFolderPath);
}
/*
* Returns whether the given resource matches one of the exclusion patterns.
* NOTE: should not be asked directly using pkg root pathes
* @see IClasspathEntry#getExclusionPatterns
*/
public final static boolean isExcluded(IResource resource, char[][] inclusionPatterns, char[][] exclusionPatterns) {
IPath path = resource.getFullPath();
// ensure that folders are only excluded if all of their children are excluded
int resourceType = resource.getType();
return isExcluded(path, inclusionPatterns, exclusionPatterns, resourceType == IResource.FOLDER || resourceType == IResource.PROJECT);
}
/**
* Validate the given .class file name.
* A .class file name must obey the following rules:
* <ul>
* <li> it must not be null
* <li> it must include the <code>".class"</code> suffix
* <li> its prefix must be a valid identifier
* </ul>
* </p>
* @param name the name of a .class file
* @param sourceLevel the source level
* @param complianceLevel the compliance level
* @return a status object with code <code>IStatus.OK</code> if
* the given name is valid as a .class file name, otherwise a status
* object indicating what is wrong with the name
*/
public static boolean isValidClassFileName(String name, String sourceLevel, String complianceLevel) {
return JavaConventions.validateClassFileName(name, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
}
/**
* Validate the given compilation unit name.
* A compilation unit name must obey the following rules:
* <ul>
* <li> it must not be null
* <li> it must include the <code>".java"</code> suffix
* <li> its prefix must be a valid identifier
* </ul>
* </p>
* @param name the name of a compilation unit
* @param sourceLevel the source level
* @param complianceLevel the compliance level
* @return a status object with code <code>IStatus.OK</code> if
* the given name is valid as a compilation unit name, otherwise a status
* object indicating what is wrong with the name
*/
public static boolean isValidCompilationUnitName(String name, String sourceLevel, String complianceLevel) {
return JavaConventions.validateCompilationUnitName(name, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
}
/**
* Returns true if the given folder name is valid for a package,
* false if it is not.
* @param folderName the name of the folder
* @param sourceLevel the source level
* @param complianceLevel the compliance level
*/
public static boolean isValidFolderNameForPackage(String folderName, String sourceLevel, String complianceLevel) {
return JavaConventions.validateIdentifier(folderName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
}
/**
* Returns true if the given method signature is valid,
* false if it is not.
*/
public static boolean isValidMethodSignature(String sig) {
int len = sig.length();
if (len == 0) return false;
int i = 0;
char c = sig.charAt(i++);
if (c != '(') return false;
if (i >= len) return false;
while (sig.charAt(i) != ')') {
// Void is not allowed as a parameter type.
i = checkTypeSignature(sig, i, len, false);
if (i == -1) return false;
if (i >= len) return false;
}
++i;
i = checkTypeSignature(sig, i, len, true);
return i == len;
}
/**
* Returns true if the given type signature is valid,
* false if it is not.
*/
public static boolean isValidTypeSignature(String sig, boolean allowVoid) {
int len = sig.length();
return checkTypeSignature(sig, 0, len, allowVoid) == len;
}
/*
* Returns the simple name of a local type from the given binary type name.
* The last '$' is at lastDollar. The last character of the type name is at end-1.
*/
public static String localTypeName(String binaryTypeName, int lastDollar, int end) {
if (lastDollar > 0 && binaryTypeName.charAt(lastDollar-1) == '$')
// local name starts with a dollar sign
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=103466)
return binaryTypeName;
int nameStart = lastDollar+1;
while (nameStart < end && Character.isDigit(binaryTypeName.charAt(nameStart)))
nameStart++;
return binaryTypeName.substring(nameStart, end);
}
/*
* Add a log entry
*/
public static void log(Throwable e, String message) {
Throwable nestedException;
if (e instanceof JavaModelException
&& (nestedException = ((JavaModelException)e).getException()) != null) {
e = nestedException;
}
log(new Status(
IStatus.ERROR,
JavaCore.PLUGIN_ID,
IStatus.ERROR,
message,
e));
}
/**
* Log a message that is potentially repeated in the same session.
* The first time this method is called with a given exception, the
* exception stack trace is written to the log.
* <p>Only intended for use in debug statements.</p>
*
* @param key the given key
* @param e the given exception
* @throws IllegalArgumentException if the given key is null
*/
public static void logRepeatedMessage(String key, Exception e) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null"); //$NON-NLS-1$
}
if (fgRepeatedMessages.contains(key)) {
return;
}
fgRepeatedMessages.add(key);
log(e);
}
public static void logRepeatedMessage(String key, int statusErrorID, String message) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null"); //$NON-NLS-1$
}
if (fgRepeatedMessages.contains(key)) {
return;
}
fgRepeatedMessages.add(key);
log(statusErrorID, message);
}
/*
* Add a log entry
*/
public static void log(int statusErrorID, String message) {
log(new Status(
statusErrorID,
JavaCore.PLUGIN_ID,
message));
}
/*
* Add a log entry
*/
public static void log(IStatus status) {
JavaCore.getPlugin().getLog().log(status);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Messages.code_assist_internal_error, e));
}
public static ClassFileReader newClassFileReader(IResource resource) throws CoreException, ClassFormatException, IOException {
InputStream in = null;
try {
in = ((IFile) resource).getContents(true);
return ClassFileReader.read(in, resource.getFullPath().toString());
} finally {
if (in != null)
in.close();
}
}
/**
* Normalizes the cariage returns in the given text.
* They are all changed to use the given buffer's line separator.
*/
public static char[] normalizeCRs(char[] text, char[] buffer) {
CharArrayBuffer result = new CharArrayBuffer();
int lineStart = 0;
int length = text.length;
if (length == 0) return text;
String lineSeparator = getLineSeparator(text, buffer);
char nextChar = text[0];
for (int i = 0; i < length; i++) {
char currentChar = nextChar;
nextChar = i < length-1 ? text[i+1] : ' ';
switch (currentChar) {
case '\n':
int lineLength = i-lineStart;
char[] line = new char[lineLength];
System.arraycopy(text, lineStart, line, 0, lineLength);
result.append(line);
result.append(lineSeparator);
lineStart = i+1;
break;
case '\r':
lineLength = i-lineStart;
if (lineLength >= 0) {
line = new char[lineLength];
System.arraycopy(text, lineStart, line, 0, lineLength);
result.append(line);
result.append(lineSeparator);
if (nextChar == '\n') {
nextChar = ' ';
lineStart = i+2;
} else {
// when line separator are mixed in the same file
// \r might not be followed by a \n. If not, we should increment
// lineStart by one and not by two.
lineStart = i+1;
}
} else {
// when line separator are mixed in the same file
// we need to prevent NegativeArraySizeException
lineStart = i+1;
}
break;
}
}
char[] lastLine;
if (lineStart > 0) {
int lastLineLength = length-lineStart;
if (lastLineLength > 0) {
lastLine = new char[lastLineLength];
System.arraycopy(text, lineStart, lastLine, 0, lastLineLength);
result.append(lastLine);
}
return result.getContents();
}
return text;
}
/**
* Normalizes the carriage returns in the given text.
* They are all changed to use given buffer's line separator.
*/
public static String normalizeCRs(String text, String buffer) {
return new String(normalizeCRs(text.toCharArray(), buffer.toCharArray()));
}
/**
* Converts the given relative path into a package name.
* Returns null if the path is not a valid package name.
* @param pkgPath the package path
* @param sourceLevel the source level
* @param complianceLevel the compliance level
*/
public static String packageName(IPath pkgPath, String sourceLevel, String complianceLevel) {
StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) {
String segment = pkgPath.segment(j);
if (!isValidFolderNameForPackage(segment, sourceLevel, complianceLevel)) {
return null;
}
pkgName.append(segment);
if (j < pkgPath.segmentCount() - 1) {
pkgName.append("." ); //$NON-NLS-1$
}
}
return pkgName.toString();
}
/**
* Returns the length of the common prefix between s1 and s2.
*/
public static int prefixLength(char[] s1, char[] s2) {
int len= 0;
int max= Math.min(s1.length, s2.length);
for (int i= 0; i < max && s1[i] == s2[i]; ++i)
++len;
return len;
}
/**
* Returns the length of the common prefix between s1 and s2.
*/
public static int prefixLength(String s1, String s2) {
int len= 0;
int max= Math.min(s1.length(), s2.length());
for (int i= 0; i < max && s1.charAt(i) == s2.charAt(i); ++i)
++len;
return len;
}
private static void quickSort(char[][] list, int left, int right) {
int original_left= left;
int original_right= right;
char[] mid= list[left + (right - left) / 2];
do {
while (compare(list[left], mid) < 0) {
left++;
}
while (compare(mid, list[right]) < 0) {
right--;
}
if (left <= right) {
char[] tmp= list[left];
list[left]= list[right];
list[right]= tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(list, original_left, right);
}
if (left < original_right) {
quickSort(list, left, original_right);
}
}
/**
* Sort the comparable objects in the given collection.
*/
private static void quickSort(Comparable[] sortedCollection, int left, int right) {
int original_left = left;
int original_right = right;
Comparable mid = sortedCollection[ left + (right - left) / 2];
do {
while (sortedCollection[left].compareTo(mid) < 0) {
left++;
}
while (mid.compareTo(sortedCollection[right]) < 0) {
right--;
}
if (left <= right) {
Comparable tmp = sortedCollection[left];
sortedCollection[left] = sortedCollection[right];
sortedCollection[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(sortedCollection, original_left, right);
}
if (left < original_right) {
quickSort(sortedCollection, left, original_right);
}
}
private static void quickSort(int[] list, int left, int right) {
int original_left= left;
int original_right= right;
int mid= list[left + (right - left) / 2];
do {
while (list[left] < mid) {
left++;
}
while (mid < list[right]) {
right--;
}
if (left <= right) {
int tmp= list[left];
list[left]= list[right];
list[right]= tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(list, original_left, right);
}
if (left < original_right) {
quickSort(list, left, original_right);
}
}
/**
* Sort the objects in the given collection using the given comparer.
*/
private static void quickSort(Object[] sortedCollection, int left, int right, Comparer comparer) {
int original_left = left;
int original_right = right;
Object mid = sortedCollection[ left + (right - left) / 2];
do {
while (comparer.compare(sortedCollection[left], mid) < 0) {
left++;
}
while (comparer.compare(mid, sortedCollection[right]) < 0) {
right--;
}
if (left <= right) {
Object tmp = sortedCollection[left];
sortedCollection[left] = sortedCollection[right];
sortedCollection[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(sortedCollection, original_left, right, comparer);
}
if (left < original_right) {
quickSort(sortedCollection, left, original_right, comparer);
}
}
/**
* Sort the strings in the given collection.
*/
private static void quickSort(String[] sortedCollection, int left, int right) {
int original_left = left;
int original_right = right;
String mid = sortedCollection[ left + (right - left) / 2];
do {
while (sortedCollection[left].compareTo(mid) < 0) {
left++;
}
while (mid.compareTo(sortedCollection[right]) < 0) {
right--;
}
if (left <= right) {
String tmp = sortedCollection[left];
sortedCollection[left] = sortedCollection[right];
sortedCollection[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(sortedCollection, original_left, right);
}
if (left < original_right) {
quickSort(sortedCollection, left, original_right);
}
}
/**
* Returns the toString() of the given full path minus the first given number of segments.
* The returned string is always a relative path (it has no leading slash)
*/
public static String relativePath(IPath fullPath, int skipSegmentCount) {
boolean hasTrailingSeparator = fullPath.hasTrailingSeparator();
String[] segments = fullPath.segments();
// compute length
int length = 0;
int max = segments.length;
if (max > skipSegmentCount) {
for (int i1 = skipSegmentCount; i1 < max; i1++) {
length += segments[i1].length();
}
//add the separator lengths
length += max - skipSegmentCount - 1;
}
if (hasTrailingSeparator)
length++;
char[] result = new char[length];
int offset = 0;
int len = segments.length - 1;
if (len >= skipSegmentCount) {
//append all but the last segment, with separators
for (int i = skipSegmentCount; i < len; i++) {
int size = segments[i].length();
segments[i].getChars(0, size, result, offset);
offset += size;
result[offset++] = '/';
}
//append the last segment
int size = segments[len].length();
segments[len].getChars(0, size, result, offset);
offset += size;
}
if (hasTrailingSeparator)
result[offset++] = '/';
return new String(result);
}
/*
* Resets the list of Java-like extensions after a change in content-type.
*/
public static void resetJavaLikeExtensions() {
JAVA_LIKE_EXTENSIONS = null;
}
/**
* Scans the given string for a type signature starting at the given index
* and returns the index of the last character.
* <pre>
* TypeSignature:
* | BaseTypeSignature
* | ArrayTypeSignature
* | ClassTypeSignature
* | TypeVariableSignature
* </pre>
*
* @param string the signature string
* @param start the 0-based character index of the first character
* @return the 0-based character index of the last character
* @exception IllegalArgumentException if this is not a type signature
*/
public static int scanTypeSignature(char[] string, int start) {
// this method is used in jdt.debug
return org.eclipse.jdt.internal.compiler.util.Util.scanTypeSignature(string, start);
}
/**
* Return a new array which is the split of the given string using the given divider. The given end
* is exclusive and the given start is inclusive.
* <br>
* <br>
* For example:
* <ol>
* <li><pre>
* divider = 'b'
* string = "abbaba"
* start = 2
* end = 5
* result => { "", "a", "" }
* </pre>
* </li>
* </ol>
*
* @param divider the given divider
* @param string the given string
* @param start the given starting index
* @param end the given ending index
* @return a new array which is the split of the given string using the given divider
* @throws ArrayIndexOutOfBoundsException if start is lower than 0 or end is greater than the array length
*/
public static final String[] splitOn(
char divider,
String string,
int start,
int end) {
int length = string == null ? 0 : string.length();
if (length == 0 || start > end)
return CharOperation.NO_STRINGS;
int wordCount = 1;
for (int i = start; i < end; i++)
if (string.charAt(i) == divider)
wordCount++;
String[] split = new String[wordCount];
int last = start, currentWord = 0;
for (int i = start; i < end; i++) {
if (string.charAt(i) == divider) {
split[currentWord++] = string.substring(last, i);
last = i + 1;
}
}
split[currentWord] = string.substring(last, end);
return split;
}
/**
* Sets or unsets the given resource as read-only in the file system.
* It's a no-op if the file system does not support the read-only attribute.
*
* @param resource The resource to set as read-only
* @param readOnly <code>true</code> to set it to read-only,
* <code>false</code> to unset
*/
public static void setReadOnly(IResource resource, boolean readOnly) {
if (isReadOnlySupported()) {
ResourceAttributes resourceAttributes = resource.getResourceAttributes();
if (resourceAttributes == null) return; // not supported on this platform for this resource
resourceAttributes.setReadOnly(readOnly);
try {
resource.setResourceAttributes(resourceAttributes);
} catch (CoreException e) {
// ignore
}
}
}
public static void sort(char[][] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
/**
* Sorts an array of Comparable objects in place.
*/
public static void sort(Comparable[] objects) {
if (objects.length > 1)
quickSort(objects, 0, objects.length - 1);
}
public static void sort(int[] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
/**
* Sorts an array of objects in place.
* The given comparer compares pairs of items.
*/
public static void sort(Object[] objects, Comparer comparer) {
if (objects.length > 1)
quickSort(objects, 0, objects.length - 1, comparer);
}
/**
* Sorts an array of strings in place using quicksort.
*/
public static void sort(String[] strings) {
if (strings.length > 1)
quickSort(strings, 0, strings.length - 1);
}
/**
* Sorts an array of Comparable objects, returning a new array
* with the sorted items. The original array is left untouched.
*/
public static Comparable[] sortCopy(Comparable[] objects) {
int len = objects.length;
Comparable[] copy = new Comparable[len];
System.arraycopy(objects, 0, copy, 0, len);
sort(copy);
return copy;
}
/**
* Sorts an array of Java elements based on their toStringWithAncestors(),
* returning a new array with the sorted items.
* The original array is left untouched.
*/
public static IJavaElement[] sortCopy(IJavaElement[] elements) {
int len = elements.length;
IJavaElement[] copy = new IJavaElement[len];
System.arraycopy(elements, 0, copy, 0, len);
sort(copy, new Comparer() {
public int compare(Object a, Object b) {
return ((JavaElement) a).toStringWithAncestors().compareTo(((JavaElement) b).toStringWithAncestors());
}
});
return copy;
}
/**
* Sorts an array of Strings, returning a new array
* with the sorted items. The original array is left untouched.
*/
public static Object[] sortCopy(Object[] objects, Comparer comparer) {
int len = objects.length;
Object[] copy = new Object[len];
System.arraycopy(objects, 0, copy, 0, len);
sort(copy, comparer);
return copy;
}
/**
* Sorts an array of Strings, returning a new array
* with the sorted items. The original array is left untouched.
*/
public static String[] sortCopy(String[] objects) {
int len = objects.length;
String[] copy = new String[len];
System.arraycopy(objects, 0, copy, 0, len);
sort(copy);
return copy;
}
/*
* Returns whether the given compound name starts with the given prefix.
* Returns true if the n first elements of the prefix are equals and the last element of the
* prefix is a prefix of the corresponding element in the compound name.
*/
public static boolean startsWithIgnoreCase(String[] compoundName, String[] prefix, boolean partialMatch) {
int prefixLength = prefix.length;
int nameLength = compoundName.length;
if (prefixLength > nameLength) return false;
for (int i = 0; i < prefixLength - 1; i++) {
if (!compoundName[i].equalsIgnoreCase(prefix[i]))
return false;
}
return (partialMatch || prefixLength == nameLength) && compoundName[prefixLength-1].toLowerCase().startsWith(prefix[prefixLength-1].toLowerCase());
}
/**
* Converts a String[] to char[][].
*/
public static char[][] toCharArrays(String[] a) {
int len = a.length;
if (len == 0) return CharOperation.NO_CHAR_CHAR;
char[][] result = new char[len][];
for (int i = 0; i < len; ++i) {
result[i] = a[i].toCharArray();
}
return result;
}
/**
* Converts a String to char[][], where segments are separate by '.'.
*/
public static char[][] toCompoundChars(String s) {
int len = s.length();
if (len == 0) {
return CharOperation.NO_CHAR_CHAR;
}
int segCount = 1;
for (int off = s.indexOf('.'); off != -1; off = s.indexOf('.', off + 1)) {
++segCount;
}
char[][] segs = new char[segCount][];
int start = 0;
for (int i = 0; i < segCount; ++i) {
int dot = s.indexOf('.', start);
int end = (dot == -1 ? s.length() : dot);
segs[i] = new char[end - start];
s.getChars(start, end, segs[i], 0);
start = end + 1;
}
return segs;
}
/*
* Converts the given URI to a local file. Use the existing file if the uri is on the local file system.
* Otherwise fetch it.
* Returns null if unable to fetch it.
*/
public static File toLocalFile(URI uri, IProgressMonitor monitor) throws CoreException {
IFileStore fileStore = EFS.getStore(uri);
File localFile = fileStore.toLocalFile(EFS.NONE, monitor);
if (localFile ==null)
// non local file system
localFile= fileStore.toLocalFile(EFS.CACHE, monitor);
return localFile;
}
/**
* Converts a char[][] to String, where segments are separated by '.'.
*/
public static String toString(char[][] c) {
StringBuffer sb = new StringBuffer();
for (int i = 0, max = c.length; i < max; ++i) {
if (i != 0) sb.append('.');
sb.append(c[i]);
}
return sb.toString();
}
/**
* Converts a char[][] and a char[] to String, where segments are separated by '.'.
*/
public static String toString(char[][] c, char[] d) {
if (c == null) return new String(d);
StringBuffer sb = new StringBuffer();
for (int i = 0, max = c.length; i < max; ++i) {
sb.append(c[i]);
sb.append('.');
}
sb.append(d);
return sb.toString();
}
/*
* Converts a char[][] to String[].
*/
public static String[] toStrings(char[][] a) {
int len = a.length;
String[] result = new String[len];
for (int i = 0; i < len; ++i) {
result[i] = new String(a[i]);
}
return result;
}
private static char[] toUnresolvedTypeSignature(char[] signature) {
int length = signature.length;
if (length <= 1)
return signature;
StringBuffer buffer = new StringBuffer(length);
toUnresolvedTypeSignature(signature, 0, length, buffer);
int bufferLength = buffer.length();
char[] result = new char[bufferLength];
buffer.getChars(0, bufferLength, result, 0);
return result;
}
private static int toUnresolvedTypeSignature(char[] signature, int start, int length, StringBuffer buffer) {
if (signature[start] == Signature.C_RESOLVED)
buffer.append(Signature.C_UNRESOLVED);
else
buffer.append(signature[start]);
for (int i = start+1; i < length; i++) {
char c = signature[i];
switch (c) {
case '/':
case Signature.C_DOLLAR:
buffer.append(Signature.C_DOT);
break;
case Signature.C_GENERIC_START:
buffer.append(Signature.C_GENERIC_START);
i = toUnresolvedTypeSignature(signature, i+1, length, buffer);
break;
case Signature.C_GENERIC_END:
buffer.append(Signature.C_GENERIC_END);
return i;
default:
buffer.append(c);
break;
}
}
return length;
}
private static void appendArrayTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
int length = string.length;
// need a minimum 2 char
if (start >= length - 1) {
throw new IllegalArgumentException();
}
char c = string[start];
if (c != Signature.C_ARRAY) {
throw new IllegalArgumentException();
}
int index = start;
c = string[++index];
while(c == Signature.C_ARRAY) {
// need a minimum 2 char
if (index >= length - 1) {
throw new IllegalArgumentException();
}
c = string[++index];
}
appendTypeSignature(string, index, buffer, compact);
for(int i = 0, dims = index - start; i < dims; i++) {
buffer.append('[').append(']');
}
}
private static void appendClassTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
char c = string[start];
if (c != Signature.C_RESOLVED) {
return;
}
int p = start + 1;
int checkpoint = buffer.length();
while (true) {
c = string[p];
switch(c) {
case Signature.C_SEMICOLON :
// all done
return;
case Signature.C_DOT :
case '/' :
// erase package prefix
if (compact) {
buffer.setLength(checkpoint);
} else {
buffer.append('.');
}
break;
case Signature.C_DOLLAR :
/**
* Convert '$' in resolved type signatures into '.'.
* NOTE: This assumes that the type signature is an inner type
* signature. This is true in most cases, but someone can define a
* non-inner type name containing a '$'.
*/
buffer.append('.');
break;
default :
buffer.append(c);
}
p++;
}
}
static void appendTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
char c = string[start];
switch (c) {
case Signature.C_ARRAY :
appendArrayTypeSignature(string, start, buffer, compact);
break;
case Signature.C_RESOLVED :
appendClassTypeSignature(string, start, buffer, compact);
break;
case Signature.C_TYPE_VARIABLE :
int e = org.eclipse.jdt.internal.compiler.util.Util.scanTypeVariableSignature(string, start);
buffer.append(string, start + 1, e - start - 1);
break;
case Signature.C_BOOLEAN :
buffer.append(BOOLEAN);
break;
case Signature.C_BYTE :
buffer.append(BYTE);
break;
case Signature.C_CHAR :
buffer.append(CHAR);
break;
case Signature.C_DOUBLE :
buffer.append(DOUBLE);
break;
case Signature.C_FLOAT :
buffer.append(FLOAT);
break;
case Signature.C_INT :
buffer.append(INT);
break;
case Signature.C_LONG :
buffer.append(LONG);
break;
case Signature.C_SHORT :
buffer.append(SHORT);
break;
case Signature.C_VOID :
buffer.append(VOID);
break;
}
}
public static String toString(char[] declaringClass, char[] methodName, char[] methodSignature, boolean includeReturnType, boolean compact) {
final boolean isConstructor = CharOperation.equals(methodName, INIT);
int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature);
if (firstParen == -1) {
return ""; //$NON-NLS-1$
}
StringBuffer buffer = new StringBuffer(methodSignature.length + 10);
// decode declaring class name
// it can be either an array signature or a type signature
if (declaringClass != null && declaringClass.length > 0) {
char[] declaringClassSignature = null;
if (declaringClass[0] == Signature.C_ARRAY) {
CharOperation.replace(declaringClass, '/', '.');
declaringClassSignature = Signature.toCharArray(declaringClass);
} else {
CharOperation.replace(declaringClass, '/', '.');
declaringClassSignature = declaringClass;
}
int lastIndexOfSlash = CharOperation.lastIndexOf('.', declaringClassSignature);
if (compact && lastIndexOfSlash != -1) {
buffer.append(declaringClassSignature, lastIndexOfSlash + 1, declaringClassSignature.length - lastIndexOfSlash - 1);
} else {
buffer.append(declaringClassSignature);
}
if (!isConstructor) {
buffer.append('.');
}
}
// selector
if (!isConstructor && methodName != null) {
buffer.append(methodName);
}
// parameters
buffer.append('(');
char[][] pts = Signature.getParameterTypes(methodSignature);
for (int i = 0, max = pts.length; i < max; i++) {
appendTypeSignature(pts[i], 0 , buffer, compact);
if (i != pts.length - 1) {
buffer.append(',');
buffer.append(' ');
}
}
buffer.append(')');
if (!isConstructor) {
buffer.append(" : "); //$NON-NLS-1$
// return type
if (includeReturnType) {
char[] rts = Signature.getReturnType(methodSignature);
appendTypeSignature(rts, 0 , buffer, compact);
}
}
return String.valueOf(buffer);
}
/*
* Returns the unresolved type parameter signatures of the given method
* e.g. {"QString;", "[int", "[[Qjava.util.Vector;"}
*/
public static String[] typeParameterSignatures(AbstractMethodDeclaration method) {
Argument[] args = method.arguments;
if (args != null) {
int length = args.length;
String[] signatures = new String[length];
for (int i = 0; i < args.length; i++) {
Argument arg = args[i];
signatures[i] = typeSignature(arg.type);
}
return signatures;
}
return CharOperation.NO_STRINGS;
}
/*
* Returns the unresolved type signature of the given type reference,
* e.g. "QString;", "[int", "[[Qjava.util.Vector;"
*/
public static String typeSignature(TypeReference type) {
char[][] compoundName = type.getParameterizedTypeName();
char[] typeName =CharOperation.concatWith(compoundName, '.');
String signature = Signature.createTypeSignature(typeName, false/*don't resolve*/);
return signature;
}
/**
* Asserts that the given method signature is valid.
*/
public static void validateMethodSignature(String sig) {
Assert.isTrue(isValidMethodSignature(sig));
}
/**
* Asserts that the given type signature is valid.
*/
public static void validateTypeSignature(String sig, boolean allowVoid) {
Assert.isTrue(isValidTypeSignature(sig, allowVoid));
}
public static void verbose(String log) {
verbose(log, System.out);
}
public static synchronized void verbose(String log, PrintStream printStream) {
int start = 0;
do {
int end = log.indexOf('\n', start);
printStream.print(Thread.currentThread());
printStream.print(" "); //$NON-NLS-1$
printStream.print(log.substring(start, end == -1 ? log.length() : end+1));
start = end+1;
} while (start != 0);
printStream.println();
}
/**
* Returns true if the given name ends with one of the known java like extension.
* (implementation is not creating extra strings)
*/
public final static boolean isJavaLikeFileName(String name) {
if (name == null) return false;
return indexOfJavaLikeExtension(name) != -1;
}
/**
* Returns true if the given name ends with one of the known java like extension.
* (implementation is not creating extra strings)
*/
public final static boolean isJavaLikeFileName(char[] fileName) {
if (fileName == null) return false;
int fileNameLength = fileName.length;
char[][] javaLikeExtensions = getJavaLikeExtensions();
extensions: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
char[] extension = javaLikeExtensions[i];
int extensionLength = extension.length;
int extensionStart = fileNameLength - extensionLength;
if (extensionStart-1 < 0) continue;
if (fileName[extensionStart-1] != '.') continue;
for (int j = 0; j < extensionLength; j++) {
if (fileName[extensionStart + j] != extension[j])
continue extensions;
}
return true;
}
return false;
}
/**
* Get all type arguments from an array of signatures.
*
* Example:
* For following type X<Y<Z>,V<W>,U>.A<B> signatures is:
* [
* ['L','X','<','L','Y','<','L','Z',';'>',';','L','V','<','L','W',';'>',';','L','U',';',>',';'],
* ['L','A','<','L','B',';','>',';']
* ]
* @see #splitTypeLevelsSignature(String)
* Then, this method returns:
* [
* [
* ['L','Y','<','L','Z',';'>',';'],
* ['L','V','<','L','W',';'>',';'],
* ['L','U',';']
* ],
* [
* ['L','B',';']
* ]
* ]
*
* @param typeSignatures Array of signatures (one per each type levels)
* @throws IllegalArgumentException If one of provided signature is malformed
* @return char[][][] Array of type arguments for each signature
*/
public final static char[][][] getAllTypeArguments(char[][] typeSignatures) {
if (typeSignatures == null) return null;
int length = typeSignatures.length;
char[][][] typeArguments = new char[length][][];
for (int i=0; i<length; i++){
typeArguments[i] = Signature.getTypeArguments(typeSignatures[i]);
}
return typeArguments;
}
public static IAnnotation getAnnotation(JavaElement parent, IBinaryAnnotation binaryAnnotation, String memberValuePairName) {
char[] typeName = org.eclipse.jdt.core.Signature.toCharArray(CharOperation.replaceOnCopy(binaryAnnotation.getTypeName(), '/', '.'));
return new Annotation(parent, new String(typeName), memberValuePairName);
}
public static Object getAnnotationMemberValue(JavaElement parent, MemberValuePair memberValuePair, Object binaryValue) {
if (binaryValue instanceof Constant) {
return getAnnotationMemberValue(memberValuePair, (Constant) binaryValue);
} else if (binaryValue instanceof IBinaryAnnotation) {
memberValuePair.valueKind = IMemberValuePair.K_ANNOTATION;
return getAnnotation(parent, (IBinaryAnnotation) binaryValue, memberValuePair.getMemberName());
} else if (binaryValue instanceof ClassSignature) {
memberValuePair.valueKind = IMemberValuePair.K_CLASS;
char[] className = Signature.toCharArray(CharOperation.replaceOnCopy(((ClassSignature) binaryValue).getTypeName(), '/', '.'));
return new String(className);
} else if (binaryValue instanceof EnumConstantSignature) {
memberValuePair.valueKind = IMemberValuePair.K_QUALIFIED_NAME;
EnumConstantSignature enumConstant = (EnumConstantSignature) binaryValue;
char[] enumName = Signature.toCharArray(CharOperation.replaceOnCopy(enumConstant.getTypeName(), '/', '.'));
char[] qualifiedName = CharOperation.concat(enumName, enumConstant.getEnumConstantName(), '.');
return new String(qualifiedName);
} else if (binaryValue instanceof Object[]) {
memberValuePair.valueKind = -1; // modified below by the first call to getMemberValue(...)
Object[] binaryValues = (Object[]) binaryValue;
int length = binaryValues.length;
Object[] values = new Object[length];
for (int i = 0; i < length; i++) {
int previousValueKind = memberValuePair.valueKind;
Object value = getAnnotationMemberValue(parent, memberValuePair, binaryValues[i]);
if (previousValueKind != -1 && memberValuePair.valueKind != previousValueKind) {
// values are heterogeneous, value kind is thus unknown
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
}
if (value instanceof Annotation) {
Annotation annotation = (Annotation) value;
for (int j = 0; j < i; j++) {
if (annotation.equals(values[j])) {
annotation.occurrenceCount++;
}
}
}
values[i] = value;
}
if (memberValuePair.valueKind == -1)
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return values;
} else {
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
}
/*
* Creates a member value from the given constant, and sets the valueKind on the given memberValuePair
*/
public static Object getAnnotationMemberValue(MemberValuePair memberValuePair, Constant constant) {
if (constant == null) {
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
switch (constant.typeID()) {
case TypeIds.T_int :
memberValuePair.valueKind = IMemberValuePair.K_INT;
return new Integer(constant.intValue());
case TypeIds.T_byte :
memberValuePair.valueKind = IMemberValuePair.K_BYTE;
return new Byte(constant.byteValue());
case TypeIds.T_short :
memberValuePair.valueKind = IMemberValuePair.K_SHORT;
return new Short(constant.shortValue());
case TypeIds.T_char :
memberValuePair.valueKind = IMemberValuePair.K_CHAR;
return new Character(constant.charValue());
case TypeIds.T_float :
memberValuePair.valueKind = IMemberValuePair.K_FLOAT;
return new Float(constant.floatValue());
case TypeIds.T_double :
memberValuePair.valueKind = IMemberValuePair.K_DOUBLE;
return new Double(constant.doubleValue());
case TypeIds.T_boolean :
memberValuePair.valueKind = IMemberValuePair.K_BOOLEAN;
return Boolean.valueOf(constant.booleanValue());
case TypeIds.T_long :
memberValuePair.valueKind = IMemberValuePair.K_LONG;
return new Long(constant.longValue());
case TypeIds.T_JavaLangString :
memberValuePair.valueKind = IMemberValuePair.K_STRING;
return constant.stringValue();
default:
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
}
/*
* Creates a member value from the given constant in case of negative numerals,
* and sets the valueKind on the given memberValuePair
*/
public static Object getNegativeAnnotationMemberValue(MemberValuePair memberValuePair, Constant constant) {
if (constant == null) {
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
switch (constant.typeID()) {
case TypeIds.T_int :
memberValuePair.valueKind = IMemberValuePair.K_INT;
return new Integer(constant.intValue() * -1);
case TypeIds.T_float :
memberValuePair.valueKind = IMemberValuePair.K_FLOAT;
return new Float(constant.floatValue() * -1.0f);
case TypeIds.T_double :
memberValuePair.valueKind = IMemberValuePair.K_DOUBLE;
return new Double(constant.doubleValue() * -1.0);
case TypeIds.T_long :
memberValuePair.valueKind = IMemberValuePair.K_LONG;
return new Long(constant.longValue() * -1L);
default:
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
}
/**
* Split signatures of all levels from a type unique key.
*
* Example:
* For following type X<Y<Z>,V<W>,U>.A<B>, unique key is:
* "LX<LY<LZ;>;LV<LW;>;LU;>.LA<LB;>;"
*
* The return splitted signatures array is:
* [
* ['L','X','<','L','Y','<','L','Z',';'>',';','L','V','<','L','W',';'>',';','L','U','>',';'],
* ['L','A','<','L','B',';','>',';']
*
* @param typeSignature ParameterizedSourceType type signature
* @return char[][] Array of signatures for each level of given unique key
*/
public final static char[][] splitTypeLevelsSignature(String typeSignature) {
// In case of IJavaElement signature, replace '$' by '.'
char[] source = Signature.removeCapture(typeSignature.toCharArray());
CharOperation.replace(source, '$', '.');
// Init counters and arrays
char[][] signatures = new char[10][];
int signaturesCount = 0;
// int[] lengthes = new int [10];
int paramOpening = 0;
// Scan each signature character
for (int idx=0, ln = source.length; idx < ln; idx++) {
switch (source[idx]) {
case '>':
paramOpening--;
if (paramOpening == 0) {
if (signaturesCount == signatures.length) {
System.arraycopy(signatures, 0, signatures = new char[signaturesCount+10][], 0, signaturesCount);
}
}
break;
case '<':
paramOpening++;
break;
case '.':
if (paramOpening == 0) {
if (signaturesCount == signatures.length) {
System.arraycopy(signatures, 0, signatures = new char[signaturesCount+10][], 0, signaturesCount);
}
signatures[signaturesCount] = new char[idx+1];
System.arraycopy(source, 0, signatures[signaturesCount], 0, idx);
signatures[signaturesCount][idx] = Signature.C_SEMICOLON;
signaturesCount++;
}
break;
case '/':
source[idx] = '.';
break;
}
}
// Resize signatures array
char[][] typeSignatures = new char[signaturesCount+1][];
typeSignatures[0] = source;
for (int i=1, j=signaturesCount-1; i<=signaturesCount; i++, j--){
typeSignatures[i] = signatures[j];
}
return typeSignatures;
}
/*
* Can throw IllegalArgumentException or ArrayIndexOutOfBoundsException
*/
public static String toAnchor(int startingIndex, char[] methodSignature, String methodName, boolean isVarArgs) {
try {
return new String(toAnchor(startingIndex, methodSignature, methodName.toCharArray(), isVarArgs));
} catch(IllegalArgumentException e) {
return null;
}
}
public static char[] toAnchor(int startingIndex, char[] methodSignature, char[] methodName, boolean isVargArgs) {
int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature);
if (firstParen == -1) {
throw new IllegalArgumentException();
}
StringBuffer buffer = new StringBuffer(methodSignature.length + 10);
// selector
if (methodName != null) {
buffer.append(methodName);
}
// parameters
buffer.append('(');
char[][] pts = Signature.getParameterTypes(methodSignature);
for (int i = startingIndex, max = pts.length; i < max; i++) {
if (i == max - 1) {
appendTypeSignatureForAnchor(pts[i], 0 , buffer, isVargArgs);
} else {
appendTypeSignatureForAnchor(pts[i], 0 , buffer, false);
}
if (i != pts.length - 1) {
buffer.append(',');
buffer.append(' ');
}
}
buffer.append(')');
char[] result = new char[buffer.length()];
buffer.getChars(0, buffer.length(), result, 0);
return result;
}
private static int appendTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) {
// need a minimum 1 char
if (start >= string.length) {
throw new IllegalArgumentException();
}
char c = string[start];
if (isVarArgs) {
switch (c) {
case Signature.C_ARRAY :
return appendArrayTypeSignatureForAnchor(string, start, buffer, true);
case Signature.C_RESOLVED :
case Signature.C_TYPE_VARIABLE :
case Signature.C_BOOLEAN :
case Signature.C_BYTE :
case Signature.C_CHAR :
case Signature.C_DOUBLE :
case Signature.C_FLOAT :
case Signature.C_INT :
case Signature.C_LONG :
case Signature.C_SHORT :
case Signature.C_VOID :
case Signature.C_STAR:
case Signature.C_EXTENDS:
case Signature.C_SUPER:
case Signature.C_CAPTURE:
default:
throw new IllegalArgumentException(); // a var args is an array type
}
} else {
switch (c) {
case Signature.C_ARRAY :
return appendArrayTypeSignatureForAnchor(string, start, buffer, false);
case Signature.C_RESOLVED :
return appendClassTypeSignatureForAnchor(string, start, buffer);
case Signature.C_TYPE_VARIABLE :
int e = org.eclipse.jdt.internal.compiler.util.Util.scanTypeVariableSignature(string, start);
buffer.append(string, start + 1, e - start - 1);
return e;
case Signature.C_BOOLEAN :
buffer.append(BOOLEAN);
return start;
case Signature.C_BYTE :
buffer.append(BYTE);
return start;
case Signature.C_CHAR :
buffer.append(CHAR);
return start;
case Signature.C_DOUBLE :
buffer.append(DOUBLE);
return start;
case Signature.C_FLOAT :
buffer.append(FLOAT);
return start;
case Signature.C_INT :
buffer.append(INT);
return start;
case Signature.C_LONG :
buffer.append(LONG);
return start;
case Signature.C_SHORT :
buffer.append(SHORT);
return start;
case Signature.C_VOID :
buffer.append(VOID);
return start;
case Signature.C_CAPTURE :
return appendCaptureTypeSignatureForAnchor(string, start, buffer);
case Signature.C_STAR:
case Signature.C_EXTENDS:
case Signature.C_SUPER:
return appendTypeArgumentSignatureForAnchor(string, start, buffer);
default :
throw new IllegalArgumentException();
}
}
}
private static int appendTypeArgumentSignatureForAnchor(char[] string, int start, StringBuffer buffer) {
// need a minimum 1 char
if (start >= string.length) {
throw new IllegalArgumentException();
}
char c = string[start];
switch(c) {
case Signature.C_STAR :
return start;
case Signature.C_EXTENDS :
return appendTypeSignatureForAnchor(string, start + 1, buffer, false);
case Signature.C_SUPER :
return appendTypeSignatureForAnchor(string, start + 1, buffer, false);
default :
return appendTypeSignatureForAnchor(string, start, buffer, false);
}
}
private static int appendCaptureTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) {
// need a minimum 2 char
if (start >= string.length - 1) {
throw new IllegalArgumentException();
}
char c = string[start];
if (c != Signature.C_CAPTURE) {
throw new IllegalArgumentException();
}
return appendTypeArgumentSignatureForAnchor(string, start + 1, buffer);
}
private static int appendArrayTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) {
int length = string.length;
// need a minimum 2 char
if (start >= length - 1) {
throw new IllegalArgumentException();
}
char c = string[start];
if (c != Signature.C_ARRAY) {
throw new IllegalArgumentException();
}
int index = start;
c = string[++index];
while(c == Signature.C_ARRAY) {
// need a minimum 2 char
if (index >= length - 1) {
throw new IllegalArgumentException();
}
c = string[++index];
}
int e = appendTypeSignatureForAnchor(string, index, buffer, false);
for(int i = 1, dims = index - start; i < dims; i++) {
buffer.append('[').append(']');
}
if (isVarArgs) {
buffer.append('.').append('.').append('.');
} else {
buffer.append('[').append(']');
}
return e;
}
private static int appendClassTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) {
// need a minimum 3 chars "Lx;"
if (start >= string.length - 2) {
throw new IllegalArgumentException();
}
// must start in "L" or "Q"
char c = string[start];
if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) {
throw new IllegalArgumentException();
}
int p = start + 1;
while (true) {
if (p >= string.length) {
throw new IllegalArgumentException();
}
c = string[p];
switch(c) {
case Signature.C_SEMICOLON :
// all done
return p;
case Signature.C_GENERIC_START :
int e = scanGenericEnd(string, p + 1);
// once we hit type arguments there are no more package prefixes
p = e;
break;
case Signature.C_DOT :
buffer.append('.');
break;
case '/' :
buffer.append('/');
break;
case Signature.C_DOLLAR :
// once we hit "$" there are no more package prefixes
/**
* Convert '$' in resolved type signatures into '.'.
* NOTE: This assumes that the type signature is an inner type
* signature. This is true in most cases, but someone can define a
* non-inner type name containing a '$'.
*/
buffer.append('.');
break;
default :
buffer.append(c);
}
p++;
}
}
private static int scanGenericEnd(char[] string, int start) {
if (string[start] == Signature.C_GENERIC_END) {
return start;
}
int length = string.length;
int balance = 1;
start++;
while (start <= length) {
switch(string[start]) {
case Signature.C_GENERIC_END :
balance--;
if (balance == 0) {
return start;
}
break;
case Signature.C_GENERIC_START :
balance++;
break;
}
start++;
}
return start;
}
/*
* This method adjusts the task tags and task priorities so that they have the same size
*/
public static void fixTaskTags(Map defaultOptionsMap) {
Object taskTagsValue = defaultOptionsMap.get(JavaCore.COMPILER_TASK_TAGS);
char[][] taskTags = null;
if (taskTagsValue instanceof String) {
taskTags = CharOperation.splitAndTrimOn(',', ((String) taskTagsValue).toCharArray());
}
Object taskPrioritiesValue = defaultOptionsMap.get(JavaCore.COMPILER_TASK_PRIORITIES);
char[][] taskPriorities = null;
if (taskPrioritiesValue instanceof String) {
taskPriorities = CharOperation.splitAndTrimOn(',', ((String) taskPrioritiesValue).toCharArray());
}
if (taskPriorities == null) {
if (taskTags != null) {
Util.logRepeatedMessage(TASK_PRIORITIES_PROBLEM, IStatus.ERROR, "Inconsistent values for taskTags (not null) and task priorities (null)"); //$NON-NLS-1$
defaultOptionsMap.remove(JavaCore.COMPILER_TASK_TAGS);
}
return;
} else if (taskTags == null) {
Util.logRepeatedMessage(TASK_PRIORITIES_PROBLEM, IStatus.ERROR, "Inconsistent values for taskTags (null) and task priorities (not null)"); //$NON-NLS-1$
defaultOptionsMap.remove(JavaCore.COMPILER_TASK_PRIORITIES);
return;
}
int taskTagsLength = taskTags.length;
int taskPrioritiesLength = taskPriorities.length;
if (taskTagsLength != taskPrioritiesLength) {
Util.logRepeatedMessage(TASK_PRIORITIES_PROBLEM, IStatus.ERROR, "Inconsistent values for taskTags and task priorities : length is different"); //$NON-NLS-1$
if (taskTagsLength > taskPrioritiesLength) {
System.arraycopy(taskTags, 0, (taskTags = new char[taskPrioritiesLength][]), 0, taskPrioritiesLength);
defaultOptionsMap.put(JavaCore.COMPILER_TASK_TAGS, new String(CharOperation.concatWith(taskTags,',')));
} else {
System.arraycopy(taskPriorities, 0, (taskPriorities = new char[taskTagsLength][]), 0, taskTagsLength);
defaultOptionsMap.put(JavaCore.COMPILER_TASK_PRIORITIES, new String(CharOperation.concatWith(taskPriorities,',')));
}
}
}
/**
* Finds the IMethod element corresponding to the given selector,
* without creating a new dummy instance of a binary method.
* @param type the type in which the method is declared
* @param selector the method name
* @param paramTypeSignatures the type signatures of the method arguments
* @param isConstructor whether we're looking for a constructor
* @return an IMethod if found, otherwise null
* @throws JavaModelException
*/
public static IMethod findMethod(IType type, char[] selector, String[] paramTypeSignatures, boolean isConstructor) throws JavaModelException {
IMethod method = null;
int startingIndex = 0;
String[] args;
IType enclosingType = type.getDeclaringType();
// If the method is a constructor of a non-static inner type, add the enclosing type as an
// additional parameter to the constructor
if (enclosingType != null
&& isConstructor
&& !Flags.isStatic(type.getFlags())) {
args = new String[paramTypeSignatures.length+1];
startingIndex = 1;
args[0] = Signature.createTypeSignature(enclosingType.getFullyQualifiedName(), true);
} else {
args = new String[paramTypeSignatures.length];
}
int length = args.length;
for(int i = startingIndex; i< length ; i++){
args[i] = new String(paramTypeSignatures[i-startingIndex]);
}
method = type.getMethod(new String(selector), args);
IMethod[] methods = type.findMethods(method);
if (methods != null && methods.length > 0) {
method = methods[0];
}
return method;
}
}
|
Java
|
public class ShardingValueWrapper {
private final Comparable<?> value;
public ShardingValueWrapper(final Comparable<?> value) {
Preconditions.checkArgument(value instanceof Number || value instanceof Date || value instanceof String,
String.format("Value must be type of Number, Data or String, your value type is '%s'", value.getClass().getName()));
this.value = value;
}
/**
* Get long value.
*
* @return long value
*/
public long longValue() {
return numberValue().longValue();
}
/**
* Get double value.
*
* @return double value
*/
public double doubleValue() {
return numberValue().doubleValue();
}
private Number numberValue() {
if (value instanceof Number) {
return (Number) value;
}
if (value instanceof Date) {
return ((Date) value).getTime();
}
return new BigDecimal(value.toString());
}
/**
* Get date value.
*
* @param format date format
* @return date value
* @throws ParseException date format parse exception
*/
public Date dateValue(final String format) throws ParseException {
if (value instanceof Number) {
return new Date(((Number) value).longValue());
}
if (value instanceof Date) {
return (Date) value;
}
Preconditions.checkArgument(!Strings.isNullOrEmpty(format));
return new SimpleDateFormat(format).parse(value.toString());
}
/**
* Get date value.
*
* @return date value
* @throws ParseException date format parse exception
*/
public Date dateValue() throws ParseException {
return dateValue(null);
}
/**
* Convert date to string.
*
* @param format date format
* @return string value
*/
public String toString(final String format) {
if (value instanceof Date) {
return new SimpleDateFormat(format).format(((Date) value).getTime());
}
if (value instanceof Number) {
return new SimpleDateFormat(format).format(((Number) value).longValue());
}
return toString();
}
@Override
public String toString() {
return value.toString();
}
}
|
Java
|
public static class LinkedList {
Node head;
/* Function to get the nth node from end of list */
void printNthFromLast(int n) {
Node main_ptr = head;
Node ref_ptr = head;
int count = 0;
if (head != null) {
while (count < n) {
if (ref_ptr == null) {
System.out.println(n + " is greater than the no " +
" of nodes in the list");
return;
}
ref_ptr = ref_ptr.next;
count++;
}
while (ref_ptr != null) {
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
System.out.println("Node no. " + n + " from last is " +
main_ptr.data);
}
}
/* Inserts a new Node at front of the list. */
public void push(int new_data) {
/*
* 1 & 2: Allocate the Node & Put in the data
* */
Node new_node = new Node(new_data);
/*
* 3. Make next of new Node as head
* */
new_node.next = head;
/*
* 4. Move the head to point to new Node
* */
head = new_node;
}
public class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
}
|
Java
|
public class QuestionList extends JPanel implements Observer {
private JTable questionTable;
private MyTableModel defaultTableModel;
private JButton newQuestionButton = new JButton("New");
private JButton deleteQuestionButton = new JButton("Delete");
private int selectedRowIndex = 0;
private QuestionPanelModel questionPanelModel;
// This field variable is mainly used for determining whether the list is actually updated
private final ArrayList<Question> tableQuestions = new ArrayList<>();
public QuestionList(QuestionPanelModel questionPanelModel) {
this.questionPanelModel = questionPanelModel;
questionPanelModel.addObserver(this);
// set layout
setLayout(new GridBagLayout());
// set up questionTable
String[][] tableData = QuestionPanelModel.questions2TableData(tableQuestions);
defaultTableModel = new MyTableModel(tableData, new String[]{"ID", "Question Text", "Mark"});
questionTable = new JTable(defaultTableModel);
questionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
questionTable.setDefaultEditor(Object.class, null); // disable editing
questionTable.getColumnModel().getColumn(0).setPreferredWidth(35);
questionTable.getColumnModel().getColumn(1).setMinWidth(50);
questionTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
// fix size
questionTable.setPreferredScrollableViewportSize(new Dimension(200, (int) questionTable.getPreferredSize().getHeight())); // it works!
questionTable.getSelectionModel().addListSelectionListener(e -> {
selectedRowIndex = questionTable.getSelectedRow();
questionPanelModel.setSelectedQuestionIndex(selectedRowIndex);
System.out.println("setSelectedQuestionIndex: " + selectedRowIndex);
});
final int LIST_HEIGHT_WEIGHT = 10;
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
c.gridheight = LIST_HEIGHT_WEIGHT;
c.weightx = 1.0;
c.weighty = 1.0;
// Note: JTable must be wrapped by JScrollPane
add(new JScrollPane(questionTable), c);
c.gridy = LIST_HEIGHT_WEIGHT;
c.gridwidth = 1;
c.gridheight = 1;
c.weighty = 0.0;
c.fill = GridBagConstraints.CENTER;
add(newQuestionButton, c);
c.gridx = 1;
c.gridx = 2;
add(deleteQuestionButton, c);
setUpButtonListeners();
}
private void setUpButtonListeners() {
newQuestionButton.addActionListener(e -> questionPanelModel.newQuestion());
deleteQuestionButton.addActionListener(e -> {
int selectedIndex = questionPanelModel.getSelectedQuestionIndex();
Question selectedQuestion = questionPanelModel.getSelectedQuestion();
if (selectedIndex == -1 || selectedQuestion == null) {
JOptionPane.showMessageDialog(null, "Error: No question is selected.");
return;
}
questionPanelModel.deleteSelectedQuestion();
});
}
@Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
}
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
*/
@Override
public void update(Observable o, Object arg) {
// Clear the selection while the selected index is null
if (questionPanelModel.getSelectedQuestionIndex() == null) {
questionTable.clearSelection();
}
if (!tableQuestions.equals(questionPanelModel.getQuestions())) {
tableQuestions.clear();
tableQuestions.addAll(questionPanelModel.getQuestions());
defaultTableModel.updateData(tableQuestions);
}
}
/**
* Customer table model for updating data
*/
private class MyTableModel extends DefaultTableModel {
private Object[] tempColumnNames;
public MyTableModel(Object[][] data, Object[] columnNames) {
tempColumnNames = columnNames;
setDataVector(data, columnNames);
}
private void updateData(ArrayList<Question> questions) {
setDataVector(QuestionPanelModel.questions2TableData(questions), tempColumnNames);
fireTableDataChanged();
}
}
}
|
Java
|
private class MyTableModel extends DefaultTableModel {
private Object[] tempColumnNames;
public MyTableModel(Object[][] data, Object[] columnNames) {
tempColumnNames = columnNames;
setDataVector(data, columnNames);
}
private void updateData(ArrayList<Question> questions) {
setDataVector(QuestionPanelModel.questions2TableData(questions), tempColumnNames);
fireTableDataChanged();
}
}
|
Java
|
public class Testground {
static DbHibernate addressDb = EasyHibernateDbConnection.getEasyDatabase().getAddressDb();
static DaoHibernate<AddressBase> baseDao = EasyHibernateDbConnection.getEasyDatabase().getBaseDao();
static DaoHibernate<Communication> commDao = EasyHibernateDbConnection.getEasyDatabase().getCommDao();
static DaoHibernate<OrganisationalAddress> orgaDao = EasyHibernateDbConnection.getEasyDatabase().getOrgaDao();
static DaoHibernate<PersonalAddress> persDao = EasyHibernateDbConnection.getEasyDatabase().getPersDao();
static List<AddressBase> generateSample() {
List<AddressBase> result = new ArrayList<>();
Communication[] comms = {
new Communication(CommType.MOBILE, "0167 345 6789", "Nikki Handy"),
new Communication(CommType.MESSENGER, "telegram://Nico_Lausi_1234", "Nikki Telegram")
};
PersonalAddress nikki = new PersonalAddress(
"Nikki", "Nico", "Lausi", Instant.parse("1234-12-06T06:00:00Z"));
nikki.addComm(comms[0]);
nikki.addComm(comms[1]);
comms[0].setOwner(nikki);
comms[1].setOwner(nikki);
result.add(nikki);
result.add(new PersonalAddress("Doggi", "Oggi", "Dalmatian", Instant.parse("2008-11-06T00:00:00Z")));
result.add(new PersonalAddress("Pipa", "Pille", "Palle", Instant.parse("2000-01-01T00:00:00Z")));
result.add(new PersonalAddress("Lups", "Luna", "Pudel", Instant.parse("2018-11-06T00:00:00Z")));
result.add(new PersonalAddress("Lemmi", "Ein", "Lemming", Instant.now()));
result.add(new OrganisationalAddress("Die Firma", "TBQ"));
return result;
}
public static void main(String[] args) {
// runServer();
// createDbConnection();
commDao.deleteAll();
baseDao.deleteAll();
baseDao.closeSession();
generateSample().forEach(adb -> baseDao.save(adb));
List<AddressBase> adbs = baseDao.fetchAll();
assert adbs.size() == 6;
PersonalAddress sample = new PersonalAddress();
sample.setNickname("L%");
List<PersonalAddress> qbe1 = persDao.findByExample(sample);
assert qbe1.stream().map(PersonalAddress::getNickname).collect(Collectors.toList()).containsAll(Arrays.asList("Lups", "Lemmi"));
PersonalAddress anAddress = qbe1.get(0);
long id = anAddress.getId();
anAddress.setNickname("Duffy");
persDao.save(anAddress);
AddressBase toFetch = baseDao.fetch(id);
assert toFetch.getNickname().equals("Duffy");
List<Object> cl = commDao.find("from Comm");
assert cl.size() == 2;
List<Object> hql = commDao.find("select owner from Comm where commtype = :ct", Map.of("ct", CommType.MOBILE.ordinal()));
assert hql.size() == 1;
assert hql.get(0) instanceof PersonalAddress;
baseDao.commit();
toFetch.setNickname("Schnuffy");
baseDao.save(toFetch);
baseDao.rollback();
// rollback doesn't change the local object
assert toFetch.getNickname().equals("Schnuffy");
// so retrieve a new copy from db
AddressBase newFetch = baseDao.fetch(toFetch.getId());
// assert rollback succeeded
assert newFetch.getNickname().equals("Duffy");
baseDao.delete(newFetch);
baseDao.commit();
toFetch = baseDao.fetch(id);
assert toFetch == null;
baseDao.closeSession();
persDao.closeSession();
addressDb.closeSession();
System.out.println("Database " + addressDb.toString() + ", baseDao " + baseDao.toString());
// stopServer();
addressDb.closeDatabase();
// while (true) {
// Thread.sleep(1000);
// }
}
}
|
Java
|
@MavlinkMessageInfo(
id = 102,
crc = 158,
description = "Global position/attitude estimate from a vision source."
)
public final class VisionPositionEstimate {
private final BigInteger usec;
private final float x;
private final float y;
private final float z;
private final float roll;
private final float pitch;
private final float yaw;
private final List<Float> covariance;
private VisionPositionEstimate(BigInteger usec, float x, float y, float z, float roll,
float pitch, float yaw, List<Float> covariance) {
this.usec = usec;
this.x = x;
this.y = y;
this.z = z;
this.roll = roll;
this.pitch = pitch;
this.yaw = yaw;
this.covariance = covariance;
}
/**
* Returns a builder instance for this message.
*/
@MavlinkMessageBuilder
public static Builder builder() {
return new Builder();
}
/**
* Timestamp (UNIX time or time since system boot)
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 8,
description = "Timestamp (UNIX time or time since system boot)"
)
public final BigInteger usec() {
return this.usec;
}
/**
* Global X position
*/
@MavlinkFieldInfo(
position = 2,
unitSize = 4,
description = "Global X position"
)
public final float x() {
return this.x;
}
/**
* Global Y position
*/
@MavlinkFieldInfo(
position = 3,
unitSize = 4,
description = "Global Y position"
)
public final float y() {
return this.y;
}
/**
* Global Z position
*/
@MavlinkFieldInfo(
position = 4,
unitSize = 4,
description = "Global Z position"
)
public final float z() {
return this.z;
}
/**
* Roll angle
*/
@MavlinkFieldInfo(
position = 5,
unitSize = 4,
description = "Roll angle"
)
public final float roll() {
return this.roll;
}
/**
* Pitch angle
*/
@MavlinkFieldInfo(
position = 6,
unitSize = 4,
description = "Pitch angle"
)
public final float pitch() {
return this.pitch;
}
/**
* Yaw angle
*/
@MavlinkFieldInfo(
position = 7,
unitSize = 4,
description = "Yaw angle"
)
public final float yaw() {
return this.yaw;
}
/**
* Pose covariance matrix upper right triangular (first six entries are the first ROW, next five
* entries are the second ROW, etc.)
*/
@MavlinkFieldInfo(
position = 9,
unitSize = 4,
arraySize = 21,
extension = true,
description = "Pose covariance matrix upper right triangular (first six entries are the first ROW, next five entries are the second ROW, etc.)"
)
public final List<Float> covariance() {
return this.covariance;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !getClass().equals(o.getClass())) return false;
VisionPositionEstimate other = (VisionPositionEstimate)o;
if (!Objects.deepEquals(usec, other.usec)) return false;
if (!Objects.deepEquals(x, other.x)) return false;
if (!Objects.deepEquals(y, other.y)) return false;
if (!Objects.deepEquals(z, other.z)) return false;
if (!Objects.deepEquals(roll, other.roll)) return false;
if (!Objects.deepEquals(pitch, other.pitch)) return false;
if (!Objects.deepEquals(yaw, other.yaw)) return false;
if (!Objects.deepEquals(covariance, other.covariance)) return false;
return true;
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + Objects.hashCode(usec);
result = 31 * result + Objects.hashCode(x);
result = 31 * result + Objects.hashCode(y);
result = 31 * result + Objects.hashCode(z);
result = 31 * result + Objects.hashCode(roll);
result = 31 * result + Objects.hashCode(pitch);
result = 31 * result + Objects.hashCode(yaw);
result = 31 * result + Objects.hashCode(covariance);
return result;
}
@Override
public String toString() {
return "VisionPositionEstimate{usec=" + usec
+ ", x=" + x
+ ", y=" + y
+ ", z=" + z
+ ", roll=" + roll
+ ", pitch=" + pitch
+ ", yaw=" + yaw
+ ", covariance=" + covariance + "}";
}
public static final class Builder {
private BigInteger usec;
private float x;
private float y;
private float z;
private float roll;
private float pitch;
private float yaw;
private List<Float> covariance;
/**
* Timestamp (UNIX time or time since system boot)
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 8,
description = "Timestamp (UNIX time or time since system boot)"
)
public final Builder usec(BigInteger usec) {
this.usec = usec;
return this;
}
/**
* Global X position
*/
@MavlinkFieldInfo(
position = 2,
unitSize = 4,
description = "Global X position"
)
public final Builder x(float x) {
this.x = x;
return this;
}
/**
* Global Y position
*/
@MavlinkFieldInfo(
position = 3,
unitSize = 4,
description = "Global Y position"
)
public final Builder y(float y) {
this.y = y;
return this;
}
/**
* Global Z position
*/
@MavlinkFieldInfo(
position = 4,
unitSize = 4,
description = "Global Z position"
)
public final Builder z(float z) {
this.z = z;
return this;
}
/**
* Roll angle
*/
@MavlinkFieldInfo(
position = 5,
unitSize = 4,
description = "Roll angle"
)
public final Builder roll(float roll) {
this.roll = roll;
return this;
}
/**
* Pitch angle
*/
@MavlinkFieldInfo(
position = 6,
unitSize = 4,
description = "Pitch angle"
)
public final Builder pitch(float pitch) {
this.pitch = pitch;
return this;
}
/**
* Yaw angle
*/
@MavlinkFieldInfo(
position = 7,
unitSize = 4,
description = "Yaw angle"
)
public final Builder yaw(float yaw) {
this.yaw = yaw;
return this;
}
/**
* Pose covariance matrix upper right triangular (first six entries are the first ROW, next five
* entries are the second ROW, etc.)
*/
@MavlinkFieldInfo(
position = 9,
unitSize = 4,
arraySize = 21,
extension = true,
description = "Pose covariance matrix upper right triangular (first six entries are the first ROW, next five entries are the second ROW, etc.)"
)
public final Builder covariance(List<Float> covariance) {
this.covariance = covariance;
return this;
}
public final VisionPositionEstimate build() {
return new VisionPositionEstimate(usec, x, y, z, roll, pitch, yaw, covariance);
}
}
}
|
Java
|
public class DDSViewResourceForm extends ActionForm implements Serializable {
private String recordId;
private String recordFilename;
private String[] recordCollections;
private String[] recordIds;
private SimpleLuceneIndex index = null;
private ResultDocList resultDocs = null;
private ResultDoc primaryResultDoc = null;
private String primaryResultDocCollectionKey = null;
private String pathwayUrl = "";
private String error = null;
private String resourceResultLinkRedirectURL = "";
private ItemDocReader itemDocReader = null;
private String primaryResultDocId = "";
private Map vocabCache = null;
private String vocabCacheGroup = "";
private String system = "";
private MetadataVocab vocab = null;
private String relDisplayed = null;
private String collectionKey = null;
private String contextUrl = "";
private StringBuffer vocabCacheFeedbackString = new StringBuffer( "" );
private String forwardUrl;
/**
* Sets the forwardUrl attribute of the DDSViewResourceForm object
*
* @param forwardUrl The new forwardUrl value
*/
public void setForwardUrl( String forwardUrl ) {
this.forwardUrl = forwardUrl;
}
/**
* Gets the forwardUrl attribute of the DDSViewResourceForm object
*
* @return The forwardUrl value
*/
public String getForwardUrl() {
return forwardUrl;
}
/**
* Gets the vocabCacheFeedbackString attribute of the DDSViewResourceForm
* object
*
* @return The vocabCacheFeedbackString value
*/
public String getVocabCacheFeedbackString() {
if ( vocabCacheFeedbackString.length() > 1 ) {
vocabCacheFeedbackString.setLength( vocabCacheFeedbackString.length() - 2 );
}
return vocabCacheFeedbackString.toString();
}
/**
* Sets the vocabCacheFeedbackString attribute of the DDSViewResourceForm
* object
*
* @param append The new vocabCacheFeedbackString value
*/
public void setVocabCacheFeedbackString( String append ) {
vocabCacheFeedbackString.append( append + ", " );
}
/**
* Constructor for the DDSViewResourceForm object
*/
public DDSViewResourceForm() {
vocabCache = new HashMap();
}
/**
* Sets the vocab attribute of the DDSViewResourceForm object
*
* @param vocab The new vocab value
*/
public void setVocab( MetadataVocab vocab ) {
this.vocab = vocab;
}
/**
* Gets the vocab attribute of the DDSViewResourceForm object
*
* @return The vocab value
*/
public MetadataVocab getVocab() {
return vocab;
}
/**
* Sets the system attribute of the DDSViewResourceForm object
*
* @param system The new system value
*/
public void setSystem( String system ) {
this.system = system;
}
/**
* Description of the Method
*/
public void clearVocabCache() {
vocabCacheFeedbackString.setLength( 0 );
vocabCache.clear();
}
/**
* Description of the Method
*
* @param vocabValue
*/
public void setVocabCacheValue( String vocabValue ) {
vocabCache.put( vocabValue, new Boolean( true ) );
}
/**
* Sets the vocabCacheGroup attribute of the DDSViewResourceForm object
*
* @param vocabCacheGroup The new vocabCacheGroup value
*/
public void setVocabCacheGroup( String vocabCacheGroup ) {
this.vocabCacheGroup = vocabCacheGroup;
}
/**
* Gets the cachedVocabValuesInOrder attribute of the DDSViewResourceForm
* object
*
* @return The cachedVocabValuesInOrder value
*/
public ArrayList getCachedVocabValuesInOrder() {
return vocab.getCacheValuesInOrder( system, vocabCacheGroup, vocabCache );
}
/**
* Sets the resourceResultLinkRedirectURL attribute of the DDSViewResourceForm
* object
*
* @param str The new resourceResultLinkRedirectURL value
*/
public void setResourceResultLinkRedirectURL( String str ) {
resourceResultLinkRedirectURL = str;
}
/**
* Gets the resourceResultLinkRedirectURL attribute of the DDSQueryForm object
*
* @return The resourceResultLinkRedirectURL value
*/
public String getResourceResultLinkRedirectURL() {
return resourceResultLinkRedirectURL;
}
/**
* Sets the primaryResultDocId attribute of the DDSViewResourceForm object
*
* @param id The new primaryResultDocId value
*/
public void setPrimaryResultDocId( String id ) {
this.primaryResultDocId = id;
}
/**
* Gets the primaryResultDocId attribute of the DDSViewResourceForm object
*
* @return The primaryResultDocId value
*/
public String getPrimaryResultDocId() {
return primaryResultDocId;
}
/**
* Sets the error attribute of the DDSViewResourceForm object
*
* @param error The new error value
*/
public void setError( String error ) {
this.error = error;
}
/**
* Gets the error attribute of the DDSViewResourceForm object
*
* @return The error value
*/
public String getError() {
return error;
}
/**
* Sets the primaryResultDoc attribute of the DDSViewResourceForm object
*
* @param primaryResultDoc The new primaryResultDoc value
*/
public void setPrimaryResultDoc( ResultDoc primaryResultDoc ) {
this.primaryResultDoc = primaryResultDoc;
itemDocReader = (ItemDocReader)primaryResultDoc.getDocReader();
}
/**
* Gets the primaryResultDocReader attribute of the DDSViewResourceForm object
*
* @return The primaryResultDoc value
*/
public ResultDoc getPrimaryResultDoc() {
return primaryResultDoc;
}
/**
* Gets the itemDocReader attribute of the DDSViewResourceForm object
*
* @return The itemDocReader value
*/
public ItemDocReader getItemDocReader() {
return itemDocReader;
}
/**
* Sets the primaryResultDocCollectionId attribute of the DDSViewResourceForm
* object
*
* @param primaryResultDocCollectionKey The new primaryResultDocCollectionKey
* value
*/
public void setPrimaryResultDocCollectionKey( String primaryResultDocCollectionKey ) {
this.primaryResultDocCollectionKey = primaryResultDocCollectionKey;
}
/**
* Gets the primaryResultDocCollectionId attribute of the DDSViewResourceForm
* object
*
* @return The primaryRequestedCollectionKey value
*/
public String getPrimaryRequestedCollectionKey() {
return primaryResultDocCollectionKey;
}
/**
* Gets the hasReviews attribute of the DDSViewResourceForm object
*
* @return The hasReviews value
*/
public String getHasReviews() {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
if ( annoResults != null ) {
for ( int i = 0; i < annoResults.size(); i++ ) {
DleseAnnoDocReader annoReader = (DleseAnnoDocReader)annoResults.get(i).getDocReader();
if ( ( annoReader != null ) &&
( annoReader.getType().equals( "Review" ) ||
annoReader.getType().equals( "Average scores of aggregated indices" ) ||
annoReader.getType().equals( "Editor's summary" ) ) &&
!annoReader.getStatus().matches( ".*progress" ) ) {
return "true";
}
}
}
return "false";
}
/**
* Gets the hasDrcReviews attribute of the DDSViewResourceForm object
*
* @return The hasDrcReviews value
*/
public String getHasDrcReviews() {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
if ( annoResults != null ) {
for ( int i = 0; i < annoResults.size(); i++ ) {
DleseAnnoDocReader annoReader = (DleseAnnoDocReader)annoResults.get(i).getDocReader();
if ( ( annoReader != null ) &&
( annoReader.getType().equals( "Review" ) ||
annoReader.getType().equals( "Average scores of aggregated indices" ) ||
annoReader.getType().equals( "Editor's summary" ) ) &&
( annoReader.getPathway().length() > 0 ) &&
!annoReader.getStatus().matches( ".*progress" ) ) {
return "true";
}
}
}
return "false";
}
/**
* Gets the isDrcReview attribute of the DDSViewResourceForm object
*
* @param index
* @return The isDrcReview value
*/
public String getIsDrcReview( int index ) {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
if ( annoResults != null ) {
DleseAnnoDocReader annoReader = (DleseAnnoDocReader)annoResults.get(index).getDocReader();
if ( ( annoReader != null )
&& ( annoReader.getType().equals( "Review" ) ||
annoReader.getType().equals( "Average scores of aggregated indices" ) ||
annoReader.getType().equals( "Editor's summary" ) ) &&
( annoReader.getPathway().length() > 0 ) ) {
return "true";
}
}
return "false";
}
/**
* Gets the isDrcReviewInProgress attribute of the DDSViewResourceForm object
*
* @return The isDrcReviewInProgress value
*/
public String getIsDrcReviewInProgress() {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
if ( annoResults != null ) {
for ( int i = 0; i < annoResults.size(); i++ ) {
DleseAnnoDocReader annoReader = (DleseAnnoDocReader)annoResults.get(i).getDocReader();
if ( ( annoReader != null ) &&
( annoReader.getType().equals( "Review" ) ||
annoReader.getType().equals( "Average scores of aggregated indices" ) ||
annoReader.getType().equals( "Editor's summary" ) ) &&
( annoReader.getPathway().length() > 0 ) &&
annoReader.getStatus().matches( ".*progress" ) ) {
pathwayUrl = annoReader.getUrl();
return "true";
}
}
}
return "false";
}
/**
* Gets the pathwayUrl attribute of the DDSViewResourceForm object
*
* @return The pathwayUrl value
*/
public String getPathwayUrl() {
return pathwayUrl;
}
/**
* Gets the hasOtherReviews attribute of the DDSViewResourceForm object
*
* @return The hasOtherReviews value
*/
public String getHasOtherReviews() {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
if ( annoResults != null ) {
for ( int i = 0; i < annoResults.size(); i++ ) {
DleseAnnoDocReader annoReader = (DleseAnnoDocReader)annoResults.get(i).getDocReader();
if ( ( annoReader != null )
&& annoReader.getType().equals( "Review" ) &&
annoReader.getPathway().length() == 0 ) {
return "true";
}
}
}
return "false";
}
/**
* Gets the teachingTips attribute of the DDSViewResourceForm object
*
* @return The hasTeachingTips value
*/
public String getHasTeachingTips() {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
if(annoResults == null)
return "false";
for ( int i = 0; i < annoResults.size(); i++ ) {
if ( ( (DleseAnnoDocReader)annoResults.get(i).getDocReader() ).getType().equals( "Teaching tip" ) ) {
return "true";
}
}
return "false";
}
/**
* Gets the hasIdeasForUse attribute of the DDSViewResourceForm object
*
* @return The hasIdeasForUse value
*/
public String getHasIdeasForUse() {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
for ( int i = 0; i < annoResults.size(); i++ ) {
if ( ( (DleseAnnoDocReader)annoResults.get(i).getDocReader() ).getType().equals( "See also" ) ) {
return "true";
}
}
return "false";
}
/**
* Gets the hasChallengingLearningContexts attribute of the
* DDSViewResourceForm object
*
* @return The hasChallengingLearningContexts value
*/
public String getHasChallengingLearningContexts() {
ResultDocList annoResults = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getAnnotationResultDocs();
for ( int i = 0; i < annoResults.size(); i++ ) {
if ( ( (DleseAnnoDocReader)annoResults.get(i).getDocReader() ).getType().equals( "Information on challenging teaching and learning situations" ) ) {
return "true";
}
}
return "false";
}
/**
* Sets the idSearch attribute of the DDSViewResourceForm object
*
* @param id The new idSearch value
*/
public void setIdSearch( String id ) {
RepositoryManager rm =
(RepositoryManager)getServlet().getServletContext().getAttribute( "repositoryManager" );
String discoverableItemsQuery = "";
if ( rm != null ) {
discoverableItemsQuery = rm.getDiscoverableItemsQuery();
}
String q = "id:" + SimpleLuceneIndex.encodeToTerm( id );
if ( discoverableItemsQuery.length() > 0 ) {
q += " AND " + discoverableItemsQuery;
}
resultDocs = index.searchDocs( q );
}
/**
* Sets the relDisplayed attribute of the DDSViewResourceForm object
*
* @param val The new relDisplayed value
*/
public void setRelDisplayed( String val ) {
relDisplayed = val;
}
/**
* Gets the relDisplayed attribute of the DDSViewResourceForm object
*
* @return The relDisplayed value.
*/
public String getRelDisplayed() {
return relDisplayed;
}
/**
* Gets the idSearchTitle attribute of the DDSViewResourceForm object
*
* @return The idSearchTitle value
*/
public String getIdSearchTitle() {
if ( resultDocs == null || resultDocs.size() == 0 ) {
return null;
}
return ( (ItemDocReader)resultDocs.get(0).getDocReader() ).getTitle();
}
/**
* Gets the idSearchUrl attribute of the DDSViewResourceForm object
*
* @return The idSearchUrl value
*/
public String getIdSearchUrl() {
if ( resultDocs == null || resultDocs.size() == 0 ) {
return null;
}
return ( (ItemDocReader)resultDocs.get(0).getDocReader() ).getUrl();
}
/**
* Gets the resourceTitle attribute of the DDSViewResourceForm object
*
* @return The resourceTitle value
*/
public String getResourceTitle() {
return ( (ItemDocReader)primaryResultDoc.getDocReader() ).getTitle();
}
/**
* Gets the resourceUrl attribute of the DDSViewResourceForm object
*
* @return The resourceUrl value
*/
public String getResourceUrl() {
return ( (ItemDocReader)primaryResultDoc.getDocReader() ).getUrl();
}
/**
* Sets the recordFilename attribute of the DDSViewResourceForm object
*
* @param recordFilename The new recordFilename value
*/
public void setRecordFilename( String recordFilename ) {
this.recordFilename = recordFilename;
}
/**
* Gets the recordFilename attribute of the DDSViewResourceForm object
*
* @return The recordFilename value
*/
public String getRecordFilename() {
return recordFilename;
}
/**
* Gets the recordCollection attribute of the DDSViewResourceForm object
*
* @return The recordCollections value
*/
public String[] getRecordCollections() {
return recordCollections;
}
/**
* Gets the recordCollection attribute of the DDSViewResourceForm object
*
* @param index
* @return The recordCollection value
*/
public String getRecordCollection( int index ) {
return recordCollections[index];
}
/**
* Gets the recordIds attribute of the DDSViewResourceForm object
*
* @return The recordIds value
*/
public String[] getRecordIds() {
return recordIds;
}
/**
* Gets the recordIds attribute of the DDSViewResourceForm object
*
* @param index
* @return The recordIds value
*/
public String getRecordIds( int index ) {
return recordIds[index];
}
/**
* Gets the numRecordCollections attribute of the DDSViewResourceForm object
*
* @return The numRecordCollections value
*/
public int getNumRecordCollections() {
String[] colls = ( (ItemDocReader)primaryResultDoc.getDocReader() ).getCollections();
return colls.length;
}
/**
* Sets the resourceId attribute of the DDSViewResourceForm object
*
* @param recordId The new recordId value
*/
public void setRecordId( String recordId ) {
this.recordId = recordId;
System.out.println( "setRecordId = " + recordId );
}
/**
* Gets the resourceId attribute of the DDSViewResourceForm object
*
* @return The recordId value
*/
public String getRecordId() {
System.out.println( "getRecordId = " + recordId );
return recordId;
}
/**
* Sets the searcher attribute of the DDSViewResourceForm object
*
* @param index The new searcher value
*/
public void setSearcher( SimpleLuceneIndex index ) {
this.index = index;
}
// The following are used by the "collections that contain" page:
/**
* Sets the collectionKey attribute of the DDSViewResourceForm object
*
* @param collectionKey The new collectionKey value
*/
public void setCollectionKey( String collectionKey ) {
this.collectionKey = collectionKey;
}
/**
* Sets the contextUrl attribute of the DDSViewResourceForm object
*
* @param contextUrl The new contextUrl value
*/
public void setContextUrl( String contextUrl ) {
this.contextUrl = contextUrl;
}
/**
* Gets the collectionDescription attribute of the DDSViewResourceForm object
*
* @return The collectionDescription value
*/
public String getCollectionDescription() {
return GetURL.getURL( contextUrl + "/collection.do?ky=" + collectionKey + "&noHead=true", false );
}
}
|
Java
|
@Deprecated
public class FieldInverseOp_BehaviorDescriptor extends BaseConcept_BehaviorDescriptor implements IOperation_BehaviorDescriptor, IBinaryLike_BehaviorDescriptor {
public boolean virtual_canPropagateUnmatchedParenUp_1742226163722653670(SNode __thisNode__, SNode leaf, boolean rightParen) {
return DefaultValuesHolder.defaultValue(Boolean.TYPE);
}
public SNode virtual_getSyntacticallyLeftSideExpression_1742226163722653708(SNode __thisNode__) {
return null;
}
public SNode virtual_getSyntacticallyRightSideExpression_1742226163722653714(SNode __thisNode__) {
return null;
}
public String virtual_getVariableExpectedName_1213877410087(SNode __thisNode__) {
return null;
}
public boolean virtual_isDotExpressionLegalAsStatement_1239212437413(SNode __thisNode__) {
return DefaultValuesHolder.defaultValue(Boolean.TYPE);
}
public boolean virtual_isLValue_1213877410080(SNode __thisNode__) {
return DefaultValuesHolder.defaultValue(Boolean.TYPE);
}
public boolean virtual_lvalue_1262430001741498364(SConcept __thisConcept__) {
return DefaultValuesHolder.defaultValue(Boolean.TYPE);
}
public boolean virtual_operandCanBeNull_323410281720656291(SNode __thisNode__) {
return DefaultValuesHolder.defaultValue(Boolean.TYPE);
}
public void virtual_setSyntacticallyLeftSideExpression_1742226163722653680(SNode __thisNode__, SNode expr) {
}
public void virtual_setSyntacticallyRightSideExpression_1742226163722653694(SNode __thisNode__, SNode expr) {
}
@Override
public String getConceptFqName() {
return "xjsnark.structure.FieldInverseOp";
}
}
|
Java
|
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
name = "",
propOrder = {"extension", "counts", "numericInfo", "frequenciesType"})
@XmlRootElement(name = "PartitionFieldStats")
public class PartitionFieldStats
implements org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.PartitionFieldStats {
@XmlElement(name = "Extension", type = Extension.class)
protected List<org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.Extension> extension;
@XmlElement(name = "Counts", type = Counts.class)
protected org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.Counts counts;
@XmlElement(name = "NumericInfo", type = NumericInfo.class)
protected org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.NumericInfo numericInfo;
@XmlElement(name = "NUM-ARRAY", type = NUMARRAY.class)
protected List<org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.NUMARRAY>
frequenciesType;
@XmlAttribute(name = "field", required = true)
protected String field;
@XmlAttribute(name = "weighted")
protected String weighted;
/**
* Gets the value of the extension property.
*
* <p>This accessor method returns a reference to the live list, not a snapshot. Therefore any
* modification you make to the returned list will be present inside the JAXB object. This is why
* there is not a <CODE>set</CODE> method for the extension property.
*
* <p>For example, to add a new item, do as follows:
*
* <pre>
* getExtension().add(newItem);
* </pre>
*
* <p>Objects of the following type(s) are allowed in the list {@link Extension }
*/
public List<org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.Extension> getExtension() {
if (extension == null) {
extension =
new ArrayList<org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.Extension>();
}
return this.extension;
}
/**
* Gets the value of the counts property.
*
* @return possible object is {@link Counts }
*/
public org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.Counts getCounts() {
return counts;
}
/**
* Sets the value of the counts property.
*
* @param value allowed object is {@link Counts }
*/
public void setCounts(org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.Counts value) {
this.counts = value;
}
/**
* Gets the value of the numericInfo property.
*
* @return possible object is {@link NumericInfo }
*/
public org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.NumericInfo getNumericInfo() {
return numericInfo;
}
/**
* Sets the value of the numericInfo property.
*
* @param value allowed object is {@link NumericInfo }
*/
public void setNumericInfo(
org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.NumericInfo value) {
this.numericInfo = value;
}
/**
* Gets the value of the frequenciesType property.
*
* <p>This accessor method returns a reference to the live list, not a snapshot. Therefore any
* modification you make to the returned list will be present inside the JAXB object. This is why
* there is not a <CODE>set</CODE> method for the frequenciesType property.
*
* <p>For example, to add a new item, do as follows:
*
* <pre>
* getFrequenciesType().add(newItem);
* </pre>
*
* <p>Objects of the following type(s) are allowed in the list {@link NUMARRAY }
*/
public List<org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.NUMARRAY>
getFrequenciesType() {
if (frequenciesType == null) {
frequenciesType =
new ArrayList<org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api.NUMARRAY>();
}
return this.frequenciesType;
}
/**
* Gets the value of the field property.
*
* @return possible object is {@link String }
*/
public String getField() {
return field;
}
/**
* Sets the value of the field property.
*
* @param value allowed object is {@link String }
*/
public void setField(String value) {
this.field = value;
}
/**
* Gets the value of the weighted property.
*
* @return possible object is {@link String }
*/
public String getWeighted() {
if (weighted == null) {
return "0";
} else {
return weighted;
}
}
/**
* Sets the value of the weighted property.
*
* @param value allowed object is {@link String }
*/
public void setWeighted(String value) {
this.weighted = value;
}
}
|
Java
|
@Category(IntegrationTest.class)
public class TestAccessToken extends AbstractIntegrationTest {
// TEST_ACCESS_TOKEN must be defined to run this test
private static final String TEST_ACCESS_TOKEN = TestUtils.getProperty("TEST_ACCESS_TOKEN");
private static GitLabApi gitLabApi;
public TestAccessToken() {
super();
}
@BeforeClass
public static void testSetup() {
// Must setup the connection to the GitLab test server
gitLabApi = baseTestSetup();
if (TEST_ACCESS_TOKEN == null || TEST_ACCESS_TOKEN.trim().isEmpty()) {
System.err.println("TEST_ACCESS_TOKEN cannot be empty");
}
}
@Before
public void beforeMethod() {
assumeNotNull(gitLabApi);
}
@Test
public void testPrivateToken() throws GitLabApiException {
// This test uses the GitLabApi instance created in setup()
Version version = gitLabApi.getVersion();
assertNotNull(version);
System.out.format("tokenType: %s, version=%s, revision=%s%n", TokenType.PRIVATE, gitLabApi.getIgnoreCertificateErrors(), version.getVersion(), version.getRevision());
assertNotNull(version.getVersion());
assertNotNull(version.getRevision());
}
@Test
public void testAccessToken() throws GitLabApiException {
assumeNotNull(TEST_ACCESS_TOKEN);
GitLabApi gitLabApi = new GitLabApi(ApiVersion.V4, TEST_HOST_URL, TokenType.ACCESS, TEST_ACCESS_TOKEN);
Version version = gitLabApi.getVersion();
assertNotNull(version);
System.out.format("tokenType: %s, version=%s, revision=%s%n", TokenType.ACCESS, gitLabApi.getIgnoreCertificateErrors(), version.getVersion(), version.getRevision());
assertNotNull(version.getVersion());
assertNotNull(version.getRevision());
}
}
|
Java
|
public class IssuedCommandProcessor {
private IssuedCommandProcessor() {
throw new AssertionError();
}
/**
* Evaluates an IssuedCommand. This method will check if the IssuedCommand is valid or not and provide suggestions if
* it is not.
*/
public static IssuedCommandEvaluation evaluateIssuedCommand(@NotNull IssuedCommand issuedCommand) {
CommandSet collection;
String commandToken;
if (issuedCommand.getTokens().size() > 1 && CommandSets.hasCommandSet(issuedCommand.getTokens().get(0))) {
collection = CommandSets.getCommandSet(issuedCommand.getTokens().get(0));
commandToken = issuedCommand.getTokens().get(1);
} else {
collection = CommandSets.getCommandSet("default");
commandToken = issuedCommand.getTokens().get(0);
}
// At this point. Both collection and commandToken are not null.
if (collection.getCommand(commandToken) == null) {
return new IssuedCommandEvaluation(false, collection.getClosestCommands(commandToken));
} else {
return new IssuedCommandEvaluation(true, Collections.<String>emptyList());
}
}
/**
* Prepares an IssuedCommand. As a precondition, evaluateIssueCommand should have considered this IssuedCommand
* valid.
*/
public static PreparedIssuedCommand prepareIssuedCommand(@NotNull IssuedCommand issuedCommand) {
CommandSet collection;
String commandToken;
int indexOfFirstArgument;
if (issuedCommand.getTokens().size() > 1 && CommandSets.hasCommandSet(issuedCommand.getTokens().get(0))) {
collection = CommandSets.getCommandSet(issuedCommand.getTokens().get(0));
commandToken = issuedCommand.getTokens().get(1);
indexOfFirstArgument = 2;
} else {
collection = CommandSets.getCommandSet("default");
commandToken = issuedCommand.getTokens().get(0);
indexOfFirstArgument = 1;
}
String[] arguments = makeArgumentArray(issuedCommand, indexOfFirstArgument);
Command selectedCommand = collection.getCommand(commandToken);
return new PreparedIssuedCommand(selectedCommand, arguments);
}
private static String[] makeArgumentArray(IssuedCommand issuedCommand, int indexOfFirstArgument) {
String[] tokenArray = issuedCommand.getTokens().toArray(new String[issuedCommand.getTokens().size()]);
int argumentCount = issuedCommand.getTokens().size() - indexOfFirstArgument;
String[] arguments = new String[issuedCommand.getTokens().size() - indexOfFirstArgument];
System.arraycopy(tokenArray, indexOfFirstArgument, arguments, 0, argumentCount);
return arguments;
}
}
|
Java
|
public class PhotoAsyncTask extends AsyncTask<byte[], Void, Void> {
@Override
protected Void doInBackground(byte[]... photoArrays) {
for (byte[] photoArray : photoArrays) {
// Escape early if cancel() is called
if (isCancelled()) break;
TenBus.get().post(EventFactory.sendPhotoByteArray(photoArray));
}
return null;
}
}
|
Java
|
@Configuration
@ComponentScan(basePackages = { "com.stackoverflow.tests" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
@PropertySource("classpath:application.properties")
@ImportResource("classpath:META-INF/spring/applicationContext.xml")
@Import(DatabaseContext.class)
public class ApplicationContext {
}
|
Java
|
public class DateTypeAdapter extends BaseLongTypeAdapter<Date> {
@Override
public Long getDefaultValue() {
return Long.MIN_VALUE;
}
@Override
public Long adaptForPreferences(@Nullable Date value) {
if (value == null) {
return Long.MIN_VALUE;
}
return value.getTime();
}
@Nullable
@Override
public Date adaptFromPreferences(Long value) {
if (value == Long.MIN_VALUE) {
return null;
}
return new Date(value);
}
}
|
Java
|
public class FractalPanel extends JPanel implements PatternEditor {
// Constants to define the way panel should be repainted
static int MODE_PATTERN = 0;
static int MODE_FRACTAL = 1;
// Variables to keep state and mode of the panel (operations and repaint mode)
private boolean choosingStartLine = true;
private int mode = FractalPanel.MODE_PATTERN;
// Base FractalLine, vectors of FractalLine that keep the pattern and the actual lines that compose the fractal result
private FractalLine base = null;
private List<FractalLine> patterns = new ArrayList<FractalLine>();
// Temporary points for one cycle of defining a FractalLine
private Point editA, editB;
// Temporary variables declare here to accelerate fractal process creation
private boolean definingBase = true;
public boolean onlyLastIter = false;
private Color color;
// Fractal builder
private GeometricPatternFractalGenerator<FractalLine> fractalGenerator;
// Constructor: define listeners for mouse operations
public FractalPanel() {
setBackground(Color.cyan);
setCurrentColor(Color.black);
setLayout(null);
addMouseListener(new SymMouse());
addMouseMotionListener(new SymMouseMotion());
}
public void validate() {
super.validate();
SwingUtilities.invokeLater(() -> repaint());
}
// Class handling click events
class SymMouse extends MouseAdapter {
public void mouseClicked(MouseEvent event) {
// EDIT MODE!
if (mode == FractalPanel.MODE_PATTERN) {
// Definition of the first point of a FractalLine
if (choosingStartLine) {
editA = event.getPoint();
choosingStartLine = false;
return;
}
// Definition of the second point of a FractalLine
if (!choosingStartLine) {
editB = event.getPoint();
FractalLine temp = new FractalLine(editA.x, editA.y, editB.x, editB.y, color.getRGB());
if (definingBase) {
base = temp;
definingBase = false;
} else
patterns.add(temp);
choosingStartLine = true;
return;
}
}
}
}
// Class handling mouse move events
class SymMouseMotion extends MouseMotionAdapter {
public void mouseMoved(MouseEvent event) {
if (choosingStartLine) return;
editB = event.getPoint();
repaint();
}
}
public void setCurrentColor(Color c) {
color = c;
}
// paint method redefinition
public void paintComponent(Graphics g) {
g.setPaintMode();
if (mode == FractalPanel.MODE_PATTERN || !onlyLastIter) {
if (base != null)
drawLine(g, base);
patterns.stream().forEach(line -> drawLine(g, line));
}
if (!choosingStartLine && mode == FractalPanel.MODE_PATTERN)
drawLine(g, editA.x, editA.y, editB.x, editB.y, color);
if (mode == FractalPanel.MODE_FRACTAL)
fractalGenerator.getFractal().parallelStream().forEach(line -> drawLine(g, line));
}
private void drawLine(Graphics g, FractalLine line) {
drawLine(g, (int)line.Ax, (int)line.Ay, (int)line.Bx, (int)line.By, new Color(line.rgbColorValue));
}
private void drawLine(Graphics g, int Ax, int Ay, int Bx, int By, Color color) {
g.setColor(color);
g.drawLine(Ax, Ay, Bx, By);
}
// Interface with users to set definingBase state
public void startBaseDefinition() {
definingBase = true;
choosingStartLine = true;
mode = FractalPanel.MODE_PATTERN;
}
// Reset all the information contained in the panel related to the fractal
public void clear() {
fractalGenerator.stop();
// Reset data
base = null;
patterns.clear();
fractalGenerator.getFractal().clear();
// Reset state
startBaseDefinition();
repaint();
}
public void show(int newMode) {
mode = newMode;
repaint();
}
@Override
public void showPattern() {
}
@Override
public void showFractal() {
}
// Interface with users to create fractal
public void computeFractal(int numIter, boolean onlyLastIter, Consumer<Float> progressWriter) {
this.onlyLastIter = onlyLastIter;
fractalGenerator = new GeometricPatternFractalGenerator<FractalLine>(base, patterns, numIter, onlyLastIter, progressWriter);
fractalGenerator.generateFractal();
}
}
|
Java
|
class SymMouse extends MouseAdapter {
public void mouseClicked(MouseEvent event) {
// EDIT MODE!
if (mode == FractalPanel.MODE_PATTERN) {
// Definition of the first point of a FractalLine
if (choosingStartLine) {
editA = event.getPoint();
choosingStartLine = false;
return;
}
// Definition of the second point of a FractalLine
if (!choosingStartLine) {
editB = event.getPoint();
FractalLine temp = new FractalLine(editA.x, editA.y, editB.x, editB.y, color.getRGB());
if (definingBase) {
base = temp;
definingBase = false;
} else
patterns.add(temp);
choosingStartLine = true;
return;
}
}
}
}
|
Java
|
class SymMouseMotion extends MouseMotionAdapter {
public void mouseMoved(MouseEvent event) {
if (choosingStartLine) return;
editB = event.getPoint();
repaint();
}
}
|
Java
|
@XmlRootElement(name = DisplayParameters.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = DisplayParameters.Constants.TYPE_NAME, propOrder = {
DisplayParameters.Elements.FRAME_HEIGHT,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class DisplayParameters implements Serializable, DisplayParametersContract {
private static final long serialVersionUID = 8859107918934290768L;
@XmlElement(name = Elements.FRAME_HEIGHT, required = true)
private final Integer frameHeight;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Private constructor used only by JAXB.
*
*/
private DisplayParameters(){
this.frameHeight = null;
}
/**
* Constructs a DisplayParameters from the given builder. This constructor is private and should only
* ever be invoked from the builder.
*
* @param builder the Builder from which to construct the DisplayParameters
*/
private DisplayParameters(Builder builder){
this.frameHeight = builder.getFrameHeight();
}
@Override
public Integer getFrameHeight() {
return this.frameHeight;
}
/**
* A builder which can be used to construct {@link DisplayParameters} instances. Enforces the constraints of the {@link DocumentContentContract}.
*/
public final static class Builder implements Serializable, ModelBuilder, DisplayParametersContract {
private static final long serialVersionUID = 2709781019428490297L;
private Integer frameHeight;
/**
* Private constructor for creating a builder with all of it's required attributes.
*/
private Builder(Integer frameHeight){
setFrameHeight(frameHeight);
}
public static Builder create(Integer frameHeight){
return new Builder(frameHeight);
}
/**
* Creates a builder by populating it with data from the given {@linkDisplayParametersContract}.
*
* @param contract the contract from which to populate this builder
* @return an instance of the builder populated with data from the contract
*/
public static Builder create(DisplayParametersContract contract){
if (contract == null) {
throw new IllegalArgumentException("contract was null");
}
Builder builder = create(contract.getFrameHeight());
return builder;
}
/**
* Builds an instance of a DisplayParameters based on the current state of the builder.
*
* @return the fully-constructed CampusType
*/
@Override
public DisplayParameters build() {
return new DisplayParameters(this);
}
@Override
public Integer getFrameHeight() {
return this.frameHeight;
}
public void setFrameHeight(Integer frameHeight){
if (frameHeight == null) {
throw new IllegalArgumentException("frameHeight is null");
}
this.frameHeight = frameHeight;
}
}
/**
* Defines some internal constants used on this class.
*/
static class Constants {
final static String ROOT_ELEMENT_NAME = "displayParameters";
final static String TYPE_NAME = "DisplayParametersType";
}
/**
* A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
*/
static class Elements {
final static String FRAME_HEIGHT = "frameHeight";
}
}
|
Java
|
public final static class Builder implements Serializable, ModelBuilder, DisplayParametersContract {
private static final long serialVersionUID = 2709781019428490297L;
private Integer frameHeight;
/**
* Private constructor for creating a builder with all of it's required attributes.
*/
private Builder(Integer frameHeight){
setFrameHeight(frameHeight);
}
public static Builder create(Integer frameHeight){
return new Builder(frameHeight);
}
/**
* Creates a builder by populating it with data from the given {@linkDisplayParametersContract}.
*
* @param contract the contract from which to populate this builder
* @return an instance of the builder populated with data from the contract
*/
public static Builder create(DisplayParametersContract contract){
if (contract == null) {
throw new IllegalArgumentException("contract was null");
}
Builder builder = create(contract.getFrameHeight());
return builder;
}
/**
* Builds an instance of a DisplayParameters based on the current state of the builder.
*
* @return the fully-constructed CampusType
*/
@Override
public DisplayParameters build() {
return new DisplayParameters(this);
}
@Override
public Integer getFrameHeight() {
return this.frameHeight;
}
public void setFrameHeight(Integer frameHeight){
if (frameHeight == null) {
throw new IllegalArgumentException("frameHeight is null");
}
this.frameHeight = frameHeight;
}
}
|
Java
|
static class Constants {
final static String ROOT_ELEMENT_NAME = "displayParameters";
final static String TYPE_NAME = "DisplayParametersType";
}
|
Java
|
@RunWith(AndroidJUnit4.class)
public class XmlParserInstrumentedTest {
@Test
public void xmlParser() throws Exception {
// Get test data stream
InputStream in = this.getClass().getClassLoader().getResourceAsStream("test_data.xml");
assertNotNull(in);
// Fire up a parser
EndClothingParser parser = new EndClothingParser();
// Run it!
try {
EndClothingProductsList p = parser.parse(in);
Assert.assertEquals(p.getItemCount(), 10);
for (int i = 0; i < p.getItemCount(); i++) {
ProductItem item = p.getItem(i);
String colour = "none";
ItemAttribute value = item.getAttribute("colour");
if (value != null) {
colour = value.toString();
}
Log.d("item", ">>>" + item.getAttribute("name").toString() + " : " + colour);
}
} catch (XmlPullParserException ex) {
ex.printStackTrace();
Assert.fail(ex.getMessage());
} catch (IOException ioex) {
Assert.fail(ioex.getMessage());
}
}
}
|
Java
|
public final class ErrorsITCase {
@Test
public void fetchItems() throws Exception {
final MkGithub github = new MkGithub();
final Errors.Github errors = new Errors.Github(
new Errors(new ExtDynamo().value()),
github
);
final Repo repo = github.repos()
.create(new Repos.RepoCreate("test", false));
final Issue issue = repo.issues()
.create("A bug", "RuntimeException in main()");
final Comment comment = issue.comments().post("error");
Thread.sleep(TimeUnit.SECONDS.toMillis(1L));
final Comment deleted = issue.comments().post("to-delete");
errors.add(comment);
errors.add(deleted);
errors.remove(deleted);
MatcherAssert.assertThat(
"Error comment was not found",
errors.iterate(2, 0L),
Matchers.not(Matchers.emptyIterable())
);
}
}
|
Java
|
public class SmileUtils {
public static final String f1 = "[:f1]";
public static final String f2 = "[:f2]";
public static final String f3 = "[:f3]";
public static final String f4 = "[:f4]";
public static final String f5 = "[:f5]";
public static final String f6 = "[:f6]";
public static final String f7 = "[:f7]";
public static final String f8 = "[:f8]";
public static final String f9 = "[:f9]";
public static final String f10 = "[:f10]";
public static final String f11 = "[:f11]";
public static final String f12 = "[:f12]";
public static final String f13 = "[:f13]";
public static final String f14 = "[:f14]";
public static final String f15 = "[:f15]";
public static final String f16 = "[:f16]";
public static final String f17 = "[:f17]";
public static final String f18 = "[:f18]";
public static final String f19 = "[:f19]";
public static final String f20 = "[:f20]";
public static final String f21 = "[:f21]";
public static final String f22 = "[:f22]";
public static final String f23 = "[:f23]";
public static final String f24 = "[:f24]";
public static final String f25 = "[:f25]";
public static final String f26 = "[:f26]";
public static final String f27 = "[:f27]";
public static final String f28 = "[:f28]";
public static final String f29 = "[:f29]";
public static final String f30 = "[:f30]";
public static final String f31 = "[:f31]";
public static final String f32 = "[:f32]";
public static final String f33 = "[:f33]";
public static final String f34 = "[:f34]";
public static final String f35 = "[:f35]";
public static final String f36 = "[:f36]";
public static final String f37 = "[:f37]";
public static final String f38 = "[:f38]";
public static final String f39 = "[:f39]";
public static final String f40 = "[:f40]";
private static final Factory spannableFactory = Factory.getInstance();
private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>();
static {
addPattern(emoticons, f1, R.mipmap.f1);
addPattern(emoticons, f2, R.mipmap.f2);
addPattern(emoticons, f3, R.mipmap.f3);
addPattern(emoticons, f4, R.mipmap.f4);
addPattern(emoticons, f5, R.mipmap.f5);
addPattern(emoticons, f6, R.mipmap.f6);
addPattern(emoticons, f7, R.mipmap.f7);
addPattern(emoticons, f8, R.mipmap.f8);
addPattern(emoticons, f9, R.mipmap.f9);
addPattern(emoticons, f10, R.mipmap.f10);
addPattern(emoticons, f11, R.mipmap.f11);
addPattern(emoticons, f12, R.mipmap.f12);
addPattern(emoticons, f13, R.mipmap.f13);
addPattern(emoticons, f14, R.mipmap.f14);
addPattern(emoticons, f15, R.mipmap.f15);
addPattern(emoticons, f16, R.mipmap.f16);
addPattern(emoticons, f17, R.mipmap.f17);
addPattern(emoticons, f18, R.mipmap.f18);
addPattern(emoticons, f19, R.mipmap.f19);
addPattern(emoticons, f20, R.mipmap.f20);
addPattern(emoticons, f21, R.mipmap.f21);
addPattern(emoticons, f22, R.mipmap.f22);
addPattern(emoticons, f23, R.mipmap.f23);
addPattern(emoticons, f24, R.mipmap.f24);
addPattern(emoticons, f25, R.mipmap.f25);
addPattern(emoticons, f26, R.mipmap.f26);
addPattern(emoticons, f27, R.mipmap.f27);
addPattern(emoticons, f28, R.mipmap.f28);
addPattern(emoticons, f29, R.mipmap.f29);
addPattern(emoticons, f30, R.mipmap.f30);
addPattern(emoticons, f31, R.mipmap.f31);
addPattern(emoticons, f32, R.mipmap.f32);
addPattern(emoticons, f33, R.mipmap.f33);
addPattern(emoticons, f34, R.mipmap.f34);
addPattern(emoticons, f35, R.mipmap.f35);
addPattern(emoticons, f36, R.mipmap.f36);
addPattern(emoticons, f37, R.mipmap.f37);
addPattern(emoticons, f38, R.mipmap.f38);
addPattern(emoticons, f39, R.mipmap.f39);
addPattern(emoticons, f40, R.mipmap.f40);
}
private static void addPattern(Map<Pattern, Integer> map, String smile, int resource){
map.put(Pattern.compile(Pattern.quote(smile)), resource);
}
public static boolean addSmiles(Context context, Spannable spannable){
boolean hasChanges = true;
for(Entry<Pattern, Integer> entry : emoticons.entrySet()){
Matcher matcher = entry.getKey().matcher(spannable);
while(matcher.find()){
boolean set = true;
for(ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)){
if(spannable.getSpanStart(span) >= matcher.start() && spannable.getSpanEnd(span) <= matcher.end()){
spannable.removeSpan(span);
}else {
set = false;
break;
}
if(set){
hasChanges = true;
spannable.setSpan(new ImageSpan(context, entry.getValue()), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
}
return hasChanges;
}
public static Spannable getSmiledText(Context context, CharSequence text){
Spannable spannable = spannableFactory.newSpannable(text);
addSmiles(context, spannable);
return spannable;
}
public static boolean containsKey(String key){
boolean b = false;
for(Entry<Pattern, Integer> entry : emoticons.entrySet()){
Matcher matcher = entry.getKey().matcher(key);
if(matcher.find()){
b = true;
break;
}
}
return b;
}
}
|
Java
|
public class ExportDataCreator extends ToolBase {
public static final String APP_NAME = "application";
public static final String ORG_NAME = "organization";
public static final String NUM_USERS = "users";
public static final String NUM_COLLECTIONS = "collections";
public static final String NUM_ENTITIES = "entities";
public static final String ADMIN_USERNAME = "username";
public static final String ADMIN_PASSWORD = "password";
public String appName = "test-app";
public String orgName = "test-organization";
public int numUsers = 100;
public int numCollections = 20;
public int numEntities = 100;
public String adminUsername = "adminuser";
public String adminPassword = "test";
@Override
public void runTool(CommandLine line) throws Exception {
startSpring();
setVerbose( line );
if (line.hasOption( APP_NAME )) {
appName = line.getOptionValue( APP_NAME );
}
if (line.hasOption( ORG_NAME )) {
orgName = line.getOptionValue( ORG_NAME );
}
if (line.hasOption( NUM_USERS )) {
numUsers = Integer.parseInt( line.getOptionValue( NUM_USERS ) );
}
if (line.hasOption( NUM_COLLECTIONS )) {
numCollections = Integer.parseInt( line.getOptionValue( NUM_COLLECTIONS ) );
}
if (line.hasOption( NUM_ENTITIES )) {
numEntities = Integer.parseInt( line.getOptionValue( NUM_ENTITIES ) );
}
if (line.hasOption( ADMIN_USERNAME )) {
adminUsername = line.getOptionValue( ADMIN_USERNAME );
}
if (line.hasOption( ADMIN_PASSWORD )) {
adminPassword = line.getOptionValue( ADMIN_PASSWORD );
}
createTestData();
}
@Override
@SuppressWarnings("static-access")
public Options createOptions() {
Options options = super.createOptions();
Option appName = OptionBuilder.hasArg()
.withDescription( "Application name to use" ).create( APP_NAME );
Option orgName = OptionBuilder.hasArg()
.withDescription( "Organization to use (will create if not present)" ).create( ORG_NAME );
Option numUsers = OptionBuilder.hasArg()
.withDescription( "Number of users create (in addition to users)" ).create( NUM_USERS );
Option numCollection = OptionBuilder.hasArg()
.withDescription( "Number of collections to create (in addition to users)" ).create( NUM_COLLECTIONS );
Option numEntities = OptionBuilder.hasArg()
.withDescription( "Number of entities to create per collection" ).create( NUM_ENTITIES );
Option adminUsername = OptionBuilder.hasArg()
.withDescription( "Admin Username" ).create( ADMIN_USERNAME );
Option adminPassword = OptionBuilder.hasArg()
.withDescription( "Admin Password" ).create( ADMIN_PASSWORD );
options.addOption( appName );
options.addOption( orgName );
options.addOption( numUsers );
options.addOption( numCollection );
options.addOption( numEntities );
options.addOption( adminUsername );
options.addOption( adminPassword );
return options;
}
public void createTestData() throws Exception {
OrganizationInfo orgInfo = managementService.getOrganizationByName( orgName );
if (orgInfo == null) {
OrganizationOwnerInfo ownerInfo = managementService.createOwnerAndOrganization(
orgName, adminUsername + "@example.com", adminUsername,
adminUsername + "@example.com", adminPassword, true, false );
orgInfo = ownerInfo.getOrganization();
}
ApplicationInfo appInfo = managementService.getApplicationInfo( orgName + "/" + appName );
if (appInfo == null) {
UUID appId = managementService.createApplication( orgInfo.getUuid(), appName ).getId();
appInfo = managementService.getApplicationInfo( appId );
}
EntityManager em = emf.getEntityManager( appInfo.getId() );
Fairy fairy = Fairy.create();
List<Entity> users = new ArrayList<Entity>( numUsers );
for (int i = 0; i < numUsers; i++) {
final Person person = fairy.person();
Entity userEntity = null;
try {
final Map<String, Object> userMap = new HashMap<String, Object>() {{
put( "name", person.username() );
put( "username", person.username() );
put( "password", person.password() );
put( "email", person.email() );
put( "companyEmail", person.companyEmail() );
put( "dateOfBirth", person.dateOfBirth().toDate().toString());
put( "firstName", person.firstName() );
put( "lastName", person.lastName() );
put( "nationalIdentificationNumber", person.nationalIdentificationNumber() );
put( "telephoneNumber", person.telephoneNumber() );
put( "passportNumber", person.passportNumber() );
put( "address", new HashMap<String, Object>() {{
put("streetNumber", person.getAddress().streetNumber());
put("street", person.getAddress().street());
put("city", person.getAddress().getCity());
put("postalCode", person.getAddress().getPostalCode());
}});
}};
userEntity = em.create( "user", userMap );
users.add( userEntity );
logger.debug("Created user {}", userEntity.getName());
} catch (DuplicateUniquePropertyExistsException e) {
logger.error( "Dup user generated: " + person.username() );
continue;
} catch (Exception e) {
logger.error("Error creating user", e);
continue;
}
em.refreshIndex();
final Company company = person.getCompany();
try {
EntityRef ref = em.getAlias( "company", company.name() );
Entity companyEntity = (ref == null) ? null : em.get( ref );
// create company if it does not exist yet
if ( companyEntity == null ) {
final Map<String, Object> companyMap = new HashMap<String, Object>() {{
put( "name", company.name() );
put( "domain", company.domain() );
put( "email", company.email() );
put( "url", company.url() );
put( "vatIdentificationNumber", company.vatIdentificationNumber() );
}};
companyEntity = em.create( "company", companyMap );
} else {
logger.info("Company {} already exists", company.name());
}
em.createConnection( userEntity, "employer", companyEntity );
logger.debug("User {} now employed by {}", userEntity.getName(), companyEntity.getName());
} catch (DuplicateUniquePropertyExistsException e) {
logger.error( "Dup company generated {} property={}", company.name(), e.getPropertyName() );
continue;
} catch (Exception e) {
logger.error("Error creating or connecting company", e);
continue;
}
em.refreshIndex();
try {
for (int j = 0; j < 5; j++) {
Activity activity = new Activity();
Activity.ActivityObject actor = new Activity.ActivityObject();
actor.setEntityType( "user" );
actor.setId( userEntity.getUuid().toString() );
activity.setActor( actor );
activity.setVerb( "POST" );
activity.setContent( "User " + person.username() + " generated a random string "
+ RandomStringUtils.randomAlphanumeric( 5 ) );
em.createItemInCollection( userEntity, "activities", "activity", activity.getProperties() );
logger.debug("Created activity {}", activity.getContent());
}
if (users.size() > 10) {
for (int j = 0; j < 5; j++) {
try {
Entity otherUser = users.get( (int) (Math.random() * users.size()) );
em.createConnection( userEntity, "associate", otherUser );
logger.debug("User {} now associated with user {}",
userEntity.getName(), otherUser.getName());
} catch (Exception e) {
logger.error( "Error connecting user to user: " + e.getMessage() );
}
}
}
em.refreshIndex();
Set<String> connectionTypes = em.getConnectionTypes( userEntity );
logger.debug("User {} now has {} connection types: {}",
new Object[] { userEntity.getName(), connectionTypes.size(), connectionTypes});
} catch (Exception e) {
logger.error("Error creating activities", e);
continue;
}
}
em.refreshIndex();
}
}
|
Java
|
@JsonIgnoreProperties(ignoreUnknown = true)
public class OAuthToken {
@JsonProperty("iss")
public String issuer;
@JsonProperty("aud")
public String audience;
@JsonProperty("exp")
public Integer expiry;
@JsonProperty("iat")
public Integer issuedAt;
@JsonProperty("scope")
public String scope;
public boolean isExpired(){
return expiry < System.currentTimeMillis()/1000;
}
public List<String> getScopes(){
return (scope != null) ? Arrays.asList(scope.split(" ")) : new ArrayList<>();
}
/**
* Check if there are any scopes on the Token which grant access to the protected resource
*
* @param requiredScope
* @param method
* @return true is access is granted by 1 or more scopes otherwise false
*/
public boolean allowsAccess(String requiredScope, String method){
return getScopes().stream().anyMatch(getScopeFilter(requiredScope, method));
}
/**
* Create a Predicate which will be used to filter the list of available scopes.
*
* TODO - At present we are not associating the HTTP Request Method with the *.read, or *.write suffixes on the Scope
* TODO - This is left as a future exercise since we are currently only allowing read-only access.
*
* @param requiredScoped - The Scope that is required to access the resource e.g. 'Patient'
* @param method - The HTTP Method which is being processed e.g. 'GET' or 'POST'
* @return A Predicate to find the Scopes which match this Resource.
*/
private Predicate<String> getScopeFilter(String requiredScoped, String method) {
// Match either the resource name or wildcard '*'
String scopeRegex = String.format("^\\w*/(?:\\*|%1s)\\..*", requiredScoped);
return scope -> scope.matches(scopeRegex);
}
}
|
Java
|
public class MongoIrcIgnoreList implements IrcIgnoreList {
private final MongoCollection<Document> list;
public MongoIrcIgnoreList(MongoDatabase database) {
this.list = database.getCollection("ircignorelist");
}
@Override
public void add(String nickname) {
if (!contains(nickname)) {
this.list.insertOne(new Document("_id", nickname));
}
}
@Override
public void remove(String nickname) {
this.list.deleteOne(new Document("_id", nickname));
}
@Override
public List<String> list() {
List<String> result = new ArrayList<>();
this.list.find().forEach((Consumer<Document>) document -> result.add(document.get("_id").toString()));
return result;
}
@Override
public boolean contains(String nickname) {
return this.list.find(new BasicDBObject("_id", nickname)).iterator().hasNext();
}
}
|
Java
|
public class VaultInvalidTypeException extends RuntimeVaultException
{
public VaultInvalidTypeException(String message) { super(message); }
public VaultInvalidTypeException(String message, Throwable cause)
{
super(message, cause);
}
}
|
Java
|
public class BrokerComponentFactory {
Logger logger = LoggerFactory.getLogger(this.getClass());
private synchronized Component getBrokerComponent(URI brokerURI, MessagingType type) {
// TODO: make this configurable for different broker implementations.
logger.info("establishing activemq connection for brokerUri {} (with specified type)", brokerURI);
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
brokerURI + "?jms.prefetchPolicy.all=50&jms.useAsyncSend=true");
return getBrokerComponent(type, activeMQConnectionFactory);
}
private synchronized Component getBrokerComponent(URI brokerURI, MessagingType type, KeyManager keyManager,
TrustManager trustManager) {
// TODO: make this configurable for different broker implementations.
logger.info("establishing activemq ssl connection for brokerUri {} (with specified type, keyManager, and TrustManager)",
brokerURI);
// jms.prefetchPolicy parameter is added to prevent matcher-consumer death due
// to overflowing with messages,
// see http://activemq.apache.org/what-is-the-prefetch-limit-for.html
ActiveMQSslConnectionFactory activeMQConnectionFactory = new ActiveMQSslConnectionFactory(
brokerURI + "?jms.prefetchPolicy.all=50&jms.useAsyncSend=true");
activeMQConnectionFactory.setKeyAndTrustManagers(new KeyManager[] { keyManager },
new TrustManager[] { trustManager }, null);
return getBrokerComponent(type, activeMQConnectionFactory);
}
public synchronized Component getBrokerComponent(URI brokerURI, MessagingType type,
MessagingContext messagingContext) {
// TODO: make this configurable for different broker implementations.
logger.info("establishing activemq connection for brokerUri {}", brokerURI);
KeyManager keyManager = null;
TrustManager trustManager = null;
try {
keyManager = messagingContext.getClientKeyManager();
trustManager = messagingContext.getClientTrustManager();
} catch (Exception e) {
logger.error("Key- or Trust- manager initialization problem");
}
if (keyManager == null || trustManager == null) {
return getBrokerComponent(brokerURI, type);
} else {
return getBrokerComponent(brokerURI, type, keyManager, trustManager);
}
}
private synchronized Component getBrokerComponent(MessagingType type, ActiveMQConnectionFactory connectionFactory) {
CachingConnectionFactory cachingConnectionFactory = (CachingConnectionFactory) configureCachingConnectionFactory(
connectionFactory);
WonJmsConfiguration jmsConfiguration = new WonJmsConfiguration(cachingConnectionFactory);
switch (type) {
case Queue:
jmsConfiguration.configureJmsConfigurationForQueues();
break;
case Topic:
jmsConfiguration.configureJmsConfigurationForTopics();
break;
}
ActiveMQComponent activeMQComponent = ActiveMQComponent.activeMQComponent();
activeMQComponent.setConfiguration(jmsConfiguration);
return activeMQComponent;
}
public synchronized ConnectionFactory configureCachingConnectionFactory(
ActiveMQConnectionFactory connectionFactory) {
// for non-persistent messages setting "AlwaysSyncSend" to true makes it slow,
// but ensures that a producer is immediately informed
// about the memory issues on broker (is blocked or gets exception depending on
// <systemUsage> config)
// see more info http://activemq.apache.org/producer-flow-control.html
connectionFactory.setAlwaysSyncSend(false);
// disable timestamps by default so that ttl of messages is not checked
connectionFactory.setDisableTimeStampsByDefault(true);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
cachingConnectionFactory.setCacheConsumers(true);
cachingConnectionFactory.setCacheProducers(true);
return cachingConnectionFactory;
}
}
|
Java
|
public class CreateAuthenticatorRegistrationRequest extends RpcAcsRequest<CreateAuthenticatorRegistrationResponse> {
private String clientExtendParamsJson;
private String userId;
private String userDisplayName;
private String serverExtendParamsJson;
private String registrationContext;
private String authenticatorType;
private String clientExtendParamsJsonSign;
private String applicationExternalId;
private String userName;
public CreateAuthenticatorRegistrationRequest() {
super("idaas-doraemon", "2021-05-20", "CreateAuthenticatorRegistration");
setProtocol(ProtocolType.HTTPS);
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getClientExtendParamsJson() {
return this.clientExtendParamsJson;
}
public void setClientExtendParamsJson(String clientExtendParamsJson) {
this.clientExtendParamsJson = clientExtendParamsJson;
if(clientExtendParamsJson != null){
putQueryParameter("ClientExtendParamsJson", clientExtendParamsJson);
}
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
if(userId != null){
putQueryParameter("UserId", userId);
}
}
public String getUserDisplayName() {
return this.userDisplayName;
}
public void setUserDisplayName(String userDisplayName) {
this.userDisplayName = userDisplayName;
if(userDisplayName != null){
putQueryParameter("UserDisplayName", userDisplayName);
}
}
public String getServerExtendParamsJson() {
return this.serverExtendParamsJson;
}
public void setServerExtendParamsJson(String serverExtendParamsJson) {
this.serverExtendParamsJson = serverExtendParamsJson;
if(serverExtendParamsJson != null){
putQueryParameter("ServerExtendParamsJson", serverExtendParamsJson);
}
}
public String getRegistrationContext() {
return this.registrationContext;
}
public void setRegistrationContext(String registrationContext) {
this.registrationContext = registrationContext;
if(registrationContext != null){
putQueryParameter("RegistrationContext", registrationContext);
}
}
public String getAuthenticatorType() {
return this.authenticatorType;
}
public void setAuthenticatorType(String authenticatorType) {
this.authenticatorType = authenticatorType;
if(authenticatorType != null){
putQueryParameter("AuthenticatorType", authenticatorType);
}
}
public String getClientExtendParamsJsonSign() {
return this.clientExtendParamsJsonSign;
}
public void setClientExtendParamsJsonSign(String clientExtendParamsJsonSign) {
this.clientExtendParamsJsonSign = clientExtendParamsJsonSign;
if(clientExtendParamsJsonSign != null){
putQueryParameter("ClientExtendParamsJsonSign", clientExtendParamsJsonSign);
}
}
public String getApplicationExternalId() {
return this.applicationExternalId;
}
public void setApplicationExternalId(String applicationExternalId) {
this.applicationExternalId = applicationExternalId;
if(applicationExternalId != null){
putQueryParameter("ApplicationExternalId", applicationExternalId);
}
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
if(userName != null){
putQueryParameter("UserName", userName);
}
}
@Override
public Class<CreateAuthenticatorRegistrationResponse> getResponseClass() {
return CreateAuthenticatorRegistrationResponse.class;
}
}
|
Java
|
public class RunAsApplet extends JApplet
{
/**
* Implements java.io.Serializable interface
*/
private static final long serialVersionUID = 6183165032705642517L;
/**
* Main component is instance of the <code>JPWorld</code>.
*/
private JPWorld wopComponent = new JPWorld ();
/**
* Adds main component <code>JPWorld</code> to the content pane.
*/
@Override
public void init ()
{
super.init ();
setSize( 1024, 600 );
getContentPane ().add( wopComponent, BorderLayout.CENTER );
validate ();
/* Start T1 & T2 tests delayed for 1 sec
*/
wopComponent.startTests( 1f /*sec delay*/ );
}
}
|
Java
|
public abstract class InmemQueueFactory<T extends InmemQueue<ID, DATA>, ID, DATA>
extends AbstractQueueFactory<T, ID, DATA> {
/**
* s {@inheritDoc}
*
* @throws Exception
*/
@Override
protected void initQueue(T queue, QueueSpec spec) throws Exception {
queue.setBoundary(getDefaultMaxSize()).setEphemeralDisabled(getDefaultEphemeralDisabled())
.setEphemeralMaxSize(getDefaultEphemeralMaxSize());
Integer maxSize = spec.getField(QueueSpec.FIELD_MAX_SIZE, Integer.class);
if (maxSize != null) {
queue.setBoundary(maxSize.intValue());
}
Boolean ephemeralDisabled = spec.getField(QueueSpec.FIELD_EPHEMERAL_DISABLED,
Boolean.class);
if (ephemeralDisabled != null) {
queue.setEphemeralDisabled(ephemeralDisabled.booleanValue());
}
Integer maxEphemeralSize = spec.getField(QueueSpec.FIELD_EPHEMERAL_MAX_SIZE, Integer.class);
if (maxEphemeralSize != null) {
queue.setEphemeralMaxSize(maxEphemeralSize.intValue());
}
super.initQueue(queue, spec);
}
}
|
Java
|
public class HorizontalLineHandler extends WrappingStyleHandler {
public HorizontalLineHandler(StyledTextHandler handler) {
super(handler);
}
@Override
public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end,
Style useStyle, SpanStack spanStack) {
end+=2;
Log.d("HorizontalLineHandler", "Draw hr from " + start + " to " + end);
spanStack.pushSpan(new HorizontalLineSpan(useStyle), start, end);
appendNewLine(builder);
super.handleTagNode(node, builder, start, end, useStyle, spanStack);
}
@Override
protected boolean appendNewLine(SpannableStringBuilder builder) {
builder.append(" \n");
return true;
}
}
|
Java
|
public class RegionNavigatorDialog extends JDialog implements Observer {
private static Logger log = Logger.getLogger(AttributePanel.class);
//Column indexes, in case table structure changes
private static final int TABLE_COLINDEX_GENOME = 0;
private static final int TABLE_COLINDEX_CHR = 1;
private static final int TABLE_COLINDEX_START = 2;
private static final int TABLE_COLINDEX_END = 3;
private static final int TABLE_COLINDEX_DESC = 4;
//The active instance of RegionNavigatorDialog (only one at a time)
public static RegionNavigatorDialog activeInstance;
private DefaultTableModel regionTableModel;
// private List<RegionOfInterest> regions;
private TableRowSorter<TableModel> regionTableRowSorter;
//Indicates that we're in the process of synching the table with the regions list, so we shouldn't
//do anything about TableChanged events.
private boolean synchingRegions = false;
/**
* Return the active RegionNavigatorDialog, or null if none.
*
* @return
*/
public static RegionNavigatorDialog getActiveInstance() {
return activeInstance;
}
/**
* dispose the active instance and get rid of the pointer. Return whether or not there was an
* active instance
*/
public static boolean destroyActiveInstance() {
if (activeInstance == null)
return false;
activeInstance.dispose();
activeInstance = null;
return true;
}
public RegionNavigatorDialog(Frame owner) {
super(owner);
initComponents();
postInit();
}
public RegionNavigatorDialog(Dialog owner) {
super(owner);
initComponents();
postInit();
}
public void update(Observable observable, Object object) {
synchRegions();
}
/**
* Synchronize the regions ArrayList with the passed-in regionsCollection, and update UI
*/
public void synchRegions() {
//Indicate that we're synching regions, so that we don't respond to tableChanged events
synchingRegions = true;
List<RegionOfInterest> regions = retrieveRegionsAsList();
regionTableModel = (DefaultTableModel) regionTable.getModel();
while (regionTableModel.getRowCount() > 0)
regionTableModel.removeRow(0);
regionTableModel.setRowCount(regions.size());
for (int i = 0; i < regions.size(); i++) {
RegionOfInterest region = regions.get(i);
regionTableModel.setValueAt(region.getDescription(), i, TABLE_COLINDEX_DESC);
regionTableModel.setValueAt(region.getDisplayStart(), i, TABLE_COLINDEX_START);
regionTableModel.setValueAt(region.getDisplayEnd(), i, TABLE_COLINDEX_END);
regionTableModel.setValueAt(region.getChr(), i, TABLE_COLINDEX_CHR);
regionTableModel.setValueAt(region.getGenome(), i, TABLE_COLINDEX_GENOME);
}
//Done synching regions, allow ourselves to respond to tableChanged events
synchingRegions = false;
regionTableModel.fireTableDataChanged();
}
private List<RegionOfInterest> retrieveRegionsAsList() {
return new ArrayList<RegionOfInterest>(IGV.getInstance().getSession().getAllRegionsOfInterest());
}
/**
* Populate the table with the loaded regions
*/
private void postInit() {
regionTableModel = (DefaultTableModel) regionTable.getModel();
regionTable.getSelectionModel().addListSelectionListener(new RegionTableSelectionListener());
regionTableModel.addTableModelListener(new RegionTableModelListener());
//custom row sorter required for displaying only a subset of rows
regionTableRowSorter = new TableRowSorter<TableModel>(regionTableModel);
regionTable.setRowSorter(regionTableRowSorter);
regionTableRowSorter.setRowFilter(new RegionRowFilter());
textFieldSearch.getDocument().addDocumentListener(new SearchFieldDocumentListener());
activeInstance = this;
updateChromosomeDisplayed();
synchRegions();
IGV.getInstance().getSession().getRegionsOfInterestObservable().addObserver(this);
//resize window if small number of regions. By default, tables are initialized with 20
//rows, and that can look ungainly for empty windows or windows with a few rows.
//This correction is rather hacky. Minimum size of 5 rows set.
int newTableHeight = Math.min(regionTableModel.getRowCount() + 1, 5) * regionTable.getRowHeight();
//This is quite hacky -- need to find the size of the other components programmatically somehow, since
//it will vary on different platforms
int extraHeight = 225;
int newDialogHeight = newTableHeight + extraHeight;
if (newDialogHeight < getHeight()) {
regionTable.setPreferredScrollableViewportSize(new Dimension(regionTable.getPreferredSize().width,
newTableHeight));
setSize(getWidth(), newTableHeight + extraHeight);
update(getGraphics());
}
regionTable.addMouseListener(new RegionTablePopupHandler());
}
private class SearchFieldDocumentListener implements DocumentListener {
public void changedUpdate(DocumentEvent e) {
System.err.println("This should not happen");
}
public void insertUpdate(DocumentEvent e) {
regionTableModel.fireTableDataChanged();
}
public void removeUpdate(DocumentEvent e) {
regionTableModel.fireTableDataChanged();
}
}
/**
* When chromosome that's displayed is changed, need to update displayed regions. showSearchedRegions will do that
*/
public void updateChromosomeDisplayed() {
// regionTable.updateUI();
// showSearchedRegions();
regionTableModel.fireTableDataChanged();
}
/**
* Test whether we should display an entry
*
* @param regionChr
* @param regionDesc
* @return
*/
protected boolean shouldIncludeRegion(String regionGenome, String regionChr, String regionDesc) {
//if table is empty, a non-region event is fed here. Test for it and don't display
if (regionChr == null)
return false;
String filterStringLowercase = null;
if (textFieldSearch.getText() != null)
filterStringLowercase = textFieldSearch.getText().toLowerCase();
String chr = FrameManager.getDefaultFrame().getChrName();
String genome = IGV.getInstance().getGenomeManager().currentGenome.getId();
//show only regions matching the search string (if specified)
if ((filterStringLowercase != null && !filterStringLowercase.isEmpty() &&
(regionDesc == null || !regionDesc.toLowerCase().contains(filterStringLowercase))))
return false;
boolean chrOK = true;
boolean genomeOK = true;
//if this checkbox is checked, show all chromosomes
if (checkBoxShowAllChrs.isSelected())
chrOK = true;
else if (chr != null && !chr.isEmpty() && !regionChr.equals(chr))
chrOK = false;
//if this checkbox is checked, show all genomes
if (checkBoxShowAllGenomes.isSelected())
genomeOK = true;
else if (genome != null && !genome.isEmpty() && !regionGenome.equals(genome))
genomeOK = false;
return chrOK && genomeOK;
}
/**
* A row filter that shows only rows that contain filterString, case-insensitive
*/
private class RegionRowFilter extends RowFilter<TableModel, Object> {
public RegionRowFilter() {
super();
}
public boolean include(RowFilter.Entry entry) {
return shouldIncludeRegion(
(String) entry.getValue(TABLE_COLINDEX_GENOME),
(String) entry.getValue(TABLE_COLINDEX_CHR),
(String) entry.getValue(TABLE_COLINDEX_DESC));
}
}
/**
* Listen for updates to the cells, save changes to the Regions
*/
private class RegionTableModelListener implements TableModelListener {
public void tableChanged(TableModelEvent e) {
//If we're in the middle of synching regions, do nothing
if (synchingRegions)
return;
List<RegionOfInterest> regions = retrieveRegionsAsList();
int firstRow = e.getFirstRow();
//range checking because this method gets called after a clear event, and we don't want to
//try to find an updated region then
if (firstRow > regions.size() - 1)
return;
//update all rows affected
for (int i = firstRow; i <= Math.max(firstRow, Math.min(regionTable.getRowCount(), e.getLastRow())); i++)
updateROIFromRegionTable(i);
}
}
/**
* Updates all ROIs with the values currently stored in the region table
*/
public void updateROIsFromRegionTable() {
for (int i = 0; i < regionTable.getRowSorter().getModelRowCount(); i++)
updateROIFromRegionTable(i);
}
/**
* Updates a single ROI with the values currently stored in the region table
*
* @param tableRow: the viewable index of the table row
*/
public void updateROIFromRegionTable(int tableRow) {
List<RegionOfInterest> regions = retrieveRegionsAsList();
if (tableRow > regionTable.getRowCount() - 1)
return;
//must convert row index from view to model, in case of sorting, filtering
int rowIdx = 0;
try {
rowIdx = regionTable.getRowSorter().convertRowIndexToModel(tableRow);
} catch (ArrayIndexOutOfBoundsException x) {
return;
}
// add protection
if ( rowIdx < 0 || rowIdx >= regions.size() )
{
log.warn("invalid rowIdx: " + rowIdx);
return;
}
RegionOfInterest region = regions.get(rowIdx);
if ( region == null )
{
log.error("null region at rowIdx: " + rowIdx);
}
//dhmay changing 20110505: just update region values from all columns, instead of checking the event
//to see which column is affected. This is in response to an intermittent bug.
Object descObject = regionTableModel.getValueAt(rowIdx, TABLE_COLINDEX_DESC);
if (descObject != null)
region.setDescription(descObject.toString());
//stored values are 0-based, viewed values are 1-based. Check for negative number just in case
int storeStartValue =
Math.max(0, (Integer) regionTableModel.getValueAt(rowIdx, TABLE_COLINDEX_START) - 1);
region.setStart(storeStartValue);
//stored values are 0-based, viewed values are 1-based. Check for negative number just in case
int storeEndValue =
Math.max(0, (Integer) regionTableModel.getValueAt(rowIdx, TABLE_COLINDEX_END) - 1);
region.setEnd(storeEndValue);
}
/**
* Listen for selection change events, navigate UI to start of selected region
*/
private class RegionTableSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
List<RegionOfInterest> regions = retrieveRegionsAsList();
int[] selectedRows = regionTable.getSelectedRows();
if (selectedRows != null && selectedRows.length > 0
&& regions.size() >= selectedRows.length) //dhmay: this is hacky. Bad things can happen with clear regions
{
RegionOfInterest firstStartRegion = null;
RegionOfInterest lastEndRegion = null;
Set<String> selectedChrs = new HashSet<String>();
Set<String> selectedGenomes = new HashSet<String>();
//Figure out which region has the first start and which has the last end
for (int selectedRowIndex : selectedRows) {
int selectedModelRow = regionTableRowSorter.convertRowIndexToModel(selectedRowIndex);
if ( selectedModelRow >= regions.size() )
continue;
RegionOfInterest region = regions.get(selectedModelRow);
selectedChrs.add(region.getChr());
if ( region.getGenome() != null )
selectedGenomes.add(region.getGenome());
if (firstStartRegion == null || region.getStart() < firstStartRegion.getStart())
firstStartRegion = region;
if (lastEndRegion == null || region.getEnd() > lastEndRegion.getEnd())
lastEndRegion = region;
}
//If there are multiple chromosomes represented in the selection, do nothing.
//Because what would we do? Maybe a status message should be displayed somehow, but a
//dialog would get annoying.
if (selectedChrs.size() > 1)
return;
if ( selectedGenomes.size() > 1)
return;
// genome nagivation
if ( selectedGenomes.size() > 0 )
{
final String genome = selectedGenomes.iterator().next();
final String tabName = firstStartRegion.getPreferedTab();
if ( !genome.equals(IGV.getInstance().getGenomeManager().currentGenome.getId()) )
{
final RegionOfInterest firstStartRegionFinal = firstStartRegion;
final RegionOfInterest lastEndRegionFinal = lastEndRegion;
final Set<String> selectedChrsFinal = selectedChrs;
Runnable runnable =
new Runnable() {
@Override
public void run() {
int tabIndex = -1;
if ( tabName != null )
tabIndex = IGV.getInstance().getContentPane().tabsNameList().indexOf(tabName);
if ( tabIndex < 0 )
tabIndex = IGV.getInstance().getContentPane().tabsGenomeTabIndex(IGV.getInstance().getGenomeManager().getCachedGenomeById(genome));
if ( tabIndex >= 0 )
{
IGV.getInstance().getContentPane().getCommandBar().setRegionGenomeSwitch(firstStartRegionFinal != null);
IGV.getInstance().getContentPane().tabsSwitchTo(tabIndex);
do
{
try {
Thread.sleep(250);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
while ( !genome.equals(IGV.getInstance().getGenomeManager().currentGenome.getId()) );
}
if ( firstStartRegionFinal != null ) {
if (checkBoxZoomWhenNav.isSelected()) {
// Option (1), zoom and center on group of selected regions, with an interval equal to
// 20% of the length of the end regions on either side for context (dhmay reduced from 100%)
int start = firstStartRegionFinal.getStart() - (int) (0.2 * firstStartRegionFinal.getLength());
int end = lastEndRegionFinal.getEnd() + (int) (0.2 * lastEndRegionFinal.getLength());
FrameManager.getDefaultFrame().jumpTo(selectedChrsFinal.iterator().next(), start, end);
} else {
// Option (2), center on the FIRST selected region without changing resolution
FrameManager.getDefaultFrame().centerOnLocation(firstStartRegionFinal.getCenter());
}
}
}
};
IGV.getInstance().runDelayedRunnable(0, runnable);
return;
}
}
if ( firstStartRegion != null ) {
if (checkBoxZoomWhenNav.isSelected() ) {
// Option (1), zoom and center on group of selected regions, with an interval equal to
// 20% of the length of the end regions on either side for context (dhmay reduced from 100%)
int start = firstStartRegion.getStart() - (int) (0.2 * firstStartRegion.getLength());
int end = lastEndRegion.getEnd() + (int) (0.2 * lastEndRegion.getLength());
FrameManager.getDefaultFrame().jumpTo(selectedChrs.iterator().next(), start, end);
} else {
// Option (2), center on the FIRST selected region without changing resolution
FrameManager.getDefaultFrame().centerOnLocation(firstStartRegion.getCenter());
}
}
}
}
}
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
dialogPane = new JPanel();
contentPanel = new JPanel();
scrollPane1 = new JScrollPane();
regionTable = new JTable();
panel1 = new JPanel();
textFieldSearch = new JTextField();
label1 = new JLabel();
button1 = new JButton();
panel2 = new JPanel();
buttonAddRegion = new JButton();
button2 = new JButton();
panel3 = new JPanel();
checkBoxZoomWhenNav = new JCheckBox();
checkBoxShowAllChrs = new JCheckBox();
checkBoxShowAllGenomes = new JCheckBox();
cancelAction = new CancelAction();
addRegionAction = new AddRegionAction();
actionRemoveRegions = new RemoveSelectedRegionsAction();
showAllChromosomesCheckboxAction = new ShowAllChromosomesCheckboxAction();
showAllGenomesCheckboxAction = new ShowAllGenomesCheckboxAction();
//======== this ========
setTitle("Regions of Interest (w/ genome)");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== dialogPane ========
{
dialogPane.setBorder(null);
dialogPane.setLayout(new BorderLayout());
//======== contentPanel ========
{
contentPanel.setLayout(new BorderLayout());
//======== scrollPane1 ========
{
//---- regionTable ----
regionTable.setModel(new DefaultTableModel(
new Object[][]{
{null, null, null, null, null},
},
new String[]{
"Genome", "Chr", "Start", "End", "Description"
}
) {
Class<?>[] columnTypes = new Class<?>[]{
String.class, String.class, Integer.class, Integer.class, Object.class
};
boolean[] columnEditable = new boolean[]{
false, false, true, true, true
};
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnEditable[columnIndex];
}
});
{
TableColumnModel cm = regionTable.getColumnModel();
cm.getColumn(0).setPreferredWidth(70);
cm.getColumn(1).setPreferredWidth(50);
cm.getColumn(2).setPreferredWidth(100);
cm.getColumn(3).setPreferredWidth(100);
cm.getColumn(4).setPreferredWidth(200);
}
regionTable.setAutoCreateRowSorter(true);
scrollPane1.setViewportView(regionTable);
}
contentPanel.add(scrollPane1, BorderLayout.CENTER);
//======== panel1 ========
{
panel1.setLayout(new BorderLayout());
//---- textFieldSearch ----
textFieldSearch.setToolTipText("Search for regions containing the specified description text.");
panel1.add(textFieldSearch, BorderLayout.CENTER);
//---- label1 ----
label1.setText("Search");
panel1.add(label1, BorderLayout.WEST);
//---- button1 ----
button1.setAction(cancelAction);
button1.setText("Clear Search");
panel1.add(button1, BorderLayout.EAST);
//======== panel2 ========
{
panel2.setLayout(new BorderLayout());
//---- buttonAddRegion ----
buttonAddRegion.setAction(addRegionAction);
buttonAddRegion.setText("Add");
panel2.add(buttonAddRegion, BorderLayout.WEST);
//---- button2 ----
button2.setAction(actionRemoveRegions);
button2.setText("Remove Selected");
panel2.add(button2, BorderLayout.CENTER);
//======== panel3 ========
{
panel3.setLayout(new BorderLayout());
//---- checkBoxZoomWhenNav ----
checkBoxZoomWhenNav.setText("Zoom to Region");
checkBoxZoomWhenNav.setToolTipText("When navigating to a region, change zoom level?");
checkBoxZoomWhenNav.setSelected(true);
panel3.add(checkBoxZoomWhenNav, BorderLayout.EAST);
//---- checkBoxShowAllChrs ----
checkBoxShowAllChrs.setAction(showAllChromosomesCheckboxAction);
checkBoxShowAllChrs.setToolTipText("View regions from all chromosomes (othrwise, current chromosome only)");
checkBoxShowAllChrs.setSelected(true);
panel3.add(checkBoxShowAllChrs, BorderLayout.CENTER);
//---- checkBoxShowAllGenomes ----
checkBoxShowAllGenomes.setAction(showAllGenomesCheckboxAction);
checkBoxShowAllGenomes.setToolTipText("View regions from all genome (othrwise, current genome only)");
checkBoxShowAllGenomes.setSelected(true);
panel3.add(checkBoxShowAllGenomes, BorderLayout.WEST);
}
panel2.add(panel3, BorderLayout.EAST);
}
panel1.add(panel2, BorderLayout.NORTH);
}
contentPanel.add(panel1, BorderLayout.SOUTH);
}
dialogPane.add(contentPanel, BorderLayout.CENTER);
}
contentPane.add(dialogPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner non-commercial license
private JPanel dialogPane;
private JPanel contentPanel;
private JScrollPane scrollPane1;
private JTable regionTable;
private JPanel panel1;
private JTextField textFieldSearch;
private JLabel label1;
private JButton button1;
private JPanel panel2;
private JButton buttonAddRegion;
private JButton button2;
private JPanel panel3;
private JCheckBox checkBoxZoomWhenNav;
private JCheckBox checkBoxShowAllChrs;
private JCheckBox checkBoxShowAllGenomes;
private CancelAction cancelAction;
private AddRegionAction addRegionAction;
private RemoveSelectedRegionsAction actionRemoveRegions;
private ShowAllChromosomesCheckboxAction showAllChromosomesCheckboxAction;
private ShowAllGenomesCheckboxAction showAllGenomesCheckboxAction;
// JFormDesigner - End of variables declaration //GEN-END:variables
private class CancelAction extends AbstractAction {
private CancelAction() {
// JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
putValue(NAME, "Cancel");
putValue(SHORT_DESCRIPTION, "Clear search box");
// JFormDesigner - End of action initialization //GEN-END:initComponents
}
public void actionPerformed(ActionEvent e) {
textFieldSearch.setText("");
}
}
/**
* Add a new RegionOfInterest for the current chromosome, with 0 start and end
*/
private class AddRegionAction extends AbstractAction {
private AddRegionAction() {
// JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
putValue(NAME, "Add Region");
putValue(SHORT_DESCRIPTION, "Add a new region");
// JFormDesigner - End of action initialization //GEN-END:initComponents
}
public void actionPerformed(ActionEvent e) {
String chr = FrameManager.getDefaultFrame().getChrName();
if (FrameManager.isGeneListMode()) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
"Regions cannot be created in gene list or split-screen views.",
"Error", JOptionPane.INFORMATION_MESSAGE);
} else if (chr == null || chr.isEmpty()) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
"No chromosome is specified. Can't create a region without a chromosome.",
"Error", JOptionPane.INFORMATION_MESSAGE);
} else if (chr.equalsIgnoreCase("All")) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
"Regions cannot be created in the All Chromosomes view.",
"Error", JOptionPane.INFORMATION_MESSAGE);
} else {
ReferenceFrame.Range r = FrameManager.getDefaultFrame().getCurrentRange();
RegionOfInterest newRegion = new RegionOfInterest(
r.getChr(), r.getStart(), r.getEnd(), "");
newRegion.setPreferedTab(IGV.getInstance().getContentPane().tabsCurrentTab());
IGV.getInstance().getSession().addRegionOfInterestWithNoListeners(newRegion);
}
}
}
private class RemoveSelectedRegionsAction extends AbstractAction {
private RemoveSelectedRegionsAction() {
// JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
putValue(NAME, "Remove");
putValue(SHORT_DESCRIPTION, "Remove all selected regions");
// JFormDesigner - End of action initialization //GEN-END:initComponents
}
public void actionPerformed(ActionEvent e) {
int[] selectedRows = regionTable.getSelectedRows();
if (selectedRows != null && selectedRows.length > 0) {
List<RegionOfInterest> selectedRegions = new ArrayList<RegionOfInterest>();
List<RegionOfInterest> regions = retrieveRegionsAsList();
for (int selectedRowIndex : selectedRows) {
int selectedModelRow = regionTableRowSorter.convertRowIndexToModel(selectedRowIndex);
selectedRegions.add(regions.get(selectedModelRow));
}
regionTable.clearSelection();
IGV.getInstance().getSession().removeRegionsOfInterest(selectedRegions);
} else {
//todo dhmay -- I don't fully understand this call. Clean this up.
JOptionPane.showMessageDialog(IGV.getMainFrame(), "No regions have been selected for removal.",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
private class ShowAllChromosomesCheckboxAction extends AbstractAction {
private ShowAllChromosomesCheckboxAction() {
// JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
putValue(NAME, "Show All Chrs");
// JFormDesigner - End of action initialization //GEN-END:initComponents
}
public void actionPerformed(ActionEvent e) {
// TODO add your code here
synchRegions();
}
}
private class ShowAllGenomesCheckboxAction extends AbstractAction {
private ShowAllGenomesCheckboxAction() {
// JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
putValue(NAME, "Show All Genomes");
// JFormDesigner - End of action initialization //GEN-END:initComponents
}
public void actionPerformed(ActionEvent e) {
// TODO add your code here
synchRegions();
}
}
/**
* Creates an appropriate popup for the row under the cursor, with Copy Sequence and Copy Details actions.
* This class doesn't go back to the RegionOfInterest model -- it relies on the values stored in the
* TableModel, since that's all we need. It could easily grab the Region, though, like in RegionTableModelListener
*/
private class RegionTablePopupHandler extends MouseAdapter {
// Maximum length for "copy sequence" action
private static final int MAX_SEQUENCE_LENGTH = 1000000;
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
Point p = e.getPoint();
//must convert row index from view to model, in case of sorting, filtering
int row = regionTable.getRowSorter().convertRowIndexToModel(regionTable.rowAtPoint(p));
int col = regionTable.columnAtPoint(p);
if (row >= 0 && col >= 0) {
final String genome = (String) regionTableModel.getValueAt(row, TABLE_COLINDEX_GENOME);
final String chr = (String) regionTableModel.getValueAt(row, TABLE_COLINDEX_CHR);
//displayed values are 1-based, so subract 1
final int start = (Integer) regionTableModel.getValueAt(row, TABLE_COLINDEX_START) - 1;
final int end = (Integer) regionTableModel.getValueAt(row, TABLE_COLINDEX_END) - 1;
final String desc = (String) regionTableModel.getValueAt(row, TABLE_COLINDEX_DESC);
JPopupMenu popupMenu = new IGVPopupMenu();
JMenuItem copySequenceItem = new JMenuItem("Copy Sequence");
copySequenceItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int length = end - start;
if (length > MAX_SEQUENCE_LENGTH) {
JOptionPane.showMessageDialog(RegionNavigatorDialog.this, "Region is to large to copy sequence data.");
} else {
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome();
byte[] seqBytes = genome.getSequence(chr, start, end);
if (seqBytes == null) {
MessageUtils.showMessage("Sequence not available");
} else {
String sequence = new String(seqBytes);
copyTextToClipboard(sequence);
}
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
});
popupMenu.add(copySequenceItem);
JMenuItem copyDetailsItem = new JMenuItem("Copy Details");
copyDetailsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String details = chr + ":" + start + "-" + end;
if (desc != null && !desc.isEmpty())
details = details + ", " + desc;
copyTextToClipboard(details);
}
});
popupMenu.add(copyDetailsItem);
popupMenu.show(regionTable, p.x, p.y);
}
}
}
/**
* Copy a text string to the clipboard
*
* @param text
*/
private void copyTextToClipboard(String text) {
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
}
}
|
Java
|
private class RegionRowFilter extends RowFilter<TableModel, Object> {
public RegionRowFilter() {
super();
}
public boolean include(RowFilter.Entry entry) {
return shouldIncludeRegion(
(String) entry.getValue(TABLE_COLINDEX_GENOME),
(String) entry.getValue(TABLE_COLINDEX_CHR),
(String) entry.getValue(TABLE_COLINDEX_DESC));
}
}
|
Java
|
private class RegionTableModelListener implements TableModelListener {
public void tableChanged(TableModelEvent e) {
//If we're in the middle of synching regions, do nothing
if (synchingRegions)
return;
List<RegionOfInterest> regions = retrieveRegionsAsList();
int firstRow = e.getFirstRow();
//range checking because this method gets called after a clear event, and we don't want to
//try to find an updated region then
if (firstRow > regions.size() - 1)
return;
//update all rows affected
for (int i = firstRow; i <= Math.max(firstRow, Math.min(regionTable.getRowCount(), e.getLastRow())); i++)
updateROIFromRegionTable(i);
}
}
|
Java
|
private class RegionTableSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
List<RegionOfInterest> regions = retrieveRegionsAsList();
int[] selectedRows = regionTable.getSelectedRows();
if (selectedRows != null && selectedRows.length > 0
&& regions.size() >= selectedRows.length) //dhmay: this is hacky. Bad things can happen with clear regions
{
RegionOfInterest firstStartRegion = null;
RegionOfInterest lastEndRegion = null;
Set<String> selectedChrs = new HashSet<String>();
Set<String> selectedGenomes = new HashSet<String>();
//Figure out which region has the first start and which has the last end
for (int selectedRowIndex : selectedRows) {
int selectedModelRow = regionTableRowSorter.convertRowIndexToModel(selectedRowIndex);
if ( selectedModelRow >= regions.size() )
continue;
RegionOfInterest region = regions.get(selectedModelRow);
selectedChrs.add(region.getChr());
if ( region.getGenome() != null )
selectedGenomes.add(region.getGenome());
if (firstStartRegion == null || region.getStart() < firstStartRegion.getStart())
firstStartRegion = region;
if (lastEndRegion == null || region.getEnd() > lastEndRegion.getEnd())
lastEndRegion = region;
}
//If there are multiple chromosomes represented in the selection, do nothing.
//Because what would we do? Maybe a status message should be displayed somehow, but a
//dialog would get annoying.
if (selectedChrs.size() > 1)
return;
if ( selectedGenomes.size() > 1)
return;
// genome nagivation
if ( selectedGenomes.size() > 0 )
{
final String genome = selectedGenomes.iterator().next();
final String tabName = firstStartRegion.getPreferedTab();
if ( !genome.equals(IGV.getInstance().getGenomeManager().currentGenome.getId()) )
{
final RegionOfInterest firstStartRegionFinal = firstStartRegion;
final RegionOfInterest lastEndRegionFinal = lastEndRegion;
final Set<String> selectedChrsFinal = selectedChrs;
Runnable runnable =
new Runnable() {
@Override
public void run() {
int tabIndex = -1;
if ( tabName != null )
tabIndex = IGV.getInstance().getContentPane().tabsNameList().indexOf(tabName);
if ( tabIndex < 0 )
tabIndex = IGV.getInstance().getContentPane().tabsGenomeTabIndex(IGV.getInstance().getGenomeManager().getCachedGenomeById(genome));
if ( tabIndex >= 0 )
{
IGV.getInstance().getContentPane().getCommandBar().setRegionGenomeSwitch(firstStartRegionFinal != null);
IGV.getInstance().getContentPane().tabsSwitchTo(tabIndex);
do
{
try {
Thread.sleep(250);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
while ( !genome.equals(IGV.getInstance().getGenomeManager().currentGenome.getId()) );
}
if ( firstStartRegionFinal != null ) {
if (checkBoxZoomWhenNav.isSelected()) {
// Option (1), zoom and center on group of selected regions, with an interval equal to
// 20% of the length of the end regions on either side for context (dhmay reduced from 100%)
int start = firstStartRegionFinal.getStart() - (int) (0.2 * firstStartRegionFinal.getLength());
int end = lastEndRegionFinal.getEnd() + (int) (0.2 * lastEndRegionFinal.getLength());
FrameManager.getDefaultFrame().jumpTo(selectedChrsFinal.iterator().next(), start, end);
} else {
// Option (2), center on the FIRST selected region without changing resolution
FrameManager.getDefaultFrame().centerOnLocation(firstStartRegionFinal.getCenter());
}
}
}
};
IGV.getInstance().runDelayedRunnable(0, runnable);
return;
}
}
if ( firstStartRegion != null ) {
if (checkBoxZoomWhenNav.isSelected() ) {
// Option (1), zoom and center on group of selected regions, with an interval equal to
// 20% of the length of the end regions on either side for context (dhmay reduced from 100%)
int start = firstStartRegion.getStart() - (int) (0.2 * firstStartRegion.getLength());
int end = lastEndRegion.getEnd() + (int) (0.2 * lastEndRegion.getLength());
FrameManager.getDefaultFrame().jumpTo(selectedChrs.iterator().next(), start, end);
} else {
// Option (2), center on the FIRST selected region without changing resolution
FrameManager.getDefaultFrame().centerOnLocation(firstStartRegion.getCenter());
}
}
}
}
}
}
|
Java
|
private class CancelAction extends AbstractAction {
private CancelAction() {
// JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
putValue(NAME, "Cancel");
putValue(SHORT_DESCRIPTION, "Clear search box");
// JFormDesigner - End of action initialization //GEN-END:initComponents
}
public void actionPerformed(ActionEvent e) {
textFieldSearch.setText("");
}
}
|
Java
|
private class AddRegionAction extends AbstractAction {
private AddRegionAction() {
// JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
putValue(NAME, "Add Region");
putValue(SHORT_DESCRIPTION, "Add a new region");
// JFormDesigner - End of action initialization //GEN-END:initComponents
}
public void actionPerformed(ActionEvent e) {
String chr = FrameManager.getDefaultFrame().getChrName();
if (FrameManager.isGeneListMode()) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
"Regions cannot be created in gene list or split-screen views.",
"Error", JOptionPane.INFORMATION_MESSAGE);
} else if (chr == null || chr.isEmpty()) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
"No chromosome is specified. Can't create a region without a chromosome.",
"Error", JOptionPane.INFORMATION_MESSAGE);
} else if (chr.equalsIgnoreCase("All")) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
"Regions cannot be created in the All Chromosomes view.",
"Error", JOptionPane.INFORMATION_MESSAGE);
} else {
ReferenceFrame.Range r = FrameManager.getDefaultFrame().getCurrentRange();
RegionOfInterest newRegion = new RegionOfInterest(
r.getChr(), r.getStart(), r.getEnd(), "");
newRegion.setPreferedTab(IGV.getInstance().getContentPane().tabsCurrentTab());
IGV.getInstance().getSession().addRegionOfInterestWithNoListeners(newRegion);
}
}
}
|
Java
|
private class RegionTablePopupHandler extends MouseAdapter {
// Maximum length for "copy sequence" action
private static final int MAX_SEQUENCE_LENGTH = 1000000;
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
Point p = e.getPoint();
//must convert row index from view to model, in case of sorting, filtering
int row = regionTable.getRowSorter().convertRowIndexToModel(regionTable.rowAtPoint(p));
int col = regionTable.columnAtPoint(p);
if (row >= 0 && col >= 0) {
final String genome = (String) regionTableModel.getValueAt(row, TABLE_COLINDEX_GENOME);
final String chr = (String) regionTableModel.getValueAt(row, TABLE_COLINDEX_CHR);
//displayed values are 1-based, so subract 1
final int start = (Integer) regionTableModel.getValueAt(row, TABLE_COLINDEX_START) - 1;
final int end = (Integer) regionTableModel.getValueAt(row, TABLE_COLINDEX_END) - 1;
final String desc = (String) regionTableModel.getValueAt(row, TABLE_COLINDEX_DESC);
JPopupMenu popupMenu = new IGVPopupMenu();
JMenuItem copySequenceItem = new JMenuItem("Copy Sequence");
copySequenceItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int length = end - start;
if (length > MAX_SEQUENCE_LENGTH) {
JOptionPane.showMessageDialog(RegionNavigatorDialog.this, "Region is to large to copy sequence data.");
} else {
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome();
byte[] seqBytes = genome.getSequence(chr, start, end);
if (seqBytes == null) {
MessageUtils.showMessage("Sequence not available");
} else {
String sequence = new String(seqBytes);
copyTextToClipboard(sequence);
}
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
});
popupMenu.add(copySequenceItem);
JMenuItem copyDetailsItem = new JMenuItem("Copy Details");
copyDetailsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String details = chr + ":" + start + "-" + end;
if (desc != null && !desc.isEmpty())
details = details + ", " + desc;
copyTextToClipboard(details);
}
});
popupMenu.add(copyDetailsItem);
popupMenu.show(regionTable, p.x, p.y);
}
}
}
/**
* Copy a text string to the clipboard
*
* @param text
*/
private void copyTextToClipboard(String text) {
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
}
|
Java
|
public class ModDetectionController {
@FXML public ChoiceBox stageChoice;
@FXML public Slider scaleSlider;
@FXML public Label scaleLabel;
@FXML public Slider neighbourSlider;
@FXML public Label neighbourLabel;
@FXML public Label totalWorthLabel;
@FXML private ImageView imageViewer;
private Manager manager;
private String platform;
private BufferedImage image;
public void initScreen(Manager manager, BufferedImage image, String platform) {
this.manager = manager;
this.platform = platform;
setupImage(image);
setupDragDrop();
setupSliders();
runModFinder();
}
// sets the values of the labels as they are being changed
private void setupSliders() {
scaleSlider
.valueProperty()
.addListener(
(observable, oldValue, newValue) -> {
DecimalFormat df = new DecimalFormat("#.000");
String twoDp = df.format(newValue);
scaleLabel.setText(twoDp);
});
neighbourSlider
.valueProperty()
.addListener(
(observable, oldValue, newValue) -> {
neighbourLabel.setText(String.valueOf(Math.round((Double) newValue)));
});
scaleSlider
.valueChangingProperty()
.addListener(
(obs, wasChanging, isNowChanging) -> {
if (!isNowChanging) {
runModFinder();
}
});
neighbourSlider
.valueChangingProperty()
.addListener(
(obs, wasChanging, isNowChanging) -> {
if (!isNowChanging) {
runModFinder();
}
});
}
// sets the drag and drop ability to allow users to drag images into the application
private void setupDragDrop() {
Scene scene = imageViewer.getScene();
scene.setOnDragOver(
event -> {
Dragboard db = event.getDragboard();
if (db.hasFiles() && db.getFiles().size() == 1) {
event.acceptTransferModes(TransferMode.COPY);
} else {
event.consume();
}
});
// Dropping over surface
scene.setOnDragDropped(
event -> {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasFiles()) {
success = true;
for (File file : db.getFiles()) {
try {
setupImage(ImageIO.read(file));
} catch (IOException ignored) {
/* invalid image */
}
}
}
event.setDropCompleted(success);
event.consume();
});
}
// setup the image viewer and openCV recogniser
private void setupImage(BufferedImage image) {
imageViewer.setImage(SwingFXUtils.toFXImage(image, null));
imageViewer.fitWidthProperty().bind(imageViewer.getScene().widthProperty().subtract(200));
MainApplication.setHeight(400);
MainApplication.setWidth(1200);
stageChoice.getSelectionModel().selectLast();
this.image = image;
}
private void runModFinder() {
try {
runModFinder(null);
} catch (IOException ignored) {
/* invalid image */
}
}
// run the image against OpenCV with the adjustable values
private void runModFinder(ActionEvent actionEvent) throws IOException {
String cascadeValue = (String) stageChoice.getValue(); // cascadexx
double scale = scaleSlider.getValue();
int neighbours = Math.toIntExact(Math.round(neighbourSlider.getValue()));
Map.Entry<BufferedImage, Integer> results =
DetectMods.run(image, cascadeValue, scale, neighbours, platform);
Image imageShown = SwingFXUtils.toFXImage(results.getKey(), null);
imageViewer.setImage(imageShown);
imageViewer.fitWidthProperty().bind(imageViewer.getScene().widthProperty().subtract(200));
totalWorthLabel.setText("Total worth: " + results.getValue());
}
public void increaseScale(ActionEvent actionEvent) throws IOException {
scaleSlider.setValue(scaleSlider.getValue() + 0.001);
runModFinder();
}
public void decreaseScale(ActionEvent actionEvent) {
scaleSlider.setValue(scaleSlider.getValue() - 0.001);
runModFinder();
}
public void increaseNeighbour(ActionEvent actionEvent) {
neighbourSlider.setValue(neighbourSlider.getValue() + 1);
runModFinder();
}
public void decreaseNeighbour(ActionEvent actionEvent) {
neighbourSlider.setValue(neighbourSlider.getValue() - 1);
runModFinder();
}
public void runModFinderAction(ActionEvent actionEvent) {
runModFinder();
}
}
|
Java
|
public class LoggingErrorHandler implements ErrorHandler {
private final Logger logger;
public LoggingErrorHandler(Logger logger) {
this.logger = logger;
}
@Override
public void onWaitError(Throwable error) {
logger.log(Level.WARNING, "Error while waiting", error);
}
@Override
public void onRepeatError(Repeat repeat, Throwable error) {
logger.log(Level.WARNING, String.format("Error computing repeat %s in %s",
repeat.getVar(), repeat.getList()), error);
}
@Override
public void onPathError(Path path, Throwable error) {
logger.log(Level.WARNING, String.format("Error computing path %s",
path.getName()), error);
}
}
|
Java
|
@Command(scope = "byon", name = "create-network", description = "Create a network")
public class CreateNetworkCommand extends AbstractShellCommand {
@Argument(index = 0, name = "network", description = "Network name",
required = true, multiValued = false)
String network = null;
@Override
protected void execute() {
NetworkService networkService = get(NetworkService.class);
networkService.createNetwork(network);
print("Created network %s", network);
}
}
|
Java
|
public class CreateCategoryGraph {
public final static Label articleLbl = DynamicLabel.label( "Article" );
public final static Label categoryLbl = DynamicLabel.label( "Category" );
public final static DynamicRelationshipType inCategoryRel = DynamicRelationshipType.withName("IN_CATEGORY");
public final static DynamicRelationshipType subCategoryOfRel = DynamicRelationshipType.withName("SUBCATEGORY_OF");
public static void main(String args[]) throws FileNotFoundException, IOException{
if(args.length!=3){
System.err.println("wrong usage, expecting 3 arguments: category.sql categorylinks.sql graphfolder");
}
String categoryFile=args[0];
String categoryLinksFile=args[1];
String dbFolder=args[2];
System.out.println("Initializing the database...");
GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbFolder);
//there are two kinds of nodes: labels and categories
if(false){
try ( Transaction tx = graphDb.beginTx()){
for(Node n:graphDb.findNodesByLabelAndProperty(categoryLbl, "name", "Materialism")){
n.getLabels().forEach(l->System.out.println("label: "+l));
n.getPropertyKeys().forEach(pname->System.out.println(pname+":"+n.getProperty(pname)));
}
System.exit(3);
}
}
try ( Transaction tx = graphDb.beginTx()){
Schema schema = graphDb.schema();
//articles and categories have both a name and an ID
schema.indexFor(articleLbl).on( "name" ).create();
schema.indexFor(categoryLbl).on( "name" ).create();
schema.indexFor(articleLbl).on( "ID" ).create();
schema.indexFor(categoryLbl).on( "ID" ).create();
tx.success();
}
System.out.println("Loading the categories and their IDs...");
long lastTime=System.currentTimeMillis();
final AtomicInteger done=new AtomicInteger(0);
//read the file line by line
try(BufferedReader br = new BufferedReader(new FileReader(categoryFile))){
br.lines().parallel().forEach(line->{
//while((line=br.readLine())!=null){
//pick the lines containing inserts, not comments or DDL
if(!line.startsWith("INSERT INTO ") || line.length()<2)
return;
try ( Transaction tx = graphDb.beginTx()){
//split values in single inserts, in the form
//(2,'Unprintworthy_redirects',1102027,15,0)
//where the first values are the ID and the category name (the others the number of articles, subcategories and files)
//the awkward regular expressions matches the numbers between values so strange article titles do not break the splitting
//Arrays.stream(line.split("[0-9]\\),\\((?=[0-9])")).forEach(v->System.out.println(" "+v));
Arrays.stream(line.split("[0-9]\\),\\((?=[0-9])"))
.filter(v->!v.startsWith("INSERT INTO"))
.forEach(category->{
String name=category.replaceAll(".+[0-9],'", "").replaceAll("',[0-9]+.+", "");
int ID=Integer.parseInt(category.replaceAll(",'.+", ""));
if(isInternalCategory(name))
return;
Node cat = graphDb.createNode(categoryLbl);
cat.setProperty("name", name);
cat.setProperty("ID", ID);
//System.out.println(name+" --> "+ID);
if(done.incrementAndGet()%100000==0)
System.out.println(" - loaded "+done.get()+" categories");
});
tx.success();
}
});
System.out.println("Loaded "+done.get()+" categories in "+(System.currentTimeMillis()-lastTime)/1000 +" seconds");
}
System.out.println("waiting up to 2 minutes for the names and ID indexes to be online...");
try (Transaction tx=graphDb.beginTx()){
Schema schema = graphDb.schema();
schema.awaitIndexesOnline(2, TimeUnit.MINUTES);
}
done.set(0);
final AtomicInteger doneCats=new AtomicInteger(0);
final AtomicInteger doneArts=new AtomicInteger(0);
lastTime=System.currentTimeMillis();
System.out.println("Loading the subcategory edges");
try(BufferedReader br = new BufferedReader(new FileReader(categoryLinksFile))){
final ConcurrentHashMap <Integer,Long>articleNodes=new ConcurrentHashMap<>(5000);
br.lines().forEach(line->{
//pick the lines containing inserts, not comments or DDL
if(!line.startsWith("INSERT INTO ") || line.length()<2)
return;
try ( Transaction tx = graphDb.beginTx()){
//split values in single inserts, in the form
//(cl_from,cl_to,sortkey,...)
//where the first value is the ID of the sub-category or article,
//the second is the name of the containing category
//and the third is the uppercase normalized name of the article or category
Arrays.stream(line.split("'\\),\\((?=[0-9])"))
.filter(v->!v.startsWith("INSERT INTO"))
.forEach(edge->{
if(edge.endsWith("','file")){
return;
}
int ID=Integer.parseInt(edge.split(",")[0]);
String catname=edge.replaceAll("[0-9]+,'", "").replaceAll("',.+", "");
ResourceIterator<Node> matches = graphDb.findNodesByLabelAndProperty(categoryLbl, "name", catname).iterator();
if(!matches.hasNext()){
matches.close();
return;
}
//System.out.println(edge);
Node container = matches.next();
matches.close();
if(edge.endsWith("'page")||edge.endsWith("'page');")){
Node article=null;
//if the article was in the map, use it, otherwise create it and put it into the map
//we can't use the index of Neo4j because it's eventually consistent
if(articleNodes.containsKey(ID)){
article=graphDb.getNodeById(articleNodes.get(ID));
}
else{
article=graphDb.createNode(articleLbl);
article.setProperty("ID", ID);
article.setProperty("name", edge.replace(catname, "EEE").replaceAll(".+EEE',", "").replaceAll("',.+", ""));
articleNodes.put(ID, article.getId());
}
doneArts.incrementAndGet();
article.createRelationshipTo(container,inCategoryRel );
if(done.incrementAndGet()%100000==0)
System.out.println(" - parsed "+done.get()+" edges ("+doneArts.get()+" articles and "+doneCats.get()+" categories so far)");
return;
}
if(edge.endsWith("'subcat")){
//if the subcategory was stored, is already indexed
matches = graphDb.findNodesByLabelAndProperty(categoryLbl, "ID", ID).iterator();
if(!matches.hasNext()){
matches.close();
return;
}
doneCats.incrementAndGet();
matches.next().createRelationshipTo(container, subCategoryOfRel);
matches.close();
if(done.incrementAndGet()%100000==0)
System.out.println(" - parsed "+done.get()+" edges ("+doneArts.get()+" articles and "+doneCats.get()+" categories so far)");
return;
}
if(done.incrementAndGet()%100000==0)
System.out.println(" - parsed "+done.get()+" edges ("+doneArts.get()+" articles and "+doneCats.get()+" categories so far)");
});
tx.success();
}
});
}
System.out.println("Loaded "+done.get()+" edges ("+doneArts.get()+" articles and "+doneCats.get()+" categories) in "+(System.currentTimeMillis()-lastTime)/1000 +" seconds");
graphDb.shutdown();
}
private static boolean isInternalCategory(String name) {
if(name.startsWith("Wikipedia_articles_")) return true;
if(name.startsWith("Suspected_Wikipedia_sockpuppets")) return true;
if(name.startsWith("Articles_with_")) return true;
if(name.startsWith("Redirects_")) return true;
if(name.startsWith("WikiProject_")) return true;
if(name.startsWith("Articles_needing_")) return true;
return name.startsWith("Wikipedians_");
}
}
|
Java
|
public final class UncompressedBitmap
{
private final int _numCols;
/** Distinct values that appear in the column. Linearized as value groups <v11 v12> <v21 v22>.*/
private double[] _values;
/** Bitmaps (as lists of offsets) for each of the values. */
private IntArrayList[] _offsetsLists;
public UncompressedBitmap( DblArrayIntListHashMap distinctVals, int numColumns )
{
// added for one pass bitmap construction
// Convert inputs to arrays
int numVals = distinctVals.size();
_values = new double[numVals*numColumns];
_offsetsLists = new IntArrayList[numVals];
int bitmapIx = 0;
for( DArrayIListEntry val : distinctVals.extractValues()) {
System.arraycopy(val.key.getData(), 0, _values, bitmapIx*numColumns, numColumns);
_offsetsLists[bitmapIx++] = val.value;
}
_numCols = numColumns;
}
public UncompressedBitmap( DoubleIntListHashMap distinctVals )
{
// added for one pass bitmap construction
// Convert inputs to arrays
int numVals = distinctVals.size();
_values = new double[numVals];
_offsetsLists = new IntArrayList[numVals];
int bitmapIx = 0;
for(DIListEntry val : distinctVals.extractValues()) {
_values[bitmapIx] = val.key;
_offsetsLists[bitmapIx++] = val.value;
}
_numCols = 1;
}
public int getNumColumns() {
return _numCols;
}
/**
* Get all values without unnecessary allocations and copies.
*
* @return dictionary of value tuples
*/
public double[] getValues() {
return _values;
}
/**
* Obtain tuple of column values associated with index.
*
* @param ix index of a particular distinct value
* @return the tuple of column values associated with the specified index
*/
public double[] getValues(int ix) {
return Arrays.copyOfRange(_values, ix*_numCols, (ix+1)*_numCols);
}
/**
* Obtain number of distinct values in the column.
*
* @return number of distinct values in the column; this number is also the
* number of bitmaps, since there is one bitmap per value
*/
public int getNumValues() {
return _values.length / _numCols;
}
public IntArrayList getOffsetsList(int ix) {
return _offsetsLists[ix];
}
public long getNumOffsets() {
long ret = 0;
for( IntArrayList offlist : _offsetsLists )
ret += offlist.size();
return ret;
}
public int getNumOffsets(int ix) {
return _offsetsLists[ix].size();
}
public void sortValuesByFrequency() {
int numVals = getNumValues();
int numCols = getNumColumns();
double[] freq = new double[numVals];
int[] pos = new int[numVals];
//populate the temporary arrays
for(int i=0; i<numVals; i++) {
freq[i] = getNumOffsets(i);
pos[i] = i;
}
//sort ascending and reverse (descending)
SortUtils.sortByValue(0, numVals, freq, pos);
ArrayUtils.reverse(pos);
//create new value and offset list arrays
double[] lvalues = new double[numVals*numCols];
IntArrayList[] loffsets = new IntArrayList[numVals];
for(int i=0; i<numVals; i++) {
System.arraycopy(_values, pos[i]*numCols, lvalues, i*numCols, numCols);
loffsets[i] = _offsetsLists[pos[i]];
}
_values = lvalues;
_offsetsLists = loffsets;
}
}
|
Java
|
@GwtIncompatible("com.google.protobuf")
public final class CheckConformance implements Callback, CompilerPass {
static final DiagnosticType CONFORMANCE_ERROR =
DiagnosticType.error("JSC_CONFORMANCE_ERROR", "Violation: {0}{1}{2}");
static final DiagnosticType CONFORMANCE_VIOLATION =
DiagnosticType.warning(
"JSC_CONFORMANCE_VIOLATION",
"Violation: {0}{1}{2}");
static final DiagnosticType CONFORMANCE_POSSIBLE_VIOLATION =
DiagnosticType.warning(
"JSC_CONFORMANCE_POSSIBLE_VIOLATION",
"Possible violation: {0}{1}{2}");
static final DiagnosticType INVALID_REQUIREMENT_SPEC =
DiagnosticType.error(
"JSC_INVALID_REQUIREMENT_SPEC",
"Invalid requirement. Reason: {0}\nRequirement spec:\n{1}");
private final AbstractCompiler compiler;
private final ImmutableList<Rule> rules;
public static interface Rule {
/** Perform conformance check */
void check(NodeTraversal t, Node n);
}
/**
* @param configs The rules to check.
*/
CheckConformance(
AbstractCompiler compiler,
ImmutableList<ConformanceConfig> configs) {
this.compiler = compiler;
// Initialize the map of functions to inspect for renaming candidates.
this.rules = initRules(compiler, configs);
}
@Override
public void process(Node externs, Node root) {
if (!rules.isEmpty()) {
NodeTraversal.traverseRoots(compiler, this, externs, root);
}
}
@Override
public final boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
// Don't inspect extern files
return !n.isScript() || !t.getInput().getSourceFile().isExtern();
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
for (int i = 0, len = rules.size(); i < len; i++) {
Rule rule = rules.get(i);
rule.check(t, n);
}
}
/**
* Build the data structures need by this pass from the provided
* configurations.
*/
private static ImmutableList<Rule> initRules(
AbstractCompiler compiler, ImmutableList<ConformanceConfig> configs) {
ImmutableList.Builder<Rule> builder = ImmutableList.builder();
List<Requirement> requirements = mergeRequirements(compiler, configs);
for (Requirement requirement : requirements) {
Rule rule = initRule(compiler, requirement);
if (rule != null) {
builder.add(rule);
}
}
return builder.build();
}
private static final ImmutableSet<String> EXTENDABLE_FIELDS =
ImmutableSet.of(
"extends", "whitelist", "whitelist_regexp", "only_apply_to", "only_apply_to_regexp");
/**
* Gets requirements from all configs. Merges whitelists of requirements with 'extends' equal to
* 'rule_id' of other rule.
*/
static List<Requirement> mergeRequirements(AbstractCompiler compiler,
List<ConformanceConfig> configs) {
List<Requirement.Builder> builders = new ArrayList<>();
Map<String, Requirement.Builder> extendable = new HashMap<>();
for (ConformanceConfig config : configs) {
for (Requirement requirement : config.getRequirementList()) {
Requirement.Builder builder = requirement.toBuilder();
if (requirement.hasRuleId()) {
if (requirement.getRuleId().isEmpty()) {
reportInvalidRequirement(compiler, requirement, "empty rule_id");
continue;
}
if (extendable.containsKey(requirement.getRuleId())) {
reportInvalidRequirement(compiler, requirement,
"two requirements with the same rule_id: " + requirement.getRuleId());
continue;
}
extendable.put(requirement.getRuleId(), builder);
}
if (!requirement.hasExtends()) {
builders.add(builder);
}
}
}
for (ConformanceConfig config : configs) {
for (Requirement requirement : config.getRequirementList()) {
if (requirement.hasExtends()) {
Requirement.Builder existing = extendable.get(requirement.getExtends());
if (existing == null) {
reportInvalidRequirement(compiler, requirement,
"no requirement with rule_id: " + requirement.getExtends());
continue;
}
for (Descriptors.FieldDescriptor field : requirement.getAllFields().keySet()) {
if (!EXTENDABLE_FIELDS.contains(field.getName())) {
reportInvalidRequirement(compiler, requirement,
"extending rules allow only " + EXTENDABLE_FIELDS);
}
}
existing.addAllWhitelist(requirement.getWhitelistList());
existing.addAllWhitelistRegexp(requirement.getWhitelistRegexpList());
existing.addAllOnlyApplyTo(requirement.getOnlyApplyToList());
existing.addAllOnlyApplyToRegexp(requirement.getOnlyApplyToRegexpList());
existing.addAllWhitelistEntry(requirement.getWhitelistEntryList());
}
}
}
List<Requirement> requirements = new ArrayList<>(builders.size());
for (Requirement.Builder builder : builders) {
removeDuplicates(builder);
requirements.add(builder.build());
}
return requirements;
}
private static void removeDuplicates(Requirement.Builder requirement) {
final Set<String> list1 = ImmutableSet.copyOf(requirement.getWhitelistList());
requirement.clearWhitelist();
requirement.addAllWhitelist(list1);
final Set<String> list2 = ImmutableSet.copyOf(requirement.getWhitelistRegexpList());
requirement.clearWhitelistRegexp();
requirement.addAllWhitelistRegexp(list2);
final Set<String> list3 = ImmutableSet.copyOf(requirement.getOnlyApplyToList());
requirement.clearOnlyApplyTo();
requirement.addAllOnlyApplyTo(list3);
final Set<String> list4 = ImmutableSet.copyOf(requirement.getOnlyApplyToRegexpList());
requirement.clearOnlyApplyToRegexp();
requirement.addAllOnlyApplyToRegexp(list4);
}
private static Rule initRule(
AbstractCompiler compiler, Requirement requirement) {
try {
switch (requirement.getType()) {
case CUSTOM:
return new ConformanceRules.CustomRuleProxy(compiler, requirement);
case BANNED_CODE_PATTERN:
return new ConformanceRules.BannedCodePattern(compiler, requirement);
case BANNED_DEPENDENCY:
return new ConformanceRules.BannedDependency(compiler, requirement);
case BANNED_NAME:
case BANNED_NAME_CALL:
return new ConformanceRules.BannedName(compiler, requirement);
case BANNED_PROPERTY:
case BANNED_PROPERTY_READ:
case BANNED_PROPERTY_WRITE:
case BANNED_PROPERTY_NON_CONSTANT_WRITE:
case BANNED_PROPERTY_CALL:
return new ConformanceRules.BannedProperty(compiler, requirement);
case RESTRICTED_NAME_CALL:
return new ConformanceRules.RestrictedNameCall(
compiler, requirement);
case RESTRICTED_METHOD_CALL:
return new ConformanceRules.RestrictedMethodCall(
compiler, requirement);
default:
reportInvalidRequirement(
compiler, requirement, "unknown requirement type");
return null;
}
} catch (InvalidRequirementSpec e){
reportInvalidRequirement(compiler, requirement, e.getMessage());
return null;
}
}
public static class InvalidRequirementSpec extends Exception {
InvalidRequirementSpec(String message) {
super(message);
}
}
/**
* @param requirement
*/
private static void reportInvalidRequirement(
AbstractCompiler compiler, Requirement requirement, String reason) {
compiler.report(JSError.make(INVALID_REQUIREMENT_SPEC,
reason,
TextFormat.printToString(requirement)));
}
}
|
Java
|
public class VaadinBot extends Bot {
private static final int DEFUALT_WAIT_TIMEOUT = 30;
public static void openAndWait(String url) {
open(url);
waitForVaadin();
}
public static void clickAndWait(WebElement webElement) {
clickAndWait(webElement, DEFUALT_WAIT_TIMEOUT);
}
public static void clickAndWait(WebElement webElement, long secontsToWait) {
Bot.click(webElement);
waitForVaadin(secontsToWait);
}
public static void doubleClickAndWait(WebElement webElement) {
doubleClickAndWait(webElement, DEFUALT_WAIT_TIMEOUT);
}
public static void doubleClickAndWait(WebElement webElement, long secondsToWait) {
doubleClick(webElement);
waitForVaadin(secondsToWait);
}
public static void waitForVaadin() {
waitForVaadin(DEFUALT_WAIT_TIMEOUT);
}
public static void waitForVaadin(long secondsToWait) {
waitUntil(VaadinConditions.ajaxCallsCompleted(), secondsToWait);
}
}
|
Java
|
public class Linker_Main_SingleLinker_Factory {
private static final Logger log = LoggerFactory.getLogger( Linker_Main_SingleLinker_Factory.class );
/**
* @param linkersDBDataSingleSearchSingleLinker
* @return
* @throws ProxlBaseDataException
*/
public static ILinker_Main getILinker_Main( LinkersDBDataSingleSearchSingleLinker linkersDBDataSingleSearchSingleLinker ) throws ProxlBaseDataException {
return getLinker_Main( linkersDBDataSingleSearchSingleLinker );
}
/**
* Package Private
*
* @param linkersDBDataSingleSearchSingleLinker
* @return
* @throws ProxlBaseDataException
*/
static Linker_Main getLinker_Main( LinkersDBDataSingleSearchSingleLinker linkersDBDataSingleSearchSingleLinker ) throws ProxlBaseDataException {
SearchLinkerDTO searchLinkerDTO = linkersDBDataSingleSearchSingleLinker.getSearchLinkerDTO();
String linkerAbbreviation = searchLinkerDTO.getLinkerAbbr();
ILinker_Builtin_Linker linker_Builtin_Linker = Get_BuiltIn_Linker_From_Abbreviation_Factory.getLinkerForAbbr( linkerAbbreviation );
Z_SingleLinkerDefinition_Internal z_SingleLinkerDefinition_Internal = getZ_SingleLinkerDefinition_Internal( linkersDBDataSingleSearchSingleLinker );
List<LinkerPerSearchCrosslinkMassDTO> linkerPerSearchCrosslinkMassDTOList = null;
List<LinkerPerSearchMonolinkMassDTO> linkerPerSearchMonolinkMassDTOList = null;
List<LinkerPerSearchCleavedCrosslinkMassDTO> linkerPerSearchCleavedCrosslinkMassDTOList = null;
if ( linkersDBDataSingleSearchSingleLinker.getLinkerPerSearchCrosslinkMassDTOList() != null ) {
linkerPerSearchCrosslinkMassDTOList = Collections.unmodifiableList( linkersDBDataSingleSearchSingleLinker.getLinkerPerSearchCrosslinkMassDTOList() );
}
if ( linkersDBDataSingleSearchSingleLinker.getLinkerPerSearchMonolinkMassDTOList() != null ) {
linkerPerSearchMonolinkMassDTOList = Collections.unmodifiableList( linkersDBDataSingleSearchSingleLinker.getLinkerPerSearchMonolinkMassDTOList() );
}
if ( linkersDBDataSingleSearchSingleLinker.getLinkerPerSearchCleavedCrosslinkMassDTOList() != null ) {
linkerPerSearchCleavedCrosslinkMassDTOList = Collections.unmodifiableList( linkersDBDataSingleSearchSingleLinker.getLinkerPerSearchCleavedCrosslinkMassDTOList() );
}
Linker_Main linker_Main = new Linker_Main( linkerAbbreviation, linker_Builtin_Linker, z_SingleLinkerDefinition_Internal,
linkerPerSearchCrosslinkMassDTOList,
linkerPerSearchMonolinkMassDTOList,
linkerPerSearchCleavedCrosslinkMassDTOList );
linker_Main.setSearchId( searchLinkerDTO.getSearchId() );
linker_Main.setSpacerArmLength( searchLinkerDTO.getSpacerArmLength() );
linker_Main.setSpacerArmLengthString( searchLinkerDTO.getSpacerArmLengthString() );
return linker_Main;
}
/**
* @param linkersDBDataSingleSearchSingleLinker
* @return
*/
private static Z_SingleLinkerDefinition_Internal getZ_SingleLinkerDefinition_Internal( LinkersDBDataSingleSearchSingleLinker linkersDBDataSingleSearchSingleLinker) {
List<SearchLinkerPerSideDefinitionObj> searchLinkerPerSideDefinitionObjList = linkersDBDataSingleSearchSingleLinker.getSearchLinkerPerSideDefinitionObjList();
if ( searchLinkerPerSideDefinitionObjList == null || searchLinkerPerSideDefinitionObjList.isEmpty() ) {
return null; // EARLY EXIT
}
if ( searchLinkerPerSideDefinitionObjList.size() != 2 ) {
String msg = "searchLinkerPerSideDefinitionObjList must be size 2, is size: " + searchLinkerPerSideDefinitionObjList.size();
log.error(msg);
throw new ProxlBaseInternalErrorException(msg);
}
Z_SingleLinkerDefinition_Internal z_SingleLinkerDefinition_Internal = new Z_SingleLinkerDefinition_Internal();
Iterator<SearchLinkerPerSideDefinitionObj> searchLinkerPerSideDefinitionObjListIter = searchLinkerPerSideDefinitionObjList.iterator();
z_SingleLinkerDefinition_Internal.linkerPerSide_1 = createLinkerPerSide( searchLinkerPerSideDefinitionObjListIter.next() );
z_SingleLinkerDefinition_Internal.linkerPerSide_2 = createLinkerPerSide( searchLinkerPerSideDefinitionObjListIter.next() );
return z_SingleLinkerDefinition_Internal;
}
/**
* @param searchLinkerPerSideDefinitionObj
* @return
*/
private static LinkerPerSide createLinkerPerSide( SearchLinkerPerSideDefinitionObj searchLinkerPerSideDefinitionObj ) {
LinkerPerSide linkerPerSide = new LinkerPerSide();
linkerPerSide.linkableResidueList = searchLinkerPerSideDefinitionObj.getResidues();
if ( searchLinkerPerSideDefinitionObj.getProteinTerminiList() != null ) {
linkerPerSide.linkableProteinTerminusList = new ArrayList<>( searchLinkerPerSideDefinitionObj.getProteinTerminiList().size() );
for ( SearchLinkerPerSideLinkableProteinTerminiObj dbObj : searchLinkerPerSideDefinitionObj.getProteinTerminiList() ) {
LinkableProteinTerminus linkableProteinTerminus = new LinkableProteinTerminus();
linkableProteinTerminus.proteinTerminus_c_n = dbObj.getProteinTerminus_c_n();
linkableProteinTerminus.distanceFromTerminus = dbObj.getDistanceFromTerminus();
linkerPerSide.linkableProteinTerminusList.add( linkableProteinTerminus );
}
}
return linkerPerSide;
}
}
|
Java
|
public class IntegerSlideWidget extends OptionWidget
implements ChangeListener
{
//////////////////////////////////////////////////
// @@ Members
//////////////////////////////////////////////////
/** Component that will be returned */
private Box panel;
/** Slider */
private JSlider slider;
/** Slider value label */
private JLabel label;
//////////////////////////////////////////////////
// @@ Construction
//////////////////////////////////////////////////
/**
* Constructor.
*
* @param option Option the widget refers to
* @param min Minimum value
* @param max Maximum value
*/
public IntegerSlideWidget(Option option, int min, int max)
{
this(option, min, max, SwingConstants.HORIZONTAL);
}
/**
* Constructor.
*
* @param option Option the widget refers to
* @param min Minimum value
* @param max Maximum value
* @param orientation Orientation of the slider
*/
public IntegerSlideWidget(Option option, int min, int max, int orientation)
{
this(option, min, max, 10, orientation);
}
/**
* Constructor.
*
* @param option Option the widget refers to
* @param min Minimum value
* @param max Maximum value
* @param steps Slider step setting
* @param orientation Orientation of the slider
*/
public IntegerSlideWidget(Option option, int min, int max, int steps, int orientation)
{
super(option);
slider = new JSlider(orientation, min, max, min);
slider.setSnapToTicks(true);
slider.addChangeListener(this);
JPanel labelpan = new JPanel(new BorderLayout());
label = new JLabel(Integer.toString(slider.getValue()), SwingUtilities.CENTER);
label.setOpaque(false);
labelpan.setBorder(new ReverseShadowBorder());
labelpan.add(label);
panel = Box.createVerticalBox();
panel.setBorder(SimpleBorder.getStandardBorder());
panel.add(slider);
panel.add(labelpan);
}
/**
* @see javax.swing.event.ChangeListener#stateChanged(ChangeEvent)
*/
public void stateChanged(ChangeEvent e)
{
// Update the text under the slider.
label.setText(Integer.toString(slider.getValue()));
notifyOptionMgrOfOptionChange();
}
//////////////////////////////////////////////////
// @@ OptionWidget implementation
//////////////////////////////////////////////////
public Object getValue()
{
return Integer.valueOf(slider.getValue());
}
public void setValue(Object o)
{
slider.setValue(((Integer) o).intValue());
}
public JComponent getWidgetComponent()
{
return panel;
}
}
|
Java
|
public static class Parameterizer extends AbstractDistribution.Parameterizer {
/** Parameters. */
double mu, sigma, k;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
DoubleParameter muP = new DoubleParameter(LOCATION_ID);
if(config.grab(muP)) {
mu = muP.doubleValue();
}
DoubleParameter sigmaP = new DoubleParameter(SCALE_ID);
if(config.grab(sigmaP)) {
sigma = sigmaP.doubleValue();
}
DoubleParameter kP = new DoubleParameter(SHAPE_ID);
if(config.grab(kP)) {
k = kP.doubleValue();
}
}
@Override
protected GeneralizedExtremeValueDistribution makeInstance() {
return new GeneralizedExtremeValueDistribution(mu, sigma, k, rnd);
}
}
|
Java
|
public class ItemBurppleFoodFeaturedAdapter extends RecyclerView.Adapter<ItemBurppleFoodFeaturedViewHolder> {
private List<PromotionsVO> mPromotionsItemsList;
public ItemBurppleFoodFeaturedAdapter() {
mPromotionsItemsList = new ArrayList<>();
}
@Override
public ItemBurppleFoodFeaturedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View foodItemView = inflater.inflate(R.layout.item_burpple_food_featured, parent,false);
ItemBurppleFoodFeaturedViewHolder itemBurppleFoodFeaturedViewHolder = new ItemBurppleFoodFeaturedViewHolder(foodItemView);
return itemBurppleFoodFeaturedViewHolder;
}
@Override
public void onBindViewHolder(ItemBurppleFoodFeaturedViewHolder holder, int position) {
holder.setFeaturedItems(mPromotionsItemsList.get(position));
}
@Override
public int getItemCount() {
return mPromotionsItemsList.size();
}
public void setFeaturedItems(List<PromotionsVO> featuredItemsList){
mPromotionsItemsList = featuredItemsList;
notifyDataSetChanged();
}
}
|
Java
|
public final /* synthetic */ class C2830y implements C0132p {
/* renamed from: a */
private final /* synthetic */ Class f6061a;
/* renamed from: b */
private final /* synthetic */ String f6062b;
/* renamed from: c */
private final /* synthetic */ Long f6063c;
public /* synthetic */ C2830y(Class cls, String str, Long l) {
this.f6061a = cls;
this.f6062b = str;
this.f6063c = l;
}
public final Object call(Object obj) {
return Database.m187a(this.f6061a, this.f6062b, this.f6063c, (C13990F) obj);
}
}
|
Java
|
public class RocksDBGenericOptionsToDbOptionsColumnFamilyOptionsAdapter extends Options {
private static final Logger log = LoggerFactory.getLogger(RocksDBGenericOptionsToDbOptionsColumnFamilyOptionsAdapter.class);
private final DBOptions dbOptions;
private final ColumnFamilyOptions columnFamilyOptions;
RocksDBGenericOptionsToDbOptionsColumnFamilyOptionsAdapter(final DBOptions dbOptions,
final ColumnFamilyOptions columnFamilyOptions) {
this.dbOptions = dbOptions;
this.columnFamilyOptions = columnFamilyOptions;
}
@Override
public Options setIncreaseParallelism(final int totalThreads) {
dbOptions.setIncreaseParallelism(totalThreads);
return this;
}
@Override
public Options setCreateIfMissing(final boolean flag) {
dbOptions.setCreateIfMissing(flag);
return this;
}
@Override
public Options setCreateMissingColumnFamilies(final boolean flag) {
dbOptions.setCreateMissingColumnFamilies(flag);
return this;
}
@Override
public Options setEnv(final Env env) {
dbOptions.setEnv(env);
return this;
}
@Override
public Env getEnv() {
return dbOptions.getEnv();
}
@Override
public Options prepareForBulkLoad() {
super.prepareForBulkLoad();
return this;
}
@Override
public boolean createIfMissing() {
return dbOptions.createIfMissing();
}
@Override
public boolean createMissingColumnFamilies() {
return dbOptions.createMissingColumnFamilies();
}
@Override
public Options optimizeForSmallDb() {
dbOptions.optimizeForSmallDb();
columnFamilyOptions.optimizeForSmallDb();
return this;
}
@Override
public Options optimizeForPointLookup(final long blockCacheSizeMb) {
columnFamilyOptions.optimizeForPointLookup(blockCacheSizeMb);
return this;
}
@Override
public Options optimizeLevelStyleCompaction() {
columnFamilyOptions.optimizeLevelStyleCompaction();
return this;
}
@Override
public Options optimizeLevelStyleCompaction(final long memtableMemoryBudget) {
columnFamilyOptions.optimizeLevelStyleCompaction(memtableMemoryBudget);
return this;
}
@Override
public Options optimizeUniversalStyleCompaction() {
columnFamilyOptions.optimizeUniversalStyleCompaction();
return this;
}
@Override
public Options optimizeUniversalStyleCompaction(final long memtableMemoryBudget) {
columnFamilyOptions.optimizeUniversalStyleCompaction(memtableMemoryBudget);
return this;
}
@Override
public Options setComparator(final BuiltinComparator builtinComparator) {
columnFamilyOptions.setComparator(builtinComparator);
return this;
}
@Override
public Options setComparator(final AbstractComparator comparator) {
columnFamilyOptions.setComparator(comparator);
return this;
}
@Override
public Options setMergeOperatorName(final String name) {
columnFamilyOptions.setMergeOperatorName(name);
return this;
}
@Override
public Options setMergeOperator(final MergeOperator mergeOperator) {
columnFamilyOptions.setMergeOperator(mergeOperator);
return this;
}
@Override
public Options setWriteBufferSize(final long writeBufferSize) {
columnFamilyOptions.setWriteBufferSize(writeBufferSize);
return this;
}
@Override
public long writeBufferSize() {
return columnFamilyOptions.writeBufferSize();
}
@Override
public Options setMaxWriteBufferNumber(final int maxWriteBufferNumber) {
columnFamilyOptions.setMaxWriteBufferNumber(maxWriteBufferNumber);
return this;
}
@Override
public int maxWriteBufferNumber() {
return columnFamilyOptions.maxWriteBufferNumber();
}
@Override
public boolean errorIfExists() {
return dbOptions.errorIfExists();
}
@Override
public Options setErrorIfExists(final boolean errorIfExists) {
dbOptions.setErrorIfExists(errorIfExists);
return this;
}
@Override
public boolean paranoidChecks() {
final boolean columnFamilyParanoidFileChecks = columnFamilyOptions.paranoidFileChecks();
final boolean dbOptionsParanoidChecks = dbOptions.paranoidChecks();
if (columnFamilyParanoidFileChecks != dbOptionsParanoidChecks) {
throw new IllegalStateException("Config for paranoid checks for RockDB and ColumnFamilies should be the same.");
}
return dbOptionsParanoidChecks;
}
@Override
public Options setParanoidChecks(final boolean paranoidChecks) {
columnFamilyOptions.paranoidFileChecks();
dbOptions.setParanoidChecks(paranoidChecks);
return this;
}
@Override
public int maxOpenFiles() {
return dbOptions.maxOpenFiles();
}
@Override
public Options setMaxFileOpeningThreads(final int maxFileOpeningThreads) {
dbOptions.setMaxFileOpeningThreads(maxFileOpeningThreads);
return this;
}
@Override
public int maxFileOpeningThreads() {
return dbOptions.maxFileOpeningThreads();
}
@Override
public Options setMaxTotalWalSize(final long maxTotalWalSize) {
logIgnoreWalOption("maxTotalWalSize");
return this;
}
@Override
public long maxTotalWalSize() {
return dbOptions.maxTotalWalSize();
}
@Override
public Options setMaxOpenFiles(final int maxOpenFiles) {
dbOptions.setMaxOpenFiles(maxOpenFiles);
return this;
}
@Override
public boolean useFsync() {
return dbOptions.useFsync();
}
@Override
public Options setUseFsync(final boolean useFsync) {
dbOptions.setUseFsync(useFsync);
return this;
}
@Override
public Options setDbPaths(final Collection<DbPath> dbPaths) {
dbOptions.setDbPaths(dbPaths);
return this;
}
@Override
public List<DbPath> dbPaths() {
return dbOptions.dbPaths();
}
@Override
public String dbLogDir() {
return dbOptions.dbLogDir();
}
@Override
public Options setDbLogDir(final String dbLogDir) {
dbOptions.setDbLogDir(dbLogDir);
return this;
}
@Override
public String walDir() {
return dbOptions.walDir();
}
@Override
public Options setWalDir(final String walDir) {
logIgnoreWalOption("walDir");
return this;
}
@Override
public long deleteObsoleteFilesPeriodMicros() {
return dbOptions.deleteObsoleteFilesPeriodMicros();
}
@Override
public Options setDeleteObsoleteFilesPeriodMicros(final long micros) {
dbOptions.setDeleteObsoleteFilesPeriodMicros(micros);
return this;
}
@Deprecated
@Override
public int maxBackgroundCompactions() {
return dbOptions.maxBackgroundCompactions();
}
@Override
public Options setStatistics(final Statistics statistics) {
dbOptions.setStatistics(statistics);
return this;
}
@Override
public Statistics statistics() {
return dbOptions.statistics();
}
@Deprecated
@Override
public void setBaseBackgroundCompactions(final int baseBackgroundCompactions) {
dbOptions.setBaseBackgroundCompactions(baseBackgroundCompactions);
}
@Override
public int baseBackgroundCompactions() {
return dbOptions.baseBackgroundCompactions();
}
@Deprecated
@Override
public Options setMaxBackgroundCompactions(final int maxBackgroundCompactions) {
dbOptions.setMaxBackgroundCompactions(maxBackgroundCompactions);
return this;
}
@Override
public Options setMaxSubcompactions(final int maxSubcompactions) {
dbOptions.setMaxSubcompactions(maxSubcompactions);
return this;
}
@Override
public int maxSubcompactions() {
return dbOptions.maxSubcompactions();
}
@Deprecated
@Override
public int maxBackgroundFlushes() {
return dbOptions.maxBackgroundFlushes();
}
@Deprecated
@Override
public Options setMaxBackgroundFlushes(final int maxBackgroundFlushes) {
dbOptions.setMaxBackgroundFlushes(maxBackgroundFlushes);
return this;
}
@Override
public int maxBackgroundJobs() {
return dbOptions.maxBackgroundJobs();
}
@Override
public Options setMaxBackgroundJobs(final int maxBackgroundJobs) {
dbOptions.setMaxBackgroundJobs(maxBackgroundJobs);
return this;
}
@Override
public long maxLogFileSize() {
return dbOptions.maxLogFileSize();
}
@Override
public Options setMaxLogFileSize(final long maxLogFileSize) {
dbOptions.setMaxLogFileSize(maxLogFileSize);
return this;
}
@Override
public long logFileTimeToRoll() {
return dbOptions.logFileTimeToRoll();
}
@Override
public Options setLogFileTimeToRoll(final long logFileTimeToRoll) {
dbOptions.setLogFileTimeToRoll(logFileTimeToRoll);
return this;
}
@Override
public long keepLogFileNum() {
return dbOptions.keepLogFileNum();
}
@Override
public Options setKeepLogFileNum(final long keepLogFileNum) {
dbOptions.setKeepLogFileNum(keepLogFileNum);
return this;
}
@Override
public Options setRecycleLogFileNum(final long recycleLogFileNum) {
dbOptions.setRecycleLogFileNum(recycleLogFileNum);
return this;
}
@Override
public long recycleLogFileNum() {
return dbOptions.recycleLogFileNum();
}
@Override
public long maxManifestFileSize() {
return dbOptions.maxManifestFileSize();
}
@Override
public Options setMaxManifestFileSize(final long maxManifestFileSize) {
dbOptions.setMaxManifestFileSize(maxManifestFileSize);
return this;
}
@Override
public Options setMaxTableFilesSizeFIFO(final long maxTableFilesSize) {
columnFamilyOptions.setMaxTableFilesSizeFIFO(maxTableFilesSize);
return this;
}
@Override
public long maxTableFilesSizeFIFO() {
return columnFamilyOptions.maxTableFilesSizeFIFO();
}
@Override
public int tableCacheNumshardbits() {
return dbOptions.tableCacheNumshardbits();
}
@Override
public Options setTableCacheNumshardbits(final int tableCacheNumshardbits) {
dbOptions.setTableCacheNumshardbits(tableCacheNumshardbits);
return this;
}
@Override
public long walTtlSeconds() {
return dbOptions.walTtlSeconds();
}
@Override
public Options setWalTtlSeconds(final long walTtlSeconds) {
logIgnoreWalOption("walTtlSeconds");
return this;
}
@Override
public long walSizeLimitMB() {
return dbOptions.walSizeLimitMB();
}
@Override
public Options setWalSizeLimitMB(final long sizeLimitMB) {
logIgnoreWalOption("walSizeLimitMB");
return this;
}
@Override
public long manifestPreallocationSize() {
return dbOptions.manifestPreallocationSize();
}
@Override
public Options setManifestPreallocationSize(final long size) {
dbOptions.setManifestPreallocationSize(size);
return this;
}
@Override
public Options setUseDirectReads(final boolean useDirectReads) {
dbOptions.setUseDirectReads(useDirectReads);
return this;
}
@Override
public boolean useDirectReads() {
return dbOptions.useDirectReads();
}
@Override
public Options setUseDirectIoForFlushAndCompaction(final boolean useDirectIoForFlushAndCompaction) {
dbOptions.setUseDirectIoForFlushAndCompaction(useDirectIoForFlushAndCompaction);
return this;
}
@Override
public boolean useDirectIoForFlushAndCompaction() {
return dbOptions.useDirectIoForFlushAndCompaction();
}
@Override
public Options setAllowFAllocate(final boolean allowFAllocate) {
dbOptions.setAllowFAllocate(allowFAllocate);
return this;
}
@Override
public boolean allowFAllocate() {
return dbOptions.allowFAllocate();
}
@Override
public boolean allowMmapReads() {
return dbOptions.allowMmapReads();
}
@Override
public Options setAllowMmapReads(final boolean allowMmapReads) {
dbOptions.setAllowMmapReads(allowMmapReads);
return this;
}
@Override
public boolean allowMmapWrites() {
return dbOptions.allowMmapWrites();
}
@Override
public Options setAllowMmapWrites(final boolean allowMmapWrites) {
dbOptions.setAllowMmapWrites(allowMmapWrites);
return this;
}
@Override
public boolean isFdCloseOnExec() {
return dbOptions.isFdCloseOnExec();
}
@Override
public Options setIsFdCloseOnExec(final boolean isFdCloseOnExec) {
dbOptions.setIsFdCloseOnExec(isFdCloseOnExec);
return this;
}
@Override
public int statsDumpPeriodSec() {
return dbOptions.statsDumpPeriodSec();
}
@Override
public Options setStatsDumpPeriodSec(final int statsDumpPeriodSec) {
dbOptions.setStatsDumpPeriodSec(statsDumpPeriodSec);
return this;
}
@Override
public boolean adviseRandomOnOpen() {
return dbOptions.adviseRandomOnOpen();
}
@Override
public Options setAdviseRandomOnOpen(final boolean adviseRandomOnOpen) {
dbOptions.setAdviseRandomOnOpen(adviseRandomOnOpen);
return this;
}
@Override
public Options setDbWriteBufferSize(final long dbWriteBufferSize) {
dbOptions.setDbWriteBufferSize(dbWriteBufferSize);
return this;
}
@Override
public long dbWriteBufferSize() {
return dbOptions.dbWriteBufferSize();
}
@Override
public Options setAccessHintOnCompactionStart(final AccessHint accessHint) {
dbOptions.setAccessHintOnCompactionStart(accessHint);
return this;
}
@Override
public AccessHint accessHintOnCompactionStart() {
return dbOptions.accessHintOnCompactionStart();
}
@Override
public Options setNewTableReaderForCompactionInputs(final boolean newTableReaderForCompactionInputs) {
dbOptions.setNewTableReaderForCompactionInputs(newTableReaderForCompactionInputs);
return this;
}
@Override
public boolean newTableReaderForCompactionInputs() {
return dbOptions.newTableReaderForCompactionInputs();
}
@Override
public Options setCompactionReadaheadSize(final long compactionReadaheadSize) {
dbOptions.setCompactionReadaheadSize(compactionReadaheadSize);
return this;
}
@Override
public long compactionReadaheadSize() {
return dbOptions.compactionReadaheadSize();
}
@Override
public Options setRandomAccessMaxBufferSize(final long randomAccessMaxBufferSize) {
dbOptions.setRandomAccessMaxBufferSize(randomAccessMaxBufferSize);
return this;
}
@Override
public long randomAccessMaxBufferSize() {
return dbOptions.randomAccessMaxBufferSize();
}
@Override
public Options setWritableFileMaxBufferSize(final long writableFileMaxBufferSize) {
dbOptions.setWritableFileMaxBufferSize(writableFileMaxBufferSize);
return this;
}
@Override
public long writableFileMaxBufferSize() {
return dbOptions.writableFileMaxBufferSize();
}
@Override
public boolean useAdaptiveMutex() {
return dbOptions.useAdaptiveMutex();
}
@Override
public Options setUseAdaptiveMutex(final boolean useAdaptiveMutex) {
dbOptions.setUseAdaptiveMutex(useAdaptiveMutex);
return this;
}
@Override
public long bytesPerSync() {
return dbOptions.bytesPerSync();
}
@Override
public Options setBytesPerSync(final long bytesPerSync) {
dbOptions.setBytesPerSync(bytesPerSync);
return this;
}
@Override
public Options setWalBytesPerSync(final long walBytesPerSync) {
logIgnoreWalOption("walBytesPerSync");
return this;
}
@Override
public long walBytesPerSync() {
return dbOptions.walBytesPerSync();
}
@Override
public Options setEnableThreadTracking(final boolean enableThreadTracking) {
dbOptions.setEnableThreadTracking(enableThreadTracking);
return this;
}
@Override
public boolean enableThreadTracking() {
return dbOptions.enableThreadTracking();
}
@Override
public Options setDelayedWriteRate(final long delayedWriteRate) {
dbOptions.setDelayedWriteRate(delayedWriteRate);
return this;
}
@Override
public long delayedWriteRate() {
return dbOptions.delayedWriteRate();
}
@Override
public Options setAllowConcurrentMemtableWrite(final boolean allowConcurrentMemtableWrite) {
dbOptions.setAllowConcurrentMemtableWrite(allowConcurrentMemtableWrite);
return this;
}
@Override
public boolean allowConcurrentMemtableWrite() {
return dbOptions.allowConcurrentMemtableWrite();
}
@Override
public Options setEnableWriteThreadAdaptiveYield(final boolean enableWriteThreadAdaptiveYield) {
dbOptions.setEnableWriteThreadAdaptiveYield(enableWriteThreadAdaptiveYield);
return this;
}
@Override
public boolean enableWriteThreadAdaptiveYield() {
return dbOptions.enableWriteThreadAdaptiveYield();
}
@Override
public Options setWriteThreadMaxYieldUsec(final long writeThreadMaxYieldUsec) {
dbOptions.setWriteThreadMaxYieldUsec(writeThreadMaxYieldUsec);
return this;
}
@Override
public long writeThreadMaxYieldUsec() {
return dbOptions.writeThreadMaxYieldUsec();
}
@Override
public Options setWriteThreadSlowYieldUsec(final long writeThreadSlowYieldUsec) {
dbOptions.setWriteThreadSlowYieldUsec(writeThreadSlowYieldUsec);
return this;
}
@Override
public long writeThreadSlowYieldUsec() {
return dbOptions.writeThreadSlowYieldUsec();
}
@Override
public Options setSkipStatsUpdateOnDbOpen(final boolean skipStatsUpdateOnDbOpen) {
dbOptions.setSkipStatsUpdateOnDbOpen(skipStatsUpdateOnDbOpen);
return this;
}
@Override
public boolean skipStatsUpdateOnDbOpen() {
return dbOptions.skipStatsUpdateOnDbOpen();
}
@Override
public Options setWalRecoveryMode(final WALRecoveryMode walRecoveryMode) {
logIgnoreWalOption("walRecoveryMode");
return this;
}
@Override
public WALRecoveryMode walRecoveryMode() {
return dbOptions.walRecoveryMode();
}
@Override
public Options setAllow2pc(final boolean allow2pc) {
dbOptions.setAllow2pc(allow2pc);
return this;
}
@Override
public boolean allow2pc() {
return dbOptions.allow2pc();
}
@Override
public Options setRowCache(final Cache rowCache) {
dbOptions.setRowCache(rowCache);
return this;
}
@Override
public Cache rowCache() {
return dbOptions.rowCache();
}
@Override
public Options setFailIfOptionsFileError(final boolean failIfOptionsFileError) {
dbOptions.setFailIfOptionsFileError(failIfOptionsFileError);
return this;
}
@Override
public boolean failIfOptionsFileError() {
return dbOptions.failIfOptionsFileError();
}
@Override
public Options setDumpMallocStats(final boolean dumpMallocStats) {
dbOptions.setDumpMallocStats(dumpMallocStats);
return this;
}
@Override
public boolean dumpMallocStats() {
return dbOptions.dumpMallocStats();
}
@Override
public Options setAvoidFlushDuringRecovery(final boolean avoidFlushDuringRecovery) {
dbOptions.setAvoidFlushDuringRecovery(avoidFlushDuringRecovery);
return this;
}
@Override
public boolean avoidFlushDuringRecovery() {
return dbOptions.avoidFlushDuringRecovery();
}
@Override
public Options setAvoidFlushDuringShutdown(final boolean avoidFlushDuringShutdown) {
dbOptions.setAvoidFlushDuringShutdown(avoidFlushDuringShutdown);
return this;
}
@Override
public boolean avoidFlushDuringShutdown() {
return dbOptions.avoidFlushDuringShutdown();
}
@Override
public MemTableConfig memTableConfig() {
return columnFamilyOptions.memTableConfig();
}
@Override
public Options setMemTableConfig(final MemTableConfig config) {
columnFamilyOptions.setMemTableConfig(config);
return this;
}
@Override
public Options setRateLimiter(final RateLimiter rateLimiter) {
dbOptions.setRateLimiter(rateLimiter);
return this;
}
@Override
public Options setSstFileManager(final SstFileManager sstFileManager) {
dbOptions.setSstFileManager(sstFileManager);
return this;
}
@Override
public Options setLogger(final org.rocksdb.Logger logger) {
dbOptions.setLogger(logger);
return this;
}
@Override
public Options setInfoLogLevel(final InfoLogLevel infoLogLevel) {
dbOptions.setInfoLogLevel(infoLogLevel);
return this;
}
@Override
public InfoLogLevel infoLogLevel() {
return dbOptions.infoLogLevel();
}
@Override
public String memTableFactoryName() {
return columnFamilyOptions.memTableFactoryName();
}
@Override
public TableFormatConfig tableFormatConfig() {
return columnFamilyOptions.tableFormatConfig();
}
@Override
public Options setTableFormatConfig(final TableFormatConfig config) {
columnFamilyOptions.setTableFormatConfig(config);
return this;
}
@Override
public String tableFactoryName() {
return columnFamilyOptions.tableFactoryName();
}
@Override
public Options useFixedLengthPrefixExtractor(final int n) {
columnFamilyOptions.useFixedLengthPrefixExtractor(n);
return this;
}
@Override
public Options useCappedPrefixExtractor(final int n) {
columnFamilyOptions.useCappedPrefixExtractor(n);
return this;
}
@Override
public CompressionType compressionType() {
return columnFamilyOptions.compressionType();
}
@Override
public Options setCompressionPerLevel(final List<CompressionType> compressionLevels) {
columnFamilyOptions.setCompressionPerLevel(compressionLevels);
return this;
}
@Override
public List<CompressionType> compressionPerLevel() {
return columnFamilyOptions.compressionPerLevel();
}
@Override
public Options setCompressionType(final CompressionType compressionType) {
columnFamilyOptions.setCompressionType(compressionType);
return this;
}
@Override
public Options setBottommostCompressionType(final CompressionType bottommostCompressionType) {
columnFamilyOptions.setBottommostCompressionType(bottommostCompressionType);
return this;
}
@Override
public CompressionType bottommostCompressionType() {
return columnFamilyOptions.bottommostCompressionType();
}
@Override
public Options setCompressionOptions(final CompressionOptions compressionOptions) {
columnFamilyOptions.setCompressionOptions(compressionOptions);
return this;
}
@Override
public CompressionOptions compressionOptions() {
return columnFamilyOptions.compressionOptions();
}
@Override
public CompactionStyle compactionStyle() {
return columnFamilyOptions.compactionStyle();
}
@Override
public Options setCompactionStyle(final CompactionStyle compactionStyle) {
columnFamilyOptions.setCompactionStyle(compactionStyle);
return this;
}
@Override
public int numLevels() {
return columnFamilyOptions.numLevels();
}
@Override
public Options setNumLevels(final int numLevels) {
columnFamilyOptions.setNumLevels(numLevels);
return this;
}
@Override
public int levelZeroFileNumCompactionTrigger() {
return columnFamilyOptions.levelZeroFileNumCompactionTrigger();
}
@Override
public Options setLevelZeroFileNumCompactionTrigger(final int numFiles) {
columnFamilyOptions.setLevelZeroFileNumCompactionTrigger(numFiles);
return this;
}
@Override
public int levelZeroSlowdownWritesTrigger() {
return columnFamilyOptions.levelZeroSlowdownWritesTrigger();
}
@Override
public Options setLevelZeroSlowdownWritesTrigger(final int numFiles) {
columnFamilyOptions.setLevelZeroSlowdownWritesTrigger(numFiles);
return this;
}
@Override
public int levelZeroStopWritesTrigger() {
return columnFamilyOptions.levelZeroStopWritesTrigger();
}
@Override
public Options setLevelZeroStopWritesTrigger(final int numFiles) {
columnFamilyOptions.setLevelZeroStopWritesTrigger(numFiles);
return this;
}
@Override
public long targetFileSizeBase() {
return columnFamilyOptions.targetFileSizeBase();
}
@Override
public Options setTargetFileSizeBase(final long targetFileSizeBase) {
columnFamilyOptions.setTargetFileSizeBase(targetFileSizeBase);
return this;
}
@Override
public int targetFileSizeMultiplier() {
return columnFamilyOptions.targetFileSizeMultiplier();
}
@Override
public Options setTargetFileSizeMultiplier(final int multiplier) {
columnFamilyOptions.setTargetFileSizeMultiplier(multiplier);
return this;
}
@Override
public Options setMaxBytesForLevelBase(final long maxBytesForLevelBase) {
columnFamilyOptions.setMaxBytesForLevelBase(maxBytesForLevelBase);
return this;
}
@Override
public long maxBytesForLevelBase() {
return columnFamilyOptions.maxBytesForLevelBase();
}
@Override
public Options setLevelCompactionDynamicLevelBytes(final boolean enableLevelCompactionDynamicLevelBytes) {
columnFamilyOptions.setLevelCompactionDynamicLevelBytes(enableLevelCompactionDynamicLevelBytes);
return this;
}
@Override
public boolean levelCompactionDynamicLevelBytes() {
return columnFamilyOptions.levelCompactionDynamicLevelBytes();
}
@Override
public double maxBytesForLevelMultiplier() {
return columnFamilyOptions.maxBytesForLevelMultiplier();
}
@Override
public Options setMaxBytesForLevelMultiplier(final double multiplier) {
columnFamilyOptions.setMaxBytesForLevelMultiplier(multiplier);
return this;
}
@Override
public long maxCompactionBytes() {
return columnFamilyOptions.maxCompactionBytes();
}
@Override
public Options setMaxCompactionBytes(final long maxCompactionBytes) {
columnFamilyOptions.setMaxCompactionBytes(maxCompactionBytes);
return this;
}
@Override
public long arenaBlockSize() {
return columnFamilyOptions.arenaBlockSize();
}
@Override
public Options setArenaBlockSize(final long arenaBlockSize) {
columnFamilyOptions.setArenaBlockSize(arenaBlockSize);
return this;
}
@Override
public boolean disableAutoCompactions() {
return columnFamilyOptions.disableAutoCompactions();
}
@Override
public Options setDisableAutoCompactions(final boolean disableAutoCompactions) {
columnFamilyOptions.setDisableAutoCompactions(disableAutoCompactions);
return this;
}
@Override
public long maxSequentialSkipInIterations() {
return columnFamilyOptions.maxSequentialSkipInIterations();
}
@Override
public Options setMaxSequentialSkipInIterations(final long maxSequentialSkipInIterations) {
columnFamilyOptions.setMaxSequentialSkipInIterations(maxSequentialSkipInIterations);
return this;
}
@Override
public boolean inplaceUpdateSupport() {
return columnFamilyOptions.inplaceUpdateSupport();
}
@Override
public Options setInplaceUpdateSupport(final boolean inplaceUpdateSupport) {
columnFamilyOptions.setInplaceUpdateSupport(inplaceUpdateSupport);
return this;
}
@Override
public long inplaceUpdateNumLocks() {
return columnFamilyOptions.inplaceUpdateNumLocks();
}
@Override
public Options setInplaceUpdateNumLocks(final long inplaceUpdateNumLocks) {
columnFamilyOptions.setInplaceUpdateNumLocks(inplaceUpdateNumLocks);
return this;
}
@Override
public double memtablePrefixBloomSizeRatio() {
return columnFamilyOptions.memtablePrefixBloomSizeRatio();
}
@Override
public Options setMemtablePrefixBloomSizeRatio(final double memtablePrefixBloomSizeRatio) {
columnFamilyOptions.setMemtablePrefixBloomSizeRatio(memtablePrefixBloomSizeRatio);
return this;
}
@Override
public int bloomLocality() {
return columnFamilyOptions.bloomLocality();
}
@Override
public Options setBloomLocality(final int bloomLocality) {
columnFamilyOptions.setBloomLocality(bloomLocality);
return this;
}
@Override
public long maxSuccessiveMerges() {
return columnFamilyOptions.maxSuccessiveMerges();
}
@Override
public Options setMaxSuccessiveMerges(final long maxSuccessiveMerges) {
columnFamilyOptions.setMaxSuccessiveMerges(maxSuccessiveMerges);
return this;
}
@Override
public int minWriteBufferNumberToMerge() {
return columnFamilyOptions.minWriteBufferNumberToMerge();
}
@Override
public Options setMinWriteBufferNumberToMerge(final int minWriteBufferNumberToMerge) {
columnFamilyOptions.setMinWriteBufferNumberToMerge(minWriteBufferNumberToMerge);
return this;
}
@Override
public Options setOptimizeFiltersForHits(final boolean optimizeFiltersForHits) {
columnFamilyOptions.setOptimizeFiltersForHits(optimizeFiltersForHits);
return this;
}
@Override
public boolean optimizeFiltersForHits() {
return columnFamilyOptions.optimizeFiltersForHits();
}
@Override
public Options setMemtableHugePageSize(final long memtableHugePageSize) {
columnFamilyOptions.setMemtableHugePageSize(memtableHugePageSize);
return this;
}
@Override
public long memtableHugePageSize() {
return columnFamilyOptions.memtableHugePageSize();
}
@Override
public Options setSoftPendingCompactionBytesLimit(final long softPendingCompactionBytesLimit) {
columnFamilyOptions.setSoftPendingCompactionBytesLimit(softPendingCompactionBytesLimit);
return this;
}
@Override
public long softPendingCompactionBytesLimit() {
return columnFamilyOptions.softPendingCompactionBytesLimit();
}
@Override
public Options setHardPendingCompactionBytesLimit(final long hardPendingCompactionBytesLimit) {
columnFamilyOptions.setHardPendingCompactionBytesLimit(hardPendingCompactionBytesLimit);
return this;
}
@Override
public long hardPendingCompactionBytesLimit() {
return columnFamilyOptions.hardPendingCompactionBytesLimit();
}
@Override
public Options setLevel0FileNumCompactionTrigger(final int level0FileNumCompactionTrigger) {
columnFamilyOptions.setLevel0FileNumCompactionTrigger(level0FileNumCompactionTrigger);
return this;
}
@Override
public int level0FileNumCompactionTrigger() {
return columnFamilyOptions.level0FileNumCompactionTrigger();
}
@Override
public Options setLevel0SlowdownWritesTrigger(final int level0SlowdownWritesTrigger) {
columnFamilyOptions.setLevel0SlowdownWritesTrigger(level0SlowdownWritesTrigger);
return this;
}
@Override
public int level0SlowdownWritesTrigger() {
return columnFamilyOptions.level0SlowdownWritesTrigger();
}
@Override
public Options setLevel0StopWritesTrigger(final int level0StopWritesTrigger) {
columnFamilyOptions.setLevel0StopWritesTrigger(level0StopWritesTrigger);
return this;
}
@Override
public int level0StopWritesTrigger() {
return columnFamilyOptions.level0StopWritesTrigger();
}
@Override
public Options setMaxBytesForLevelMultiplierAdditional(final int[] maxBytesForLevelMultiplierAdditional) {
columnFamilyOptions.setMaxBytesForLevelMultiplierAdditional(maxBytesForLevelMultiplierAdditional);
return this;
}
@Override
public int[] maxBytesForLevelMultiplierAdditional() {
return columnFamilyOptions.maxBytesForLevelMultiplierAdditional();
}
@Override
public Options setParanoidFileChecks(final boolean paranoidFileChecks) {
columnFamilyOptions.setParanoidFileChecks(paranoidFileChecks);
return this;
}
@Override
public boolean paranoidFileChecks() {
return columnFamilyOptions.paranoidFileChecks();
}
@Override
public Options setMaxWriteBufferNumberToMaintain(final int maxWriteBufferNumberToMaintain) {
columnFamilyOptions.setMaxWriteBufferNumberToMaintain(maxWriteBufferNumberToMaintain);
return this;
}
@Override
public int maxWriteBufferNumberToMaintain() {
return columnFamilyOptions.maxWriteBufferNumberToMaintain();
}
@Override
public Options setCompactionPriority(final CompactionPriority compactionPriority) {
columnFamilyOptions.setCompactionPriority(compactionPriority);
return this;
}
@Override
public CompactionPriority compactionPriority() {
return columnFamilyOptions.compactionPriority();
}
@Override
public Options setReportBgIoStats(final boolean reportBgIoStats) {
columnFamilyOptions.setReportBgIoStats(reportBgIoStats);
return this;
}
@Override
public boolean reportBgIoStats() {
return columnFamilyOptions.reportBgIoStats();
}
@Override
public Options setCompactionOptionsUniversal(final CompactionOptionsUniversal compactionOptionsUniversal) {
columnFamilyOptions.setCompactionOptionsUniversal(compactionOptionsUniversal);
return this;
}
@Override
public CompactionOptionsUniversal compactionOptionsUniversal() {
return columnFamilyOptions.compactionOptionsUniversal();
}
@Override
public Options setCompactionOptionsFIFO(final CompactionOptionsFIFO compactionOptionsFIFO) {
columnFamilyOptions.setCompactionOptionsFIFO(compactionOptionsFIFO);
return this;
}
@Override
public CompactionOptionsFIFO compactionOptionsFIFO() {
return columnFamilyOptions.compactionOptionsFIFO();
}
@Override
public Options setForceConsistencyChecks(final boolean forceConsistencyChecks) {
columnFamilyOptions.setForceConsistencyChecks(forceConsistencyChecks);
return this;
}
@Override
public boolean forceConsistencyChecks() {
return columnFamilyOptions.forceConsistencyChecks();
}
@Override
public Options setWriteBufferManager(final WriteBufferManager writeBufferManager) {
dbOptions.setWriteBufferManager(writeBufferManager);
return this;
}
@Override
public WriteBufferManager writeBufferManager() {
return dbOptions.writeBufferManager();
}
@Override
public Options setMaxWriteBatchGroupSizeBytes(final long maxWriteBatchGroupSizeBytes) {
dbOptions.setMaxWriteBatchGroupSizeBytes(maxWriteBatchGroupSizeBytes);
return this;
}
@Override
public long maxWriteBatchGroupSizeBytes() {
return dbOptions.maxWriteBatchGroupSizeBytes();
}
@Override
public Options oldDefaults(final int majorVersion, final int minorVersion) {
columnFamilyOptions.oldDefaults(majorVersion, minorVersion);
return this;
}
@Override
public Options optimizeForSmallDb(final Cache cache) {
return super.optimizeForSmallDb(cache);
}
@Override
public AbstractCompactionFilter<? extends AbstractSlice<?>> compactionFilter() {
return columnFamilyOptions.compactionFilter();
}
@Override
public AbstractCompactionFilterFactory<? extends AbstractCompactionFilter<?>> compactionFilterFactory() {
return columnFamilyOptions.compactionFilterFactory();
}
@Override
public Options setStatsPersistPeriodSec(final int statsPersistPeriodSec) {
dbOptions.setStatsPersistPeriodSec(statsPersistPeriodSec);
return this;
}
@Override
public int statsPersistPeriodSec() {
return dbOptions.statsPersistPeriodSec();
}
@Override
public Options setStatsHistoryBufferSize(final long statsHistoryBufferSize) {
dbOptions.setStatsHistoryBufferSize(statsHistoryBufferSize);
return this;
}
@Override
public long statsHistoryBufferSize() {
return dbOptions.statsHistoryBufferSize();
}
@Override
public Options setStrictBytesPerSync(final boolean strictBytesPerSync) {
dbOptions.setStrictBytesPerSync(strictBytesPerSync);
return this;
}
@Override
public boolean strictBytesPerSync() {
return dbOptions.strictBytesPerSync();
}
@Override
public Options setListeners(final List<AbstractEventListener> listeners) {
dbOptions.setListeners(listeners);
return this;
}
@Override
public List<AbstractEventListener> listeners() {
return dbOptions.listeners();
}
@Override
public Options setEnablePipelinedWrite(final boolean enablePipelinedWrite) {
dbOptions.setEnablePipelinedWrite(enablePipelinedWrite);
return this;
}
@Override
public boolean enablePipelinedWrite() {
return dbOptions.enablePipelinedWrite();
}
@Override
public Options setUnorderedWrite(final boolean unorderedWrite) {
dbOptions.setUnorderedWrite(unorderedWrite);
return this;
}
@Override
public boolean unorderedWrite() {
return dbOptions.unorderedWrite();
}
@Override
public Options setSkipCheckingSstFileSizesOnDbOpen(final boolean skipCheckingSstFileSizesOnDbOpen) {
dbOptions.setSkipCheckingSstFileSizesOnDbOpen(skipCheckingSstFileSizesOnDbOpen);
return this;
}
@Override
public boolean skipCheckingSstFileSizesOnDbOpen() {
return dbOptions.skipCheckingSstFileSizesOnDbOpen();
}
@Override
public Options setWalFilter(final AbstractWalFilter walFilter) {
logIgnoreWalOption("walFilter");
return this;
}
@Override
public WalFilter walFilter() {
return dbOptions.walFilter();
}
@Override
public Options setAllowIngestBehind(final boolean allowIngestBehind) {
dbOptions.setAllowIngestBehind(allowIngestBehind);
return this;
}
@Override
public boolean allowIngestBehind() {
return dbOptions.allowIngestBehind();
}
@Override
public Options setPreserveDeletes(final boolean preserveDeletes) {
dbOptions.setPreserveDeletes(preserveDeletes);
return this;
}
@Override
public boolean preserveDeletes() {
return dbOptions.preserveDeletes();
}
@Override
public Options setTwoWriteQueues(final boolean twoWriteQueues) {
dbOptions.setTwoWriteQueues(twoWriteQueues);
return this;
}
@Override
public boolean twoWriteQueues() {
return dbOptions.twoWriteQueues();
}
@Override
public Options setManualWalFlush(final boolean manualWalFlush) {
logIgnoreWalOption("manualWalFlush");
return this;
}
@Override
public boolean manualWalFlush() {
return dbOptions.manualWalFlush();
}
@Override
public Options setCfPaths(final Collection<DbPath> cfPaths) {
columnFamilyOptions.setCfPaths(cfPaths);
return this;
}
@Override
public List<DbPath> cfPaths() {
return columnFamilyOptions.cfPaths();
}
@Override
public Options setBottommostCompressionOptions(final CompressionOptions bottommostCompressionOptions) {
columnFamilyOptions.setBottommostCompressionOptions(bottommostCompressionOptions);
return this;
}
@Override
public CompressionOptions bottommostCompressionOptions() {
return columnFamilyOptions.bottommostCompressionOptions();
}
@Override
public Options setTtl(final long ttl) {
columnFamilyOptions.setTtl(ttl);
return this;
}
@Override
public long ttl() {
return columnFamilyOptions.ttl();
}
@Override
public Options setAtomicFlush(final boolean atomicFlush) {
dbOptions.setAtomicFlush(atomicFlush);
return this;
}
@Override
public boolean atomicFlush() {
return dbOptions.atomicFlush();
}
@Override
public Options setAvoidUnnecessaryBlockingIO(final boolean avoidUnnecessaryBlockingIO) {
dbOptions.setAvoidUnnecessaryBlockingIO(avoidUnnecessaryBlockingIO);
return this;
}
@Override
public boolean avoidUnnecessaryBlockingIO() {
return dbOptions.avoidUnnecessaryBlockingIO();
}
@Override
public Options setPersistStatsToDisk(final boolean persistStatsToDisk) {
dbOptions.setPersistStatsToDisk(persistStatsToDisk);
return this;
}
@Override
public boolean persistStatsToDisk() {
return dbOptions.persistStatsToDisk();
}
@Override
public Options setWriteDbidToManifest(final boolean writeDbidToManifest) {
dbOptions.setWriteDbidToManifest(writeDbidToManifest);
return this;
}
@Override
public boolean writeDbidToManifest() {
return dbOptions.writeDbidToManifest();
}
@Override
public Options setLogReadaheadSize(final long logReadaheadSize) {
dbOptions.setLogReadaheadSize(logReadaheadSize);
return this;
}
@Override
public long logReadaheadSize() {
return dbOptions.logReadaheadSize();
}
@Override
public Options setBestEffortsRecovery(final boolean bestEffortsRecovery) {
dbOptions.setBestEffortsRecovery(bestEffortsRecovery);
return this;
}
@Override
public boolean bestEffortsRecovery() {
return dbOptions.bestEffortsRecovery();
}
@Override
public Options setMaxBgErrorResumeCount(final int maxBgerrorResumeCount) {
dbOptions.setMaxBgErrorResumeCount(maxBgerrorResumeCount);
return this;
}
@Override
public int maxBgerrorResumeCount() {
return dbOptions.maxBgerrorResumeCount();
}
@Override
public Options setBgerrorResumeRetryInterval(final long bgerrorResumeRetryInterval) {
dbOptions.setBgerrorResumeRetryInterval(bgerrorResumeRetryInterval);
return this;
}
@Override
public long bgerrorResumeRetryInterval() {
return dbOptions.bgerrorResumeRetryInterval();
}
@Override
public Options setSstPartitionerFactory(final SstPartitionerFactory sstPartitionerFactory) {
columnFamilyOptions.setSstPartitionerFactory(sstPartitionerFactory);
return this;
}
@Override
public SstPartitionerFactory sstPartitionerFactory() {
return columnFamilyOptions.sstPartitionerFactory();
}
@Override
public Options setCompactionThreadLimiter(final ConcurrentTaskLimiter compactionThreadLimiter) {
columnFamilyOptions.setCompactionThreadLimiter(compactionThreadLimiter);
return this;
}
@Override
public ConcurrentTaskLimiter compactionThreadLimiter() {
return columnFamilyOptions.compactionThreadLimiter();
}
public Options setCompactionFilter(final AbstractCompactionFilter<? extends AbstractSlice<?>> compactionFilter) {
columnFamilyOptions.setCompactionFilter(compactionFilter);
return this;
}
public Options setCompactionFilterFactory(final AbstractCompactionFilterFactory<? extends AbstractCompactionFilter<?>> compactionFilterFactory) {
columnFamilyOptions.setCompactionFilterFactory(compactionFilterFactory);
return this;
}
@Override
public void close() {
// ColumnFamilyOptions should be closed after DBOptions
dbOptions.close();
columnFamilyOptions.close();
// close super last since we initialized it first
super.close();
}
private void logIgnoreWalOption(final String option) {
log.warn("WAL is explicitly disabled by Streams in RocksDB. Setting option '{}' will be ignored", option);
}
}
|
Java
|
public class LocationResult {
@SerializedName("lat")
private String lat;
@SerializedName("lon")
private String lon;
@SerializedName("display_name")
private String name;
public String getLat() {
return lat;
}
public String getLon() {
return lon;
}
public String getName() {
return name;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.