answer stringlengths 17 10.2M |
|---|
package org.apache.prepbuddy.rdds;
import com.n1analytics.paillier.PaillierContext;
import com.n1analytics.paillier.PaillierPublicKey;
import org.apache.prepbuddy.datacleansers.RowPurger;
import org.apache.prepbuddy.datacleansers.dedupe.DuplicationHandler;
import org.apache.prepbuddy.datacleansers.imputation.ImputationStrategy;
import org.apache.prepbuddy.encryptors.HomomorphicallyEncryptedRDD;
import org.apache.prepbuddy.exceptions.ApplicationException;
import org.apache.prepbuddy.exceptions.ErrorMessages;
import org.apache.prepbuddy.groupingops.Cluster;
import org.apache.prepbuddy.groupingops.ClusteringAlgorithm;
import org.apache.prepbuddy.groupingops.Clusters;
import org.apache.prepbuddy.groupingops.TextFacets;
import org.apache.prepbuddy.normalizers.NormalizationStrategy;
import org.apache.prepbuddy.smoothers.SmoothingMethod;
import org.apache.prepbuddy.transformations.MarkerPredicate;
import org.apache.prepbuddy.transformations.MergePlan;
import org.apache.prepbuddy.transformations.SplitPlan;
import org.apache.prepbuddy.typesystem.BaseDataType;
import org.apache.prepbuddy.typesystem.DataType;
import org.apache.prepbuddy.typesystem.FileType;
import org.apache.prepbuddy.typesystem.TypeAnalyzer;
import org.apache.prepbuddy.utils.EncryptionKeyPair;
import org.apache.prepbuddy.utils.PivotTable;
import org.apache.prepbuddy.utils.ReplacementFunction;
import org.apache.prepbuddy.utils.RowRecord;
import org.apache.spark.Partitioner;
import org.apache.spark.api.java.JavaDoubleRDD;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.*;
import org.apache.spark.rdd.RDD;
import org.apache.spark.storage.StorageLevel;
import scala.Tuple2;
import java.util.*;
public class TransformableRDD extends JavaRDD<String> {
private FileType fileType;
public TransformableRDD(JavaRDD rdd, FileType fileType) {
super(rdd.rdd(), rdd.rdd().elementClassTag());
this.fileType = fileType;
}
public TransformableRDD(JavaRDD rdd) {
this(rdd, FileType.CSV);
}
/**
* Returns a HomomorphicallyEncryptedRDD containing encrypted values of @columnIndex using @keyPair
*
* @param keyPair
* @param columnIndex
* @return HomomorphicallyEncryptedRDD
*/
public HomomorphicallyEncryptedRDD encryptHomomorphically(final EncryptionKeyPair keyPair, final int columnIndex) {
validateColumnIndex(columnIndex);
final PaillierPublicKey publicKey = keyPair.getPublicKey();
final PaillierContext signedContext = publicKey.createSignedContext();
JavaRDD encryptedRDD = this.map(new Function<String, String>() {
@Override
public String call(String row) throws Exception {
String[] values = fileType.parseRecord(row);
String numericValue = values[columnIndex];
values[columnIndex] = signedContext.encrypt(Double.parseDouble(numericValue)).toString();
return fileType.join(values);
}
});
return new HomomorphicallyEncryptedRDD(encryptedRDD, keyPair, fileType);
}
/**
* Returns a new TransformableRDD containing only unique elements.
* @return TransformableRDD
*/
public TransformableRDD deduplicate() {
JavaRDD transformed = DuplicationHandler.deduplicate(this);
return new TransformableRDD(transformed, fileType);
}
public TransformableRDD deduplicate(List<Integer> primaryColumnIndexes) {
JavaRDD transformed = DuplicationHandler.deduplicateByColumns(this, primaryColumnIndexes, fileType);
return new TransformableRDD(transformed, fileType);
}
/**
* Returns a new TransformableRDD containing the duplicate elements of this TransformableRDD.
* @return TransformableRDD
*/
public TransformableRDD getDuplicates() {
JavaRDD duplicates = DuplicationHandler.detectDuplicates(this);
return new TransformableRDD(duplicates);
}
public TransformableRDD getDuplicates(List<Integer> primaryColumnIndexes) {
JavaRDD transformed = DuplicationHandler.detectDuplicatesByColumns(this, primaryColumnIndexes, fileType);
return new TransformableRDD(transformed);
}
/**
* Returns a new TransformableRDD containing only the elements that satisfy the predicate.
* @param predicate
* @return TransformableRDD
*/
public TransformableRDD removeRows(RowPurger.Predicate predicate) {
JavaRDD<String> transformed = new RowPurger(predicate).apply(this, fileType);
return new TransformableRDD(transformed, fileType);
}
public TransformableRDD replace(final int columnIndex, final ReplacementFunction replacement) {
validateColumnIndex(columnIndex);
JavaRDD<String> transformed = this.map(new Function<String, String>() {
@Override
public String call(String record) throws Exception {
String[] recordAsArray = fileType.parseRecord(record);
recordAsArray[columnIndex] = replacement.replace(new RowRecord(recordAsArray));
return fileType.join(recordAsArray);
}
});
return new TransformableRDD(transformed, fileType);
}
/**
* Returns a new TextFacet containing the facets of @columnIndex
* @param columnIndex
* @return TextFacets
*/
public TextFacets listFacets(final int columnIndex) {
validateColumnIndex(columnIndex);
JavaPairRDD<String, Integer> columnValuePair = this.mapToPair(new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String record) throws Exception {
String[] columnValues = fileType.parseRecord(record);
return new Tuple2<>(columnValues[columnIndex], 1);
}
});
JavaPairRDD<String, Integer> facets = columnValuePair.reduceByKey(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer accumulator, Integer currentValue) throws Exception {
return accumulator + currentValue;
}
});
return new TextFacets(facets);
}
/**
* Returns a new TextFacet containing the facets of @columnIndexes
* @param columnIndexes
* @return TextFacets
*/
public TextFacets listFacets(final int[] columnIndexes) {
validateColumnIndex(columnIndexes);
JavaPairRDD<String, Integer> columnValuePair = this.mapToPair(new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String record) throws Exception {
String[] columnValues = fileType.parseRecord(record);
String joinValue = "";
for (int columnIndex : columnIndexes) {
joinValue += "\n" + columnValues[columnIndex];
}
return new Tuple2<>(joinValue.trim(), 1);
}
});
JavaPairRDD<String, Integer> facets = columnValuePair.reduceByKey(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer accumulator, Integer currentValue) throws Exception {
return accumulator + currentValue;
}
});
return new TextFacets(facets);
}
/**
* Returns Clusters that has all cluster of text of @columnIndex according to @algorithm
* @param columnIndex
* @param algorithm
* @return Clusters
*/
public Clusters clusters(int columnIndex, ClusteringAlgorithm algorithm) {
validateColumnIndex(columnIndex);
TextFacets textFacets = this.listFacets(columnIndex);
JavaPairRDD<String, Integer> rdd = textFacets.rdd();
List<Tuple2<String, Integer>> tuples = rdd.collect();
return algorithm.getClusters(tuples);
}
/**
* Returns a new TransformableRDD containing split columns using @splitPlan
* @param splitPlan
* @return TransformableRDD
*/
public TransformableRDD splitColumn(final SplitPlan splitPlan) {
JavaRDD<String> transformed = this.map(new Function<String, String>() {
@Override
public String call(String record) throws Exception {
String[] recordAsArray = fileType.parseRecord(record);
String[] transformedRow = splitPlan.splitColumn(recordAsArray);
return fileType.join(transformedRow);
}
});
return new TransformableRDD(transformed, fileType);
}
/**
* Returns a new TransformableRDD containing the merged column using @mergePlan
* @param mergePlan
* @return TransformableRDD
*/
public TransformableRDD mergeColumns(final MergePlan mergePlan) {
JavaRDD<String> transformed = this.map(new Function<String, String>() {
@Override
public String call(String record) throws Exception {
String[] recordAsArray = fileType.parseRecord(record);
String[] transformedRow = mergePlan.apply(recordAsArray);
return fileType.join(transformedRow);
}
});
return new TransformableRDD(transformed, fileType);
}
/**
* Returns a new TransformableRDD that contains records flagged by @symbol
* based on the evaluation of @markerPredicate
* @param symbol
* @param markerPredicate
* @return TransformableRDD
*/
public TransformableRDD flag(final String symbol, final MarkerPredicate markerPredicate) {
JavaRDD<String> transformed = this.map(new Function<String, String>() {
@Override
public String call(String row) throws Exception {
String newRow = fileType.appendDelimiter(row);
if (markerPredicate.evaluate(new RowRecord(fileType.parseRecord(row))))
return newRow + symbol;
return newRow;
}
});
return new TransformableRDD(transformed, fileType);
}
/**
* Returns a new TransformableRDD by applying the function on all rows marked as @flag
* @param flag
* @param symbolColumnIndex
* @param mapFunction
* @return TransformableRDD
*/
public TransformableRDD mapByFlag(final String flag, final int symbolColumnIndex, final Function<String, String> mapFunction) {
JavaRDD<String> mappedRDD = this.map(new Function<String, String>() {
@Override
public String call(String row) throws Exception {
String[] records = fileType.parseRecord(row);
String lastColumn = records[symbolColumnIndex];
return lastColumn.equals(flag) ? mapFunction.call(row) : row;
}
});
return new TransformableRDD(mappedRDD, fileType);
}
/**
* Returns a inferred DataType of given column index
* @param columnIndex
* @return DataType
*/
public DataType inferType(final int columnIndex) {
validateColumnIndex(columnIndex);
List<String> columnSamples = takeSampleSet(columnIndex);
TypeAnalyzer typeAnalyzer = new TypeAnalyzer(columnSamples);
return typeAnalyzer.getType();
}
/**
* Returns a new TransformableRDD by dropping the column at given index
* @param columnIndex
* @return TransformableRDD
*/
public TransformableRDD dropColumn(final int columnIndex) {
validateColumnIndex(columnIndex);
JavaRDD<String> mapped = this.map(new Function<String, String>() {
@Override
public String call(String row) throws Exception {
int newArrayIndex = 0;
String[] recordAsArray = fileType.parseRecord(row);
String[] newRecordArray = new String[recordAsArray.length - 1];
for (int i = 0; i < recordAsArray.length; i++) {
String columnValue = recordAsArray[i];
if (i != columnIndex)
newRecordArray[newArrayIndex++] = columnValue;
}
return fileType.join(newRecordArray);
}
});
return new TransformableRDD(mapped, fileType);
}
/**
* Returns a new TransformableRDD by replacing the @cluster's text with specified @newValue
* @param cluster
* @param newValue
* @param columnIndex
* @return TransformableRDD
*/
public TransformableRDD replaceValues(final Cluster cluster, final String newValue, final int columnIndex) {
validateColumnIndex(columnIndex);
JavaRDD<String> mapped = this.map(new Function<String, String>() {
@Override
public String call(String row) throws Exception {
String[] recordAsArray = fileType.parseRecord(row);
String value = recordAsArray[columnIndex];
if (cluster.containValue(value))
recordAsArray[columnIndex] = newValue;
return fileType.join(recordAsArray);
}
});
return new TransformableRDD(mapped, fileType);
}
/**
* Returns a new TransformableRDD by imputing missing values of the @columnIndex using the @strategy
* @param columnIndex
* @param strategy
* @return TransformableRDD
*/
public TransformableRDD impute(final int columnIndex, final ImputationStrategy strategy) {
validateColumnIndex(columnIndex);
strategy.prepareSubstitute(this, columnIndex);
JavaRDD<String> transformed = this.map(new Function<String, String>() {
@Override
public String call(String record) throws Exception {
String[] recordAsArray = fileType.parseRecord(record);
String value = recordAsArray[columnIndex];
String replacementValue = value;
if (value == null || value.trim().isEmpty()) {
replacementValue = strategy.handleMissingData(new RowRecord(recordAsArray));
}
recordAsArray[columnIndex] = replacementValue;
return fileType.join(recordAsArray);
}
});
return new TransformableRDD(transformed, fileType);
}
private void validateColumnIndex(int... columnIndexes) {
int size = getNumberOfColumns();
for (int index : columnIndexes) {
if (index < 0 || size <= index)
throw new ApplicationException(ErrorMessages.COLUMN_INDEX_OUT_OF_BOUND);
}
}
/**
* Returns a JavaDoubleRdd of given column index
* @param columnIndex
* @return JavaDoubleRDD
*/
public JavaDoubleRDD toDoubleRDD(final int columnIndex) {
if (!isNumericColumn(columnIndex))
throw new ApplicationException(ErrorMessages.COLUMN_VALUES_ARE_NOT_NUMERIC);
return this.mapToDouble(new DoubleFunction<String>() {
@Override
public double call(String row) throws Exception {
String[] recordAsArray = fileType.parseRecord(row);
String columnValue = recordAsArray[columnIndex];
if (!columnValue.trim().isEmpty())
return Double.parseDouble(recordAsArray[columnIndex]);
return 0;
}
});
}
private boolean isNumericColumn(int columnIndex) {
List<String> columnSamples = takeSampleSet(columnIndex);
BaseDataType baseType = BaseDataType.getBaseType(columnSamples);
return baseType.equals(BaseDataType.NUMERIC);
}
private List<String> takeSampleSet(int columnIndex) {
List<String> rowSamples = this.takeSample(false, 100);
List<String> columnSamples = new LinkedList<>();
for (String row : rowSamples) {
String[] strings = fileType.parseRecord(row);
columnSamples.add(strings[columnIndex]);
}
return columnSamples;
}
/**
* Returns a JavaDoubleRDD which is a product of the values in @fistColumn and @secondColumn
*
* @param fistColumn
* @param secondColumn
* @return JavaDoubleRDD
*/
public JavaDoubleRDD multiplyColumns(final int fistColumn, final int secondColumn) {
if (!isNumericColumn(fistColumn) || !isNumericColumn(secondColumn))
throw new ApplicationException(ErrorMessages.COLUMN_VALUES_ARE_NOT_NUMERIC);
return this.mapToDouble(new DoubleFunction<String>() {
@Override
public double call(String row) throws Exception {
String[] recordAsArray = fileType.parseRecord(row);
String columnValue = recordAsArray[fistColumn];
String otherColumnValue = recordAsArray[secondColumn];
if (columnValue.trim().isEmpty() || otherColumnValue.trim().isEmpty())
return 0;
return Double.parseDouble(recordAsArray[fistColumn]) * Double.parseDouble(recordAsArray[secondColumn]);
}
});
}
/**
* Returns a new TransformableRDD by normalizing values of the given column using different Normalizers
* @param columnIndex
* @param normalizer
* @return TransformableRDD
*/
public TransformableRDD normalize(final int columnIndex, final NormalizationStrategy normalizer) {
validateColumnIndex(columnIndex);
normalizer.prepare(this, columnIndex);
JavaRDD<String> normalized = this.map(new Function<String, String>() {
@Override
public String call(String record) throws Exception {
String[] columns = fileType.parseRecord(record);
String normalized = normalizer.normalize(columns[columnIndex]);
columns[columnIndex] = normalized;
return fileType.join(columns);
}
});
return new TransformableRDD(normalized);
}
/**
* Returns a JavaRDD of given column
* @param columnIndex
* @return JavaRDD<String>
*/
public JavaRDD<String> select(final int columnIndex) {
return map(new Function<String, String>() {
@Override
public String call(String record) throws Exception {
return fileType.parseRecord(record)[columnIndex];
}
});
}
/**
* Returns the number of columns in this RDD
*
* @return int
*/
public int getNumberOfColumns() {
List<String> sample = this.takeSample(false, 5);
Map<Integer, Integer> noOfColsAndCount = new HashMap<>();
for (String row : sample) {
Set<Integer> lengths = noOfColsAndCount.keySet();
int rowLength = fileType.parseRecord(row).length;
if (!lengths.contains(rowLength))
noOfColsAndCount.put(rowLength, 1);
else {
Integer count = noOfColsAndCount.get(rowLength);
noOfColsAndCount.put(rowLength, count + 1);
}
}
return getHighestCountKey(noOfColsAndCount);
}
private int getHighestCountKey(Map<Integer, Integer> lengthWithCount) {
Integer highest = 0;
Integer highestKey = 0;
for (Integer key : lengthWithCount.keySet()) {
Integer count = lengthWithCount.get(key);
if (highest < count) {
highest = count;
highestKey = key;
}
}
return highestKey;
}
/**
* Generates a PivotTable by pivoting data in the pivotalColumn
* @param pivotalColumn
* @param independentColumnIndexes
* @return PivotTable
*/
public PivotTable pivotByCount(int pivotalColumn, int[] independentColumnIndexes) {
PivotTable<Integer> pivotTable = new PivotTable<>(0);
for (int index : independentColumnIndexes) {
TextFacets facets = listFacets(new int[]{pivotalColumn, index});
List<Tuple2<String, Integer>> tuples = facets.rdd().collect();
for (Tuple2<String, Integer> tuple : tuples) {
String[] split = tuple._1().split("\n");
pivotTable.addEntry(split[0], split[1], tuple._2());
}
}
return pivotTable;
}
/**
* Returns a new TransformableRDD containing values of @columnIndexes
* @param columnIndexes
* @return TransformableRDD
*/
public TransformableRDD select(final int... columnIndexes) {
validateColumnIndex(columnIndexes);
JavaRDD<String> reducedRDD = map(new Function<String, String>() {
@Override
public String call(String record) throws Exception {
String[] reducedRecord = new String[columnIndexes.length];
String[] columns = fileType.parseRecord(record);
for (int i = 0; i < columnIndexes.length; i++)
reducedRecord[i] = (columns[columnIndexes[i]]);
return fileType.join(reducedRecord);
}
});
return new TransformableRDD(reducedRDD, fileType);
}
/**
* Returns a new JavaRDD containing smoothed values of @columnIndex using @smoothingMethod
* @param columnIndex
* @param smoothingMethod
* @return JavaRDD<Double>
*/
public JavaRDD<Double> smooth(int columnIndex, SmoothingMethod smoothingMethod) {
JavaRDD<String> rdd = this.select(columnIndex);
return smoothingMethod.smooth(rdd);
}
@Override
public TransformableRDD map(Function function) {
return new TransformableRDD(super.map(function), fileType);
}
@Override
public TransformableRDD filter(Function function) {
return new TransformableRDD(super.filter(function), fileType);
}
@Override
public TransformableRDD cache() {
return new TransformableRDD(super.cache(), fileType);
}
@Override
public TransformableRDD coalesce(int numPartitions) {
return new TransformableRDD(super.coalesce(numPartitions), fileType);
}
@Override
public TransformableRDD coalesce(int numPartitions, boolean shuffle) {
return new TransformableRDD(super.coalesce(numPartitions, shuffle), fileType);
}
@Override
public TransformableRDD distinct() {
return new TransformableRDD(super.distinct(), fileType);
}
@Override
public TransformableRDD distinct(int numPartition) {
return new TransformableRDD(super.distinct(numPartition), fileType);
}
@Override
public TransformableRDD flatMap(FlatMapFunction flatmapFunction) {
return new TransformableRDD(super.flatMap(flatmapFunction), fileType);
}
@Override
public TransformableRDD intersection(JavaRDD other) {
return new TransformableRDD(super.intersection(other), fileType);
}
public TransformableRDD intersection(TransformableRDD other) {
return new TransformableRDD(super.intersection(other), fileType);
}
@Override
public TransformableRDD persist(StorageLevel newLevel) {
return new TransformableRDD(super.persist(newLevel), fileType);
}
@Override
public TransformableRDD unpersist() {
return new TransformableRDD(super.unpersist(), fileType);
}
@Override
public TransformableRDD unpersist(boolean blocking) {
return new TransformableRDD(super.unpersist(blocking), fileType);
}
@Override
public TransformableRDD union(JavaRDD other) {
return new TransformableRDD(super.union(other), fileType);
}
public TransformableRDD union(TransformableRDD other) {
return new TransformableRDD(super.union(other), fileType);
}
@Override
public TransformableRDD mapPartitions(FlatMapFunction flatMapFunction) {
return new TransformableRDD(super.mapPartitions(flatMapFunction), fileType);
}
@Override
public TransformableRDD mapPartitions(FlatMapFunction flatMapFunction, boolean preservesPartitioning) {
return new TransformableRDD(super.mapPartitions(flatMapFunction, preservesPartitioning), fileType);
}
@Override
public TransformableRDD mapPartitionsWithIndex(Function2 function, boolean preservesPartitioning) {
return new TransformableRDD(super.mapPartitionsWithIndex(function, preservesPartitioning), fileType);
}
@Override
public TransformableRDD sortBy(Function function, boolean ascending, int numPartitions) {
return new TransformableRDD(super.sortBy(function, ascending, numPartitions), fileType);
}
@Override
public TransformableRDD setName(String name) {
return new TransformableRDD(super.setName(name), fileType);
}
@Override
public TransformableRDD subtract(JavaRDD other) {
return new TransformableRDD(super.subtract(other), fileType);
}
@Override
public TransformableRDD subtract(JavaRDD other, int numPartitions) {
return new TransformableRDD(super.subtract(other, numPartitions), fileType);
}
@Override
public TransformableRDD subtract(JavaRDD other, Partitioner partitioner) {
return new TransformableRDD(super.subtract(other, partitioner), fileType);
}
@Override
public TransformableRDD sample(boolean withReplacement, double fraction) {
return new TransformableRDD(super.sample(withReplacement, fraction), fileType);
}
@Override
public TransformableRDD sample(boolean withReplacement, double fraction, long seed) {
return new TransformableRDD(super.sample(withReplacement, fraction, seed), fileType);
}
@Override
public TransformableRDD repartition(int numPartitions) {
return new TransformableRDD(super.repartition(numPartitions), fileType);
}
@Override
public TransformableRDD pipe(String command) {
return new TransformableRDD(super.pipe(command), fileType);
}
@Override
public TransformableRDD pipe(List<String> command) {
return new TransformableRDD(super.pipe(command), fileType);
}
@Override
public TransformableRDD pipe(List<String> command, Map<String, String> env) {
return new TransformableRDD(super.pipe(command, env), fileType);
}
@Override
public TransformableRDD wrapRDD(RDD rdd) {
return new TransformableRDD(super.wrapRDD(rdd), fileType);
}
} |
package org.b3log.symphony.service;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.Latkes;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.*;
import org.b3log.latke.repository.annotation.Transactional;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.Ids;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.Strings;
import org.b3log.symphony.model.*;
import org.b3log.symphony.repository.*;
import org.b3log.symphony.util.Crypts;
import org.b3log.symphony.util.Geos;
import org.b3log.symphony.util.Sessions;
import org.b3log.symphony.util.Symphonys;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Pattern;
@Service
public class UserMgmtService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(UserMgmtService.class.getName());
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* Option repository.
*/
@Inject
private OptionRepository optionRepository;
/**
* Tag repository.
*/
@Inject
private TagRepository tagRepository;
/**
* User-Tag repository.
*/
@Inject
private UserTagRepository userTagRepository;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Pointtransfer management service.
*/
@Inject
private PointtransferMgmtService pointtransferMgmtService;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Notification management service.
*/
@Inject
private NotificationMgmtService notificationMgmtService;
/**
* Tries to login with cookie.
*
* @param request the specified request
* @param response the specified response
* @return returns {@code true} if logged in, returns {@code false} otherwise
*/
public boolean tryLogInWithCookie(final HttpServletRequest request, final HttpServletResponse response) {
final Cookie[] cookies = request.getCookies();
if (null == cookies || 0 == cookies.length) {
return false;
}
try {
for (final Cookie cookie : cookies) {
if (!"b3log-latke".equals(cookie.getName())) {
continue;
}
final String value = Crypts.decryptByAES(cookie.getValue(), Symphonys.get("cookie.secret"));
final JSONObject cookieJSONObject = new JSONObject(value);
final String userId = cookieJSONObject.optString(Keys.OBJECT_ID);
if (Strings.isEmptyOrNull(userId)) {
break;
}
final JSONObject user = userRepository.get(userId);
if (null == user) {
break;
}
final String ip = Requests.getRemoteAddr(request);
if (UserExt.USER_STATUS_C_INVALID == user.optInt(UserExt.USER_STATUS)
|| UserExt.USER_STATUS_C_INVALID_LOGIN == user.optInt(UserExt.USER_STATUS)) {
Sessions.logout(request, response);
updateOnlineStatus(userId, ip, false);
return false;
}
final String userPassword = user.optString(User.USER_PASSWORD);
final String token = cookieJSONObject.optString(Common.TOKEN);
final String password = StringUtils.substringBeforeLast(token, ":");
if (userPassword.equals(password)) {
Sessions.login(request, response, user, cookieJSONObject.optBoolean(Common.REMEMBER_LOGIN));
updateOnlineStatus(userId, ip, true);
LOGGER.log(Level.TRACE, "Logged in with cookie[userId={0}]", userId);
return true;
}
}
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Parses cookie failed, clears the cookie[name=b3log-latke]");
final Cookie cookie = new Cookie("b3log-latke", null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
return false;
}
/**
* Updates a user's online status and saves the login time and IP.
*
* @param userId the specified user id
* @param ip the specified IP, could be "" if the {@code onlineFlag} is {@code false}
* @param onlineFlag the specified online flag
* @throws ServiceException service exception
*/
public void updateOnlineStatus(final String userId, final String ip, final boolean onlineFlag) throws ServiceException {
Transaction transaction = null;
try {
final JSONObject address = Geos.getAddress(ip);
final JSONObject user = userRepository.get(userId);
if (null == user) {
return;
}
if (null != address) {
final String country = address.optString(Common.COUNTRY);
final String province = address.optString(Common.PROVINCE);
final String city = address.optString(Common.CITY);
user.put(UserExt.USER_COUNTRY, country);
user.put(UserExt.USER_PROVINCE, province);
user.put(UserExt.USER_CITY, city);
}
transaction = userRepository.beginTransaction();
user.put(UserExt.USER_ONLINE_FLAG, onlineFlag);
user.put(UserExt.USER_LATEST_LOGIN_TIME, System.currentTimeMillis());
if (onlineFlag) {
user.put(UserExt.USER_LATEST_LOGIN_IP, ip);
}
userRepository.update(userId, user);
transaction.commit();
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Updates user online status failed [id=" + userId + "]", e);
if (null != transaction && transaction.isActive()) {
transaction.rollback();
}
throw new ServiceException(e);
}
}
/**
* Updates a user's profiles by the specified request json object.
*
* @param requestJSONObject the specified request json object (user), for example,
* "oId": "",
* "userNickname": "",
* "userTags": "",
* "userURL": "",
* "userQQ": "",
* "userIntro": "",
* "userAvatarType": int,
* "userAvatarURL": "",
* "userCommentViewMode": int
* @throws ServiceException service exception
*/
public void updateProfiles(final JSONObject requestJSONObject) throws ServiceException {
final Transaction transaction = userRepository.beginTransaction();
try {
final String oldUserId = requestJSONObject.optString(Keys.OBJECT_ID);
final JSONObject oldUser = userRepository.get(oldUserId);
if (null == oldUser) {
throw new ServiceException(langPropsService.get("updateFailLabel"));
}
// Tag
final String userTags = requestJSONObject.optString(UserExt.USER_TAGS);
oldUser.put(UserExt.USER_TAGS, userTags);
tag(oldUser);
// Update
oldUser.put(UserExt.USER_NICKNAME, requestJSONObject.optString(UserExt.USER_NICKNAME));
oldUser.put(User.USER_URL, requestJSONObject.optString(User.USER_URL));
oldUser.put(UserExt.USER_QQ, requestJSONObject.optString(UserExt.USER_QQ));
oldUser.put(UserExt.USER_INTRO, requestJSONObject.optString(UserExt.USER_INTRO));
oldUser.put(UserExt.USER_AVATAR_TYPE, requestJSONObject.optString(UserExt.USER_AVATAR_TYPE));
oldUser.put(UserExt.USER_AVATAR_URL, requestJSONObject.optString(UserExt.USER_AVATAR_URL));
oldUser.put(UserExt.USER_COMMENT_VIEW_MODE, requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE));
oldUser.put(UserExt.USER_UPDATE_TIME, System.currentTimeMillis());
userRepository.update(oldUserId, oldUser);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates user profiles failed", e);
throw new ServiceException(langPropsService.get("updateFailLabel"));
}
}
/**
* Updates a user's sync B3log settings by the specified request json object.
*
* @param requestJSONObject the specified request json object (user), for example,
* "oId": "",
* "userB3Key": "",
* "userB3ClientAddArticleURL": "",
* "userB3ClientUpdateArticleURL": "",
* "userB3ClientAddCommentURL": "",
* "syncWithSymphonyClient": boolean // optional, default to false
* @throws ServiceException service exception
*/
public void updateSyncB3(final JSONObject requestJSONObject) throws ServiceException {
final Transaction transaction = userRepository.beginTransaction();
try {
final String oldUserId = requestJSONObject.optString(Keys.OBJECT_ID);
final JSONObject oldUser = userRepository.get(oldUserId);
if (null == oldUser) {
throw new ServiceException(langPropsService.get("updateFailLabel"));
}
// Update
oldUser.put(UserExt.USER_B3_KEY, requestJSONObject.optString(UserExt.USER_B3_KEY));
oldUser.put(UserExt.USER_B3_CLIENT_ADD_ARTICLE_URL, requestJSONObject.optString(UserExt.USER_B3_CLIENT_ADD_ARTICLE_URL));
oldUser.put(UserExt.USER_B3_CLIENT_UPDATE_ARTICLE_URL, requestJSONObject.optString(UserExt.USER_B3_CLIENT_UPDATE_ARTICLE_URL));
oldUser.put(UserExt.USER_B3_CLIENT_ADD_COMMENT_URL, requestJSONObject.optString(UserExt.USER_B3_CLIENT_ADD_COMMENT_URL));
oldUser.put(UserExt.SYNC_TO_CLIENT, requestJSONObject.optBoolean(UserExt.SYNC_TO_CLIENT, false));
userRepository.update(oldUserId, oldUser);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates user sync b3log settings failed", e);
throw new ServiceException(e);
}
}
/**
* Updates a user's password by the specified request json object.
*
* @param requestJSONObject the specified request json object (user), for example,
* "oId": "",
* "userPassword": "", // Hashed
* @throws ServiceException service exception
*/
public void updatePassword(final JSONObject requestJSONObject) throws ServiceException {
final Transaction transaction = userRepository.beginTransaction();
try {
final String oldUserId = requestJSONObject.optString(Keys.OBJECT_ID);
final JSONObject oldUser = userRepository.get(oldUserId);
if (null == oldUser) {
throw new ServiceException(langPropsService.get("updateFailLabel"));
}
// Update
oldUser.put(User.USER_PASSWORD, requestJSONObject.optString(User.USER_PASSWORD));
userRepository.update(oldUserId, oldUser);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates user password failed", e);
throw new ServiceException(e);
}
}
/**
* Adds a user with the specified request json object.
*
* @param requestJSONObject the specified request json object, for example,
* "userName": "",
* "userEmail": "",
* "userPassword": "", // Hashed
* "userLanguage": "",
* "userAppRole": int, // optional, default to 0
* "userRole": "", // optional, uses {@value Role#ROLE_ID_C_DEFAULT} instead if not specified
* "userStatus": int, // optional, uses {@value UserExt#USER_STATUS_C_NOT_VERIFIED} instead if not specified
* ,see {@link User} for more details
* @return generated user id
* @throws ServiceException if user name or email duplicated, or repository exception
*/
public synchronized String addUser(final JSONObject requestJSONObject) throws ServiceException {
final Transaction transaction = userRepository.beginTransaction();
try {
final String userEmail = requestJSONObject.optString(User.USER_EMAIL).trim().toLowerCase();
final String userName = requestJSONObject.optString(User.USER_NAME);
JSONObject user = userRepository.getByName(userName);
if (null != user && (UserExt.USER_STATUS_C_VALID == user.optInt(UserExt.USER_STATUS)
|| UserExt.NULL_USER_NAME.equals(userName))) {
if (transaction.isActive()) {
transaction.rollback();
}
throw new ServiceException(langPropsService.get("duplicatedUserNameLabel") + " [" + userName + "]");
}
boolean toUpdate = false;
String ret = null;
String avatarURL = null;
user = userRepository.getByEmail(userEmail);
int userNo = 0;
if (null != user) {
if (UserExt.USER_STATUS_C_VALID == user.optInt(UserExt.USER_STATUS)) {
if (transaction.isActive()) {
transaction.rollback();
}
throw new ServiceException(langPropsService.get("duplicatedEmailLabel"));
}
toUpdate = true;
ret = user.optString(Keys.OBJECT_ID);
userNo = user.optInt(UserExt.USER_NO);
avatarURL = user.optString(UserExt.USER_AVATAR_URL);
}
user = new JSONObject();
user.put(User.USER_NAME, userName);
user.put(User.USER_EMAIL, userEmail);
user.put(UserExt.USER_APP_ROLE, requestJSONObject.optInt(UserExt.USER_APP_ROLE));
user.put(User.USER_PASSWORD, requestJSONObject.optString(User.USER_PASSWORD));
user.put(User.USER_ROLE, requestJSONObject.optString(User.USER_ROLE, Role.ROLE_ID_C_DEFAULT));
user.put(User.USER_URL, "");
user.put(UserExt.USER_ARTICLE_COUNT, 0);
user.put(UserExt.USER_COMMENT_COUNT, 0);
user.put(UserExt.USER_TAG_COUNT, 0);
user.put(UserExt.USER_B3_KEY, "");
user.put(UserExt.USER_B3_CLIENT_ADD_ARTICLE_URL, "");
user.put(UserExt.USER_B3_CLIENT_UPDATE_ARTICLE_URL, "");
user.put(UserExt.USER_B3_CLIENT_ADD_COMMENT_URL, "");
user.put(UserExt.USER_INTRO, "");
user.put(UserExt.USER_NICKNAME, "");
user.put(UserExt.USER_AVATAR_TYPE, UserExt.USER_AVATAR_TYPE_C_UPLOAD);
user.put(UserExt.USER_QQ, "");
user.put(UserExt.USER_ONLINE_FLAG, false);
user.put(UserExt.USER_LATEST_ARTICLE_TIME, 0L);
user.put(UserExt.USER_LATEST_CMT_TIME, 0L);
user.put(UserExt.USER_LATEST_LOGIN_TIME, 0L);
user.put(UserExt.USER_LATEST_LOGIN_IP, "");
user.put(UserExt.USER_CHECKIN_TIME, 0);
user.put(UserExt.USER_CURRENT_CHECKIN_STREAK_START, 0);
user.put(UserExt.USER_CURRENT_CHECKIN_STREAK_END, 0);
user.put(UserExt.USER_LONGEST_CHECKIN_STREAK_START, 0);
user.put(UserExt.USER_LONGEST_CHECKIN_STREAK_END, 0);
user.put(UserExt.USER_LONGEST_CHECKIN_STREAK, 0);
user.put(UserExt.USER_CURRENT_CHECKIN_STREAK, 0);
user.put(UserExt.USER_POINT, 0);
user.put(UserExt.USER_USED_POINT, 0);
user.put(UserExt.USER_JOIN_POINT_RANK, UserExt.USER_JOIN_POINT_RANK_C_JOIN);
user.put(UserExt.USER_JOIN_USED_POINT_RANK, UserExt.USER_JOIN_USED_POINT_RANK_C_JOIN);
user.put(UserExt.USER_TAGS, "");
user.put(UserExt.USER_SKIN, Symphonys.get("skinDirName")); // TODO: set default skin by app role
user.put(UserExt.USER_MOBILE_SKIN, Symphonys.get("mobileSkinDirName"));
user.put(UserExt.USER_COUNTRY, "");
user.put(UserExt.USER_PROVINCE, "");
user.put(UserExt.USER_CITY, "");
user.put(UserExt.USER_UPDATE_TIME, 0L);
user.put(UserExt.USER_GEO_STATUS, UserExt.USER_GEO_STATUS_C_PUBLIC);
user.put(UserExt.SYNC_TO_CLIENT, false);
final int status = requestJSONObject.optInt(UserExt.USER_STATUS, UserExt.USER_STATUS_C_NOT_VERIFIED);
user.put(UserExt.USER_STATUS, status);
user.put(UserExt.USER_COMMENT_VIEW_MODE, UserExt.USER_COMMENT_VIEW_MODE_C_REALTIME);
user.put(UserExt.USER_ONLINE_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_ARTICLE_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_COMMENT_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_FOLLOWING_ARTICLE_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_FOLLOWING_TAG_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_FOLLOWING_USER_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_FOLLOWER_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_POINT_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_TIMELINE_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_UA_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_FORGE_LINK_STATUS, UserExt.USER_XXX_STATUS_C_PUBLIC);
user.put(UserExt.USER_NOTIFY_STATUS, UserExt.USER_XXX_STATUS_C_ENABLED);
user.put(UserExt.USER_SUB_MAIL_STATUS, UserExt.USER_XXX_STATUS_C_ENABLED);
user.put(UserExt.USER_LIST_PAGE_SIZE, Symphonys.getInt("indexArticlesCnt"));
user.put(UserExt.USER_AVATAR_VIEW_MODE, UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL);
user.put(UserExt.USER_SUB_MAIL_SEND_TIME, System.currentTimeMillis());
user.put(UserExt.USER_KEYBOARD_SHORTCUTS_STATUS, UserExt.USER_XXX_STATUS_C_DISABLED);
final JSONObject optionLanguage = optionRepository.get(Option.ID_C_MISC_LANGUAGE);
final String adminSpecifiedLang = optionLanguage.optString(Option.OPTION_VALUE);
if ("0".equals(adminSpecifiedLang)) {
user.put(UserExt.USER_LANGUAGE, requestJSONObject.optString(UserExt.USER_LANGUAGE, "zh_CN"));
} else {
user.put(UserExt.USER_LANGUAGE, adminSpecifiedLang);
}
user.put(UserExt.USER_TIMEZONE,
requestJSONObject.optString(UserExt.USER_TIMEZONE, TimeZone.getDefault().getID()));
if (toUpdate) {
user.put(UserExt.USER_NO, userNo);
if (!Symphonys.get("defaultThumbnailURL").equals(avatarURL)) { // generate/upload avatar succ
if (Symphonys.getBoolean("qiniu.enabled")) {
user.put(UserExt.USER_AVATAR_URL, Symphonys.get("qiniu.domain") + "/avatar/" + ret + "?"
+ new Date().getTime());
} else {
user.put(UserExt.USER_AVATAR_URL, avatarURL + "?" + new Date().getTime());
}
userRepository.update(ret, user);
}
} else {
ret = Ids.genTimeMillisId();
user.put(Keys.OBJECT_ID, ret);
try {
final BufferedImage img = avatarQueryService.createAvatar(MD5.hash(ret), 512);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
final byte[] bytes = baos.toByteArray();
baos.close();
if (Symphonys.getBoolean("qiniu.enabled")) {
final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey"));
final UploadManager uploadManager = new UploadManager();
uploadManager.put(bytes, "avatar/" + ret, auth.uploadToken(Symphonys.get("qiniu.bucket")),
null, "image/jpeg", false);
user.put(UserExt.USER_AVATAR_URL, Symphonys.get("qiniu.domain") + "/avatar/" + ret + "?"
+ new Date().getTime());
} else {
final String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
final OutputStream output = new FileOutputStream(Symphonys.get("upload.dir") + fileName);
IOUtils.write(bytes, output);
IOUtils.closeQuietly(output);
user.put(UserExt.USER_AVATAR_URL, Latkes.getServePath() + "/upload/" + fileName);
}
} catch (final IOException e) {
LOGGER.log(Level.ERROR, "Generates avatar error, using default thumbnail instead", e);
user.put(UserExt.USER_AVATAR_URL, Symphonys.get("defaultThumbnailURL"));
}
final JSONObject memberCntOption = optionRepository.get(Option.ID_C_STATISTIC_MEMBER_COUNT);
final int memberCount = memberCntOption.optInt(Option.OPTION_VALUE) + 1; // Updates stat. (member count +1)
user.put(UserExt.USER_NO, memberCount);
userRepository.add(user);
memberCntOption.put(Option.OPTION_VALUE, String.valueOf(memberCount));
optionRepository.update(Option.ID_C_STATISTIC_MEMBER_COUNT, memberCntOption);
}
transaction.commit();
if (UserExt.USER_STATUS_C_VALID == status) {
// Point
pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, ret,
Pointtransfer.TRANSFER_TYPE_C_INIT, Pointtransfer.TRANSFER_SUM_C_INIT, ret, System.currentTimeMillis());
// Occupy the username, defeat others
final Transaction trans = userRepository.beginTransaction();
try {
final Query query = new Query();
final List<Filter> filters = new ArrayList<>();
filters.add(new PropertyFilter(User.USER_NAME, FilterOperator.EQUAL, userName));
filters.add(new PropertyFilter(UserExt.USER_STATUS, FilterOperator.EQUAL,
UserExt.USER_STATUS_C_NOT_VERIFIED));
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
final JSONArray others = userRepository.get(query).optJSONArray(Keys.RESULTS);
for (int i = 0; i < others.length(); i++) {
final JSONObject u = others.optJSONObject(i);
final String id = u.optString(Keys.OBJECT_ID);
u.put(User.USER_NAME, UserExt.NULL_USER_NAME);
u.put(UserExt.USER_STATUS, UserExt.USER_STATUS_C_NOT_VERIFIED);
userRepository.update(id, u);
LOGGER.log(Level.INFO, "Defeated a user [email=" + u.optString(User.USER_EMAIL) + "]");
}
trans.commit();
} catch (final RepositoryException e) {
if (trans.isActive()) {
trans.rollback();
}
LOGGER.log(Level.ERROR, "Defeat others error", e);
}
final JSONObject notification = new JSONObject();
notification.put(Notification.NOTIFICATION_USER_ID, ret);
notification.put(Notification.NOTIFICATION_DATA_ID, "");
notificationMgmtService.addSysAnnounceNewUserNotification(notification);
}
return ret;
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Adds a user failed", e);
throw new ServiceException(e);
}
}
/**
* Removes a user specified by the given user id.
*
* @param userId the given user id
* @throws ServiceException service exception
*/
public void removeUser(final String userId) throws ServiceException {
final Transaction transaction = userRepository.beginTransaction();
try {
userRepository.remove(userId);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Removes a user[id=" + userId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Updates the specified user by the given user id.
*
* @param userId the given user id
* @param user the specified user
* @throws ServiceException service exception
*/
public void updateUser(final String userId, final JSONObject user) throws ServiceException {
final Transaction transaction = userRepository.beginTransaction();
try {
userRepository.update(userId, user);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates a user[id=" + userId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Updates the specified user's email by the given user id.
*
* @param userId the given user id
* @param user the specified user, contains the new email
* @throws ServiceException service exception
*/
public void updateUserEmail(final String userId, final JSONObject user) throws ServiceException {
final String newEmail = user.optString(User.USER_EMAIL);
final Transaction transaction = userRepository.beginTransaction();
try {
if (null != userRepository.getByEmail(newEmail)) {
throw new ServiceException(langPropsService.get("duplicatedEmailLabel") + " [" + newEmail + "]");
}
// Update relevent comments of the user
final Query commentQuery = new Query().setFilter(new PropertyFilter(Comment.COMMENT_AUTHOR_ID, FilterOperator.EQUAL, userId));
final JSONObject commentResult = commentRepository.get(commentQuery);
final JSONArray comments = commentResult.optJSONArray(Keys.RESULTS);
for (int i = 0; i < comments.length(); i++) {
final JSONObject comment = comments.optJSONObject(i);
comment.put(Comment.COMMENT_AUTHOR_EMAIL, newEmail);
commentRepository.update(comment.optString(Keys.OBJECT_ID), comment);
}
// Update relevent articles of the user
final Query articleQuery = new Query().setFilter(new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, userId));
final JSONObject articleResult = articleRepository.get(articleQuery);
final JSONArray articles = articleResult.optJSONArray(Keys.RESULTS);
for (int i = 0; i < articles.length(); i++) {
final JSONObject article = articles.optJSONObject(i);
article.put(Article.ARTICLE_AUTHOR_EMAIL, newEmail);
articleRepository.update(article.optString(Keys.OBJECT_ID), article);
}
// Update the user
userRepository.update(userId, user);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates email of the user[id=" + userId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Updates the specified user's username by the given user id.
*
* @param userId the given user id
* @param user the specified user, contains the new username
* @throws ServiceException service exception
*/
public void updateUserName(final String userId, final JSONObject user) throws ServiceException {
final String newUserName = user.optString(User.USER_NAME);
final Transaction transaction = userRepository.beginTransaction();
try {
if (!UserExt.NULL_USER_NAME.equals(newUserName) && null != userRepository.getByName(newUserName)) {
throw new ServiceException(langPropsService.get("duplicatedUserNameLabel") + " [" + newUserName + "]");
}
// Update the user
userRepository.update(userId, user);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates username of the user[id=" + userId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Resets unverified users.
*/
@Transactional
public void resetUnverifiedUsers() {
final Date now = new Date();
final long yesterdayTime = DateUtils.addDays(now, -1).getTime();
final List<Filter> filters = new ArrayList<>();
filters.add(new PropertyFilter(UserExt.USER_STATUS, FilterOperator.EQUAL, UserExt.USER_STATUS_C_NOT_VERIFIED));
filters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.LESS_THAN_OR_EQUAL, yesterdayTime));
filters.add(new PropertyFilter(User.USER_NAME, FilterOperator.NOT_EQUAL, UserExt.NULL_USER_NAME));
final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
try {
final JSONObject result = userRepository.get(query);
final JSONArray users = result.optJSONArray(Keys.RESULTS);
for (int i = 0; i < users.length(); i++) {
final JSONObject user = users.optJSONObject(i);
final String id = user.optString(Keys.OBJECT_ID);
user.put(User.USER_NAME, UserExt.NULL_USER_NAME);
userRepository.update(id, user);
LOGGER.log(Level.INFO, "Reset unverified user [email=" + user.optString(User.USER_EMAIL));
}
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Reset unverified users failed", e);
}
}
/**
* Tags the specified user with the specified tag titles.
*
* @param user the specified article
* @throws RepositoryException repository exception
*/
private synchronized void tag(final JSONObject user) throws RepositoryException {
// Clear
final List<Filter> filters = new ArrayList<>();
filters.add(new PropertyFilter(User.USER + '_' + Keys.OBJECT_ID,
FilterOperator.EQUAL, user.optString(Keys.OBJECT_ID)));
filters.add(new PropertyFilter(Common.TYPE, FilterOperator.EQUAL, Tag.TAG_TYPE_C_USER_SELF));
final Query query = new Query();
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
final JSONArray results = userTagRepository.get(query).optJSONArray(Keys.RESULTS);
for (int i = 0; i < results.length(); i++) {
final JSONObject rel = results.optJSONObject(i);
final String id = rel.optString(Keys.OBJECT_ID);
userTagRepository.remove(id);
}
// Add
String tagTitleStr = user.optString(UserExt.USER_TAGS);
final String[] tagTitles = tagTitleStr.split(",");
for (final String title : tagTitles) {
final String tagTitle = title.trim();
JSONObject tag = tagRepository.getByTitle(tagTitle);
String tagId;
if (null == tag) {
LOGGER.log(Level.TRACE, "Found a new tag[title={0}] in user [name={1}]",
new Object[]{tagTitle, user.optString(User.USER_NAME)});
tag = new JSONObject();
tag.put(Tag.TAG_TITLE, tagTitle);
String tagURI = tagTitle;
try {
tagURI = URLEncoder.encode(tagTitle, "UTF-8");
} catch (final UnsupportedEncodingException e) {
LOGGER.log(Level.ERROR, "Encode tag title [" + tagTitle + "] error", e);
}
tag.put(Tag.TAG_URI, tagURI);
tag.put(Tag.TAG_CSS, "");
tag.put(Tag.TAG_REFERENCE_CNT, 0);
tag.put(Tag.TAG_COMMENT_CNT, 0);
tag.put(Tag.TAG_FOLLOWER_CNT, 0);
tag.put(Tag.TAG_LINK_CNT, 0);
tag.put(Tag.TAG_DESCRIPTION, "");
tag.put(Tag.TAG_ICON_PATH, "");
tag.put(Tag.TAG_STATUS, 0);
tag.put(Tag.TAG_GOOD_CNT, 0);
tag.put(Tag.TAG_BAD_CNT, 0);
tag.put(Tag.TAG_SEO_TITLE, tagTitle);
tag.put(Tag.TAG_SEO_KEYWORDS, tagTitle);
tag.put(Tag.TAG_SEO_DESC, "");
tag.put(Tag.TAG_RANDOM_DOUBLE, Math.random());
tagId = tagRepository.add(tag);
final JSONObject tagCntOption = optionRepository.get(Option.ID_C_STATISTIC_TAG_COUNT);
final int tagCnt = tagCntOption.optInt(Option.OPTION_VALUE);
tagCntOption.put(Option.OPTION_VALUE, tagCnt + 1);
optionRepository.update(Option.ID_C_STATISTIC_TAG_COUNT, tagCntOption);
// User-Tag relation (creator)
final JSONObject userTagRelation = new JSONObject();
userTagRelation.put(Tag.TAG + '_' + Keys.OBJECT_ID, tagId);
userTagRelation.put(User.USER + '_' + Keys.OBJECT_ID, user.optString(Keys.OBJECT_ID));
userTagRelation.put(Common.TYPE, Tag.TAG_TYPE_C_CREATOR);
userTagRepository.add(userTagRelation);
} else {
tagId = tag.optString(Keys.OBJECT_ID);
LOGGER.log(Level.TRACE, "Found a existing tag[title={0}, id={1}] in user[name={2}]",
tag.optString(Tag.TAG_TITLE), tag.optString(Keys.OBJECT_ID), user.optString(User.USER_NAME));
tagTitleStr = tagTitleStr.replaceAll("(?i)" + Pattern.quote(tagTitle), tag.optString(Tag.TAG_TITLE));
}
// User-Tag relation (userself)
final JSONObject userTagRelation = new JSONObject();
userTagRelation.put(Tag.TAG + '_' + Keys.OBJECT_ID, tagId);
userTagRelation.put(User.USER + '_' + Keys.OBJECT_ID, user.optString(Keys.OBJECT_ID));
userTagRelation.put(Common.TYPE, Tag.TAG_TYPE_C_USER_SELF);
userTagRepository.add(userTagRelation);
}
user.put(UserExt.USER_TAGS, tagTitleStr);
}
} |
package org.cruk.mga.workflow;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.cruk.workflow.execution.TaskMonitor;
import org.cruk.workflow.execution.TaskRunner;
import org.cruk.workflow.tasks.AbstractJavaTask;
import org.cruk.workflow.xml2.pipeline.Task;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Wrapper for alignment tasks that detects zero-sized query file and
* creates an empty alignment output file instead of calling the aligner.
*
* @author eldrid01
*/
public class AlignmentWrapperTask extends AbstractJavaTask
{
private File queryFile;
private File alignmentFile;
@Autowired
private TaskRunner taskRunner;
public File getQueryFile()
{
return queryFile;
}
public void setQueryFile(File queryFile)
{
this.queryFile = queryFile;
}
public File getAlignmentFile()
{
return alignmentFile;
}
public void setAlignmentFile(File alignmentFile)
{
this.alignmentFile = alignmentFile;
}
@Override
public void execute(TaskMonitor arg0) throws Throwable
{
// if zero-size query fasta file create an empty alignment file to avoid
// exonerate error
if (queryFile.length() == 0)
{
boolean success = alignmentFile.createNewFile();
if (!success)
{
throw new IOException("Failed to create alignment file " + alignmentFile.getAbsolutePath());
}
}
else
{
Collection<Task> subtasks = task.getSubtasks();
if (subtasks.size() != 1)
{
throw new Exception("Expecting a single subtask but found " + subtasks.size());
}
else
{
Task subtask = subtasks.iterator().next();
TaskMonitor subtaskMonitor = taskRunner.runTask(configuration, subtask);
waitForMonitorsAndThrow("Alignment task failed", subtaskMonitor);
}
}
}
} |
package org.dynmap.web.handlers;
import java.io.BufferedOutputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Logger;
import org.dynmap.Event;
import org.dynmap.web.HttpField;
import org.dynmap.web.HttpHandler;
import org.dynmap.web.HttpMethod;
import org.dynmap.web.HttpRequest;
import org.dynmap.web.HttpResponse;
import org.dynmap.web.HttpStatus;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class SendMessageHandler implements HttpHandler {
protected static final Logger log = Logger.getLogger("Minecraft");
private static final JSONParser parser = new JSONParser();
public Event<Message> onMessageReceived = new Event<SendMessageHandler.Message>();
public int maximumMessageInterval = 1000;
public String spamMessage = "\"You may only chat once every %interval% seconds.\"";
private HashMap<String, WebUser> disallowedUsers = new HashMap<String, WebUser>();
private LinkedList<WebUser> disallowedUserQueue = new LinkedList<WebUser>();
private Object disallowedUsersLock = new Object();
@Override
public void handle(String path, HttpRequest request, HttpResponse response) throws Exception {
if (!request.method.equals(HttpMethod.Post)) {
response.status = HttpStatus.MethodNotAllowed;
response.fields.put(HttpField.Accept, HttpMethod.Post);
return;
}
InputStreamReader reader = new InputStreamReader(request.body);
JSONObject o = (JSONObject)parser.parse(reader);
final Message message = new Message();
message.name = String.valueOf(o.get("name"));
message.message = String.valueOf(o.get("message"));
final long now = System.currentTimeMillis();
synchronized(disallowedUsersLock) {
// Allow users that user that are now allowed to send messages.
while (!disallowedUserQueue.isEmpty()) {
WebUser wu = disallowedUserQueue.getFirst();
if (now >= wu.nextMessageTime) {
disallowedUserQueue.remove();
disallowedUsers.remove(wu.name);
} else {
break;
}
}
WebUser user = disallowedUsers.get(message.name);
if (user == null) {
user = new WebUser() {{
name = message.name;
nextMessageTime = now+maximumMessageInterval;
}};
disallowedUsers.put(user.name, user);
disallowedUserQueue.add(user);
} else {
spamMessage = spamMessage.replaceAll("%interval%", Integer.toString(maximumMessageInterval/1000));
byte[] stringBytes = spamMessage.getBytes();
String dateStr = new Date().toString();
response.fields.put("Date", dateStr);
response.fields.put("Content-Type", "text/plain");
response.fields.put("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
response.fields.put("Last-modified", dateStr);
response.fields.put("Content-Length", Integer.toString(stringBytes.length));
response.status = HttpStatus.OK;
BufferedOutputStream out = null;
out = new BufferedOutputStream(response.getBody());
out.write(stringBytes);
out.flush();
return;
}
}
onMessageReceived.trigger(message);
response.fields.put(HttpField.ContentLength, "0");
response.status = HttpStatus.OK;
response.getBody();
}
public static class Message {
public String name;
public String message;
}
public static class WebUser {
public long nextMessageTime;
public String name;
}
} |
package org.mcphoton.impl.world;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import org.mcphoton.world.ChunkColumn;
import org.mcphoton.world.ChunkSection;
import org.mcphoton.world.World;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author TheElectronWill
*/
public final class WorldChunksManager {
private static final Logger log = LoggerFactory.getLogger(WorldChunksManager.class);
private final World world;
private final File chunksDirectory;
public WorldChunksManager(World world) {
this.world = world;
this.chunksDirectory = new File(world.getDirectory(), "chunks");
}
private final Map<ChunkCoordinates, SoftReference<ChunkColumn>> chunks = new HashMap<>(512);
//TODO a ReferenceQueue that removes the chunk from the map when its reference is collected.
//TODO save the chunk, if it has been modified, before it gets garbage-collected!
public ChunkColumn getChunk(int cx, int cz, boolean createIfNeeded) {
ChunkCoordinates coords = new ChunkCoordinates(cx, cz);
SoftReference<ChunkColumn> ref = chunks.get(coords);
ChunkColumn chunk;
if (ref == null || (chunk = ref.get()) == null) {//chunk not loaded
File chunkFile = getChunkFile(cx, cz);
if (chunkFile.exists()) {//the chunk exists on the disk -> read it
chunk = tryReadChunk(chunkFile);
chunks.put(coords, new SoftReference<>(chunk));
} else {//the chunk doesn't exist at all -> generate it
chunk = generateChunk(cx, cz);
chunks.put(coords, new SoftReference<>(chunk));
}
}
return chunk;
}
ChunkColumn readChunk(File chunkFile) throws IOException {
try (FileInputStream in = new FileInputStream(chunkFile)) {
byte[] biomes = new byte[256];
in.read(biomes);
int sectionsArraySize = in.read();
ChunkSection[] sections = new ChunkSection[sectionsArraySize];
for (int i = 0; i < sectionsArraySize; i++) {
int bitsPerBlock = in.read();
byte[] data = new byte[(int) Math.ceil(bitsPerBlock * 4096 / 8)];
in.read(data);
sections[i] = new ChunkSectionImpl(bitsPerBlock, data);
}
return new ChunkColumnImpl(biomes, sections);
}
}
ChunkColumn tryReadChunk(File chunkFile) {
try {
return readChunk(chunkFile);
} catch (IOException ex) {
log.error("Unable to read chunk from {}", chunkFile, ex);
return null;
}
}
ChunkColumn generateChunk(int cx, int cz) {
return world.getChunkGenerator().generate(cx, cz);
}
void writeChunk(int cx, int cz, ChunkColumn chunk) throws IOException {
File chunkFile = getChunkFile(cx, cz);
try (FileOutputStream out = new FileOutputStream(chunkFile)) {
chunk.writeTo(out);
}
}
void writeAll() {
if (!chunksDirectory.exists()) {
chunksDirectory.mkdirs();
}
for (Map.Entry<ChunkCoordinates, SoftReference<ChunkColumn>> entry : chunks.entrySet()) {
ChunkCoordinates coords = entry.getKey();
SoftReference<ChunkColumn> ref = entry.getValue();
ChunkColumn chunk = ref.get();
if (chunk != null) {
File chunkFile = getChunkFile(coords.x, coords.z);
try (FileOutputStream out = new FileOutputStream(chunkFile)) {
chunk.writeTo(out);
} catch (IOException ex) {
log.error("Unable to write the chunk to {}", chunkFile.toString(), ex);
}
}
}
}
File getChunkFile(int cx, int cz) {
return new File(chunksDirectory, cx + "_" + cz + ".chunk");
}
} |
package org.mustangproject.ZUGFeRD;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class ZUGFeRDMigrator {
static final ClassLoader cl = ZUGFeRDMigrator.class.getClassLoader();
private static TransformerFactory factory = null;
private static final String resourcePath = ""; //$NON-NLS-1$
private static TransformerFactory getTransformerFactory() {
//TransformerFactory fact = new net.sf.saxon.TransformerFactoryImpl();
TransformerFactory fact = TransformerFactory.newInstance();
fact.setURIResolver(new ClasspathResourceURIResolver());
return fact;
}
public String migrateFromV1ToV2(String xmlFilename) {
ByteArrayOutputStream baos=new ByteArrayOutputStream();
try {
applySchematronXsl(new FileInputStream(xmlFilename), baos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String res=null;
try {
res=baos.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
private static File createTempFileResult(final Transformer transformer, final StreamSource toTransform,
final String suffix) throws TransformerException, IOException {
File result = File.createTempFile("ZUV_", suffix); //$NON-NLS-1$
result.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(result)) {
transformer.transform(toTransform, new StreamResult(fos));
}
return result;
}
private static class ClasspathResourceURIResolver implements URIResolver {
ClasspathResourceURIResolver() {
// Do nothing, just prevents synthetic access warning.
}
@Override
public Source resolve(String href, String base) throws TransformerException {
return new StreamSource(cl.getResourceAsStream(resourcePath + href));
}
}
public static void applySchematronXsl(final InputStream xmlFile,
final OutputStream EN16931Outstream) throws TransformerException {
factory=getTransformerFactory();
Transformer transformer = factory.newTransformer(new StreamSource(cl.getResourceAsStream(resourcePath+"COMFORTtoEN16931.xsl")));
transformer.transform(new StreamSource(xmlFile), new StreamResult(EN16931Outstream));
}
} |
package Debrief.GUI;
// $RCSfile: DebriefApp.java,v $
// @version $Revision: 1.3 $
// $Log: DebriefApp.java,v $
// Revision 1.3 2005/12/13 09:06:15 Ian.Mayo
// Tidying - as recommended by Eclipse
// Revision 1.2 2004/07/06 09:17:26 Ian.Mayo
// Intellij tidying
// Revision 1.1.1.2 2003/07/21 14:46:53 Ian.Mayo
// Re-import Java files to keep correct line spacing
// Revision 1.2 2002-05-29 10:05:04+01 ian_mayo
// minor tidying
// Revision 1.1 2002-05-28 12:19:16+01 ian_mayo
// Following file name change
/**
* This class can take a variable number of parameters on the command
* line. Program execution begins with the main() method. The class
* constructor is not invoked unless an object of type 'Class1'
* created in the main() method.
*/
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import Debrief.GUI.Frames.Application;
import Debrief.GUI.Frames.AWT.AWTApplication;
import Debrief.GUI.Frames.Swing.SwingApplication;
/**
* Top level class for Debrief 3 application
*/
public class DebriefApp {
/**
* Whether to create a SWING application, or an AWT application
*/
final boolean USE_SWING = true;
/**
* the application we start
*/
protected static Application aw;
/**
* The main entry point for the application.
*
* @param args Array of parameters passed to the application via the command line.
*/
public static void main(final String[] args) {
new DebriefApp();
// and now open any files, as requested
final int num = args.length;
aw.setCursor(java.awt.Cursor.WAIT_CURSOR);
for (int i = 0; i < num; i++) {
aw.openFile(new java.io.File(args[i]));
}
aw.setCursor(java.awt.Cursor.DEFAULT_CURSOR);
}
/**
* Constructor for this class
*/
public DebriefApp() {
if (USE_SWING) {
// try setting the look & feel
try {
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
aw = new SwingApplication();
} else
aw = new AWTApplication();
}
} |
package org.rascalmpl.value.io.binary;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.OutputStream;
import org.rascalmpl.interpreter.types.NonTerminalType;
import org.rascalmpl.interpreter.types.OverloadedFunctionType;
import org.rascalmpl.value.IBool;
import org.rascalmpl.value.IConstructor;
import org.rascalmpl.value.IDateTime;
import org.rascalmpl.value.IInteger;
import org.rascalmpl.value.IList;
import org.rascalmpl.value.IMap;
import org.rascalmpl.value.INode;
import org.rascalmpl.value.IRational;
import org.rascalmpl.value.IReal;
import org.rascalmpl.value.ISet;
import org.rascalmpl.value.ISourceLocation;
import org.rascalmpl.value.IString;
import org.rascalmpl.value.ITuple;
import org.rascalmpl.value.IValue;
import org.rascalmpl.value.io.binary.util.MapLastWritten;
import org.rascalmpl.value.io.binary.util.PrePostIValueIterator;
import org.rascalmpl.value.io.binary.util.PrePostTypeIterator;
import org.rascalmpl.value.io.binary.util.TrackLastWritten;
import org.rascalmpl.value.io.binary.util.TypeIteratorKind;
import org.rascalmpl.value.io.binary.util.ValueIteratorKind;
import org.rascalmpl.value.io.binary.util.Values;
import org.rascalmpl.value.type.Type;
import org.rascalmpl.value.visitors.IValueVisitor;
import org.rascalmpl.value.visitors.NullVisitor;
import org.rascalmpl.values.ValueFactoryFactory;
import org.tukaani.xz.LZMA2Options;
import org.tukaani.xz.XZOutputStream;
/**
* RSFIValueWriter is a binary serializer for IValues and Types. The main public functions is:
* - writeValue
*/
public class IValueWriter {
public enum CompressionRate {
None(0,0,0, 0),
//TypesOnly(10,0,0),
//ValuesOnly(0,10,10),
Fast(10,10,10, 1),
Normal(50,100,50,3),
Extreme(50,250,100, 6)
;
private final int uriWindow;
private final int typeWindow;
private final int valueWindow;
private int xzMode;
CompressionRate(int typeWindow, int valueWindow, int uriWindow, int xzMode) {
this.typeWindow = typeWindow;
this.valueWindow = valueWindow;
this.uriWindow = uriWindow;
this.xzMode = xzMode;
}
}
protected static final byte[] header = { 'R', 'V', 1,0,0 };
static final class CompressionHeader {
public static final byte NONE = 0;
public static final byte GZIP = 1;
public static final byte XZ = 2;
}
private static <T> TrackLastWritten<T> getWindow(int size) {
if (size == 0) {
return new TrackLastWritten<T>() {
public int howLongAgo(T obj) {
return -1;
}
public void write(T obj) {};
};
}
return new MapLastWritten<>(size * 1024);
}
public static void write(OutputStream out, IValue value, CompressionRate compression, boolean shouldClose) throws IOException {
out.write(header);
out.write(compression.typeWindow);
out.write(compression.valueWindow);
out.write(compression.uriWindow);
out.write(compression.xzMode == 0 ? CompressionHeader.NONE : CompressionHeader.XZ);
if (compression.xzMode > 0) {
out = new XZOutputStream(out, new LZMA2Options(compression.xzMode));
}
ValueWireOutputStream writer = new ValueWireOutputStream(out);
try {
TrackLastWritten<Type> typeCache = getWindow(compression.typeWindow);
TrackLastWritten<IValue> valueCache = getWindow(compression.valueWindow);
TrackLastWritten<ISourceLocation> uriCache = getWindow(compression.uriWindow);
write(writer, value, typeCache, valueCache, uriCache);
}
finally {
writer.flush();
if (shouldClose) {
writer.close();
}
else {
if (compression.xzMode > 0) {
((XZOutputStream)out).finish();
}
}
}
}
private static void writeNames(final ValueWireOutputStream writer, int fieldId, String[] names) throws IOException{
writer.writeField(fieldId, names.length);
for(int i = 0; i < names.length; i++){
writer.writeField(fieldId, names[i]);
}
}
private static void write(final ValueWireOutputStream writer, final Type type, final TrackLastWritten<Type> typeCache, final TrackLastWritten<IValue> valueCache, final TrackLastWritten<ISourceLocation> uriCache) throws IOException {
final PrePostTypeIterator iter = new PrePostTypeIterator(type);
while(iter.hasNext()){
final TypeIteratorKind kind = iter.next();
final Type currentType = iter.getItem();
if (kind.isCompound()) {
if (iter.atBeginning()) {
int lastSeen = typeCache.howLongAgo(currentType);
if (lastSeen != -1) {
writeSingleValueMessage(writer, IValueIDs.PreviousType.ID, IValueIDs.PreviousType.HOW_LONG_AGO, lastSeen);
iter.skipItem();
}
}
else {
switch(kind){
case ADT: {
writeSingleValueMessage(writer, IValueIDs.ADTType.ID, IValueIDs.ADTType.NAME, currentType.getName());
break;
}
case ALIAS: {
writeSingleValueMessage(writer, IValueIDs.AliasType.ID, IValueIDs.AliasType.NAME, currentType.getName());
break;
}
case CONSTRUCTOR : {
writeSingleValueMessage(writer, IValueIDs.ConstructorType.ID, IValueIDs.ConstructorType.NAME, currentType.getName());
break;
}
case FUNCTION: {
writer.writeEmptyMessage(IValueIDs.ConstructorType.ID);
break;
}
case REIFIED: {
writer.writeEmptyMessage(IValueIDs.ReifiedType.ID);
break;
}
case OVERLOADED: {
writeSingleValueMessage(writer, IValueIDs.OverloadedType.ID, IValueIDs.OverloadedType.SIZE, ((OverloadedFunctionType) currentType).getAlternatives().size());
break;
}
case NONTERMINAL: {
// first prefix with the Constructor
write(writer, ((NonTerminalType)currentType).getSymbol(), typeCache, valueCache, uriCache);
writer.writeEmptyMessage(IValueIDs.NonTerminalType.ID);
break;
}
case LIST: {
writer.writeEmptyMessage(IValueIDs.ListType.ID);
break;
}
case MAP: {
writer.writeEmptyMessage(IValueIDs.MapType.ID);
break;
}
case PARAMETER: {
writeSingleValueMessage(writer, IValueIDs.ParameterType.ID, IValueIDs.ParameterType.NAME,currentType.getName());
break;
}
case SET: {
writer.writeEmptyMessage(IValueIDs.SetType.ID);
break;
}
case TUPLE: {
writer.startMessage(IValueIDs.TupleType.ID);
writer.writeField(IValueIDs.TupleType.ARITY, currentType.getArity());
String[] fieldNames = currentType.getFieldNames();
if(fieldNames != null){
writeNames(writer, IValueIDs.TupleType.NAMES, fieldNames);
}
writer.endMessage();
break;
}
default:
throw new RuntimeException("Missing compound type case");
}
typeCache.write(currentType);
}
}
else {
switch(kind){
case BOOL: {
writer.writeEmptyMessage(IValueIDs.BoolType.ID);
break;
}
case DATETIME: {
writer.writeEmptyMessage(IValueIDs.DateTimeType.ID);
break;
}
case INT: {
writer.writeEmptyMessage(IValueIDs.IntegerType.ID);
break;
}
case NODE: {
writer.writeEmptyMessage(IValueIDs.NodeType.ID);
break;
}
case NUMBER: {
writer.writeEmptyMessage(IValueIDs.NumberType.ID);
break;
}
case RATIONAL: {
writer.writeEmptyMessage(IValueIDs.RationalType.ID);
break;
}
case REAL: {
writer.writeEmptyMessage(IValueIDs.RealType.ID);
break;
}
case LOC: {
writer.writeEmptyMessage(IValueIDs.SourceLocationType.ID);
break;
}
case STR: {
writer.writeEmptyMessage(IValueIDs.StringType.ID);
break;
}
case VALUE: {
writer.writeEmptyMessage(IValueIDs.ValueType.ID);
break;
}
case VOID: {
writer.writeEmptyMessage(IValueIDs.VoidType.ID);
break;
}
default:
throw new RuntimeException("Missing non-compound type case");
}
}
}
}
private static void writeSingleValueMessage(final ValueWireOutputStream writer, int messageID, int fieldId, long fieldValue) throws IOException {
writer.startMessage(messageID);
writer.writeField(fieldId, fieldValue);
writer.endMessage();
}
private static void writeSingleValueMessage(final ValueWireOutputStream writer, int messageID, int fieldId, String fieldValue) throws IOException {
writer.startMessage(messageID);
writer.writeField(fieldId, fieldValue);
writer.endMessage();
}
private static final IInteger MININT =ValueFactoryFactory.getValueFactory().integer(Integer.MIN_VALUE);
private static final IInteger MAXINT =ValueFactoryFactory.getValueFactory().integer(Integer.MAX_VALUE);
private static void write(final ValueWireOutputStream writer, final IValue value, final TrackLastWritten<Type> typeCache, final TrackLastWritten<IValue> valueCache, final TrackLastWritten<ISourceLocation> uriCache) throws IOException {
PrePostIValueIterator iter = new PrePostIValueIterator(value);
IValueVisitor<Boolean, IOException> compoundWriter = new NullVisitor<Boolean, IOException>() {
@Override
public Boolean visitConstructor(IConstructor cons) throws IOException {
write(writer, cons.getUninstantiatedConstructorType(), typeCache, valueCache, uriCache);
writer.startMessage(IValueIDs.ConstructorValue.ID);
writer.writeField(IValueIDs.ConstructorValue.ARITY, cons.arity());
if(cons.mayHaveKeywordParameters()){
if(cons.asWithKeywordParameters().hasParameters()){
writer.writeField(IValueIDs.ConstructorValue.KWPARAMS, cons.asWithKeywordParameters().getParameters().size());
}
} else {
if(cons.asAnnotatable().hasAnnotations()){
writer.writeField(IValueIDs.ConstructorValue.ANNOS, cons.asAnnotatable().getAnnotations().size());
}
}
writer.endMessage();
return true;
}
@Override
public Boolean visitNode(INode node) throws IOException {
writer.startMessage(IValueIDs.NodeValue.ID);
writer.writeField(IValueIDs.NodeValue.NAME, node.getName());
writer.writeField(IValueIDs.NodeValue.ARITY, node.arity());
if(node.mayHaveKeywordParameters()){
if(node.asWithKeywordParameters().hasParameters()){
writer.writeField(IValueIDs.NodeValue.KWPARAMS, node.asWithKeywordParameters().getParameters().size());
}
} else {
if(node.asAnnotatable().hasAnnotations()){
writer.writeField(IValueIDs.NodeValue.ANNOS, node.asAnnotatable().getAnnotations().size());
}
}
writer.endMessage();
return true;
}
@Override
public Boolean visitList(IList o) throws IOException {
writeSingleValueMessage(writer, IValueIDs.ListValue.ID, IValueIDs.ListValue.SIZE, o.length());
return true;
}
@Override
public Boolean visitMap(IMap o) throws IOException {
writeSingleValueMessage(writer, IValueIDs.MapValue.ID, IValueIDs.MapValue.SIZE, o.size());
return true;
}
@Override
public Boolean visitSet(ISet o) throws IOException {
writeSingleValueMessage(writer, IValueIDs.SetValue.ID, IValueIDs.SetValue.SIZE, o.size());
return true;
}
@Override
public Boolean visitRational(IRational o) throws IOException {
writer.writeEmptyMessage(IValueIDs.RationalValue.ID);
return true;
}
@Override
public Boolean visitTuple(ITuple o) throws IOException {
writeSingleValueMessage(writer, IValueIDs.TupleValue.ID, IValueIDs.TupleValue.SIZE, o.arity());
return true;
}
};
IValueVisitor<Boolean, IOException> singularWriter = new NullVisitor<Boolean, IOException>() {
@Override
public Boolean visitBoolean(IBool boolValue) throws IOException {
writeSingleValueMessage(writer, IValueIDs.BoolValue.ID, IValueIDs.BoolValue.VALUE, boolValue.getValue() ? 1: 0);
return true;
}
@Override
public Boolean visitDateTime(IDateTime dateTime) throws IOException {
writer.startMessage(IValueIDs.DateTimeValue.ID);
if (!dateTime.isTime()) {
writer.writeField(IValueIDs.DateTimeValue.YEAR, dateTime.getYear());
writer.writeField(IValueIDs.DateTimeValue.MONTH, dateTime.getMonthOfYear());
writer.writeField(IValueIDs.DateTimeValue.DAY, dateTime.getDayOfMonth());
}
if (!dateTime.isDate()) {
writer.writeField(IValueIDs.DateTimeValue.HOUR, dateTime.getHourOfDay());
writer.writeField(IValueIDs.DateTimeValue.MINUTE, dateTime.getMinuteOfHour());
writer.writeField(IValueIDs.DateTimeValue.SECOND, dateTime.getSecondOfMinute());
writer.writeField(IValueIDs.DateTimeValue.MILLISECOND, dateTime.getMillisecondsOfSecond());
writer.writeField(IValueIDs.DateTimeValue.TZ_HOUR, dateTime.getTimezoneOffsetHours());
writer.writeField(IValueIDs.DateTimeValue.TZ_MINUTE, dateTime.getTimezoneOffsetMinutes());
}
writer.endMessage();
return true;
}
@Override
public Boolean visitInteger(IInteger ii) throws IOException {
writer.startMessage(IValueIDs.IntegerValue.ID);
if(ii. greaterEqual(MININT).getValue() && ii.lessEqual(MAXINT).getValue()){
writer.writeField(IValueIDs.IntegerValue.INTVALUE, ii.intValue());
}
else {
writer.writeField(IValueIDs.IntegerValue.BIGVALUE, ii.getTwosComplementRepresentation());
}
writer.endMessage();
return true;
}
@Override
public Boolean visitReal(IReal o) throws IOException {
writer.startMessage(IValueIDs.RealValue.ID);
writer.writeField(IValueIDs.RealValue.CONTENT, o.unscaled().getTwosComplementRepresentation());
writer.writeField(IValueIDs.RealValue.SCALE, o.scale());
writer.endMessage();
return true;
}
@Override
public Boolean visitSourceLocation(ISourceLocation loc) throws IOException {
writer.startMessage(IValueIDs.SourceLocationValue.ID);
ISourceLocation uriPart = loc.top();
int alreadyWritten = uriCache.howLongAgo(uriPart);
if (alreadyWritten == -1) {
writer.writeField(IValueIDs.SourceLocationValue.SCHEME, uriPart.getScheme());
if (uriPart.hasAuthority()) {
writer.writeField(IValueIDs.SourceLocationValue.AUTHORITY, uriPart.getAuthority());
}
if (uriPart.hasPath()) {
writer.writeField(IValueIDs.SourceLocationValue.PATH, uriPart.getPath());
}
if (uriPart.hasQuery()) {
writer.writeField(IValueIDs.SourceLocationValue.QUERY, uriPart.getQuery());
}
if (uriPart.hasFragment()) {
writer.writeField(IValueIDs.SourceLocationValue.FRAGMENT, uriPart.getFragment());
}
uriCache.write(uriPart);
}
else {
writer.writeField(IValueIDs.SourceLocationValue.PREVIOUS_URI, alreadyWritten);
}
if(loc.hasOffsetLength()){
writer.writeField(IValueIDs.SourceLocationValue.OFFSET, loc.getOffset());
writer.writeField(IValueIDs.SourceLocationValue.LENGTH, loc.getLength());
}
if(loc.hasLineColumn()){
writer.writeField(IValueIDs.SourceLocationValue.BEGINLINE, loc.getBeginLine());
writer.writeField(IValueIDs.SourceLocationValue.ENDLINE, loc.getEndLine());
writer.writeField(IValueIDs.SourceLocationValue.BEGINCOLUMN, loc.getBeginColumn());
writer.writeField(IValueIDs.SourceLocationValue.ENDCOLUMN, loc.getEndColumn());
}
writer.endMessage();
return true;
}
@Override
public Boolean visitString(IString o) throws IOException {
writeSingleValueMessage(writer, IValueIDs.StringValue.ID, IValueIDs.StringValue.CONTENT, o.getValue());
return true;
}
};
while(iter.hasNext()){
iter.next();
final IValue currentValue = iter.getItem();
if (Values.isCompound(currentValue)) {
if (iter.atBeginning()) {
int lastSeen = valueCache.howLongAgo(currentValue);
if (lastSeen != -1) {
writeSingleValueMessage(writer, IValueIDs.PreviousValue.ID, IValueIDs.PreviousValue.HOW_FAR_BACK, lastSeen);
iter.skipItem();
}
}
else {
Boolean written = currentValue.accept(compoundWriter);
if (written == null) {
throw new RuntimeException("writeValue: unexpected kind of value " + currentValue);
}
valueCache.write(currentValue);
}
}
else {
assert iter.atBeginning();
Boolean written = currentValue.accept(singularWriter);
if (written == null) {
throw new RuntimeException("writeValue: unexpected kind of value " + currentValue);
}
}
}
}
} |
package org.spongepowered.asm.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.base.Joiner;
/**
* Provides access to the service layer which connects the mixin transformer to
* a particular host environment. Host environments are implemented as services
* implementing {@link IMixinService} in order to decouple them from mixin's
* core. This allows us to support LegacyLauncher
*/
public final class MixinService {
/**
* Log all the things
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Singleton
*/
private static MixinService instance;
private ServiceLoader<IMixinServiceBootstrap> bootstrapServiceLoader;
private final Set<String> bootedServices = new HashSet<String>();
/**
* Service loader
*/
private ServiceLoader<IMixinService> serviceLoader;
/**
* Service
*/
private IMixinService service = null;
/**
* Global Property Service
*/
private IGlobalPropertyService propertyService;
/**
* Singleton pattern
*/
private MixinService() {
this.runBootServices();
}
private void runBootServices() {
this.bootstrapServiceLoader = ServiceLoader.<IMixinServiceBootstrap>load(IMixinServiceBootstrap.class, this.getClass().getClassLoader());
Iterator<IMixinServiceBootstrap> iter = this.bootstrapServiceLoader.iterator();
while (iter.hasNext()) {
try {
IMixinServiceBootstrap bootService = iter.next();
bootService.bootstrap();
this.bootedServices.add(bootService.getServiceClassName());
} catch (ServiceInitialisationException ex) {
// Expected if service cannot start
MixinService.logger.debug("Mixin bootstrap service {} is not available: {}", ex.getStackTrace()[0].getClassName(), ex.getMessage());
} catch (Throwable th) {
MixinService.logger.debug("Catching {}:{} initialising service", th.getClass().getName(), th.getMessage(), th);
}
}
}
/**
* Singleton pattern, get or create the instance
*/
private static MixinService getInstance() {
if (MixinService.instance == null) {
MixinService.instance = new MixinService();
}
return MixinService.instance;
}
/**
* Boot
*/
public static void boot() {
MixinService.getInstance();
}
public static IMixinService getService() {
return MixinService.getInstance().getServiceInstance();
}
private synchronized IMixinService getServiceInstance() {
if (this.service == null) {
this.service = this.initService();
}
return this.service;
}
private IMixinService initService() {
this.serviceLoader = ServiceLoader.<IMixinService>load(IMixinService.class, this.getClass().getClassLoader());
Iterator<IMixinService> iter = this.serviceLoader.iterator();
List<String> rejectedServices = new ArrayList<String>();
while (iter.hasNext()) {
try {
IMixinService service = iter.next();
if (this.bootedServices.contains(service.getClass().getName())) {
MixinService.logger.debug("MixinService [{}] was successfully booted in {}", service.getName(), this.getClass().getClassLoader());
}
if (service.isValid()) {
return service;
}
rejectedServices.add(service.getName());
} catch (ServiceConfigurationError serviceError) {
// serviceError.printStackTrace();
} catch (Throwable th) {
// th.printStackTrace();
}
}
throw new ServiceNotAvailableError("No mixin host service is available. Rejected services: " + Joiner.on(", ").join(rejectedServices));
}
/**
* Blackboard
*/
public static IGlobalPropertyService getGlobalPropertyService() {
return MixinService.getInstance().getGlobalPropertyServiceInstance();
}
/**
* Retrieves the GlobalPropertyService Instance... FactoryProviderBean...
* Observer...InterfaceStream...Function...Broker... help me why won't it
* stop
*/
private IGlobalPropertyService getGlobalPropertyServiceInstance() {
if (this.propertyService == null) {
this.propertyService = this.initPropertyService();
}
return this.propertyService;
}
private IGlobalPropertyService initPropertyService() {
ServiceLoader<IGlobalPropertyService> serviceLoader = ServiceLoader.<IGlobalPropertyService>load(IGlobalPropertyService.class,
this.getClass().getClassLoader());
Iterator<IGlobalPropertyService> iter = serviceLoader.iterator();
while (iter.hasNext()) {
try {
IGlobalPropertyService service = iter.next();
return service;
} catch (ServiceConfigurationError serviceError) {
// serviceError.printStackTrace();
} catch (Throwable th) {
// th.printStackTrace();
}
}
throw new ServiceNotAvailableError("No mixin global property service is available");
}
} |
package org.tndata.android.compass.model;
import android.os.Parcel;
import com.google.gson.annotations.SerializedName;
/**
* Model class for actions.
*
* @author Edited by Ismael Alonso
* @version 1.0.0
*/
public class TDCAction extends TDCContent{
public static final String TYPE = "action";
@SerializedName("sequence_order")
private int mSequenceOrder;
@SerializedName("more_info")
private String mMoreInfo;
@SerializedName("html_more_info")
private String mHtmlMoreInfo;
@SerializedName("external_resource")
private String mExternalResource;
@SerializedName("external_resource_name")
private String mExternalResourceName;
@SerializedName("external_resource_type")
private String mExternalResourceType;
@SerializedName("behavior")
private long mBehaviorId;
@SerializedName("behavior_title")
private String mBehaviorTitle;
@SerializedName("behavior_description")
private String mBehaviorDescription;
/**
* Sequence order getter.
*
* @return the action's sequence order position.
*/
public int getSequenceOrder(){
return mSequenceOrder;
}
/**
* More info getter.
*
* @return the action's more info.
*/
public String getMoreInfo(){
return mMoreInfo;
}
/**
* HTML more info getter.
*
* @return the action's more info in HTML format.
*/
public String getHTMLMoreInfo(){
return mHtmlMoreInfo;
}
/**
* External resource getter.
*
* @return the action's external resource.
*/
public String getExternalResource(){
return mExternalResource;
}
/**
* External resource name getter.
*
* @return the action's external resource name.
*/
public String getExternalResourceName(){
return mExternalResourceName;
}
/**
* External resource type getter.
*
* @return the action's external resource type.
*/
public String getExternalResourceType(){
return mExternalResourceType;
}
/**
* Behavior id getter.
*
* @return the id of the action's parent behavior.
*/
public long getBehaviorId(){
return mBehaviorId;
}
/**
* Behavior title getter.
*
* @return the title of the action's parent behavior.
*/
public String getBehaviorTitle(){
return mBehaviorTitle;
}
/**
* Behavior description getter.
*
* @return the description of the action's parent behavior.
*/
public String getBehaviorDescription(){
return mBehaviorDescription;
}
@Override
protected String getType(){
return TYPE;
}
@Override
public String toString(){
return "ActionContent #" + getId() + ": " + getTitle();
}
@Override
public void writeToParcel(Parcel dest, int flags){
super.writeToParcel(dest, flags);
dest.writeInt(mSequenceOrder);
dest.writeString(mMoreInfo);
dest.writeString(mHtmlMoreInfo);
dest.writeString(mExternalResource);
dest.writeString(mExternalResourceName);
dest.writeString(mExternalResourceType);
dest.writeLong(mBehaviorId);
dest.writeString(mBehaviorTitle);
dest.writeString(mBehaviorDescription);
}
public boolean hasDatetimeResource() {
return getExternalResourceType().equals("datetime");
}
public boolean hasPhoneNumberResource() {
return getExternalResourceType().equals("phone");
}
public boolean hasLinkResource() {
return getExternalResourceType().equals("link");
}
public static final Creator<TDCAction> CREATOR = new Creator<TDCAction>(){
@Override
public TDCAction createFromParcel(Parcel in){
return new TDCAction(in);
}
@Override
public TDCAction[] newArray(int size){
return new TDCAction[size];
}
};
/**
* Constructor to create from parcel.
*
* @param src the parcel where the object is stored.
*/
private TDCAction(Parcel src){
super(src);
mSequenceOrder = src.readInt();
mMoreInfo = src.readString();
mHtmlMoreInfo = src.readString();
mExternalResource = src.readString();
mExternalResourceName = src.readString();
mExternalResourceType = src.readString();
mBehaviorId = src.readLong();
mBehaviorTitle = src.readString();
mBehaviorDescription = src.readString();
}
} |
package org.vaadin.viritin.fields;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.vaadin.viritin.ListContainer;
import com.vaadin.data.Property;
import com.vaadin.data.util.converter.Converter;
import com.vaadin.server.Resource;
import com.vaadin.shared.ui.MultiSelectMode;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomField;
import com.vaadin.ui.Table;
import org.vaadin.viritin.MSize;
/**
* A Table that can be used as a field to modify List>YourDomainObject< or
* Set>YourDomainObject< typed fields in your domain model.
* <p>
* The field supports only non buffered mode. Also, the field tries to keep the
* original collection and just modify its content. This helps e.g. some ORM
* libraries to create more efficient updates to the database.
* <p>
* If the field value is null (and users selects rows) the field tries to add a
* value with no-arg constructor or with ArrayList/HashMap if interface is used.
*
* @author Matti Tahvonen
* @param <ET> The type in the entity collection
*/
public class MultiSelectTable<ET> extends CustomField<Collection> {
private String[] visProps;
private String[] pendingHeaders;
Table table = new Table() {
{
setSelectable(true);
setMultiSelect(true);
setSizeFull();
setImmediate(true);
}
private boolean clientSideChange;
@Override
public void changeVariables(Object source,
Map<String, Object> variables) {
clientSideChange = true;
super.changeVariables(source, variables);
clientSideChange = false;
}
@Override
protected void setValue(Object newValue, boolean repaintIsNotNeeded) throws ReadOnlyException {
Set<ET> oldvalue = (Set<ET>) getValue();
super.setValue(newValue, repaintIsNotNeeded);
if (clientSideChange) {
// TODO add strategies for maintaining the order in case of List
// e.g. same as listing, selection order ...
Set newvalue = (Set) getValue();
Set<ET> orphaned = new HashSet<ET>(oldvalue);
orphaned.removeAll(newvalue);
removeRelation(orphaned);
allRemovedRelations.addAll(orphaned);
allAddedRelations.removeAll(orphaned);
Set<ET> newValues = new LinkedHashSet<ET>(newvalue);
newValues.removeAll(oldvalue);
addRelation(newValues);
allAddedRelations.addAll(newValues);
allRemovedRelations.removeAll(newValues);
MultiSelectTable.this.fireValueChange(true);
}
}
};
private Class<ET> optionType;
private Set<ET> allAddedRelations = new HashSet<ET>();
private Set<ET> allRemovedRelations = new HashSet<ET>();
public MultiSelectTable(Class<ET> optionType) {
this();
table.setContainerDataSource(new ListContainer(optionType));
this.optionType = optionType;
}
public MultiSelectTable(String caption) {
this();
setCaption(caption);
}
/**
* Adds given options to the modified collection. The default implementation
* simply uses java.util.Collection APIs to maintain the edited collection.
* If the underlying data model needs some some custom maintenance, e.g. a
* bi-directional many-to-many relation in JPA, you can add your own logic
* by overriding this method.
*
* @param newValues the new objects to be added to the collection.
*/
protected void addRelation(Set<ET> newValues) {
getEditedCollection().addAll(newValues);
}
/**
* Removes given options from the modified collection. The default
* implementation simply uses java.util.Collection APIs to maintain the
* edited collection. If the underlying data model needs some some custom
* maintenance, e.g. a bi-directional many-to-many relation in JPA, you can
* add your own logic by overriding this method.
*
* @param orphaned the new objects to be removed from the collection.
*/
protected void removeRelation(Set<ET> orphaned) {
getEditedCollection().removeAll(orphaned);
}
/**
* @return all objects that are added to the edited collection. The added
* relations are calculated since last call to setPropertyDataSource method
* (when the modified property/collection is set by e.g. FieldGroup) or
* explicit call to clearModifiedRelations().
*/
public Set<ET> getAllAddedRelations() {
return allAddedRelations;
}
/**
* @return all objects that are removed from the edited collection. The
* deleted relations are calculated since last call to setPropertyDataSource
* method (when the modified property/collection is set by e.g. FieldGroup)
* or explicit call to clearModifiedRelations().
*/
public Set<ET> getAllRemovedRelations() {
return allRemovedRelations;
}
/**
* @return all objects that are either added or removed to/from the edited
* collection. The objects are calculated since last call to
* setPropertyDataSource method (when the modified property/collection is
* set by e.g. FieldGroup) or explicit call to clearModifiedRelations().
*/
public Set<ET> getAllModifiedRelations() {
HashSet<ET> all = new HashSet<ET>(allAddedRelations);
all.addAll(allRemovedRelations);
return all;
}
@Override
public void setPropertyDataSource(Property newDataSource) {
clearModifiedRelations();
super.setPropertyDataSource(newDataSource);
}
/**
* Clears the fields that track the elements that are added or removed to
* the modified collection. This method is automatically called when a new
* property is assigned to this field.
*/
public void clearModifiedRelations() {
allAddedRelations.clear();
allRemovedRelations.clear();
}
/**
* @return the collection being edited by this field.
*/
protected Collection<ET> getEditedCollection() {
Collection c = getValue();
if (c == null) {
if (getPropertyDataSource() == null) {
// this should never happen :-)
return new HashSet();
}
Class fieldType = getPropertyDataSource().getType();
if (fieldType.isInterface()) {
if (fieldType == List.class) {
c = new ArrayList();
} else { // Set
c = new HashSet();
}
} else {
try {
c = (Collection) fieldType.newInstance();
} catch (Exception ex) {
throw new RuntimeException(
"Could not instantiate the used colleciton type", ex);
}
}
}
return c;
}
public MultiSelectTable<ET> withProperties(String... visibleProperties) {
visProps = visibleProperties;
if (isContainerInitialized()) {
table.setVisibleColumns((Object[]) visibleProperties);
} else {
for (String string : visibleProperties) {
table.addContainerProperty(string, String.class, "");
}
}
return this;
}
private boolean isContainerInitialized() {
return table.getContainerDataSource() instanceof ListContainer;
}
public MultiSelectTable<ET> withColumnHeaders(
String... columnNamesForVisibleProperties) {
if (isContainerInitialized()) {
table.setColumnHeaders(columnNamesForVisibleProperties);
} else {
pendingHeaders = columnNamesForVisibleProperties;
// Add headers to temporary indexed container, in case table is initially
// empty
for (String prop : columnNamesForVisibleProperties) {
table.addContainerProperty(prop, String.class, "");
}
}
return this;
}
@Override
protected Component initContent() {
return table;
}
@Override
public Class<? extends Collection> getType() {
return Collection.class;
}
@Override
protected void setInternalValue(Collection newValue) {
super.setInternalValue(newValue);
table.setValue(newValue);
}
/**
* Sets the list of options available.
*
* @param list the list of available options
* @return this for fluent configuration
*/
public MultiSelectTable<ET> setOptions(List<ET> list) {
if (visProps == null) {
table.setContainerDataSource(new ListContainer(optionType, list));
} else {
table.setContainerDataSource(new ListContainer(optionType, list), Arrays.asList(
visProps));
}
if (pendingHeaders != null) {
table.setColumnHeaders(pendingHeaders);
}
return this;
}
/**
* Sets the list of options available.
*
* @param list the list of available options
* @return this for fluent configuration
*/
public MultiSelectTable<ET> setOptions(ET... list) {
if (visProps == null) {
table.setContainerDataSource(new ListContainer(optionType, Arrays.
asList(list)));
} else {
table.setContainerDataSource(new ListContainer(optionType, Arrays.
asList(list)), Arrays.asList(
visProps));
}
if (pendingHeaders != null) {
table.setColumnHeaders(pendingHeaders);
}
return this;
}
public MultiSelectTable() {
setHeight("230px");
// TODO verify if this is needed in real usage, but at least to pass the test
setConverter(new Converter<Collection, Collection>() {
@Override
public Collection convertToModel(Collection value,
Class<? extends Collection> targetType, Locale locale) throws Converter.ConversionException {
return value;
}
@Override
public Collection convertToPresentation(Collection value,
Class<? extends Collection> targetType, Locale locale) throws Converter.ConversionException {
return value;
}
@Override
public Class<Collection> getModelType() {
return (Class<Collection>) getEditedCollection().getClass();
}
@Override
public Class<Collection> getPresentationType() {
return Collection.class;
}
});
}
public void select(ET objectToSelect) {
if (!table.isSelected(objectToSelect)) {
table.select(objectToSelect);
getEditedCollection().add(objectToSelect);
}
}
public void unSelect(ET objectToDeselect) {
if (table.isSelected(objectToDeselect)) {
table.unselect(objectToDeselect);
getEditedCollection().remove(objectToDeselect);
}
}
/**
* @return the underlaying Table
* @deprecated use getTable() instead.
*/
@Deprecated
protected Table getUnderlayingTable() {
return table;
}
/**
* @return the underlaying table implementation. Note that the component
* heavily relies on some features so changing some of the configuration
* options in Table is unsafe.
*/
public Table getTable() {
return table;
}
public MultiSelectTable<ET> withColumnHeaderMode(Table.ColumnHeaderMode mode) {
getUnderlayingTable().setColumnHeaderMode(mode);
return this;
}
public MultiSelectTable<ET> withFullWidth() {
setWidth(100, Unit.PERCENTAGE);
return this;
}
public MultiSelectTable<ET> withHeight(String height) {
setHeight(height);
return this;
}
public MultiSelectTable<ET> withFullHeight() {
return withHeight("100%");
}
public MultiSelectTable<ET> withWidth(String width) {
setWidth(width);
return this;
}
public MultiSelectTable withSize(MSize mSize) {
setWidth(mSize.getWidth(), mSize.getWidthUnit());
setHeight(mSize.getHeight(), mSize.getHeightUnit());
return this;
}
public MultiSelectTable<ET> withCaption(String caption) {
setCaption(caption);
return this;
}
public MultiSelectTable<ET> withStyleName(String... styleNames) {
for (String styleName : styleNames) {
addStyleName(styleName);
}
return this;
}
public MultiSelectTable<ET> withIcon(Resource icon) {
setIcon(icon);
return this;
}
public MultiSelectTable<ET> withId(String id) {
table.setId(id);
return this;
}
public MultiSelectTable<ET> expand(String... propertiesToExpand) {
for (String property : propertiesToExpand) {
table.setColumnExpandRatio(property, 1);
}
return this;
}
public void withRowHeaderMode(Table.RowHeaderMode rowHeaderMode) {
getUnderlayingTable().setRowHeaderMode(rowHeaderMode);
}
public MultiSelectTable<ET> setMultiSelectMode(MultiSelectMode mode) {
getTable().setMultiSelectMode(mode);
return this;
}
} |
package pl.edu.icm.oxides.open;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import pl.edu.icm.oxides.config.OpenOxidesConfig;
import pl.edu.icm.oxides.user.AuthenticationSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
import static org.springframework.http.ResponseEntity.status;
@Service
public class OpenOxidesResources {
private final OpenOxidesConfig openOxidesConfig;
private final FileResourceLoader fileResourceLoader;
private final HttpHeaders responseHeaders;
@Autowired
public OpenOxidesResources(OpenOxidesConfig openOxidesConfig, FileResourceLoader fileResourceLoader) {
this.openOxidesConfig = openOxidesConfig;
this.fileResourceLoader = fileResourceLoader;
responseHeaders = new HttpHeaders();
responseHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
}
public ResponseEntity<String> getParticleParameters(String name, AuthenticationSession authenticationSession) {
if (isValidAuthenticationSession(authenticationSession)) {
Resource resource = fileResourceLoader.getResource("classpath:data/" + name + ".json");
if (!resource.exists()) {
return serviceResponse(NOT_FOUND);
}
try {
return ResponseEntity.status(OK)
.headers(responseHeaders)
.body(getJsonString(resource));
} catch (IOException e) {
log.error("Could not get particle parameters data", e);
return serviceResponse(INTERNAL_SERVER_ERROR);
}
}
return serviceResponse(UNAUTHORIZED);
}
private String getJsonString(Resource resource) throws IOException {
String output = "";
InputStream is = resource.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
output += line;
}
br.close();
return output;
}
private <T> ResponseEntity<T> serviceResponse(HttpStatus httpStatus) {
return status(httpStatus).headers(responseHeaders).body(null);
}
private boolean isValidAuthenticationSession(AuthenticationSession authenticationSession) {
return authenticationSession != null
&& authenticationSession.isGroupMember(openOxidesConfig.getGroupName());
}
private Log log = LogFactory.getLog(OpenOxidesResources.class);
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
} |
package pw.amel.civspell.builtin;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.*;
import pw.amel.civspell.spell.CastData;
import pw.amel.civspell.spell.Effect;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class ThrowPotionEffect implements Effect {
public ThrowPotionEffect(ConfigurationSection config) {
color = config.getColor("color");
velocityMultiplier = (float) config.getDouble("velocityMultiplier", 1.0);
List<ConfigurationSection> effects = getConfigList(config, "effects");
ArrayList<PotionEffect> vanillaEffects = new ArrayList<>();
for (ConfigurationSection effect : Objects.requireNonNull(effects)) {
PotionEffectType type = PotionEffectType.getByName(effect.getString("type"));
int durationSeconds = effect.getInt("durationSeconds");
int duration = durationSeconds * 20;
int level = effect.getInt("level");
int amplifier = level - 1;
vanillaEffects.add(new PotionEffect(type, duration, amplifier));
}
this.effects = vanillaEffects;
}
private Color color;
private float velocityMultiplier;
private ArrayList<PotionEffect> effects;
@Override
@SuppressWarnings("unchecked") // fix your warnings, java
public void cast(CastData castData) {
// Construct the potion with the effects to be thrown
ItemStack potionItem = new ItemStack(Material.SPLASH_POTION);
PotionMeta potionMeta = (PotionMeta) potionItem.getItemMeta();
potionMeta.setBasePotionData(new PotionData(PotionType.MUNDANE));
for (PotionEffect effect : effects) {
potionMeta.addCustomEffect(effect, true);
}
if (color != null) {
potionMeta.setColor(color);
}
potionItem.setItemMeta(potionMeta);
// Spawn/throw the potion
ThrownPotion thrownPotion = castData.player.launchProjectile(ThrownPotion.class);
thrownPotion.setItem(potionItem);
thrownPotion.setVelocity(thrownPotion.getVelocity().multiply(velocityMultiplier));
}
@SuppressWarnings("unchecked") // fix your warnings, java
private List<ConfigurationSection> getConfigList(ConfigurationSection config, String path)
{
if (!config.isList(path)) return null;
List<ConfigurationSection> list = new ArrayList<>();
for (Object object : config.getList(path)) {
if (object instanceof Map) {
MemoryConfiguration mc = new MemoryConfiguration();
mc.addDefaults((Map<String, Object>) object);
list.add(mc);
}
}
return list;
}
} |
package ru.stqa.selenium.legrc.runner;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class HtmlScenario implements HtmlRunnable {
private String name;
private final File path;
private List<Step> steps = new ArrayList<Step>();
public HtmlScenario(File path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addStep(Step step) {
steps.add(step);
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append("\n");
for (Step step : steps) {
builder.append(step);
builder.append("\n");
}
return builder.toString();
}
public boolean run(RunContext ctx) {
System.out.print("\n" + name + " ");
boolean result = true;
for (Step step : steps) {
boolean stepResult = step.run(ctx);
result = stepResult && result;
System.out.print(stepResult ? "." : "F");
}
return result;
}
@Override
public String toHtml() {
StringBuilder sb = new StringBuilder();
sb.append("<div class='scenario'>\n");
sb.append("<p>Metadata</p>\n");
sb.append("<table class='scenario' border='1' cellpadding='1' cellspacing='1'><tbody>\n");
for (Step step : steps) {
sb.append(step.toHtml());
sb.append("\n");
}
sb.append("</tbody></table>\n");
sb.append("</div>\n");
return sb.toString();
}
} |
package seedu.address.logic.commands;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.AddressBook;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.*;
import seedu.address.model.task.UniqueTaskList.TaskNotFoundException;
import seedu.address.model.task.UniqueTaskList.DuplicateTaskException;
import java.util.HashSet;
import java.util.Set;
/**
* Updates a task in the task list.
*/
public class UpdateCommand extends Command {
public static final String COMMAND_WORD = "update";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Update a task in the task list.\n "
+ "Parameters: INDEX (must be a positive integer) NAME \n"
+ "Example: " + COMMAND_WORD
+ " 1 cs2103 t/quiz";
public static final String MESSAGE_UPDATE_TASK_SUCCESS = "Updated Task: %1$s";
public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task list";
public final int targetIndex;
private final Task toUpdate;
public String task_name;
public UpdateCommand(int targetIndex,String name,Set<String> tags) throws IllegalValueException{
this.targetIndex = targetIndex;
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
this.toUpdate = new Task(
new Name(name),
new UniqueTagList(tagSet)
);
}
@Override
public CommandResult execute() {
UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
if (lastShownList.size() < targetIndex) {
indicateAttemptToExecuteIncorrectCommand();
return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
ReadOnlyTask taskToUpdate = lastShownList.get(targetIndex - 1);
assert model != null;
try {
model.updateTask(taskToUpdate, toUpdate);
} catch (DuplicateTaskException e) {
return new CommandResult(MESSAGE_DUPLICATE_TASK);
} catch (TaskNotFoundException pnfe) {
assert false : "The target task cannot be missing";
}
return new CommandResult(String.format(MESSAGE_UPDATE_TASK_SUCCESS, toUpdate));
}
} |
package skadistats.clarity.processor.runner;
import skadistats.clarity.model.EngineType;
import skadistats.clarity.source.Source;
public interface Runner<T extends Runner> {
Context getContext();
int getTick();
Source getSource();
EngineType getEngineType();
T runWith(Object... processors);
} |
package org.restlet.ext.jetty9.internal;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.server.HttpChannel;
import org.restlet.Response;
import org.restlet.Server;
import org.restlet.data.Status;
import org.restlet.engine.adapter.ServerCall;
import org.restlet.engine.header.Header;
import org.restlet.util.Series;
/**
* Call that is used by the Jetty HTTP server connectors.
*
* @author Jerome Louvel
* @author Tal Liron
*/
public class JettyServerCall extends ServerCall
{
/**
* Constructor.
*
* @param server
* The parent server.
* @param channel
* The wrapped Jetty HTTP channel.
*/
public JettyServerCall( Server server, HttpChannel<?> channel )
{
super( server );
this.channel = channel;
this.requestHeadersAdded = false;
}
/**
* Closes the end point.
*/
public boolean abort()
{
getChannel().getEndPoint().close();
return true;
}
@Override
public void complete()
{
// Flush the response
try
{
getChannel().getResponse().flushBuffer();
}
catch( IOException e )
{
getLogger().log( Level.FINE, "Unable to flush the response", e );
}
// Fully complete the response
try
{
getChannel().getResponse().closeOutput();
}
catch( IOException e )
{
getLogger().log( Level.FINE, "Unable to complete the response", e );
}
}
@Override
public void flushBuffers() throws IOException
{
getChannel().getResponse().flushBuffer();
}
@Override
public List<Certificate> getCertificates()
{
final Object certificateArray = getChannel().getRequest().getAttribute( "javax.servlet.request.X509Certificate" );
if( certificateArray instanceof Certificate[] )
return Arrays.asList( (Certificate[]) certificateArray );
return null;
}
@Override
public String getCipherSuite()
{
final Object cipherSuite = getChannel().getRequest().getAttribute( "javax.servlet.request.cipher_suite" );
if( cipherSuite instanceof String )
return (String) cipherSuite;
return null;
}
@Override
public String getClientAddress()
{
return getChannel().getRequest().getRemoteAddr();
}
@Override
public int getClientPort()
{
return getChannel().getRequest().getRemotePort();
}
/**
* Returns the wrapped Jetty HTTP channel.
*
* @return The wrapped Jetty HTTP channel.
*/
public HttpChannel<?> getChannel()
{
return channel;
}
/**
* Returns the request method.
*
* @return The request method.
*/
@Override
public String getMethod()
{
return getChannel().getRequest().getMethod();
}
public InputStream getRequestEntityStream( long size )
{
try
{
return getChannel().getRequest().getInputStream();
}
catch( IOException e )
{
getLogger().log( Level.WARNING, "Unable to get request entity stream", e );
return null;
}
}
/**
* Returns the list of request headers.
*
* @return The list of request headers.
*/
@Override
public Series<Header> getRequestHeaders()
{
final Series<Header> result = super.getRequestHeaders();
if( !this.requestHeadersAdded )
{
// Copy the headers from the request object
for( Enumeration<String> names = getChannel().getRequest().getHeaderNames(); names.hasMoreElements(); )
{
final String headerName = names.nextElement();
for( Enumeration<String> values = getChannel().getRequest().getHeaders( headerName ); values.hasMoreElements(); )
{
final String headerValue = values.nextElement();
result.add( headerName, headerValue );
}
}
this.requestHeadersAdded = true;
}
return result;
}
public InputStream getRequestHeadStream()
{
// Not available
return null;
}
/**
* Returns the URI on the request line (most like a relative reference, but
* not necessarily).
*
* @return The URI on the request line.
*/
@Override
public String getRequestUri()
{
return getChannel().getRequest().getUri().toString();
}
/**
* Returns the response stream if it exists.
*
* @return The response stream if it exists.
*/
public OutputStream getResponseEntityStream()
{
try
{
return getChannel().getResponse().getOutputStream();
}
catch( IOException e )
{
getLogger().log( Level.WARNING, "Unable to get response entity stream", e );
return null;
}
}
/**
* Returns the response address.<br>
* Corresponds to the IP address of the responding server.
*
* @return The response address.
*/
@Override
public String getServerAddress()
{
return getChannel().getRequest().getLocalAddr();
}
@Override
public Integer getSslKeySize()
{
Integer keySize = (Integer) getChannel().getRequest().getAttribute( "javax.servlet.request.key_size" );
if( keySize == null )
keySize = super.getSslKeySize();
return keySize;
}
@Override
public String getSslSessionId()
{
final Object sessionId = getChannel().getRequest().getAttribute( "javax.servlet.request.ssl_session_id" );
if( sessionId instanceof String )
return (String) sessionId;
return null;
}
/**
* Indicates if the request was made using a confidential mean.<br>
*
* @return True if the request was made using a confidential mean.<br>
*/
@Override
public boolean isConfidential()
{
return getChannel().getRequest().isSecure();
}
@Override
public boolean isConnectionBroken( Throwable exception )
{
return ( exception instanceof EofException ) || super.isConnectionBroken( exception );
}
@Override
public void sendResponse( Response response ) throws IOException
{
// Add call headers
for( Iterator<Header> iter = getResponseHeaders().iterator(); iter.hasNext(); )
{
Header header = iter.next();
getChannel().getResponse().addHeader( header.getName(), header.getValue() );
}
// Set the status code in the response. We do this after adding the
// headers because when we have to rely on the 'sendError' method,
// the Servlet containers are expected to commit their response.
if( Status.isError( getStatusCode() ) && ( response.getEntity() == null ) )
{
try
{
getChannel().getResponse().sendError( getStatusCode(), getReasonPhrase() );
}
catch( IOException e )
{
getLogger().log( Level.WARNING, "Unable to set the response error status", e );
}
}
else
{
// Send the response entity
getChannel().getResponse().setStatus( getStatusCode() );
super.sendResponse( response );
}
}
/** The wrapped Jetty HTTP channel. */
private final HttpChannel<?> channel;
/** Indicates if the request headers were parsed and added. */
private volatile boolean requestHeadersAdded;
} |
package sample;
import com.centurylink.cloud.sdk.ClcSdk;
import com.centurylink.cloud.sdk.common.management.services.domain.datacenters.refs.DataCenter;
import com.centurylink.cloud.sdk.core.auth.services.domain.credentials.PropertiesFileCredentialsProvider;
import com.centurylink.cloud.sdk.servers.services.GroupService;
import com.centurylink.cloud.sdk.servers.services.ServerService;
import com.centurylink.cloud.sdk.servers.services.domain.InfrastructureConfig;
import com.centurylink.cloud.sdk.servers.services.domain.group.filters.GroupFilter;
import com.centurylink.cloud.sdk.servers.services.domain.group.refs.Group;
import com.centurylink.cloud.sdk.servers.services.domain.ip.CreatePublicIpConfig;
import com.centurylink.cloud.sdk.servers.services.domain.ip.port.PortConfig;
import com.centurylink.cloud.sdk.servers.services.domain.server.*;
import com.centurylink.cloud.sdk.servers.services.domain.server.filters.ServerFilter;
import com.centurylink.cloud.sdk.servers.services.domain.server.refs.Server;
import com.centurylink.cloud.sdk.servers.services.domain.template.refs.Template;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.time.ZonedDateTime;
import static com.centurylink.cloud.sdk.common.management.services.domain.datacenters.refs.DataCenter.US_CENTRAL_SALT_LAKE_CITY;
import static com.centurylink.cloud.sdk.common.management.services.domain.datacenters.refs.DataCenter.US_EAST_STERLING;
import static com.centurylink.cloud.sdk.servers.services.domain.InfrastructureConfig.dataCenter;
import static com.centurylink.cloud.sdk.servers.services.domain.group.GroupHierarchyConfig.group;
import static com.centurylink.cloud.sdk.servers.services.domain.group.refs.Group.DEFAULT_GROUP;
import static com.centurylink.cloud.sdk.servers.services.domain.server.CreateServerConfig.*;
import static com.centurylink.cloud.sdk.servers.services.domain.server.ServerType.STANDARD;
import static com.centurylink.cloud.sdk.servers.services.domain.template.filters.os.CpuArchitecture.x86_64;
import static com.centurylink.cloud.sdk.servers.services.domain.template.filters.os.OsType.CENTOS;
import static com.centurylink.cloud.sdk.tests.TestGroups.SAMPLES;
import static java.lang.Boolean.TRUE;
@Test(groups = SAMPLES)
public class PowerOperationsSampleApp extends Assert {
private final ServerService serverService;
private final GroupService groupService;
public PowerOperationsSampleApp() {
ClcSdk sdk = new ClcSdk(
new PropertiesFileCredentialsProvider("centurylink-clc-sdk-uat.properties")
);
serverService = sdk.serverService();
groupService = sdk.groupService();
}
public static CreateServerConfig centOsServer(String name) {
return new CreateServerConfig()
.name("PWROPS")
.description(name)
.type(STANDARD)
.machine(new Machine()
.cpuCount(1)
.ram(2)
)
.template(Template.refByOs()
.dataCenter(US_CENTRAL_SALT_LAKE_CITY)
.type(CENTOS)
.version("6")
.architecture(x86_64)
)
.timeToLive(ZonedDateTime.now().plusHours(2));
}
@BeforeClass
public void init() {
deleteServers();
groupService
.defineInfrastructure(dataCenter(US_EAST_STERLING).subitems(
group(DEFAULT_GROUP).subitems(
group("MyServers",
"MyServers Group Description").subitems(
centOsServer("a_nginx"),
centOsServer("a_apache"),
centOsServer("b_mysql")
)
)
))
.waitUntilComplete();
}
@AfterClass
public void deleteServers() {
serverService
.delete(new ServerFilter()
.dataCenters(US_EAST_STERLING)
.groupNames("MyServers")
.onlyActive()
)
.waitUntilComplete();
groupService
.delete(new GroupFilter()
.dataCenters(US_EAST_STERLING)
.names("MyServers")
)
.waitUntilComplete();
}
private Group myServersGroup() {
return Group.refByName()
.dataCenter(US_EAST_STERLING)
.name("MyServers");
}
private Server getMysqlServer() {
return
Server.refByDescription()
.dataCenter(US_EAST_STERLING)
.description("b_mysql");
}
@Test
public void testWholeGroupReboot() {
groupService
.reboot(myServersGroup())
.waitUntilComplete();
assert
serverService
.findLazy(new ServerFilter().groups(myServersGroup()))
.filter(s -> s.getDetails().getPowerState().equals("started"))
.count() == 3;
}
@Test
public void testCreateSnapshots() {
serverService
.createSnapshot(new ServerFilter()
.dataCenters(US_EAST_STERLING)
.groupNames("MyServers")
.descriptionContains("a_")
)
.waitUntilComplete();
assert
serverService
.findByRef(Server.refByDescription()
.dataCenter(US_EAST_STERLING)
.description("a_apache")
)
.getDetails().getSnapshots().size() == 1;
}
@Test(enabled = false)
public void testStartMaintenanceMode() {
groupService
.startMaintenance(myServersGroup())
.waitUntilComplete();
assert
serverService
.findLazy(new ServerFilter().groups(myServersGroup()))
.filter(s -> TRUE.equals(s.getDetails().getInMaintenanceMode()))
.count() == 3;
}
@Test
public void testStopMaintenanceMode() {
testStartMaintenanceMode();
groupService
.stopMaintenance(myServersGroup())
.waitUntilComplete();
assert
serverService
.findLazy(new ServerFilter().groups(myServersGroup()))
.filter(s -> !TRUE.equals(s.getDetails().getInMaintenanceMode()))
.count() == 3L;
}
@Test(enabled = false)
public void testStopMySql() {
serverService
.powerOff(new ServerFilter()
.dataCenters(US_EAST_STERLING)
.groupNames("MyServers")
.descriptionContains("b_")
)
.waitUntilComplete();
assert
serverService
.findByRef(getMysqlServer())
.getDetails()
.getPowerState()
.equals("stopped");
}
@Test
public void testStartMySql() {
testStopMySql();
serverService
.powerOn(getMysqlServer())
.waitUntilComplete();
assert
serverService
.findByRef(getMysqlServer())
.getDetails()
.getPowerState()
.equals("started");
}
} |
package jade.core;
//#MIDP_EXCLUDE_BEGIN
import java.net.InetAddress;
import java.net.UnknownHostException;
//#MIDP_EXCLUDE_END
import jade.util.Logger;
import jade.util.leap.List;
import jade.util.leap.Properties;
/**
* This class allows retrieving configuration-dependent classes.
*
* @author Federico Bergenti
* @author Giovanni Caire - TILAB
* @version 1.0, 22/11/00
*/
public abstract class Profile {
/**
This constant is the name of the property whose value contains a
boolean indicating if this is the Main Container or a peripheral
container.
*/
public static final String MAIN = "main";
/**
This constant is the name of the property whose value is a String
indicating the protocol to use to connect to the Main Container.
*/
public static final String MAIN_PROTO = "proto";
/**
This constant is the name of the property whose value is the name
(or the IP address) of the network host where the JADE Main
Container is running.
*/
public static final String MAIN_HOST = "host";
/**
This constant is the name of the property whose value contains an
integer representing the port number where the Main Container is
listening for container registrations.
*/
public static final String MAIN_PORT = "port";
/**
This constant is the name of the property whose Boolean value
tells whether to activate the automatic main container detection mechanism.
By means of this mechanism a peripheral container is able to automatically detect the
main container host and port at startup time. The mechanism is based on IP multicast communication
and must be activated on both the main container, that publishes its host and port on a given
multicast address (by default 239.255.10.99, port 1199), and on peripheral containers.
The default for this option is <code>true</code> on Main Containers and <code>false</code>
on peripheral containers
*/
public static final String DETECT_MAIN = "detect-main";
/**
This constant is the name of the property whose value contains
the host name the container must bind on. The host name must
refer to the local machine, and is generally needed only when
multiple network interfaces are present or a non-default name is
desired.
*/
public static final String LOCAL_HOST = "local-host";
/**
This constant is the name of the TCP port the container node must
listen to for incoming IMTP messages.
*/
public static final String LOCAL_PORT = "local-port";
/**
This constant is the name of the property whose Boolean value
tells whether a local Service Manager is exported by this
container (only when using JADE support for fault-tolerant
platform configurations).
*/
public static final String LOCAL_SERVICE_MANAGER = "backupmain";
/**
This constant is the name of the property whose Boolean value
tells whether startup options should be dumped. Default is false
*/
public static final String DUMP_OPTIONS = "dump-options";
/**
* This constant, when set to <code>true</code> tells the JADE runtime that it will be executed
* in an environment with no display available.
*/
public static final String NO_DISPLAY = "no-display";
//#APIDOC_EXCLUDE_BEGIN
public static final String MASTER_NODE_NAME = "master-node-name";
public static final String BE_BASE_NAME = "be-base-name";
public static final String BE_REPLICA_ZERO_ADDRESS = "be-replica-zero-address";
public static final String BE_REPLICA_INDEX = "be-replica-index";
public static final String BE_MEDIATOR_ID = "be-mediator-id";
public static final String OWNER = "owner";
// On J2SE and pJava, install mobility and notification services by default
//#J2ME_EXCLUDE_BEGIN
public static final String DEFAULT_SERVICES = "jade.core.mobility.AgentMobilityService;jade.core.event.NotificationService";
public static final String DEFAULT_SERVICES_NOMOBILITY = "jade.core.event.NotificationService";
//#J2ME_EXCLUDE_END
// On PJAVA the Notification service is not supported
//#DOTNET_EXCLUDE_BEGIN
/*#PJAVA_INCLUDE_BEGIN
public static final String DEFAULT_SERVICES = "jade.core.mobility.AgentMobilityService";
public static final String DEFAULT_SERVICES_NOMOBILITY = "";
#PJAVA_INCLUDE_END*/
//#DOTNET_EXCLUDE_END
// On DOTNET the Notification service is supported
/*#DOTNET_INCLUDE_BEGIN
public static final String DEFAULT_SERVICES = "jade.core.mobility.AgentMobilityService;jade.core.event.NotificationService";
public static final String DEFAULT_SERVICES_NOMOBILITY = "jade.core.event.NotificationService";
#DOTNET_INCLUDE_END*/
// On MIDP, no additional services are installed by default
/*#MIDP_INCLUDE_BEGIN
public static final String DEFAULT_SERVICES = "";
#MIDP_INCLUDE_END*/
//#APIDOC_EXCLUDE_END
/**
This constant is the name of the property whose value contains
the unique platform ID of a JADE platform. Agent GUIDs in JADE
are made by a platform-unique nickname, the '@' character and the
platform ID.
*/
public static final String PLATFORM_ID = "platform-id";
/**
This constant is the name of the property whose value contains
the user authentication type to be used to login to the JADE platform.
*/
public static final String USERAUTH_KEY = "userauth-key";
/**
This constant is the name of the property whose value contains the
list of agents that have to be launched at bootstrap time
*/
public static final String AGENTS = "agents";
/**
This constants is the name of the property whose value contains
the list of kernel-level services that have to be launched at
bootstrap time
*/
public static final String SERVICES = "services";
/**
This constant is the name of the property whose value contains the
list of addresses through which the platform <i>Service
Manager</i> can be reached.
*/
public static final String REMOTE_SERVICE_MANAGER_ADDRESSES = "smaddrs";
/**
* This constant is the key of the property whose value contains the
* list of MTPs that have to be launched at bootstrap time.
* This list must be retrieved via the <code>getSpecifiers(MTPS)<code>
* method.
*/
public static final String MTPS = "mtps";
public static final String IMTP = "imtp";
/**
* This constant is the key of the property whose value contains
* the desired name of the container. If this container name exists
* already, then a default name is assigned by the platform.
* The name of the main-container is always assigned by the platform
* and cannot be changed.
**/
public static final String CONTAINER_NAME = "container-name";
/**
* This constant is the key of the property whose value contains the
* list of ACLCODECSs that have to be launched at bootstrap time.
* This list must be retrieved via the <code>getSpecifiers(ACLCODECS)<code>
* method.
*/
public static final String ACLCODECS = "aclcodecs";
/**
This constant is the key of the property whose value (true or false)
indicates whether or not this platform accepts foreign agents i.e.
agents whose names are not of the form <local-name>@<platform-name>.
*/
public static final String ACCEPT_FOREIGN_AGENTS = "accept-foreign-agents";
//#APIDOC_EXCLUDE_BEGIN
/**
* This constant is the key of the property whose value contains the
* indication about the type of JVM.
*/
public static final String JVM = "jvm";
public static final String J2SE = "j2se";
public static final String PJAVA = "pjava";
public static final String MIDP = "midp";
//#APIDOC_EXCLUDE_END
/**
* This constant is the key of the property whose value contains
* the name of the directory where all the files generated by JADE
* should be put. The defaul value is the current directory.
**/
public static final String FILE_DIR = "file-dir";
public static final String LOCALHOST_CONSTANT = "localhost";
//#APIDOC_EXCLUDE_BEGIN
/**
Obtain a reference to the platform <i>Service Manager</i>, with
which kernel-level services can be added and removed.
@return A <code>ServiceManager</code> object, representing the
platform service manager.
*/
protected abstract ServiceManager getServiceManager() throws ProfileException;
/**
Obtain a reference to the platform <i>Service Finder</i>, with
which kernel-level services can be looked up.
@return A <code>ServiceFinder</code> object, representing the
platform service manager.
*/
protected abstract ServiceFinder getServiceFinder() throws ProfileException;
/**
Obtain a reference to the container <i>Command Processor</i>,
which manages kernel-level commands dispatching them to the
proper platform services.
@return A <code>ServiceManager</code> object, representing the
platform service manager.
*/
protected abstract CommandProcessor getCommandProcessor() throws ProfileException;
//#MIDP_EXCLUDE_BEGIN
protected abstract MainContainerImpl getMain() throws ProfileException;
//#MIDP_EXCLUDE_END
protected abstract IMTPManager getIMTPManager() throws ProfileException;
public abstract ResourceManager getResourceManager() throws ProfileException;
//#APIDOC_EXCLUDE_END
//#MIDP_EXCLUDE_BEGIN
/**
* Retrieve the configuration properties as they were passed to this Profile object, i.e. without
* internal initializations automatically performed by the Profile class.
*/
public abstract Properties getBootProperties();
//#MIDP_EXCLUDE_END
/**
* Retrieve a String value from the configuration properties.
* If no parameter corresponding to the specified key is found,
* return the provided default.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value to return when there is no property
* set for the given key.
*/
public abstract String getParameter(String key, String aDefault);
/**
* Retrieve a boolean value for a configuration property. If no
* corresponding property is found or if its string value cannot
* be converted to a boolean one, a default value is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value to return when there is no property
* set for the given key, or its value cannot be converted to a
* boolean value.
*/
public abstract boolean getBooleanProperty(String key, boolean aDefault);
/**
* Retrieve a list of Specifiers from the configuration properties.
* Agents, MTPs and other items are specified among the configuration
* properties in this way.
* If no list of Specifiers corresponding to the specified key is found,
* an empty list is returned.
* @param key The key identifying the list of Specifires to be retrieved
* among the configuration properties.
*/
public abstract List getSpecifiers(String key) throws ProfileException;
/**
* Assign the given value to the given property name.
*
* @param key is the property name
* @param value is the property value
*
*/
public abstract void setParameter(String key, String value);
/**
* Assign the given value to the given property name.
*
* @param key is the property name
* @param value is the property value
*
*/
public abstract void setSpecifiers(String key, List value);
public static String getDefaultNetworkName() {
String host = LOCALHOST_CONSTANT;
//#MIDP_EXCLUDE_BEGIN
try {
host = java.net.InetAddress.getLocalHost().getHostAddress();
if ("127.0.0.1".equals(host)) {
// Try with the name
host = java.net.InetAddress.getLocalHost().getHostName();
}
}
catch(Exception e) {
}
//#MIDP_EXCLUDE_END
return host;
}
//#MIDP_EXCLUDE_BEGIN
public static boolean isLocalHost(String host) {
return compareHostNames(host, LOCALHOST_CONSTANT);
}
/**
* Compares two host names regardless of whether they include domain or not.
*/
public static boolean compareHostNames(String host1, String host2) {
if (host1.equalsIgnoreCase(host2)) {
return true;
}
try {
if (host1.equalsIgnoreCase(LOCALHOST_CONSTANT)) {
host1 = InetAddress.getLocalHost().getHostName();
}
if (host2 != null && host2.equalsIgnoreCase(LOCALHOST_CONSTANT)) {
host2 = InetAddress.getLocalHost().getHostName();
}
InetAddress host1Addrs[] = InetAddress.getAllByName(host1);
InetAddress host2Addrs[] = InetAddress.getAllByName(host2);
// The trick here is to compare the InetAddress
// objects, not the strings since the one string might be a
// fully qualified Internet domain name for the host and the
// other might be a simple name.
// Example: myHost.hpl.hp.com and myHost might
// acutally be the same host even though the hostname strings do
// not match. When the InetAddress objects are compared, the IP
// addresses will be compared.
int i = 0;
boolean isEqual = false;
while ((!isEqual) && (i < host1Addrs.length)) {
int j = 0;
while ((!isEqual) && (j < host2Addrs.length)) {
isEqual = host1Addrs[i].equals(host2Addrs[j]);
j++;
}
i++;
}
return isEqual;
}
catch (UnknownHostException uhe) {
// If we can't retrieve the necessary information and the two strings are not the same,
// we have no chance to make a correct comparison --> return false
return false;
}
}
//#MIDP_EXCLUDE_END
} |
package jcifs.smb;
import org.apache.log4j.Logger;
class SmbTree {
private static final Logger LOGGER = Logger.getLogger(SmbTree.class);
private static int tree_conn_counter;
/* 0 - not connected
* 1 - connecting
* 2 - connected
* 3 - disconnecting
*/
int connectionState;
int tid;
String share;
String service = "?????";
String service0;
SmbSession session;
boolean inDfs, inDomainDfs;
int tree_num; // used by SmbFile.isOpen
SmbTree( SmbSession session, String share, String service ) {
this.session = session;
this.share = share.toUpperCase();
if( service != null && service.startsWith( "??" ) == false ) {
this.service = service;
}
this.service0 = this.service;
this.connectionState = 0;
}
boolean matches( String share, String service ) {
return this.share.equalsIgnoreCase( share ) &&
( service == null || service.startsWith( "??" ) ||
this.service.equalsIgnoreCase( service ));
}
public boolean equals(Object obj) {
if (obj instanceof SmbTree) {
SmbTree tree = (SmbTree)obj;
return matches(tree.share, tree.service);
}
return false;
}
void send( ServerMessageBlock request,
ServerMessageBlock response ) throws SmbException {
synchronized (session.transport()) {
if( response != null ) {
response.received = false;
}
treeConnect( request, response );
if( request == null || (response != null && response.received )) {
return;
}
if( service.equals( "A:" ) == false ) {
switch( request.command ) {
case ServerMessageBlock.SMB_COM_OPEN_ANDX:
case ServerMessageBlock.SMB_COM_NT_CREATE_ANDX:
case ServerMessageBlock.SMB_COM_READ_ANDX:
case ServerMessageBlock.SMB_COM_WRITE_ANDX:
case ServerMessageBlock.SMB_COM_CLOSE:
case ServerMessageBlock.SMB_COM_TREE_DISCONNECT:
break;
case ServerMessageBlock.SMB_COM_TRANSACTION:
case ServerMessageBlock.SMB_COM_TRANSACTION2:
switch( ((SmbComTransaction)request).subCommand & 0xFF ) {
case SmbComTransaction.NET_SHARE_ENUM:
case SmbComTransaction.NET_SERVER_ENUM2:
case SmbComTransaction.NET_SERVER_ENUM3:
case SmbComTransaction.TRANS_PEEK_NAMED_PIPE:
case SmbComTransaction.TRANS_WAIT_NAMED_PIPE:
case SmbComTransaction.TRANS_CALL_NAMED_PIPE:
case SmbComTransaction.TRANS_TRANSACT_NAMED_PIPE:
case SmbComTransaction.TRANS2_GET_DFS_REFERRAL:
break;
default:
throw new SmbException( "Invalid operation for " + service + " service" );
}
break;
default:
throw new SmbException( "Invalid operation for " + service + " service" + request );
}
}
request.tid = tid;
if( inDfs && !service.equals("IPC") && request.path != null && request.path.length() > 0 ) {
/* When DFS is in action all request paths are
* full UNC paths minus the first backslash like
* \server\share\path\to\file
* as opposed to normally
* \path\to\file
*/
request.flags2 = ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
request.path = '\\' + session.transport().tconHostName + '\\' + share + request.path;
}
try {
session.send( request, response );
} catch( SmbException se ) {
if (se.getNtStatus() == SmbException.NT_STATUS_NETWORK_NAME_DELETED) {
/* Someone removed the share while we were
* connected. Bastards! Disconnect this tree
* so that it reconnects cleanly should the share
* reappear in this client's lifetime.
*/
treeDisconnect( true );
}
throw se;
}
}
}
void treeConnect( ServerMessageBlock andx,
ServerMessageBlock andxResponse ) throws SmbException {
synchronized (session.transport()) {
String unc;
while (connectionState != 0) {
if (connectionState == 2 || connectionState == 3) // connected or disconnecting
return;
try {
LOGGER.debug("Waiting on transport: connectionState=" + connectionState);
session.transport().wait();
LOGGER.debug("notifyAll called on transport: connectionState=" + connectionState);
} catch (InterruptedException ie) {
LOGGER.error(ie.getMessage(), ie);
throw new SmbException(ie.getMessage(), ie);
}
}
connectionState = 1; // trying ...
try {
/* The hostname to use in the path is only known for
* sure if the NetBIOS session has been successfully
* established.
*/
session.transport.connect();
unc = "\\\\" + session.transport.tconHostName + '\\' + share;
/* IBM iSeries doesn't like specifying a service. Always reset
* the service to whatever was determined in the constructor.
*/
service = service0;
/*
* Tree Connect And X Request / Response
*/
LOGGER.debug( "treeConnect: unc=" + unc + ",service=" + service );
SmbComTreeConnectAndXResponse response =
new SmbComTreeConnectAndXResponse( andxResponse );
SmbComTreeConnectAndX request =
new SmbComTreeConnectAndX( session, unc, service, andx );
session.send( request, response );
tid = response.tid;
service = response.service;
inDfs = response.shareIsInDfs;
tree_num = tree_conn_counter++;
connectionState = 2; // connected
LOGGER.debug("Notifiing all threads waitnig on transport");
session.transport().notifyAll();
} catch (SmbException se) {
LOGGER.error("There was an error while connection", se);
treeDisconnect(true);
throw se;
} catch (RuntimeException e) {
LOGGER.error("There was an error while connection", e);
treeDisconnect(true);
throw e;
} catch (Error e) {
LOGGER.error("There was an error while connection", e);
treeDisconnect(true);
throw e;
}
}
}
void treeDisconnect( boolean inError ) {
synchronized (session.transport()) {
if (connectionState != 2) // not-connected
return;
connectionState = 3; // disconnecting
if (!inError && tid != 0) {
try {
send( new SmbComTreeDisconnect(), null );
} catch( SmbException se ) {
LOGGER.warn("", se);
}
}
inDfs = false;
inDomainDfs = false;
connectionState = 0;
session.transport.notifyAll();
}
}
public String toString() {
return "SmbTree[share=" + share +
",service=" + service +
",tid=" + tid +
",inDfs=" + inDfs +
",inDomainDfs=" + inDomainDfs +
",connectionState=" + connectionState + "]";
}
} |
package org.neo4j.backup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
/**
* A simple Runnable that is meant to consume the output and error streams of a
* detached process, for debugging purposes.
*
*/
public class StreamConsumer implements Runnable
{
private final Reader in;
private final Writer out;
private static final int BUFFER_SIZE = 32;
StreamConsumer( InputStream in, OutputStream out )
{
this.in = new InputStreamReader( in );
this.out = new OutputStreamWriter( out );
}
@Override
public void run()
{
try
{
char[] cbuf = new char[BUFFER_SIZE];
int count;
while ( ( count = in.read( cbuf, 0, BUFFER_SIZE ) ) >= 0 )
{
out.write( cbuf, 0, count );
}
out.flush();
}
catch ( IOException exc )
{
System.err.println( "Child I/O Transfer - " + exc );
}
}
} |
package jlib.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Vector;
/**
*
* @author dejan
*/
public class Utility {
public static String getLineInfo() {
StackTraceElement ste = new Throwable().getStackTrace()[1];
return ste.getFileName() + ": Line " + ste.getLineNumber();
} // getLineInfo() method
/**
* Function to export csv file
* @param file
* @param h1
* @param h2
* @param headings
* @param data
*/
public static void exportToCSV(String file, String h1, String h2, Vector<String> headings, Vector<Vector<String>> data){
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream ps = new PrintStream(out);
ps.println(h1);
ps.println(h2);
ps.println();
//print headings
Iterator<String> hi = headings.iterator();
int i = 0;
while(hi.hasNext()){
ps.print(hi.next());
if(i<headings.size()-1)
ps.print(",");
else
ps.println();
i++;
}
//print the data
Iterator<Vector<String>> di = data.iterator();
Iterator<String> si = null;
while(di.hasNext()){
//get iterator
si = di.next().iterator();
i=0;
while(si.hasNext()){
ps.print(si.next());
if(i<headings.size()-1)
ps.print(",");
else
ps.println();
i++;
}
}
ps.close();
} catch (IOException e) {
e.printStackTrace();
}
} // exportToCSV() method
} // Utility class |
package jobschedular;
import java.util.Scanner;
/**
*
* @author deepak
*/
public class Task {
public int index; // task index (ID)
public int burst; // task burst time
public Task(int index, int burst) {
this.index = index;
this.burst = burst;
}
abstract void operation();
} |
package joshua.util;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class Regex {
// Alas, Pattern is final, thus no subclassing and this indirection
private final Pattern pattern;
// Singletons -- add all common patterns here
/**
* A pattern to match if the complete string is empty except
* for whitespace and end-of-line comments beginning with
* an octothorpe (<code>#</code>).
*/
public static final Regex commentOrEmptyLine =
new Regex("^\\s*(?:\\
// BUG: this should be replaced by a real regex for numbers.
// Perhaps "^[\\+\\-]?\\d+(?:\\.\\d+)?$" is enough.
// This is only used by JoshuaDecoder.writeConfigFile so far.
/**
* A pattern to match floating point numbers. (Current
* implementation is overly permissive.)
*/
public static final Regex floatingNumber = new Regex("^[\\d\\.\\-\\+]+");
// Common patterns for splitting
/**
* A pattern for splitting on one or more whitespace.
*/
public static final Regex spaces = new Regex("\\s+");
/**
* A pattern for splitting on one or more whitespace.
*/
public static final Regex tabs = new Regex("\\t+");
/**
* A pattern for splitting on the equals character, with
* optional whitespace on each side.
*/
public static final Regex equalsWithSpaces = new Regex("\\s*=\\s*");
/**
* A pattern for splitting on three vertical pipes, with
* one or more whitespace on each side.
*/
public static final Regex threeBarsWithSpace = new Regex("\\s\\|{3}\\s");
// Constructor
public Regex(String regex) throws PatternSyntaxException {
this.pattern = Pattern.compile(regex);
}
// Convenience Methods
/**
* Returns whether the input string matches this
* <code>Regex</code>.
*/
public final boolean matches(String input) {
return this.pattern.matcher(input).matches();
}
/**
* Split a character sequence, removing instances of this
* <code>Regex</code>.
*/
public final String[] split(CharSequence input) {
return this.pattern.split(input);
}
/**
* Split a character sequence, removing instances of this
* <code>Regex</code>, up to a limited number of segments.
*/
public final String[] split(CharSequence input, int limit) {
return this.pattern.split(input, limit);
}
/**
* Replace all substrings of the input which match this
* <code>Regex</code> with the specified replacement string.
*/
public final String replaceAll(String input, String replacement) {
return this.pattern.matcher(input).replaceAll(replacement);
}
/**
* Replace the first substring of the input which matches
* this <code>Regex</code> with the specified replacement
* string.
*/
public final String replaceFirst(String input, String replacement) {
return this.pattern.matcher(input).replaceFirst(replacement);
}
} |
package io.fundrequest.core.keycloak;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.RealmResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KeycloakConfig {
@Value("${io.fundrequest.keycloak-custom.server-url}")
private String serverUrl;
@Value("${io.fundrequest.keycloak-custom.realm}")
private String realm;
@Value("${io.fundrequest.keycloak-custom.username}")
private String username;
@Value("${io.fundrequest.keycloak-custom.password}")
private String password;
@Value("${io.fundrequest.keycloak-custom.client-id}")
private String clientId;
@Value("${io.fundrequest.keycloak-custom.client-secret}")
private String clientSecret;
@Bean
public RealmResource keycloak() {
final Keycloak keycloak = Keycloak.getInstance(
serverUrl,
realm,
username,
password,
clientId,
clientSecret);
return keycloak.realm(realm);
}
} |
package aj.hadoop.monitor.examples;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.lang.management.*;
import java.util.StringTokenizer;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import aj.hadoop.monitor.util.PickerClient;
@Aspect
public class WordSearchMonitor {
private String HOST = "localhost";
private int PORT = 9999;
/** log file */
public static final String LOGFILE = "Hanoi-MethodTraceMonitor.log";
/**
* pointcut
* @param word
* @param one
*/
@Pointcut ("call(void org.apache.hadoop.mapreduce.Mapper.Context.write" +
"(" +
"java.lang.Object, " +
"java.lang.Object" +
"))" +
"&& cflow(execution(public void org.apache.hadoop.examples.WordSearch$TokenizerMapper.map(..)))" +
"&& args(word, one)")
public void catch_map_method(Object word, Object one){}
@Before ( value = "catch_map_method( key, one )")
public void logging_current_method( JoinPoint thisJoinPoint,
Object key,
Object one) {
String ret = "";
try {
String outfile = "/tmp" + "/" + this.LOGFILE;
FileOutputStream fos = new FileOutputStream(outfile, true);
OutputStreamWriter out = new OutputStreamWriter(fos);
ret += "key:" + key;
out.write(ret);
out.close();
} catch (IOException ioe) {
System.out.println(ioe);
} catch (Exception e) {
System.out.println(e);
}
System.err.println("** [POINTCUT]" + ret);
System.out.println("** [POINTCUT]" + ret);
PickerClient client = new PickerClient();
client.setHost(this.HOST);
client.setPORT(this.PORT);
client.send(ret);
System.out.println("** " + ret);
}
} |
package net.java.sip.communicator.impl.protocol.irc;
import java.io.*;
import java.security.*;
import java.util.*;
import javax.net.ssl.*;
import net.java.sip.communicator.impl.protocol.irc.ModeParser.ModeEntry;
import net.java.sip.communicator.service.certificate.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import com.ircclouds.irc.api.*;
import com.ircclouds.irc.api.domain.*;
import com.ircclouds.irc.api.domain.messages.*;
import com.ircclouds.irc.api.domain.messages.interfaces.*;
import com.ircclouds.irc.api.listeners.*;
import com.ircclouds.irc.api.state.*;
/**
* An implementation of IRC using the irc-api library.
*
* @author Danny van Heumen
*
* TODO Make irc-api OSGi aware.
* FIXME Surround expensive LOGGER calls with if-conditions.
*/
public class IrcStack
{
/**
* Expiration time for chat room list cache.
*/
private static final long CHAT_ROOM_LIST_CACHE_EXPIRATION = 60000000000L;
/**
* Logger
*/
private static final Logger LOGGER = Logger.getLogger(IrcStack.class);
/**
* Parent provider for IRC
*/
private final ProtocolProviderServiceIrcImpl provider;
/**
* Container for joined channels.
*/
private final Map<String, ChatRoomIrcImpl> joined = Collections
.synchronizedMap(new HashMap<String, ChatRoomIrcImpl>());
/**
* Server parameters that are set and provided during the connection
* process.
*/
private final ServerParameters params;
/**
* Instance of the IRC library.
*/
private IRCApi irc;
/**
* Connection state of a successful IRC connection.
*/
private IIRCState connectionState;
/**
* The cached channel list.
*
* Contained inside a simple container object in order to lock the container
* while accessing the contents.
*/
private final Container<List<String>> channellist =
new Container<List<String>>(null);
/**
* Constructor
*
* @param parentProvider Parent provider
* @param nick User's nick name
* @param login User's login name
* @param version Version
* @param finger Finger
*/
public IrcStack(final ProtocolProviderServiceIrcImpl parentProvider,
final String nick, final String login, final String version,
final String finger)
{
if (parentProvider == null)
{
throw new NullPointerException("parentProvider cannot be null");
}
this.provider = parentProvider;
this.params = new IrcStack.ServerParameters(nick, login, finger, null);
}
/**
* Check whether or not a connection is established.
*
* @return true if connected, false otherwise.
*/
public boolean isConnected()
{
return (this.irc != null && this.connectionState != null
&& this.connectionState.isConnected());
}
/**
* Check whether the connection is a secure connection (TLS).
*
* @return true if connection is secure, false otherwise.
*/
public boolean isSecureConnection()
{
return isConnected() && this.connectionState.getServer().isSSL();
}
/**
* Connect to specified host, port, optionally using a password.
*
* @param host IRC server's host name
* @param port IRC port
* @param password
* @param autoNickChange
* @throws Exception
*/
public void connect(String host, int port, String password,
boolean secureConnection, boolean autoNickChange) throws Exception
{
if (this.irc != null && this.connectionState != null
&& this.connectionState.isConnected())
return;
// Make sure we start with an empty joined-channel list.
this.joined.clear();
this.irc = new IRCApiImpl(true);
synchronized (this.irc)
{
this.params.setServer(new IRCServer(host, port, password,
secureConnection));
this.params.setCustomContext(getCustomSSLContext(host));
this.irc.addListener(new ServerListener());
connectSynchronized();
}
}
/**
* Perform synchronized connect operation.
*
* @return returns true upon successful connection, false otherwise
* @throws Exception exception thrown when connect fails
*/
private void connectSynchronized() throws Exception
{
final Result<IIRCState, Exception> result =
new Result<IIRCState, Exception>();
synchronized (result)
{
// start connecting to the specified server ...
try
{
this.irc.connect(this.params, new Callback<IIRCState>()
{
@Override
public void onSuccess(IIRCState state)
{
synchronized (result)
{
LOGGER.trace("IRC connected successfully!");
result.setDone(state);
result.notifyAll();
}
}
@Override
public void onFailure(Exception e)
{
synchronized (result)
{
LOGGER.trace("IRC connection FAILED! ("
+ e.getMessage() + ")");
result.setDone(e);
result.notifyAll();
}
}
});
while (!result.isDone())
{
LOGGER
.trace("Waiting for the connection to be established ...");
result.wait();
}
this.connectionState = result.getValue();
// TODO Implement connection timeout and a way to recognize that
// the timeout occurred.
if (this.connectionState != null
&& this.connectionState.isConnected())
{
// if connecting succeeded, set state to registered
this.provider.setCurrentRegistrationState(
RegistrationState.REGISTERED);
}
else
{
// if connecting failed, set state to unregistered and throw
// the exception if one exists
this.provider
.setCurrentRegistrationState(
RegistrationState.UNREGISTERED);
Exception e = result.getException();
if (e != null)
throw e;
}
}
catch (IOException e)
{
this.provider
.setCurrentRegistrationState(
RegistrationState.UNREGISTERED);
throw e;
}
catch (InterruptedException e)
{
this.provider
.setCurrentRegistrationState(
RegistrationState.UNREGISTERED);
throw e;
}
}
}
/**
* Create a custom SSL context for this particular server.
*
* @return returns a customized SSL context or <tt>null</tt> if one cannot
* be created.
*/
private SSLContext getCustomSSLContext(String hostname)
{
SSLContext context = null;
try
{
CertificateService cs =
IrcActivator.getCertificateService();
X509TrustManager tm =
cs.getTrustManager(hostname);
context = cs.getSSLContext(tm);
}
catch (GeneralSecurityException e)
{
LOGGER.error("failed to create custom SSL context", e);
}
return context;
}
/**
* Disconnect from the IRC server
*/
public void disconnect()
{
if (this.connectionState == null && this.irc == null)
return;
synchronized (this.joined)
{
// Leave all joined channels.
for (ChatRoomIrcImpl channel : this.joined.values())
{
leave(channel);
}
}
synchronized (this.irc)
{
// Disconnect and clean up
try
{
this.irc.disconnect();
}
catch (RuntimeException e)
{
// Disconnect might throw ChannelClosedException. Shouldn't be a
// problem, but for now lets log it just to be sure.
LOGGER.debug("exception occurred while disconnecting", e);
}
this.irc = null;
this.connectionState = null;
}
this.provider
.setCurrentRegistrationState(RegistrationState.UNREGISTERED);
}
/**
* Dispose
*/
public void dispose()
{
disconnect();
}
/**
* Get the nick name of the user.
*
* @return Returns either the acting nick if a connection is established or
* the configured nick.
*/
public String getNick()
{
return (this.connectionState == null) ? this.params.getNickname()
: this.connectionState.getNickname();
}
/**
* Set the user's new nick name.
*
* @param nick the new nick name
*/
public void setUserNickname(String nick)
{
LOGGER.trace("Setting user's nick name to " + nick);
if (this.connectionState == null)
{
this.params.setNickname(nick);
}
else
{
this.irc.changeNick(nick);
}
}
/**
* Set the subject of the specified chat room.
*
* @param chatroom The chat room for which to set the subject.
* @param subject The subject.
*/
public void setSubject(ChatRoomIrcImpl chatroom, String subject)
{
if (!isConnected())
throw new IllegalStateException(
"Please connect to an IRC server first.");
if (chatroom == null)
throw new IllegalArgumentException("Cannot have a null chatroom");
LOGGER.trace("Setting chat room topic to '" + subject + "'");
this.irc
.changeTopic(chatroom.getIdentifier(),
subject == null ? "" : subject);
}
/**
* Check whether the user has joined a particular chat room.
*
* @param chatroom Chat room to check for.
* @return Returns true in case the user is already joined, or false if the
* user has not joined.
*/
public boolean isJoined(ChatRoomIrcImpl chatroom)
{
return this.joined.containsKey(chatroom.getIdentifier());
}
/**
* Get a list of channels available on the IRC server.
*
* @return List of available channels.
*/
public List<String> getServerChatRoomList()
{
LOGGER.trace("Start retrieve server chat room list.");
// TODO Currently, not using an API library method for listing
// channels, since it isn't available.
synchronized (this.channellist)
{
List<String> list =
this.channellist.get(CHAT_ROOM_LIST_CACHE_EXPIRATION);
if (list == null)
{
LOGGER
.trace("Chat room list null or outdated. Start retrieving new chat room list.");
Result<List<String>, Exception> listSignal =
new Result<List<String>, Exception>(
new LinkedList<String>());
synchronized (listSignal)
{
try
{
this.irc.addListener(new ChannelListListener(this.irc,
listSignal));
this.irc.rawMessage("LIST");
while (!listSignal.isDone())
{
LOGGER.trace("Start waiting for list ...");
listSignal.wait();
}
LOGGER.trace("Done waiting for list.");
}
catch (InterruptedException e)
{
LOGGER.warn("INTERRUPTED while waiting for list.", e);
}
}
list = listSignal.getValue();
this.channellist.set(list);
LOGGER.trace("Finished retrieve server chat room list.");
}
else
{
LOGGER.trace("Using cached list of server chat rooms.");
}
return Collections.unmodifiableList(list);
}
}
/**
* Join a particular chat room.
*
* @param chatroom Chat room to join.
* @throws OperationFailedException failed to join the chat room
*/
public void join(ChatRoomIrcImpl chatroom) throws OperationFailedException
{
join(chatroom, "");
}
/**
* Join a particular chat room.
*
* Issue a join channel IRC operation and wait for the join operation to
* complete (either successfully or failing).
*
* @param chatroom The chatroom to join.
* @param password Optionally, a password that may be required for some
* channels.
* @throws OperationFailedException failed to join the chat room
*/
public void join(final ChatRoomIrcImpl chatroom, final String password)
throws OperationFailedException
{
if (!isConnected())
throw new IllegalStateException(
"Please connect to an IRC server first");
if (chatroom == null)
throw new IllegalArgumentException("chatroom cannot be null");
if (password == null)
throw new IllegalArgumentException("password cannot be null");
if (this.joined.containsKey(chatroom.getIdentifier())
|| chatroom.isPrivate())
{
// If we already joined this particular chatroom or if it is a
// private chat room (i.e. message from one user to another), no
// further action is required.
return;
}
LOGGER.trace("Start joining channel " + chatroom.getIdentifier());
final Result<Object, Exception> joinSignal =
new Result<Object, Exception>();
synchronized (joinSignal)
{
LOGGER
.trace("Issue join channel command to IRC library and wait for join operation to complete (un)successfully.");
// TODO Refactor this ridiculous nesting of functions and
// classes.
this.irc.joinChannel(chatroom.getIdentifier(), password,
new Callback<IRCChannel>()
{
@Override
public void onSuccess(IRCChannel channel)
{
LOGGER
.trace("Started callback for successful join of channel '"
+ chatroom.getIdentifier() + "'.");
ChatRoomIrcImpl actualChatRoom = chatroom;
synchronized (joinSignal)
{
try
{
if (!channel.getName().equalsIgnoreCase(
actualChatRoom.getIdentifier()))
{
// If the channel name is not the
// original chat room name, then we have
// been forwarded.
actualChatRoom =
new ChatRoomIrcImpl(channel.getName(),
IrcStack.this.provider);
MessageIrcImpl message =
new MessageIrcImpl(
"Forwarding to channel "
+ channel.getName(),
"text/plain", "UTF-8", null);
IrcStack.this.provider.getMUC()
.registerChatRoomInstance(
actualChatRoom);
chatroom
.fireMessageReceivedEvent(
message,
null,
new Date(),
MessageReceivedEvent
.SYSTEM_MESSAGE_RECEIVED);
}
IrcStack.this.joined.put(
actualChatRoom.getIdentifier(),
actualChatRoom);
IrcStack.this.irc
.addListener(new ChatRoomListener(
actualChatRoom));
IRCTopic topic = channel.getTopic();
actualChatRoom.updateSubject(topic.getValue());
for (IRCUser user : channel.getUsers())
{
ChatRoomMemberRole role =
ChatRoomMemberRole.SILENT_MEMBER;
Set<IRCUserStatus> statuses =
channel.getStatusesForUser(user);
for (IRCUserStatus status : statuses)
{
role =
convertMemberMode(status
.getChanModeType().charValue());
}
if (IrcStack.this.getNick().equals(
user.getNick()))
{
actualChatRoom.prepUserRole(role);
}
else
{
ChatRoomMemberIrcImpl member =
new ChatRoomMemberIrcImpl(
IrcStack.this.provider,
actualChatRoom, user.getNick(),
role);
actualChatRoom.addChatRoomMember(
member.getContactAddress(), member);
}
}
}
finally
{
// In any case, issue the local user
// presence, since the irc library notified
// us of a successful join. We should wait
// as long as possible though. First we need
// to fill the list of chat room members and
// other chat room properties.
IrcStack.this.provider
.getMUC()
.fireLocalUserPresenceEvent(
actualChatRoom,
LocalUserChatRoomPresenceChangeEvent
.LOCAL_USER_JOINED,
null);
LOGGER
.trace("Finished successful join callback "
+ "for channel '"
+ chatroom.getIdentifier()
+ "'. Waking up original thread.");
// Notify waiting threads of finished
// execution.
joinSignal.setDone();
joinSignal.notifyAll();
}
}
}
@Override
public void onFailure(Exception e)
{
LOGGER
.trace("Started callback for failed attempt to "
+ "join channel '" + chatroom.getIdentifier()
+ "'.");
// TODO how should we communicate a failed attempt
// at joining the channel? (System messages don't
// seem to show if there is no actual chat room
// presence.)
synchronized (joinSignal)
{
try
{
MessageIrcImpl message =
new MessageIrcImpl(
"Failed to join channel "
+ chatroom.getIdentifier() + " ("
+ e.getMessage() + ")",
"text/plain", "UTF-8",
"Failed to join");
chatroom
.fireMessageReceivedEvent(
message,
null,
new Date(),
MessageReceivedEvent
.SYSTEM_MESSAGE_RECEIVED);
}
finally
{
LOGGER
.trace("Finished callback for failed "
+ "attempt to join channel '"
+ chatroom.getIdentifier()
+ "'. Waking up original thread.");
// Notify waiting threads of finished
// execution
joinSignal.setDone(e);
joinSignal.notifyAll();
}
}
}
});
try
{
while (!joinSignal.isDone())
{
LOGGER.trace("Waiting for channel join message ...");
// Wait until async channel join operation has finished.
joinSignal.wait();
}
LOGGER
.trace("Finished waiting for join operation for channel '"
+ chatroom.getIdentifier() + "' to complete.");
// TODO How to handle 480 (+j): Channel throttle exceeded?
Exception e = joinSignal.getException();
if (e != null)
{
// in case an exception occurred during join process
throw new OperationFailedException(e.getMessage(),
OperationFailedException.CHAT_ROOM_NOT_JOINED, e);
}
}
catch (InterruptedException e)
{
// TODO what should we do with this? Maybe store in joinSignal
// if there's nothing else?
throw new OperationFailedException(e.getMessage(),
OperationFailedException.INTERNAL_ERROR, e);
}
}
}
/**
* Part from a joined chat room.
*
* @param chatroom The chat room to part from.
*/
public void leave(ChatRoomIrcImpl chatroom)
{
if (chatroom.isPrivate())
return;
// You only actually join non-private chat rooms, so only these ones
// need to be left.
leave(chatroom.getIdentifier());
}
/**
* Part from a joined chat room.
*
* @param chatRoomName The chat room to part from.
*/
private void leave(String chatRoomName)
{
this.irc.leaveChannel(chatRoomName);
}
public void banParticipant(ChatRoomIrcImpl chatroom, ChatRoomMember member,
String reason)
{
// TODO Implement this.
}
/**
* Kick channel member.
*
* @param chatroom channel to kick from
* @param member member to kick
* @param reason kick message to deliver
*/
public void kickParticipant(ChatRoomIrcImpl chatroom,
ChatRoomMember member, String reason)
{
this.irc.kick(chatroom.getIdentifier(), member.getContactAddress(),
reason);
}
/**
* Issue invite command to IRC server.
*
* @param memberId member to invite
* @param chatroom channel to invite to
*/
public void invite(String memberId, ChatRoomIrcImpl chatroom)
{
this.irc.rawMessage("INVITE " + memberId + " "
+ chatroom.getIdentifier());
}
/**
* Send a command to the IRC server.
*
* @param chatroom the chat room
* @param command the command message
*/
public void command(ChatRoomIrcImpl chatroom, String command)
{
String target;
if (command.toLowerCase().startsWith("/msg "))
{
command = command.substring(5);
int endOfNick = command.indexOf(' ');
if (endOfNick == -1)
{
throw new IllegalArgumentException(
"Invalid private message format. "
+ "Message was not sent.");
}
target = command.substring(0, endOfNick);
command = command.substring(endOfNick + 1);
}
else
{
target = chatroom.getIdentifier();
}
this.irc.message(target, command);
}
/**
* Send an IRC message.
*
* @param chatroom The chat room to send the message to.
* @param message The message to send.
*/
public void message(ChatRoomIrcImpl chatroom, String message)
{
String target = chatroom.getIdentifier();
this.irc.message(target, message);
}
/**
* Convert a member mode character to a ChatRoomMemberRole instance.
*
* @param modeSymbol The member mode character.
* @return Return the instance of ChatRoomMemberRole corresponding to the
* member mode character.
*/
private static ChatRoomMemberRole convertMemberMode(char modeSymbol)
{
return Mode.bySymbol(modeSymbol).getRole();
}
/**
* A listener for server-level messages (any messages that are related to
* the server, the connection, that are not related to any chatroom in
* particular) or that are personal message from user to local user.
*/
private class ServerListener
extends VariousMessageListenerAdapter
{
/**
* Print out server notices for debugging purposes and for simply
* keeping track of the connections.
*
* @param msg the server notice
*/
@Override
public void onServerNotice(ServerNotice msg)
{
LOGGER.debug("NOTICE: " + msg.getText());
}
/**
* Print out server numeric messages for debugging purposes and for
* simply keeping track of the connection.
*
* @param msg the numeric message
*/
@Override
public void onServerNumericMessage(ServerNumericMessage msg)
{
LOGGER.debug("NUM MSG: " + msg.getNumericCode() + ": "
+ msg.getText());
}
/**
* Print out received errors for debugging purposes and may be for
* expected errors that can be acted upon.
*
* @param msg the error message
*/
@Override
public void onError(ErrorMessage msg)
{
LOGGER.debug("ERROR: " + msg.getSource() + ": " + msg.getText());
}
/**
* Upon receiving a private message from a user, deliver that to a
* private chat room and create one if it does not exist. We can ignore
* normal chat rooms, since they each have their own ChatRoomListener
* for managing chat room operations.
*
* @param msg the private message
*/
@Override
public void onUserPrivMessage(UserPrivMsg msg)
{
ChatRoomIrcImpl chatroom = null;
String user = msg.getSource().getNick();
String text = Utils.parse(msg.getText());
chatroom = IrcStack.this.joined.get(user);
if (chatroom == null)
{
chatroom = initiatePrivateChatRoom(user);
}
deliverReceivedMessageToPrivateChat(chatroom, user, text);
}
/**
* Deliver a private message to the provided chat room.
*
* @param chatroom the chat room
* @param user the source user
* @param text the message
*/
private void deliverReceivedMessageToPrivateChat(
ChatRoomIrcImpl chatroom, String user, String text)
{
ChatRoomMember member = chatroom.getChatRoomMember(user);
MessageIrcImpl message =
new MessageIrcImpl(text, "text/html", "UTF-8", null);
chatroom.fireMessageReceivedEvent(message, member, new Date(),
ChatRoomMessageReceivedEvent.CONVERSATION_MESSAGE_RECEIVED);
}
/**
* Create a private chat room if one does not exist yet.
*
* @param user private chat room for this user
* @return returns the private chat room
*/
private ChatRoomIrcImpl initiatePrivateChatRoom(String user)
{
ChatRoomIrcImpl chatroom =
(ChatRoomIrcImpl) IrcStack.this.provider.getMUC()
.findRoom(user);
IrcStack.this.joined.put(chatroom.getIdentifier(), chatroom);
ChatRoomMemberIrcImpl member =
new ChatRoomMemberIrcImpl(IrcStack.this.provider, chatroom,
user, ChatRoomMemberRole.MEMBER);
chatroom.addChatRoomMember(member.getContactAddress(), member);
IrcStack.this.provider.getMUC().fireLocalUserPresenceEvent(
chatroom,
LocalUserChatRoomPresenceChangeEvent.LOCAL_USER_JOINED,
"Private conversation initiated.");
return chatroom;
}
}
/**
* A chat room listener.
*
* A chat room listener is registered for each chat room that we join. The
* chat room listener updates chat room data and fires events based on IRC
* messages that report state changes for the specified channel.
*
* @author danny
*
*/
private class ChatRoomListener
extends VariousMessageListenerAdapter
{
/**
* Chat room for which this listener is working.
*/
private ChatRoomIrcImpl chatroom;
/**
* Constructor. Instantiate listener for the provided chat room.
*
* @param chatroom
*/
private ChatRoomListener(ChatRoomIrcImpl chatroom)
{
if (chatroom == null)
throw new IllegalArgumentException("chatroom cannot be null");
this.chatroom = chatroom;
}
/**
* Event in case of topic change.
*/
@Override
public void onTopicChange(TopicMessage msg)
{
if (!isThisChatRoom(msg.getChannelName()))
return;
this.chatroom.updateSubject(msg.getTopic().getValue());
}
/**
* Event in case of channel mode changes.
*/
@Override
public void onChannelMode(ChannelModeMessage msg)
{
if (!isThisChatRoom(msg.getChannelName()))
return;
processModeMessage(msg);
}
/**
* Event in case of channel join message.
*/
@Override
public void onChannelJoin(ChanJoinMessage msg)
{
if (!isThisChatRoom(msg.getChannelName()))
return;
if (isMe(msg.getSource()))
{
// I think that this should not happen.
}
else
{
String user = msg.getSource().getNick();
ChatRoomMemberIrcImpl member =
new ChatRoomMemberIrcImpl(IrcStack.this.provider,
this.chatroom, user, ChatRoomMemberRole.SILENT_MEMBER);
this.chatroom.fireMemberPresenceEvent(member, null,
ChatRoomMemberPresenceChangeEvent.MEMBER_JOINED, null);
}
}
/**
* Event in case of channel part.
*/
@Override
public void onChannelPart(ChanPartMessage msg)
{
if (!isThisChatRoom(msg.getChannelName()))
return;
if (isMe(msg.getSource()))
{
IrcStack.this.irc.deleteListener(this);
IrcStack.this.joined.remove(this.chatroom);
IrcStack.this.provider.getMUC().fireLocalUserPresenceEvent(
this.chatroom,
LocalUserChatRoomPresenceChangeEvent.LOCAL_USER_LEFT, null);
}
else
{
String user = msg.getSource().getNick();
ChatRoomMember member = this.chatroom.getChatRoomMember(user);
try
{
// Possibility that 'member' is null (should be fixed now
// that race condition in irc-api is fixed)
this.chatroom.fireMemberPresenceEvent(member, null,
ChatRoomMemberPresenceChangeEvent.MEMBER_LEFT,
msg.getPartMsg());
}
catch (NullPointerException e)
{
LOGGER
.warn(
"This should not have happened. Please report this "
+ "as it is a bug.",
e);
}
}
}
/**
* Event in case of channel kick.
*/
@Override
public void onChannelKick(ChannelKick msg)
{
if (!isThisChatRoom(msg.getChannelName()))
return;
String kickedUser = msg.getKickedNickname();
if (isMe(kickedUser))
{
IrcStack.this.irc.deleteListener(this);
IrcStack.this.joined.remove(this.chatroom);
IrcStack.this.provider.getMUC().fireLocalUserPresenceEvent(
this.chatroom,
LocalUserChatRoomPresenceChangeEvent.LOCAL_USER_KICKED,
msg.getText());
}
else
{
ChatRoomMember kickedMember =
this.chatroom.getChatRoomMember(kickedUser);
String user = msg.getSource().getNick();
if (kickedMember != null)
{
ChatRoomMember kicker =
this.chatroom.getChatRoomMember(user);
this.chatroom.fireMemberPresenceEvent(kickedMember, kicker,
ChatRoomMemberPresenceChangeEvent.MEMBER_KICKED,
msg.getText());
}
}
}
/**
* Event in case of user quit.
*/
@Override
public void onUserQuit(QuitMessage msg)
{
String user = msg.getSource().getNick();
ChatRoomMember member = this.chatroom.getChatRoomMember(user);
if (member != null)
{
this.chatroom.fireMemberPresenceEvent(member, null,
ChatRoomMemberPresenceChangeEvent.MEMBER_QUIT,
msg.getQuitMsg());
}
}
/**
* Event in case of nick change.
*/
@Override
public void onNickChange(NickMessage msg)
{
if (msg == null)
return;
String oldNick = msg.getSource().getNick();
String newNick = msg.getNewNick();
ChatRoomMemberIrcImpl member =
(ChatRoomMemberIrcImpl) this.chatroom
.getChatRoomMember(oldNick);
if (member != null)
{
member.setName(newNick);
this.chatroom.updateChatRoomMemberName(oldNick);
ChatRoomMemberPropertyChangeEvent evt =
new ChatRoomMemberPropertyChangeEvent(member,
this.chatroom,
ChatRoomMemberPropertyChangeEvent.MEMBER_NICKNAME,
oldNick, newNick);
this.chatroom.fireMemberPropertyChangeEvent(evt);
}
}
/**
* Event in case of channel message arrival.
*/
@Override
public void onChannelMessage(ChannelPrivMsg msg)
{
if (!isThisChatRoom(msg.getChannelName()))
return;
String text = Utils.parse(msg.getText());
MessageIrcImpl message =
new MessageIrcImpl(text, "text/html", "UTF-8", null);
ChatRoomMemberIrcImpl member =
new ChatRoomMemberIrcImpl(IrcStack.this.provider,
this.chatroom, msg.getSource().getNick(),
ChatRoomMemberRole.MEMBER);
this.chatroom.fireMessageReceivedEvent(message, member, new Date(),
ChatRoomMessageReceivedEvent.CONVERSATION_MESSAGE_RECEIVED);
}
/**
* Process mode changes.
*
* @param msg raw mode message
*/
private void processModeMessage(ChannelModeMessage msg)
{
// TODO Handle or ignore ban channel mode (MODE STRING: +b
// *!*@some-ip.dynamicIP.provider.net)
ChatRoomMemberIrcImpl sourceMember = extractChatRoomMember(msg);
ModeParser parser = new ModeParser(msg);
for (ModeEntry mode : parser.getModes())
{
switch (mode.getMode())
{
case OWNER:
String ownerUserName = mode.getParams()[0];
if (isMe(ownerUserName))
{
ChatRoomLocalUserRoleChangeEvent event;
if (mode.isAdded())
{
event =
new ChatRoomLocalUserRoleChangeEvent(
this.chatroom,
ChatRoomMemberRole.SILENT_MEMBER,
ChatRoomMemberRole.OWNER, false);
}
else
{
event =
new ChatRoomLocalUserRoleChangeEvent(
this.chatroom, ChatRoomMemberRole.OWNER,
ChatRoomMemberRole.SILENT_MEMBER, false);
}
this.chatroom.fireLocalUserRoleChangedEvent(event);
}
else
{
ChatRoomMember owner =
this.chatroom
.getChatRoomMember(mode.getParams()[0]);
if (owner != null)
{
if (mode.isAdded())
{
this.chatroom.fireMemberRoleEvent(owner,
ChatRoomMemberRole.OWNER);
}
else
{
this.chatroom.fireMemberRoleEvent(owner,
ChatRoomMemberRole.SILENT_MEMBER);
}
}
}
break;
case OPERATOR:
String opUserName = mode.getParams()[0];
if (isMe(opUserName))
{
ChatRoomLocalUserRoleChangeEvent event;
if (mode.isAdded())
{
event =
new ChatRoomLocalUserRoleChangeEvent(
this.chatroom,
ChatRoomMemberRole.SILENT_MEMBER,
ChatRoomMemberRole.ADMINISTRATOR, false);
}
else
{
event =
new ChatRoomLocalUserRoleChangeEvent(
this.chatroom,
ChatRoomMemberRole.ADMINISTRATOR,
ChatRoomMemberRole.SILENT_MEMBER, false);
}
this.chatroom.fireLocalUserRoleChangedEvent(event);
}
else
{
ChatRoomMember op =
this.chatroom.getChatRoomMember(opUserName);
if (op != null)
{
if (mode.isAdded())
{
this.chatroom.fireMemberRoleEvent(op,
ChatRoomMemberRole.ADMINISTRATOR);
}
else
{
this.chatroom.fireMemberRoleEvent(op,
ChatRoomMemberRole.SILENT_MEMBER);
}
}
}
break;
case VOICE:
String voiceUserName = mode.getParams()[0];
if (isMe(voiceUserName))
{
ChatRoomLocalUserRoleChangeEvent event;
if (mode.isAdded())
{
event =
new ChatRoomLocalUserRoleChangeEvent(
this.chatroom,
ChatRoomMemberRole.SILENT_MEMBER,
ChatRoomMemberRole.MEMBER, false);
}
else
{
event =
new ChatRoomLocalUserRoleChangeEvent(
this.chatroom, ChatRoomMemberRole.MEMBER,
ChatRoomMemberRole.SILENT_MEMBER, false);
}
this.chatroom.fireLocalUserRoleChangedEvent(event);
}
else
{
ChatRoomMember voice =
this.chatroom.getChatRoomMember(voiceUserName);
if (voice != null)
{
if (mode.isAdded())
{
this.chatroom.fireMemberRoleEvent(voice,
ChatRoomMemberRole.MEMBER);
}
else
{
this.chatroom.fireMemberRoleEvent(voice,
ChatRoomMemberRole.SILENT_MEMBER);
}
}
}
break;
case LIMIT:
MessageIrcImpl message;
if (mode.isAdded())
{
try
{
message =
new MessageIrcImpl("channel limit set to "
+ Integer.parseInt(mode.getParams()[0])
+ " by "
+ (sourceMember.getContactAddress()
.length() == 0 ? "server"
: sourceMember.getContactAddress()),
"text/plain", "UTF-8", null);
}
catch (NumberFormatException e)
{
LOGGER.warn("server sent incorrect limit, "
+ "limit is not a number", e);
break;
}
}
else
{
// TODO "server" is now easily fakeable if someone
// calls himself server. There should be some other way
// to represent the server if a message comes from
// something other than a normal chat room member.
message =
new MessageIrcImpl(
"channel limit removed by "
+ (sourceMember.getContactAddress()
.length() == 0 ? "server"
: sourceMember.getContactAddress()),
"text/plain", "UTF-8", null);
}
this.chatroom.fireMessageReceivedEvent(message,
sourceMember, new Date(),
ChatRoomMessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED);
break;
case UNKNOWN:
LOGGER.info("Unknown mode: " + (mode.isAdded() ? "+" : "-")
+ mode.getParams()[0] + ". Original mode string: '"
+ msg.getModeStr() + "'");
break;
default:
LOGGER.info("Unsupported mode '"
+ (mode.isAdded() ? "+" : "-") + mode.getMode()
+ "' (from modestring '" + msg.getModeStr() + "')");
break;
}
}
}
/**
* Extract chat room member identifier from message.
*
* @param msg raw mode message
* @return returns member instance
*/
private ChatRoomMemberIrcImpl extractChatRoomMember(
ChannelModeMessage msg)
{
ChatRoomMemberIrcImpl member;
ISource source = msg.getSource();
if (source instanceof IRCServer)
{
// TODO Created chat room member with creepy empty contact ID.
// Interacting with this contact might screw up other sections
// of code which is not good. Is there a better way to represent
// an IRC server as a chat room member?
member =
new ChatRoomMemberIrcImpl(IrcStack.this.provider,
this.chatroom, "", ChatRoomMemberRole.ADMINISTRATOR);
}
else if (source instanceof IRCUser)
{
String nick = ((IRCUser) source).getNick();
member =
(ChatRoomMemberIrcImpl) this.chatroom
.getChatRoomMember(nick);
}
else
{
throw new IllegalArgumentException("Unknown source type: "
+ source.getClass().getName());
}
return member;
}
/**
* Test whether this listener corresponds to the chat room.
*
* @param chatRoomName chat room name
* @return returns true if this listener applies, false otherwise
*/
private boolean isThisChatRoom(String chatRoomName)
{
return this.chatroom.getIdentifier().equalsIgnoreCase(chatRoomName);
}
/**
* Test whether the source user is this user.
*
* @param user the source user
* @return returns true if this use, or false otherwise
*/
private boolean isMe(IRCUser user)
{
return IrcStack.this.connectionState.getNickname().equals(
user.getNick());
}
/**
* Test whether the user nick is this user.
*
* @param name nick of the user
* @return returns true if so, false otherwise
*/
private boolean isMe(String name)
{
return IrcStack.this.connectionState.getNickname().equals(name);
}
}
/**
* Special listener that processes LIST replies and signals once the list is
* completely filled.
*/
private static class ChannelListListener
extends VariousMessageListenerAdapter
{
/**
* Reference to the IRC API instance.
*/
private final IRCApi api;
/**
* Reference to the provided list instance.
*/
private Result<List<String>, Exception> signal;
/**
* Constructor for channel list listener.
* @param api irc-api library instance
* @param list signal for sync signaling
*/
private ChannelListListener(IRCApi api,
Result<List<String>, Exception> list)
{
if (api == null)
throw new IllegalArgumentException(
"IRC api instance cannot be null");
this.api = api;
this.signal = list;
}
/**
* Act on LIST messages: 321 RPL_LISTSTART, 322 RPL_LIST, 323
* RPL_LISTEND
*
* Clears the list upon starting. All received channels are added to the
* list. Upon receiving RPL_LISTEND finalize the list and signal the
* waiting thread that it can continue processing the list.
*/
@Override
public void onServerNumericMessage(ServerNumericMessage msg)
{
if (this.signal.isDone())
return;
switch (msg.getNumericCode())
{
case 321:
synchronized (this.signal)
{
this.signal.getValue().clear();
}
break;
case 322:
String channel = parse(msg.getText());
if (channel != null)
{
synchronized (this.signal)
{
this.signal.getValue().add(channel);
}
}
break;
case 323:
synchronized (this.signal)
{
// Done collecting channels. Remove listener and then we're
// done.
this.api.deleteListener(this);
this.signal.setDone();
this.signal.notifyAll();
}
break;
// TODO Add support for REPLY 416: LIST :output too large, truncated
default:
break;
}
}
/**
* Parse an IRC server response RPL_LIST. Extract the channel name.
*
* @param text raw server response
* @return returns the channel name
*/
private String parse(String text)
{
int endOfChannelName = text.indexOf(' ');
if (endOfChannelName == -1)
return null;
// Create a new string to make sure that the original (larger)
// strings can be GC'ed.
return new String(text.substring(0, endOfChannelName));
}
}
/**
* Container for storing server parameters.
*/
private static class ServerParameters
implements IServerParameters
{
/**
* Nick name.
*/
private String nick;
/**
* Alternative nick names.
*/
private List<String> alternativeNicks = new ArrayList<String>();
/**
* Real name.
*/
private String real;
/**
* Ident.
*/
private String ident;
/**
* IRC server.
*/
private IRCServer server;
/**
* Custom SSL Context.
*/
private SSLContext sslContext = null;
/**
* Construct ServerParameters instance.
* @param nickName nick name
* @param realName real name
* @param ident ident
* @param server IRC server instance
*/
private ServerParameters(String nickName, String realName,
String ident, IRCServer server)
{
this.nick = checkNick(nickName);
this.alternativeNicks.add(nickName + "_");
this.real = realName;
this.ident = ident;
this.server = server;
}
/**
* Get nick name.
*
* @return returns nick name
*/
@Override
public String getNickname()
{
return this.nick;
}
/**
* Set new nick name.
*
* @param nick nick name
*/
public void setNickname(String nick)
{
this.nick = checkNick(nick);
}
private String checkNick(String nick)
{
if (nick == null)
throw new IllegalArgumentException(
"a nick name must be provided");
if (nick.startsWith("
throw new IllegalArgumentException(
"the nick name must not start with '
+ "since this is reserved for IRC channels");
return nick;
}
/**
* Get alternative nick names.
*
* @return returns list of alternatives
*/
@Override
public List<String> getAlternativeNicknames()
{
return this.alternativeNicks;
}
/**
* Get ident string.
*
* @return returns ident
*/
@Override
public String getIdent()
{
return this.ident;
}
/**
* Get real name
*
* @return returns real name
*/
@Override
public String getRealname()
{
return this.real;
}
/**
* Get server
*
* @return returns server instance
*/
@Override
public IRCServer getServer()
{
return this.server;
}
/**
* Set server instance.
*
* @param server IRC server instance
*/
public void setServer(IRCServer server)
{
if (server == null)
throw new IllegalArgumentException("server cannot be null");
this.server = server;
}
/**
* Get the SSL Context.
*
* Returns the custom SSLContext or null in case there is no
* custom implementation.
*
* @return returns the SSLContext or null
*/
@Override
public SSLContext getCustomContext()
{
return this.sslContext;
}
/**
* Set custom SSLContext.
*
* @param context the custom SSLContext
*/
public void setCustomContext(SSLContext context)
{
this.sslContext = context;
}
}
/**
* Simplest possible container that we can use for locking while we're
* checking/modifying the contents.
*
* @param <T> The type of instance to store in the container
*/
private static class Container<T>
{
/**
* The stored instance. (Can be null)
*/
private T instance;
/**
* Time of stored instance.
*/
private long time;
/**
* Constructor that immediately sets the instance.
*
* @param instance the instance to set
*/
private Container(T instance)
{
this.instance = instance;
this.time = System.nanoTime();
}
/**
* Conditionally get the stored instance. Get the instance when time
* difference is within specified bound. Otherwise return null.
*
* @param bound maximum time difference that is allowed.
* @return returns instance if within bounds, or null otherwise
*/
public T get(long bound)
{
if (System.nanoTime() - this.time > bound)
{
return null;
}
return this.instance;
}
/**
* Set an instance
*
* @param instance the instance
*/
public void set(T instance)
{
this.instance = instance;
this.time = System.nanoTime();
}
}
} |
package net.sf.jaer.eventprocessing.filter;
import com.google.common.collect.EvictingQueue;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.jogamp.opengl.util.gl2.GLUT;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.RemoteControlCommand;
import net.sf.jaer.util.RemoteControlled;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.eventio.AEFileInputStream;
import net.sf.jaer.graphics.ChipDataFilePreview;
import net.sf.jaer.graphics.DavisRenderer;
import net.sf.jaer.util.DATFileFilter;
import net.sf.jaer.util.DrawGL;
/**
* Filter for testing noise filters
*
* @author Tobi Delbruck, Shasha Guo, Oct-Jan 2020
*/
@Description("Tests background BA denoising filters by injecting known noise and measuring how much signal and noise is filtered")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class NoiseTesterFilter extends AbstractNoiseFilter implements FrameAnnotater, RemoteControlled {
public static final int MAX_NUM_RECORDED_EVENTS = 10_0000_0000;
public static final float MAX_TOTAL_NOISE_RATE_HZ = 50e6f;
public static final float RATE_LIMIT_HZ = 25; //per pixel, separately for leak and shot rates
private FilterChain chain;
private float shotNoiseRateHz = getFloat("shotNoiseRateHz", .1f);
private float leakNoiseRateHz = getFloat("leakNoiseRateHz", .1f);
private float shotNoiseRateCoVDecades = getFloat("shotNoiseRateCoVDecades", 0);
private float[][] shotNoiseRateArray = null;
private float[] shotNoiseRateIntervals = null; // stored by column, with y changing fastest
private float poissonDtUs = 1;
private float shotOffThresholdProb; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
private float shotOnThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
private float leakOnThresholdProb; // bounds for samppling Poisson noise
private PrerecordedNoise prerecordedNoise = null;
private ROCHistory rocHistory = new ROCHistory();
private static String DEFAULT_CSV_FILENAME_BASE = "NoiseTesterFilter";
private String csvFileName = getString("csvFileName", DEFAULT_CSV_FILENAME_BASE);
private File csvFile = null;
private BufferedWriter csvWriter = null;
/**
* Chip dimensions in pixels, set in initFilter()
*/
private int sx = 0, sy = 0;
private Integer lastTimestampPreviousPacket = null, firstSignalTimestmap = null; // use Integer Object so it can be null to signify no value yet
private float TPR = 0;
private float TPO = 0;
private float TNR = 0;
private float accuracy = 0;
private float BR = 0;
float inSignalRateHz = 0, inNoiseRateHz = 0, outSignalRateHz = 0, outNoiseRateHz = 0;
// private EventPacket<ApsDvsEvent> signalAndNoisePacket = null;
private final Random random = new Random();
private EventPacket<BasicEvent> signalAndNoisePacket = null;
// private EventList<BasicEvent> noiseList = new EventList();
private AbstractNoiseFilter[] noiseFilters = null;
private AbstractNoiseFilter selectedFilter = null;
protected boolean resetCalled = true; // flag to reset on next event
// private float annotateAlpha = getFloat("annotateAlpha", 0.5f);
private DavisRenderer renderer = null;
private boolean overlayPositives = getBoolean("overlayPositives", false);
private boolean overlayNegatives = getBoolean("overlayNegatives", false);
private int rocHistoryLength = getInt("rocHistoryLength", 1);
private final int LIST_LENGTH = 10000;
private ArrayList<FilteredEventWithNNb> tpList = new ArrayList(LIST_LENGTH),
fnList = new ArrayList(LIST_LENGTH),
fpList = new ArrayList(LIST_LENGTH),
tnList = new ArrayList(LIST_LENGTH); // output of classification
private ArrayList<BasicEvent> noiseList = new ArrayList<BasicEvent>(LIST_LENGTH); // TODO make it lazy, when filter is enabled
private NNbHistograms nnbHistograms = new NNbHistograms(); // tracks stats of neighbors to events when they are filtered in or out
public enum NoiseFilterEnum {
None, BackgroundActivityFilter, SpatioTemporalCorrelationFilter, DoubleWindowFilter, OrderNBackgroundActivityFilter, MedianDtFilter
}
private NoiseFilterEnum selectedNoiseFilterEnum = NoiseFilterEnum.valueOf(getString("selectedNoiseFilter", NoiseFilterEnum.BackgroundActivityFilter.toString())); //default is BAF
private float correlationTimeS = getFloat("correlationTimeS", 20e-3f);
private volatile boolean stopMe = false; // to interrupt if filterPacket takes too long
private final long MAX_FILTER_PROCESSING_TIME_MS = 5000; // times out to avoid using up all heap
private TextRenderer textRenderer = null;
public NoiseTesterFilter(AEChip chip) {
super(chip);
String out = "5. Output";
String noise = "4. Noise";
setPropertyTooltip(noise, "shotNoiseRateHz", "rate per pixel of shot noise events");
setPropertyTooltip(noise, "shotNoiseRateCoVDecades", "Coefficient of Variation of shot noise rate in decades across pixel array");
setPropertyTooltip(noise, "leakNoiseRateHz", "rate per pixel of leak noise events");
setPropertyTooltip(noise, "openNoiseSourceRecording", "Open a pre-recorded AEDAT file as noise source.");
setPropertyTooltip(noise, "closeNoiseSourceRecording", "Closes the pre-recorded noise input.");
setPropertyTooltip(out, "closeCsvFile", "Closes the output spreadsheet data file.");
setPropertyTooltip(out, "csvFileName", "Enter a filename base here to open CSV output file (appending to it if it already exists)");
setPropertyTooltip(TT_FILT_CONTROL, "selectedNoiseFilterEnum", "Choose a noise filter to test");
// setPropertyTooltip(ann, "annotateAlpha", "Sets the transparency for the annotated pixels. Only works for Davis renderer.");
setPropertyTooltip(TT_DISP, "overlayPositives", "<html><p>Overlay positives (passed input events)<p>FPs (red) are noise in output.<p>TPs (green) are signal in output.");
setPropertyTooltip(TT_DISP, "overlayNegatives", "<html><p>Overlay negatives (rejected input events)<p>TNs (green) are noise filtered out.<p>FNs (red) are signal filtered out.");
setPropertyTooltip(TT_DISP, "rocHistoryLength", "Number of samples of ROC point to show.");
setPropertyTooltip(TT_DISP, "clearROCHistory", "Clears samples from display.");
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
boolean wasEnabled = this.filterEnabled;
this.filterEnabled = yes;
if (yes) {
resetFilter();
for (EventFilter2D f : chain) {
if (selectedFilter != null && selectedFilter == f) {
f.setFilterEnabled(yes);
}
}
} else {
for (EventFilter2D f : chain) {
f.setFilterEnabled(false);
}
if (renderer != null) {
renderer.clearAnnotationMap();
}
}
if (!isEnclosed()) {
String key = prefsEnabledKey();
getPrefs().putBoolean(key, this.filterEnabled);
}
support.firePropertyChange("filterEnabled", wasEnabled, this.filterEnabled);
}
private int rocSampleCounter = 0;
private final int ROC_LABEL_TAU_INTERVAL = 30;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
String s = null;
float x, y;
if (!showFilteringStatistics) {
return;
}
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 10));
}
final GLUT glut = new GLUT();
GL2 gl = drawable.getGL().getGL2();
rocHistory.draw(gl);
gl.glPushMatrix();
gl.glColor3f(.2f, .2f, .8f); // must set color before raster position (raster position is like glVertex)
gl.glRasterPos3f(0, sy * .9f, 0);
String overlayString = "Overlay ";
if (overlayNegatives) {
overlayString += "negatives: FN (green), TN (red)";
}
if (overlayPositives) {
overlayString += "positives: TP (green), FP (red)";
}
if ((!overlayPositives) && (!overlayNegatives)) {
overlayString += "None";
}
if (prerecordedNoise != null) {
s = String.format("NTF: Precorded noise from %s. %s", prerecordedNoise.file.getName(),
overlayString);
} else {
s = String.format("NTF: Synthetic noise: Leak %sHz, Shot %sHz. %s", eng.format(leakNoiseRateHz), eng.format(shotNoiseRateHz),
overlayString);
}
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, getAnnotationRasterYPosition("NTF"), 0);
s = String.format("TPR=%s%% FPR=%s%% TNR=%s%% dT=%.2fus", eng.format(100 * TPR), eng.format(100 * (1 - TNR)), eng.format(100 * TNR), poissonDtUs);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, getAnnotationRasterYPosition("NTF") + 10, 0);
s = String.format("In sigRate=%s noiseRate=%s, Out sigRate=%s noiseRate=%s Hz", eng.format(inSignalRateHz), eng.format(inNoiseRateHz), eng.format(outSignalRateHz), eng.format(outNoiseRateHz));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glPopMatrix();
// nnbHistograms.draw(gl); shows neighbor distributions, not informative
}
private void annotateNoiseFilteringEvents(ArrayList<FilteredEventWithNNb> outSig, ArrayList<FilteredEventWithNNb> outNoise) {
if (renderer == null) {
return;
}
renderer.clearAnnotationMap();
final int offset = 1;
// final float a = getAnnotateAlpha();
final float[] noiseColor = {1f, 0, 0, 1}, sigColor = {0, 1f, 0, 1};
for (FilteredEventWithNNb e : outSig) {
renderer.setAnnotateColorRGBA(e.e.x + 2 >= sx ? e.e.x : e.e.x + offset, e.e.y - 2 < 0 ? e.e.y : e.e.y - offset, sigColor);
}
for (FilteredEventWithNNb e : outNoise) {
renderer.setAnnotateColorRGBA(e.e.x + 2 >= sx ? e.e.x : e.e.x + offset, e.e.y - 2 < 0 ? e.e.y : e.e.y - offset, noiseColor);
// renderer.setAnnotateColorRGBA(e.x+2, e.y-2, noiseColor);
}
}
private class BackwardsTimestampException extends Exception {
public BackwardsTimestampException(String string) {
super(string);
}
}
private ArrayList<BasicEvent> createEventList(EventPacket<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.getSize());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
private ArrayList<BasicEvent> createEventList(List<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.size());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
private final boolean checkStopMe(String where) {
if (stopMe) {
log.severe(where + "\n: Processing took longer than " + MAX_FILTER_PROCESSING_TIME_MS + "ms, disabling filter");
setFilterEnabled(false);
return true;
}
return false;
}
/**
* Finds the intersection of events in a that are in b. Assumes packets are
* non-monotonic in timestamp ordering. Handles duplicates. Each duplicate
* is matched once. The matching is by event .equals() method.
*
* @param a ArrayList<BasicEvent> of a
* @param b likewise, but is list of events with NNb bits in byte
* @param intersect the target list to fill with intersections, include NNb
* bits
* @return count of intersections
*/
private int countIntersect(ArrayList<BasicEvent> a, ArrayList<FilteredEventWithNNb> b, ArrayList<FilteredEventWithNNb> intersect) {
intersect.clear();
if (a.isEmpty() || b.isEmpty()) {
return 0;
}
int count = 0;
// TODO test case
// a = new ArrayList();
// b = new ArrayList();
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 1, (short) 0));
// a.add(new BasicEvent(4, (short) 2, (short) 0));
//// a.add(new BasicEvent(2, (short) 0, (short) 0));
//// a.add(new BasicEvent(10, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 1, (short) 0));
// b.add(new BasicEvent(10, (short) 0, (short) 0));
int i = 0, j = 0;
final int na = a.size(), nb = b.size();
while (i < na && j < nb) {
if (a.get(i).timestamp < b.get(j).e.timestamp) {
i++;
} else if (b.get(j).e.timestamp < a.get(i).timestamp) {
j++;
} else {
// If timestamps equal, it mmight be identical events or maybe not
// and there might be several events with identical timestamps.
// We MUST match all a with all b.
// We don't want to increment both pointers or we can miss matches.
// We do an inner double loop for exhaustive matching as long as the timestamps
// are identical.
int i1 = i, j1 = j;
while (i1 < na && j1 < nb && a.get(i1).timestamp == b.get(j1).e.timestamp) {
boolean match = false;
while (j1 < nb && i1 < na && a.get(i1).timestamp == b.get(j1).e.timestamp) {
if (a.get(i1).equals(b.get(j1).e)) {
count++;
intersect.add(b.get(j1)); // TODO debug
// we have a match, so use up the a element
i1++;
match = true;
}
j1++;
}
if (!match) {
i1++;
}
j1 = j; // reset j to start of matching ts region
}
i = i1; // when done, timestamps are different or we reached end of either or both arrays
j = j1;
}
}
// System.out.println("%%%%%%%%%%%%%%");
// printarr(a, "a");
// printarr(b, "b");
// printarr(intersect, "intsct");
return count;
}
// TODO test case
private void printarr(ArrayList<BasicEvent> a, String n) {
final int MAX = 30;
if (a.size() > MAX) {
System.out.printf("
return;
}
System.out.printf("%s[%d]
for (int i = 0; i < a.size(); i++) {
BasicEvent e = a.get(i);
System.out.printf("%s[%d]=[%d %d %d %d]\n", n, i, e.timestamp, e.x, e.y, (e instanceof PolarityEvent) ? ((PolarityEvent) e).getPolaritySignum() : 0);
}
}
@Override
synchronized public EventPacket<? extends BasicEvent> filterPacket(EventPacket<? extends BasicEvent> in) {
totalEventCount = 0; // from super, to measure filtering
filteredOutEventCount = 0;
int TP = 0; // filter take real events as real events. the number of events
int TN = 0; // filter take noise events as noise events
int FP = 0; // filter take noise events as real events
int FN = 0; // filter take real events as noise events
if (in == null || in.isEmpty()) {
// log.warning("empty packet, cannot inject noise");
return in;
}
stopMe = false;
Timer stopper = new Timer("NoiseTesterFilter.Stopper", true);
stopper.schedule(new TimerTask() {
@Override
public void run() {
stopMe = true;
}
}, MAX_FILTER_PROCESSING_TIME_MS);
BasicEvent firstE = in.getFirstEvent();
if (firstSignalTimestmap == null) {
firstSignalTimestmap = firstE.timestamp;
}
if (resetCalled) {
resetCalled = false;
int ts = in.getLastTimestamp(); // we use getLastTimestamp because getFirstTimestamp contains event from BEFORE the rewind :-(
// initialize filters with lastTimesMap to Poisson waiting times
log.info("initializing timestamp maps with Poisson process waiting times");
for (AbstractNoiseFilter f : noiseFilters) {
f.initializeLastTimesMapForNoiseRate(shotNoiseRateHz + leakNoiseRateHz, ts); // TODO move to filter so that each filter can initialize its own map
}
}
// copy input events to inList
ArrayList<BasicEvent> signalList;
try {
signalList = createEventList((EventPacket<BasicEvent>) in);
} catch (BackwardsTimestampException ex) {
log.warning(String.format("%s: skipping nonmonotonic packet [%s]", ex, in));
return in;
}
assert signalList.size() == in.getSizeNotFilteredOut() : String.format("signalList size (%d) != in.getSizeNotFilteredOut() (%d)", signalList.size(), in.getSizeNotFilteredOut());
// add noise into signalList to get the outputPacketWithNoiseAdded, track noise in noiseList
noiseList.clear();
addNoise(in, signalAndNoisePacket, noiseList, shotNoiseRateHz, leakNoiseRateHz);
// we need to copy the augmented event packet to a HashSet for use with Collections
ArrayList<BasicEvent> signalAndNoiseList;
try {
signalAndNoiseList = createEventList((EventPacket<BasicEvent>) signalAndNoisePacket);
// filter the augmented packet
// make sure to record events, turned off by default for normal use
for (EventFilter2D f : getEnclosedFilterChain()) {
((AbstractNoiseFilter) f).setRecordFilteredOutEvents(true);
}
EventPacket<BasicEvent> passedSignalAndNoisePacket = (EventPacket<BasicEvent>) getEnclosedFilterChain().filterPacket(signalAndNoisePacket);
if (selectedFilter != null) {
ArrayList<FilteredEventWithNNb> negativeList = selectedFilter.getNegativeEvents();
ArrayList<FilteredEventWithNNb> positiveList = selectedFilter.getPositiveEvents();
// make a list of the output packet, which has noise filtered out by selected filter
ArrayList<BasicEvent> passedSignalAndNoiseList = createEventList(passedSignalAndNoisePacket);
assert (signalList.size() + noiseList.size() == signalAndNoiseList.size());
// now we sort out the mess
TP = countIntersect(signalList, positiveList, tpList); // True positives: Signal that was correctly retained by filtering
updateNnbHistograms(Classification.TP, tpList);
if (checkStopMe("after TP")) {
return in;
}
FN = countIntersect(signalList, negativeList, fnList); // False negatives: Signal that was incorrectly removed by filter.
updateNnbHistograms(Classification.FN, fnList);
if (checkStopMe("after FN")) {
return in;
}
FP = countIntersect(noiseList, positiveList, fpList); // False positives: Noise that is incorrectly passed by filter
updateNnbHistograms(Classification.FP, fpList);
if (checkStopMe("after FP")) {
return in;
}
TN = countIntersect(noiseList, negativeList, tnList); // True negatives: Noise that was correctly removed by filter
updateNnbHistograms(Classification.TN, tnList);
if (checkStopMe("after TN")) {
return in;
}
// if (TN + FP != noiseList.size()) {
// System.err.println(String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size()));
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert (TN + FP == noiseList.size()) : String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size());
totalEventCount = signalAndNoiseList.size();
int outputEventCount = passedSignalAndNoiseList.size();
filteredOutEventCount = totalEventCount - outputEventCount;
// if (TP + FP != outputEventCount) {
// System.err.printf("@@@@@@@@@ TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert TP + FP == outputEventCount : String.format("TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// if (TP + TN + FP + FN != totalEventCount) {
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
assert TP + TN + FP + FN == totalEventCount : String.format("TP (%d) + TN (%d) + FP (%d) + FN (%d) = %d != totalEventCount (%d)", TP, TN, FP, FN, TP + TN + FP + FN, totalEventCount);
assert TN + FN == filteredOutEventCount : String.format("TN (%d) + FN (%d) = %d != filteredOutEventCount (%d)", TN, FN, TN + FN, filteredOutEventCount);
// System.out.printf("every packet is: %d %d %d %d %d, %d %d %d: %d %d %d %d\n", inList.size(), newInList.size(), outList.size(), outRealList.size(), outNoiseList.size(), outInitList.size(), outInitRealList.size(), outInitNoiseList.size(), TP, TN, FP, FN);
TPR = TP + FN == 0 ? 0f : (float) (TP * 1.0 / (TP + FN)); // percentage of true positive events. that's output real events out of all real events
TPO = TP + FP == 0 ? 0f : (float) (TP * 1.0 / (TP + FP)); // percentage of real events in the filter's output
TNR = TN + FP == 0 ? 0f : (float) (TN * 1.0 / (TN + FP));
accuracy = (float) ((TP + TN) * 1.0 / (TP + TN + FP + FN));
BR = TPR + TPO == 0 ? 0f : (float) (2 * TPR * TPO / (TPR + TPO)); // wish to norm to 1. if both TPR and TPO is 1. the value is 1
// System.out.printf("shotNoiseRateHz and leakNoiseRateHz is %.2f and %.2f\n", shotNoiseRateHz, leakNoiseRateHz);
}
stopper.cancel();
if (lastTimestampPreviousPacket != null) {
int deltaTime = in.getLastTimestamp() - lastTimestampPreviousPacket;
inSignalRateHz = (1e6f * in.getSize()) / deltaTime;
inNoiseRateHz = (1e6f * noiseList.size()) / deltaTime;
outSignalRateHz = (1e6f * TP) / deltaTime;
outNoiseRateHz = (1e6f * FP) / deltaTime;
}
if (csvWriter != null) {
try {
csvWriter.write(String.format("%d,%d,%d,%d,%f,%f,%f,%d,%f,%f,%f,%f\n",
TP, TN, FP, FN, TPR, TNR, BR, firstE.timestamp,
inSignalRateHz, inNoiseRateHz, outSignalRateHz, outNoiseRateHz));
} catch (IOException e) {
doCloseCsvFile();
}
}
if (overlayPositives) {
annotateNoiseFilteringEvents(tpList, fpList);
}
if (overlayNegatives) {
annotateNoiseFilteringEvents(fnList, tnList);
}
rocHistory.addSample(1 - TNR, TPR, getCorrelationTimeS());
lastTimestampPreviousPacket = in.getLastTimestamp();
return passedSignalAndNoisePacket;
} catch (BackwardsTimestampException ex) {
Logger.getLogger(NoiseTesterFilter.class.getName()).log(Level.SEVERE, null, ex);
return in;
}
}
private void addNoise(EventPacket<? extends BasicEvent> in, EventPacket<? extends BasicEvent> augmentedPacket, List<BasicEvent> generatedNoise, float shotNoiseRateHz, float leakNoiseRateHz) {
// we need at least 1 event to be able to inject noise before it
if ((in.isEmpty())) {
log.warning("no input events in this packet, cannot inject noise because there is no end event");
return;
}
// save input packet
augmentedPacket.clear();
generatedNoise.clear();
// make the itertor to save events with added noise events
OutputEventIterator<ApsDvsEvent> outItr = (OutputEventIterator<ApsDvsEvent>) augmentedPacket.outputIterator();
if (prerecordedNoise == null && leakNoiseRateHz == 0 && shotNoiseRateHz == 0) {
for (BasicEvent ie : in) {
outItr.nextOutput().copyFrom(ie);
}
return; // no noise, just return which returns the copy from filterPacket
}
int firstTsThisPacket = in.getFirstTimestamp();
// insert noise between last event of last packet and first event of current packet
// but only if there waa a previous packet and we are monotonic
if (lastTimestampPreviousPacket != null) {
if (firstTsThisPacket < lastTimestampPreviousPacket) {
log.warning(String.format("non-monotonic timestamp: Resetting filter. (first event %d is smaller than previous event %d by %d)",
firstTsThisPacket, lastTimestampPreviousPacket, firstTsThisPacket - lastTimestampPreviousPacket));
resetFilter();
return;
}
// we had some previous event
int lastPacketTs = lastTimestampPreviousPacket + 1; // 1us more than timestamp of the last event in the last packet
insertNoiseEvents(lastPacketTs, firstTsThisPacket, outItr, generatedNoise);
checkStopMe(String.format("after insertNoiseEvents at start of packet over interval of %ss",
eng.format(1e-6f * (lastPacketTs - firstTsThisPacket))));
}
// insert noise between events of this packet after the first event, record their timestamp
// if there are no DVS events, then the iteration will not work.
// In this case, we assume there are only IMU or APS events and insert noise events between them, because devices
// typically do not include some special "clock" event to pass time.
int preEts = 0;
int dvsEventCounter = 0;
int lastEventTs = in.getFirstTimestamp();
for (BasicEvent ie : in) {
dvsEventCounter++;
// if it is the first event or any with first event timestamp then just copy them
if (ie.timestamp == firstTsThisPacket) {
outItr.nextOutput().copyFrom(ie);
continue;
}
// save the previous timestamp and get the next one, and then inject noise between them
preEts = lastEventTs;
lastEventTs = ie.timestamp;
insertNoiseEvents(preEts, lastEventTs, outItr, generatedNoise);
outItr.nextOutput().copyFrom(ie);
}
if (dvsEventCounter == 0 && (in instanceof ApsDvsEventPacket)) {
Iterator itr = ((ApsDvsEventPacket) in).fullIterator();
while (itr.hasNext()) {
BasicEvent ie = (BasicEvent) (itr.next());
// if it is the first event or any with first event timestamp then just copy them
if (ie.timestamp == firstTsThisPacket) {
outItr.nextOutput().copyFrom(ie);
continue;
}
// save the previous timestamp and get the next one, and then inject noise between them
preEts = lastEventTs;
lastEventTs = ie.timestamp;
insertNoiseEvents(preEts, lastEventTs, outItr, generatedNoise);
outItr.nextOutput().copyFrom(ie);
}
}
}
private void insertNoiseEvents(int lastPacketTs, int firstTsThisPacket, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> generatedNoise) {
// check that we don't have too many events, packet will get too large
int tstepUs = (firstTsThisPacket - lastPacketTs);
if (tstepUs > 100_0000) {
stopMe = true;
checkStopMe("timestep longer than 100ms for inserting noise events, disabling filter");
return;
}
final int checkStopInterval = 100000;
int checks = 0;
for (double ts = lastPacketTs; ts < firstTsThisPacket; ts += poissonDtUs) {
// note that poissonDtUs is float but we truncate the actual timestamp to int us value here.
// It's OK if there are events with duplicate timestamps (there are plenty in input already).
sampleNoiseEvent((int) ts, outItr, generatedNoise, shotOffThresholdProb, shotOnThresholdProb, leakOnThresholdProb); // note noise injection updates ts to make sure monotonic
if (checks++ > checkStopInterval) {
if (checkStopMe("sampling noise events")) {
break;
}
}
}
}
private int sampleNoiseEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList, float shotOffThresholdProb, float shotOnThresholdProb, float leakOnThresholdProb) {
if (prerecordedNoise == null) {
final double randomnum = random.nextDouble();
if (randomnum < shotOffThresholdProb) {
injectNoiseEvent(ts, PolarityEvent.Polarity.Off, outItr, noiseList);
} else if (randomnum > shotOnThresholdProb) {
injectNoiseEvent(ts, PolarityEvent.Polarity.On, outItr, noiseList);
}
if (random.nextDouble() < leakOnThresholdProb) {
injectNoiseEvent(ts, PolarityEvent.Polarity.On, outItr, noiseList);
}
return ts;
} else { // inject prerecorded noise event
ArrayList<BasicEvent> noiseEvents = prerecordedNoise.nextEvents(ts); // these have timestamps of the prerecorded noise
for (BasicEvent e : noiseEvents) {
PolarityEvent pe = (PolarityEvent) e;
BasicEvent ecopy = outItr.nextOutput(); // get the next event from output packet
ecopy.copyFrom(e); // copy its fields from the noise event
ecopy.timestamp = ts; // update the timestamp to the current timestamp
noiseList.add(ecopy); // add it to the list of noise events we keep for analysis
}
return ts;
}
}
private void createShotNoiseCoVArray() {
if (shotNoiseRateArray == null) {
shotNoiseRateArray = new float[sx + 1][sy + 1];
shotNoiseRateIntervals = new float[(sx + 1) * (sy + 1)];
}
// fill float[][] with random normal dist values
int idx = 0;
double summedIntvls = 0;
for (float[] col : shotNoiseRateArray) {
for (int row = 0; row < col.length; row++) {
float randomVarMult = (float) Math.exp(random.nextGaussian() * shotNoiseRateCoVDecades * Math.log(10));
col[row] = randomVarMult;
shotNoiseRateIntervals[idx++] = randomVarMult;
summedIntvls += randomVarMult;
}
}
double f = 1 / summedIntvls;
for (int i = 0; i < shotNoiseRateIntervals.length; i++) {
shotNoiseRateIntervals[i] *= f; // store normalized intervals for indiv rates, the higher the pixel's rate, the longer its interval
}
// now compute the integrated intervals
for (int i = 1; i < shotNoiseRateIntervals.length; i++) {
shotNoiseRateIntervals[i] += shotNoiseRateIntervals[i - 1]; // store normalized intervals for indiv rates, the higher the pixel's rate, the longer its interval
}
}
private class XYPt {
short x, y;
}
private XYPt xyPt = new XYPt();
private XYPt shotXYFromIdx(int idx) {
xyPt.y = (short) (idx % (sy + 1)); // y changes fastest
xyPt.x = (short) (idx / (sy + 1));
return xyPt;
}
private XYPt sampleRandomShotNoisePixelXYAddress() {
float f = random.nextFloat();
// find location of f in list of intervals
int idx = search(f, shotNoiseRateIntervals);
return shotXYFromIdx(idx);
}
public static int search(float searchnum, float[] nums) {
int low = 0;
int high = nums.length - 1;
int mid = (low + high) / 2;
while (low < high) {
if (nums[mid] < searchnum) {
if (nums[mid + 1] > searchnum) {
return mid;
} else {
low = mid + 1;
}
} else {
high = mid - 1;
}
mid = (low + high) / 2;
}
return mid;
}
private void injectNoiseEvent(int ts, PolarityEvent.Polarity pol, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
if (shotNoiseRateCoVDecades < Float.MIN_VALUE) {
e.x = (short) random.nextInt(sx);
e.y = (short) random.nextInt(sy);
} else {
XYPt p = sampleRandomShotNoisePixelXYAddress();
e.x = p.x;
e.y = p.y;
}
e.timestamp = ts;
e.polarity = pol;
e.setReadoutType(ApsDvsEvent.ReadoutType.DVS);
noiseList.add(e);
}
private void injectOnEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
final int x = (short) random.nextInt(sx);
final int y = (short) random.nextInt(sy);
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
e.polarity = PolarityEvent.Polarity.On;
e.setReadoutType(ApsDvsEvent.ReadoutType.DVS);
noiseList.add(e);
}
private void injectOffEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
final int x = (short) random.nextInt(sx);
final int y = (short) random.nextInt(sy);
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
e.polarity = PolarityEvent.Polarity.Off;
e.setReadoutType(ApsDvsEvent.ReadoutType.DVS);
noiseList.add(e);
}
@Override
synchronized public void resetFilter() {
lastTimestampPreviousPacket = null;
firstSignalTimestmap = null;
resetCalled = true;
getEnclosedFilterChain().reset();
if (prerecordedNoise != null) {
prerecordedNoise.rewind();
}
nnbHistograms.reset();
}
private void computeProbs() {
// the rate per pixel results in overall noise rate for entire sensor that is product of pixel rate and number of pixels.
// we compute this overall noise rate to determine the Poisson sample interval that is much smaller than this to enable simple Poisson noise sampling.
// Compute time step that is 10X less than the overall mean interval for noise
// dt is the time interval such that if we sample a random value 0-1 every dt us, the the overall noise rate will be correct.
int npix = (chip.getSizeX() * chip.getSizeY());
float tmp = (float) (1.0 / ((leakNoiseRateHz + shotNoiseRateHz) * npix)); // this value is very small
poissonDtUs = ((tmp / 10) * 1000000); // 1s = 1000000 us // TODO document why 10 here. It is to ensure that prob(>1 event per sample is low)
final float minPoissonDtUs = 1f / (1e-6f * MAX_TOTAL_NOISE_RATE_HZ);
if (prerecordedNoise != null) {
log.info("Prerecoded noise input: clipping max noise rate to MAX_TOTAL_NOISE_RATE_HZ=" + eng.format(MAX_TOTAL_NOISE_RATE_HZ) + "Hz");
poissonDtUs = minPoissonDtUs;
} else if (poissonDtUs < minPoissonDtUs) {
log.info("clipping max noise rate to MAX_TOTAL_NOISE_RATE_HZ=" + eng.format(MAX_TOTAL_NOISE_RATE_HZ) + "Hz");
poissonDtUs = minPoissonDtUs;
} else // if (poissonDtUs < 1) {
// log.warning(String.format("Poisson sampling rate is less than 1us which is timestep resolution, could be slow"));
{
shotOffThresholdProb = 0.5f * (poissonDtUs * 1e-6f * npix) * shotNoiseRateHz; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
}
shotOnThresholdProb = 1 - shotOffThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
leakOnThresholdProb = (poissonDtUs * 1e-6f * npix) * leakNoiseRateHz; // bounds for samppling Poisson noise
}
@Override
public void initFilter() {
if (chain == null) {
chain = new FilterChain(chip);
// for(NoiseFilterEnum en:NoiseFilterEnum.values()){
// Class cl=Class.forName(en.va);
noiseFilters = new AbstractNoiseFilter[]{new BackgroundActivityFilter(chip), new SpatioTemporalCorrelationFilter(chip), new DoubleWindowFilter(chip), new OrderNBackgroundActivityFilter((chip)), new MedianDtFilter(chip)};
for (AbstractNoiseFilter n : noiseFilters) {
n.initFilter();
chain.add(n);
getSupport().addPropertyChangeListener(n);
n.getSupport().addPropertyChangeListener(this); // make sure we are synchronized both ways for all filter parameters
}
setEnclosedFilterChain(chain);
if (getChip().getAeViewer() != null) {
getChip().getAeViewer().getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this);
getChip().getAeViewer().getSupport().addPropertyChangeListener(AEViewer.EVENT_CHIP, this);
getChip().getAeViewer().getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this);
}
if (chip.getRemoteControl() != null) {
log.info("adding RemoteControlCommand listener to AEChip\n");
chip.getRemoteControl().addCommandListener(this, "setNoiseFilterParameters", "set correlation time or distance.");
}
if (chip.getRenderer() instanceof DavisRenderer) {
renderer = (DavisRenderer) chip.getRenderer();
}
}
sx = chip.getSizeX() - 1;
sy = chip.getSizeY() - 1;
signalAndNoisePacket = new EventPacket<>(ApsDvsEvent.class);
setSelectedNoiseFilterEnum(selectedNoiseFilterEnum);
computeProbs();
// setAnnotateAlpha(annotateAlpha);
fixRendererAnnotationLayerShowing(); // make sure renderer is properly set up.
}
/**
* @return the shotNoiseRateHz
*/
public float getShotNoiseRateHz() {
return shotNoiseRateHz;
}
/**
* @param shotNoiseRateHz the shotNoiseRateHz to set
*/
synchronized public void setShotNoiseRateHz(float shotNoiseRateHz) {
if (shotNoiseRateHz < 0) {
shotNoiseRateHz = 0;
}
if (shotNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
shotNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("shotNoiseRateHz", shotNoiseRateHz);
getSupport().firePropertyChange("shotNoiseRateHz", this.shotNoiseRateHz, shotNoiseRateHz);
this.shotNoiseRateHz = shotNoiseRateHz;
computeProbs();
}
/**
* @return the leakNoiseRateHz
*/
public float getLeakNoiseRateHz() {
return leakNoiseRateHz;
}
/**
* @param leakNoiseRateHz the leakNoiseRateHz to set
*/
synchronized public void setLeakNoiseRateHz(float leakNoiseRateHz) {
if (leakNoiseRateHz < 0) {
leakNoiseRateHz = 0;
}
if (leakNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
leakNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("leakNoiseRateHz", leakNoiseRateHz);
getSupport().firePropertyChange("leakNoiseRateHz", this.leakNoiseRateHz, leakNoiseRateHz);
this.leakNoiseRateHz = leakNoiseRateHz;
computeProbs();
}
/**
* @return the csvFileName
*/
public String getCsvFilename() {
return csvFileName;
}
/**
* @param csvFileName the csvFileName to set
*/
public void setCsvFilename(String csvFileName) {
if (csvFileName.toLowerCase().endsWith(".csv")) {
csvFileName = csvFileName.substring(0, csvFileName.length() - 4);
}
putString("csvFileName", csvFileName);
getSupport().firePropertyChange("csvFileName", this.csvFileName, csvFileName);
this.csvFileName = csvFileName;
openCvsFiile();
}
public void doCloseCsvFile() {
if (csvFile != null) {
try {
log.info("closing statistics output file" + csvFile);
csvWriter.close();
} catch (IOException e) {
log.warning("could not close " + csvFile + ": caught " + e.toString());
} finally {
csvFile = null;
csvWriter = null;
}
}
}
private void openCvsFiile() {
String fn = csvFileName + ".csv";
csvFile = new File(fn);
log.info(String.format("opening %s for output", fn));
try {
csvWriter = new BufferedWriter(new FileWriter(csvFile, true));
if (!csvFile.exists()) { // write header
log.info("file did not exist, so writing header");
csvWriter.write(String.format("TP,TN,FP,FN,TPR,TNR,BR,firstE.timestamp,"
+ "inSignalRateHz,inNoiseRateHz,outSignalRateHz,outNoiseRateHz\n"));
}
} catch (IOException ex) {
log.warning(String.format("could not open %s for output; caught %s", fn, ex.toString()));
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt); //To change body of generated methods, choose Tools | Templates.
if (evt.getPropertyName() == AEInputStream.EVENT_REWOUND) {
// log.info(String.format("got rewound event %s, setting reset on next packet", evt));
resetCalled = true;
} else if (evt.getPropertyName() == AEViewer.EVENT_FILEOPEN) {
if (prerecordedNoise != null) {
prerecordedNoise.rewind();
}
}
}
/**
* @return the selectedNoiseFilter
*/
public NoiseFilterEnum getSelectedNoiseFilterEnum() {
return selectedNoiseFilterEnum;
}
/**
* @param selectedNoiseFilter the selectedNoiseFilter to set
*/
synchronized public void setSelectedNoiseFilterEnum(NoiseFilterEnum selectedNoiseFilter) {
this.selectedNoiseFilterEnum = selectedNoiseFilter;
putString("selectedNoiseFilter", selectedNoiseFilter.toString());
for (AbstractNoiseFilter n : noiseFilters) {
if (n.getClass().getSimpleName().equals(selectedNoiseFilter.toString())) {
n.initFilter();
n.setFilterEnabled(true);
log.info("setting " + n.getClass().getSimpleName() + " enabled");
selectedFilter = n;
} else {
n.setFilterEnabled(false);
}
}
resetCalled = true; // make sure we iniitialize the timestamp maps on next packet for new filter
rocHistory.reset();
}
private String USAGE = "Need at least 2 arguments: noisefilter <command> <args>\nCommands are: setNoiseFilterParameters <csvFilename> xx <shotNoiseRateHz> xx <leakNoiseRateHz> xx and specific to the filter\n";
@Override
public String processRemoteControlCommand(RemoteControlCommand command, String input) {
// parse command and set parameters of NoiseTesterFilter, and pass command to specific filter for further processing
// setNoiseFilterParameters csvFilename 10msBAFdot_500m_0m_300num0 shotNoiseRateHz 0.5 leakNoiseRateHz 0 dt 300 num 0
String[] tok = input.split("\\s");
if (tok.length < 2) {
return USAGE;
} else {
for (int i = 1; i < tok.length; i++) {
if (tok[i].equals("csvFileName")) {
setCsvFilename(tok[i + 1]);
} else if (tok[i].equals("shotNoiseRateHz")) {
setShotNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setShotNoiseRateHz %f", shotNoiseRateHz));
} else if (tok[i].equals("leakNoiseRateHz")) {
setLeakNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setLeakNoiseRateHz %f", leakNoiseRateHz));
} else if (tok[i].equals("closeFile")) {
doCloseCsvFile();
log.info(String.format("closeFile %s", csvFileName));
}
}
log.info("Received Command:" + input);
String out = selectedFilter.setParameters(command, input);
log.info("Execute Command:" + input);
return out;
}
}
@Override
public void setCorrelationTimeS(float dtS) {
super.setCorrelationTimeS(dtS);
for (AbstractNoiseFilter f : noiseFilters) {
f.setCorrelationTimeS(dtS);
}
}
@Override
public void setAdaptiveFilteringEnabled(boolean adaptiveFilteringEnabled) {
super.setAdaptiveFilteringEnabled(adaptiveFilteringEnabled);
for (AbstractNoiseFilter f : noiseFilters) {
f.setAdaptiveFilteringEnabled(adaptiveFilteringEnabled);
}
}
@Override
public synchronized void setSubsampleBy(int subsampleBy) {
super.setSubsampleBy(subsampleBy);
for (AbstractNoiseFilter f : noiseFilters) {
f.setSubsampleBy(subsampleBy);
}
}
@Override
public void setFilterHotPixels(boolean filterHotPixels) {
super.setFilterHotPixels(filterHotPixels); //To change body of generated methods, choose Tools | Templates.
for (AbstractNoiseFilter f : noiseFilters) {
f.setFilterHotPixels(filterHotPixels);
}
}
@Override
public void setLetFirstEventThrough(boolean letFirstEventThrough) {
super.setLetFirstEventThrough(letFirstEventThrough); //To change body of generated methods, choose Tools | Templates.
for (AbstractNoiseFilter f : noiseFilters) {
f.setLetFirstEventThrough(letFirstEventThrough);
}
}
@Override
public synchronized void setSigmaDistPixels(int sigmaDistPixels) {
super.setSigmaDistPixels(sigmaDistPixels); //To change body of generated methods, choose Tools | Templates.
for (AbstractNoiseFilter f : noiseFilters) {
f.setSigmaDistPixels(sigmaDistPixels);
}
}
// /**
// * @return the annotateAlpha
// */
// public float getAnnotateAlpha() {
// return annotateAlpha;
// /**
// * @param annotateAlpha the annotateAlpha to set
// */
// public void setAnnotateAlpha(float annotateAlpha) {
// if (annotateAlpha > 1.0) {
// annotateAlpha = 1.0f;
// if (annotateAlpha < 0.0) {
// annotateAlpha = 0.0f;
// this.annotateAlpha = annotateAlpha;
// if (renderer != null) {
// renderer.setAnnotateAlpha(annotateAlpha);
/**
* Sets renderer to show annotation layer
*/
private void fixRendererAnnotationLayerShowing() {
if (renderer != null) {
renderer.setDisplayAnnotation(this.overlayNegatives || this.overlayPositives);
}
}
/**
* @return the overlayPositives
*/
public boolean isOverlayPositives() {
return overlayPositives;
}
/**
* @return the overlayNegatives
*/
public boolean isOverlayNegatives() {
return overlayNegatives;
}
/**
* @param overlayNegatives the overlayNegatives to set
*/
public void setOverlayNegatives(boolean overlayNegatives) {
boolean oldOverlayNegatives = this.overlayNegatives;
this.overlayNegatives = overlayNegatives;
putBoolean("overlayNegatives", overlayNegatives);
getSupport().firePropertyChange("overlayNegatives", oldOverlayNegatives, overlayNegatives);
fixRendererAnnotationLayerShowing();
}
/**
* @param overlayPositives the overlayPositives to set
*/
public void setOverlayPositives(boolean overlayPositives) {
boolean oldOverlayPositives = this.overlayPositives;
this.overlayPositives = overlayPositives;
putBoolean("overlayPositives", overlayPositives);
getSupport().firePropertyChange("overlayPositives", oldOverlayPositives, overlayPositives);
fixRendererAnnotationLayerShowing();
}
/**
* @return the rocHistory
*/
public int getRocHistoryLength() {
return rocHistoryLength;
}
/**
* @param rocHistory the rocHistory to set
*/
synchronized public void setRocHistoryLength(int rocHistoryLength) {
if (rocHistoryLength > 10000) {
rocHistoryLength = 10000;
}
this.rocHistoryLength = rocHistoryLength;
putInt("rocHistoryLength", rocHistoryLength);
rocHistory.reset();
}
synchronized public void doClearROCHistory() {
rocHistory.reset();
}
synchronized public void doPrintNnbInfo() {
System.out.print(nnbHistograms.toString());
}
synchronized public void doCloseNoiseSourceRecording() {
if (prerecordedNoise != null) {
log.info("clearing recoerded noise input data");
prerecordedNoise = null;
}
}
synchronized public void doOpenNoiseSourceRecording() {
JFileChooser fileChooser = new JFileChooser();
ChipDataFilePreview preview = new ChipDataFilePreview(fileChooser, getChip());
// from book swing hacks
fileChooser.addPropertyChangeListener(preview);
fileChooser.setAccessory(preview);
String chosenPrerecordedNoiseFilePath = getString("chosenPrerecordedNoiseFilePath", "");
// get the last folder
DATFileFilter datFileFilter = new DATFileFilter();
fileChooser.addChoosableFileFilter(datFileFilter);
File sf = new File(chosenPrerecordedNoiseFilePath);
fileChooser.setCurrentDirectory(sf);
fileChooser.setSelectedFile(sf);
try {
int retValue = fileChooser.showOpenDialog(getChip().getAeViewer().getFilterFrame());
if (retValue == JFileChooser.APPROVE_OPTION) {
chosenPrerecordedNoiseFilePath = fileChooser.getSelectedFile().toString();
putString("chosenPrerecordedNoiseFilePath", chosenPrerecordedNoiseFilePath);
try {
prerecordedNoise = new PrerecordedNoise(fileChooser.getSelectedFile());
computeProbs(); // set poissonDtUs after we construct prerecordedNoise so it is set properly
} catch (IOException ex) {
log.warning(String.format("Exception trying to open data file: " + ex));
}
} else {
preview.showFile(null);
}
} catch (GLException e) {
log.warning(e.toString());
preview.showFile(null);
}
}
private enum Classification {
None, TP, FP, TN, FN
}
private void updateNnbHistograms(Classification classification, ArrayList<FilteredEventWithNNb> filteredInNnb) {
for (FilteredEventWithNNb e : filteredInNnb) {
nnbHistograms.addEvent(classification, e.nnb);
}
}
/**
* @return the shotNoiseRateCoVDecades
*/
public float getShotNoiseRateCoVDecades() {
return shotNoiseRateCoVDecades;
}
/**
* @param shotNoiseRateCoVDecades the shotNoiseRateCoVDecades to set
*/
public void setShotNoiseRateCoVDecades(float shotNoiseRateCoVDecades) {
this.shotNoiseRateCoVDecades = shotNoiseRateCoVDecades;
putFloat("shotNoiseRateCoVDecades", shotNoiseRateCoVDecades);
if (shotNoiseRateCoVDecades > Float.MIN_VALUE) {
createShotNoiseCoVArray();
}
}
/**
* Tracks statistics of neighbors for false and true positives and negatives
*/
private class NNbHistograms {
NnbHistogram tpHist, fpHist, tnHist, fnHist;
NnbHistogram[] histograms;
private class NnbHistogram {
Classification classification = Classification.None;
final int[] nnbcounts = new int[8]; // bit frequencies around us, 8 neighbors
final int[] byteHist = new int[256]; // array of frequency of patterns versus the pattern index
int count; // total # events
final float[] prob = new float[256];
public NnbHistogram(Classification classification) {
this.classification = classification;
}
void reset() {
Arrays.fill(nnbcounts, 0);
Arrays.fill(byteHist, 0);
count = 0;
}
void addEvent(byte nnb) {
count++;
byteHist[0xff & nnb]++; // make sure we get unsigned byte
if (nnb == 0) {
return;
}
for (int i = 0; i < 8; i++) {
if ((((nnb & 0xff) >> i) & 1) != 0) {
nnbcounts[i]++;
}
}
}
String computeProbabilities() {
for (int i = 0; i < 256; i++) {
prob[i] = (float) byteHist[i] / count;
}
final Integer[] ids = new Integer[256];
for (int i = 0; i < ids.length; i++) {
ids[i] = i;
}
Arrays.sort(ids, new Comparator<Integer>() {
@Override
public int compare(final Integer o1, final Integer o2) {
return -Float.compare(prob[o1], prob[o2]);
}
});
StringBuilder sb = new StringBuilder(classification + " probabilities (count=" + count + ")");
final int perline = 4;
if (count > 0) {
for (int i = 0; i < ids.length; i++) {
if (prob[ids[i]] < 0.005f) {
break;
}
if (i % perline == 0) {
sb.append(String.format("\n%3d-%3d: ", i, i + perline - 1));
}
String binstring = String.format("%8s", Integer.toBinaryString(ids[i] & 0xFF)).replace(' ', '0');
sb.append(String.format("%4.1f%%:%s, ", 100 * prob[ids[i]], binstring));
}
}
sb.append("\n");
// log.info(sb.toString());
// float[] sortedProb = Arrays.copyOf(prob, 0);
// Arrays.sort(sortedProb);
// ArrayUtils.reverse(prob);
return sb.toString();
}
public String toString() {
return computeProbabilities();
// StringBuilder sb = new StringBuilder(classification.toString() + " neighbors: [");
// for (int i : nnbcounts) {
// sb.append(i + " ");
// sb.append("]\n");
// sb.append("counts: ");
// final int perline = 32;
// for (int i = 0; i < byteHist.length; i++) {
// if (i % perline == 0) {
// sb.append("\n");
// sb.append(byteHist[i] + " ");
// sb.append("\n");
// return sb.toString();
}
void draw(GL2 gl) {
int sum = 0;
for (int i = 0; i < nnbcounts.length; i++) {
sum += nnbcounts[i];
}
if (sum == 0) {
sum = 1;
}
gl.glPushMatrix();
for (int i = 0; i < nnbcounts.length; i++) {
if (nnbcounts[i] == 0) {
continue;
}
int ind = i < 4 ? i : i + 1;
int y = ind % 3, x = ind / 3;
float b = (float) nnbcounts[i] / sum;
gl.glColor3f(b, b, b);
gl.glRectf(x, y, x + 1, y + 1);
}
gl.glPopMatrix();
}
}
public NNbHistograms() {
tpHist = new NnbHistogram(Classification.TP);
fpHist = new NnbHistogram(Classification.FP);
tnHist = new NnbHistogram(Classification.TN);
fnHist = new NnbHistogram(Classification.FN);
histograms = new NnbHistogram[]{tpHist, fpHist, tnHist, fnHist};
}
void reset() {
tpHist.reset();
fpHist.reset();
tnHist.reset();
fnHist.reset();
}
void addEvent(Classification classification, byte nnb) {
switch (classification) {
case TP:
tpHist.addEvent(nnb);
break;
case FP:
fpHist.addEvent(nnb);
break;
case TN:
tnHist.addEvent(nnb);
break;
case FN:
fnHist.addEvent(nnb);
break;
}
}
void draw(GL2 gl) {
int sc = 5;
int x = -20;
int y = 0;
gl.glPushMatrix();
gl.glTranslatef(-sc * 6, 0, 0);
gl.glScalef(sc, sc, 1);
for (int i = 0; i < histograms.length; i++) {
histograms[i].draw(gl);
gl.glTranslatef(0, 4, 0);
}
gl.glPopMatrix();
}
@Override
public String toString() {
return "NNbHistograms{\n" + "tpHist=" + tpHist + "\n fpHist=" + fpHist + "\n tnHist=" + tnHist + "\n fnHist=" + fnHist + "}\n";
}
}
private class ROCHistory {
private EvictingQueue<ROCSample> rocHistoryList = EvictingQueue.create(rocHistoryLength);
private Float lastTau = null;
private final double LOG10_CHANGE_TO_ADD_LABEL = .2;
GLUT glut = new GLUT();
private int counter = 0;
private final int SAMPLE_INTERVAL_NO_CHANGE = 30;
private int legendDisplayListId = 0;
private ROCSample[] legendROCs = null;
ROCSample createAbsolutePosition(float x, float y, float tau, boolean labeled) {
return new ROCSample(x, y, tau, labeled);
}
ROCSample createTprFpr(float tpr, float fpr, float tau, boolean labeled) {
return new ROCSample(fpr * sx, tpr * sy, tau, labeled);
}
class ROCSample {
float x, y, tau;
boolean labeled = false;
final int SIZE = 2; // chip pixels
private ROCSample(float x, float y, float tau, boolean labeled) {
this.x = x;
this.y = y;
this.tau = tau;
this.labeled = labeled;
}
private void draw(GL2 gl) {
float hue = (float) (Math.log10(tau) / 2 + 1.5); //. hue is 1 for tau=0.1s and is 0 for tau = 1ms
Color c = Color.getHSBColor(hue, 1f, hue);
float[] rgb = c.getRGBComponents(null);
gl.glColor3fv(rgb, 0);
gl.glLineWidth(1);
gl.glPushMatrix();
DrawGL.drawBox(gl, x, y, SIZE, SIZE, 0);
gl.glPopMatrix();
if (labeled) {
// gl.glTranslatef(5 * L, - 3 * L, 0);
gl.glRasterPos3f(x + SIZE, y, 0);
// gl.glRotatef(-45, 0, 0, 1); // can't rotate bitmaps, must use stroke and glScalef
String s = String.format("%ss", eng.format(tau));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
// glut.glutStrokeString(GLUT.STROKE_ROMAN, s);
}
}
}
private void reset() {
rocHistoryList = EvictingQueue.create(rocHistoryLength);
lastTau = null;
}
void addSample(float fpr, float tpr, float tau) {
boolean labelIt = lastTau == null
|| Math.abs(Math.log10(tau / lastTau)) > .1
|| ++counter >= SAMPLE_INTERVAL_NO_CHANGE;
rocHistoryList.add(rocHistory.createTprFpr(tpr, fpr, tau, labelIt));
if (labelIt) {
lastTau = tau;
}
if (counter > SAMPLE_INTERVAL_NO_CHANGE) {
counter = 0;
}
}
private void drawLegend(GL2 gl) {
if (legendDisplayListId == 0) {
int NLEG = 8;
legendROCs = new ROCSample[NLEG];
for (int i = 0; i < NLEG; i++) {
ROCSample r = createAbsolutePosition(sx + 5, i * 12 + 20, (float) Math.pow(10, -3 + 2f * i / (NLEG - 1)), true);
legendROCs[i] = r;
}
legendDisplayListId = gl.glGenLists(1);
gl.glNewList(legendDisplayListId, GL2.GL_COMPILE);
{ // TODO make a real list
}
gl.glEndList();
}
gl.glPushMatrix();
// gl.glCallList(legendDisplayListId);
for (ROCSample r : legendROCs) {
r.draw(gl);
}
gl.glPopMatrix();
}
void draw(GL2 gl) {
// draw axes
gl.glPushMatrix();
gl.glColor4f(.8f, .8f, .2f, .5f); // must set color before raster position (raster position is like glVertex)
gl.glLineWidth(2);
gl.glBegin(GL.GL_LINE_STRIP);
gl.glVertex2f(0, sy);
gl.glVertex2f(0, 0);
gl.glVertex2f(sx, 0);
gl.glEnd();
gl.glRasterPos3f(sx / 2 - 30, -10, 0);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, "FPR");
// gl.glPushMatrix();
// gl.glTranslatef(sx / 2, -10, 0);
// gl.glScalef(.1f, .1f, 1);
// glut.glutStrokeString(GLUT.STROKE_ROMAN, "FPR");
// gl.glPopMatrix();
gl.glRasterPos3f(-30, sy / 2, 0);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, "TPR");
gl.glPopMatrix();
for (ROCSample rocSample : rocHistoryList) {
rocSample.draw((gl));
}
// draw X at TPR / TNR point
int L = 12;
gl.glColor4f(.8f, .8f, .2f, .5f); // must set color before raster position (raster position is like glVertex)
gl.glLineWidth(6);
float x = (1 - TNR) * sx;
float y = TPR * sy;
gl.glPushMatrix();
DrawGL.drawCross(gl, x, y, L, 0);
gl.glPopMatrix();
if (rocHistoryLength > 1) {
drawLegend(gl);
}
}
}
// recorded noise to be used as input
private class PrerecordedNoise {
EventPacket<BasicEvent> recordedNoiseFileNoisePacket = null;
Iterator<BasicEvent> itr = null;
BasicEvent noiseFirstEvent, noiseNextEvent;
int noiseFirstTs;
Integer signalMostRecentTs;
private ArrayList<BasicEvent> returnedEvents = new ArrayList();
int noiseEventCounter = 0;
File file;
private PrerecordedNoise(File chosenPrerecordedNoiseFilePath) throws IOException {
file = chosenPrerecordedNoiseFilePath;
AEFileInputStream recordedNoiseAeFileInputStream = new AEFileInputStream(file, getChip());
AEPacketRaw rawPacket = recordedNoiseAeFileInputStream.readPacketByNumber(MAX_NUM_RECORDED_EVENTS);
recordedNoiseAeFileInputStream.close();
EventPacket<BasicEvent> inpack = getChip().getEventExtractor().extractPacket(rawPacket);
EventPacket<BasicEvent> recordedNoiseFileNoisePacket = new EventPacket(PolarityEvent.class);
OutputEventIterator outItr = recordedNoiseFileNoisePacket.outputIterator();
for (BasicEvent p : inpack) {
outItr.nextOutput().copyFrom(p);
}
this.recordedNoiseFileNoisePacket = recordedNoiseFileNoisePacket;
itr = recordedNoiseFileNoisePacket.inputIterator();
noiseFirstEvent = recordedNoiseFileNoisePacket.getFirstEvent();
noiseFirstTs = recordedNoiseFileNoisePacket.getFirstTimestamp();
this.noiseNextEvent = this.noiseFirstEvent;
computeProbs(); // set noise sample rate via poissonDtUs
log.info(String.format("Loaded %s pre-recorded events with duration %ss from %s", eng.format(recordedNoiseFileNoisePacket.getSize()), eng.format(1e-6f * recordedNoiseAeFileInputStream.getDurationUs()), chosenPrerecordedNoiseFilePath));
}
ArrayList<BasicEvent> nextEvents(int ts) {
returnedEvents.clear();
if (signalMostRecentTs == null) {
signalMostRecentTs = ts;
return returnedEvents; // no events at first, just get the timestamap
}
if (ts < signalMostRecentTs) { // time went backwards, rewind noise events
rewind();
return nextEvents(ts);
}
while (noiseNextEvent.timestamp - noiseFirstTs < ts - signalMostRecentTs) {
returnedEvents.add(noiseNextEvent);
noiseEventCounter++;
if (itr.hasNext()) {
noiseNextEvent = itr.next();
} else {
rewind();
return returnedEvents;
}
}
return returnedEvents;
}
private void rewind() {
log.info(String.format("rewinding noise events after %d events", noiseEventCounter));
this.itr = recordedNoiseFileNoisePacket.inputIterator();
noiseNextEvent = noiseFirstEvent;
signalMostRecentTs = null;
noiseEventCounter = 0;
}
}
} |
package ch.elexis.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import ch.elexis.core.constants.StringConstants;
import ch.elexis.util.MFUList;
import ch.rgw.tools.StringTool;
public class Kontakt extends PersistentObject {
// If you add new fields, please be sure to update KontakteView.java tidySelectedAddressesAction
// (and, most probably, other places)
// public static final String FLD_KUERZEL = "Kuerzel";
public static final String FLD_E_MAIL = "E-Mail";
public static final String FLD_WEBSITE = "Website";
public static final String FLD_MOBILEPHONE = "NatelNr";
public static final String FLD_FAX = "Fax";
public static final String FLD_IS_LAB = "istLabor"; //$NON-NLS-1$
public static final String FLD_IS_MANDATOR = "istMandant"; //$NON-NLS-1$
public static final String FLD_IS_USER = "istAnwender"; //$NON-NLS-1$
public static final String FLD_SHORT_LABEL = "Kuerzel"; //$NON-NLS-1$
public static final String FLD_IS_ORGANIZATION = "istOrganisation"; //$NON-NLS-1$
public static final String FLD_IS_PATIENT = "istPatient"; //$NON-NLS-1$
public static final String FLD_IS_PERSON = "istPerson"; //$NON-NLS-1$
public static final String FLD_ANSCHRIFT = "Anschrift"; //$NON-NLS-1$
public static final String FLD_COUNTRY = "Land"; //$NON-NLS-1$
public static final String FLD_PLACE = "Ort"; //$NON-NLS-1$
public static final String FLD_ZIP = "Plz"; //$NON-NLS-1$
public static final String FLD_STREET = "Strasse"; //$NON-NLS-1$
public static final String FLD_PHONE2 = "Telefon2"; //$NON-NLS-1$
public static final String FLD_PHONE1 = "Telefon1"; //$NON-NLS-1$
public static final String FLD_REMARK = "Bemerkung"; //$NON-NLS-1$
/**
* Contains the following values in the respective instantiations of contact isIstPatient(): ?
* isIstPerson(): if medic: area of expertise isIstMandant(): username/mandant short name
* isIstAnwender(): username/mandant short name isIstOrganisation(): contact person
* isIstLabor(): ?
*/
public static final String FLD_NAME3 = "Bezeichnung3"; //$NON-NLS-1$
public static final String FLD_NAME2 = "Bezeichnung2"; //$NON-NLS-1$
public static final String FLD_NAME1 = "Bezeichnung1"; //$NON-NLS-1$
public static final String TABLENAME = "KONTAKT"; //$NON-NLS-1$
public static final String[] DEFAULT_SORT = {
FLD_NAME1, FLD_NAME2, FLD_STREET, FLD_PLACE
};
public static final String DOMAIN_KONTAKT = Xid.DOMAIN_ELEXIS + "/kontakt/";
public static final String XID_KONTAKT_ANREDE = DOMAIN_KONTAKT + "anrede";
public static final String XID_KONTAKT_KANTON = DOMAIN_KONTAKT + "kanton";
public static final String XID_KONTAKT_SPEZ = DOMAIN_KONTAKT + "spez";
public static final String XID_KONTAKT_ROLLE = DOMAIN_KONTAKT + "rolle";
public static final String XID_KONTAKT_LAB_SENDING_FACILITY = DOMAIN_KONTAKT
+ "lab/sendingfacility";
volatile String Bezug;
protected String getTableName(){
return TABLENAME;
}
static {
addMapping(
TABLENAME,
"BezugsKontakte = JOINT:myID:otherID:KONTAKT_ADRESS_JOINT", //$NON-NLS-1$
"MyReminders = LIST:IdentID:REMINDERS", //$NON-NLS-1$
FLD_NAME1, FLD_NAME2,
FLD_NAME3,
FLD_SHORT_LABEL + "= PatientNr", //$NON-NLS-1$
FLD_REMARK, FLD_PHONE1, FLD_PHONE2, "E-Mail=EMail", FLD_WEBSITE, FLD_EXTINFO, //$NON-NLS-1$
FLD_IS_ORGANIZATION, FLD_IS_PERSON, FLD_IS_PATIENT, FLD_IS_USER, FLD_IS_MANDATOR,
FLD_IS_LAB, FLD_STREET, FLD_ZIP, FLD_PLACE, FLD_COUNTRY, FLD_FAX, FLD_ANSCHRIFT,
FLD_MOBILEPHONE);
Xid.localRegisterXIDDomainIfNotExists(XID_KONTAKT_ANREDE, "Anrede", Xid.ASSIGNMENT_REGIONAL);
Xid.localRegisterXIDDomainIfNotExists(XID_KONTAKT_KANTON, "Kanton", Xid.ASSIGNMENT_REGIONAL);
Xid.localRegisterXIDDomainIfNotExists(XID_KONTAKT_SPEZ, "Spezialität",
Xid.ASSIGNMENT_REGIONAL);
Xid.localRegisterXIDDomainIfNotExists(XID_KONTAKT_ROLLE, "Rolle", Xid.ASSIGNMENT_REGIONAL);
Xid.localRegisterXIDDomainIfNotExists(XID_KONTAKT_LAB_SENDING_FACILITY,
"Sendende Institution", Xid.ASSIGNMENT_REGIONAL);
Xid.getDomain(XID_KONTAKT_ANREDE).addDisplayOption(Person.class);
Xid.getDomain(XID_KONTAKT_KANTON).addDisplayOption(Person.class);
Xid.getDomain(XID_KONTAKT_SPEZ).addDisplayOption(Person.class);
Xid.getDomain(XID_KONTAKT_LAB_SENDING_FACILITY).addDisplayOption(Labor.class);
}
/**
* Returns a label describing this Kontakt.
*
* The default implementation returns the short label, i. e. label(false) Sublcasses should
* overwrite getLabel(boolean short) for defining their own labels.
*
* @return a string describing this Kontakt.
*/
public String getLabel(){
// return the long label
return getLabel(false);
}
/**
* Returns a label describing this Kontakt.
*
* The default implementation returns "Bezeichnung1" for the short label, and "Bezeichnung1",
* "Bezeichnung2", "Strasse", "Plz" and "Ort", separated with a comma, for the long label.
*
* Subclasses can overwrite this method and define their own label(s). If short is true, they
* should return a short label suitable for addresses. If short is false, they should return a
* long label describing all important properties of this Kontakt for unique identification by
* the user.
*
* @param shortLabel
* return a short label for true, and a long label otherwise
* @return a string describing this Kontakt.
*/
public String getLabel(boolean shortLabel){
StringBuilder bld = new StringBuilder();
if (shortLabel) {
bld.append(get(FLD_NAME1));
String bez3 = get(FLD_NAME3);
if (!StringTool.isNothing(bez3)) {
bld.append("(").append(bez3).append(")"); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
String[] ret = new String[6];
get(new String[] {
FLD_NAME1, FLD_NAME2, FLD_NAME3, FLD_STREET, FLD_ZIP, FLD_PLACE
}, ret);
bld.append(ret[0]).append(StringTool.space).append(checkNull(ret[1]));
if (!StringTool.isNothing(ret[2])) {
bld.append("(").append(ret[2]).append(")"); //$NON-NLS-1$ //$NON-NLS-2$
}
bld.append(", ").append(checkNull(ret[3])).append(", ") //$NON-NLS-1$ //$NON-NLS-2$
.append(checkNull(ret[4])).append(StringTool.space).append(checkNull(ret[5]));
}
return bld.toString();
}
public boolean isValid(){
if (!super.isValid()) {
return false;
}
return true;
}
public List<BezugsKontakt> getBezugsKontakte(){
Query<BezugsKontakt> qbe = new Query<BezugsKontakt>(BezugsKontakt.class);
qbe.add("myID", StringTool.equals, getId()); //$NON-NLS-1$
return qbe.execute();
}
/** Die Anschrift dieses Kontakts holen */
public Anschrift getAnschrift(){
return new Anschrift(this);
}
/** Die Anschrift dieses Kontakts setzen */
public void setAnschrift(Anschrift adr){
if (adr != null) {
set(new String[] {
FLD_STREET, FLD_ZIP, FLD_PLACE, FLD_COUNTRY
}, adr.getStrasse(), adr.getPlz(), adr.getOrt(), adr.getLand());
}
}
public String getPostAnschrift(){
return getPostAnschrift(false);
}
public String getPostAnschrift(boolean multiline){
String an = get(FLD_ANSCHRIFT);
if (StringTool.isNothing(an)) {
an = createStdAnschrift();
}
an = an.replaceAll("[\\r\\n]\\n", StringTool.lf); //$NON-NLS-1$
return multiline == true ? an : an.replaceAll("\\n", StringTool.space); //$NON-NLS-1$
}
public String createStdAnschrift(){
Anschrift an = getAnschrift();
String ret = StringTool.leer;
StringBuilder sb = new StringBuilder();
if (istPerson() == true) {
Person p = Person.load(getId());
// TODO default salutation should be configurable
String salutation;
if (p.getGeschlecht().equals(Person.MALE)) {
salutation = Messages.Contact_SalutationM;
} else {
salutation = Messages.Contact_SalutationF;
}
sb.append(salutation);
sb.append(StringTool.lf);
String titel = p.get("Titel"); //$NON-NLS-1$
if (!StringTool.isNothing(titel)) {
sb.append(titel).append(StringTool.space);
}
sb.append(p.getVorname()).append(StringTool.space).append(p.getName())
.append(StringTool.lf);
sb.append(an.getEtikette(false, true));
ret = sb.toString();
} else {
Organisation o = Organisation.load(getId());
String[] rx = new String[2];
o.get(new String[] {
FLD_NAME1, FLD_NAME2
}, rx);
sb.append(rx[0]).append(StringTool.space).append(checkNull(rx[1]))
.append(StringTool.lf);
sb.append(an.getEtikette(false, true));
ret = sb.toString();
}
/*
* else{ ret= an.getEtikette(true, true); }
*/
// create the postal if it does not exist yet
String old = get(FLD_ANSCHRIFT);
if (StringTool.isNothing(old)) {
set(FLD_ANSCHRIFT, ret);
}
return ret;
}
/**
* Synthesize the address lines to output from the entries in Kontakt k. added to implement the
* output format desired for the copyAddressToClipboard() buttons.
*
* @param multiline
* or single line output
* @param including_phone
* controls whether the phone numbers shall be
*
* @return string containing the needed information
*/
/*
* getPostAnschrift() does NOT use the System.getProperty("line.separator"); which I use bwlow
* after the Fax number (and also in the calling code, before a possibly succeeding addresses.
* getPostAnschrift() instead replaces all line separators by either \\n or space at the end of
* its run; and I keep that code, +-multiline support herein as well to maintain similar usage
* of both methods.
*
* On a Win2K system, `that has the following effects when pasting the address(es) into various
* targets: notepad: All elements of an address in one line, box characters instead of the
* newline (or cr?) character. textpad: New line after each line within an address and between
* addresses. winword 97: "new paragraph" after each line within an address, and before a
* succeeding address. openoffice 2.0.3: "new line" after each line within an address;
* "new paragraph" after the Fax number and before a succeeding address.
*/
public String getPostAnschriftPhoneFaxEmail(boolean multiline, boolean including_phone){
StringBuffer thisAddress = new StringBuffer();
// getPostAnschrift() already returns a line separator after the address;
// processing of the multiline flag is implemented further below as well,
// so it suffices if we call getPostAnschrift(true) and not pass the flag there.
// this also ensures that new-lines inserted in getPostAnschrift() and below,
// will finally be processed the same way, no matter what we might change below.
// Damit die Telefonnummer in dem Fall nicht direkt am Ort klebt,
thisAddress.append(getPostAnschrift(true).trim());
thisAddress.append(System.getProperty("line.separator"));
// && !k.FLD_FAX.isEmpty() is NOT sufficient to prevent empty lines, or lines with just the
// Labels "Fax" and "E-Mail".
// Apparently, the entries "Fax" or "E-Mail" exist in the respective fields instead of
// proper content.
// THIS DOES NOT WORK:
// if (k.FLD_FAX != null && k.FLD_FAX.length()>0 && !k.FLD_FAX.equals("Fax")) {
// selectedAddressesText.append(k.FLD_FAX+System.getProperty("line.separator"));
// if (k.FLD_E_MAIL != null && k.FLD_E_MAIL.length()>0 && !k.FLD_E_MAIL.equals("E-Mail")) {
// selectedAddressesText.append(k.FLD_E_MAIL+System.getProperty("line.separator"));
if (including_phone) {
String thisAddressFLD_PHONE1 = (String) get(FLD_PHONE1);
if (!StringTool.isNothing(thisAddressFLD_PHONE1)) {
thisAddress.append(thisAddressFLD_PHONE1 + System.getProperty("line.separator"));
}
String thisAddressFLD_PHONE2 = (String) get(FLD_PHONE2);
if (!StringTool.isNothing(thisAddressFLD_PHONE2)) {
thisAddress.append(thisAddressFLD_PHONE2 + System.getProperty("line.separator"));
}
String thisAddressFLD_MOBILEPHONE = (String) get(FLD_MOBILEPHONE);
if (!StringTool.isNothing(thisAddressFLD_MOBILEPHONE)) {
// With a colon after the label:
thisAddress.append(FLD_MOBILEPHONE + ":" + StringTool.space
+ thisAddressFLD_MOBILEPHONE + System.getProperty("line.separator"));
// Without a colon after the label:
// selectedPatInfosText.append(","+StringTool.space+k.FLD_MOBILEPHONE+StringTool.space+thisAddressFLD_MOBILEPHONE);
}
}
String thisAddressFLD_FAX = (String) get(FLD_FAX);
if (!StringTool.isNothing(thisAddressFLD_FAX)) {
thisAddress.append("Fax:" + StringTool.space + thisAddressFLD_FAX
+ System.getProperty("line.separator"));
}
String thisAddressFLD_E_MAIL = (String) get(FLD_E_MAIL);
if (!StringTool.isNothing(thisAddressFLD_E_MAIL)) {
thisAddress.append(thisAddressFLD_E_MAIL + System.getProperty("line.separator"));
}
String an = thisAddress.toString();
an = an.replaceAll("[\\r\\n]\\n", StringTool.lf); //$NON-NLS-1$
return multiline == true ? an : an.replaceAll("\\n", StringTool.space); //$NON-NLS-1$
}
public BezugsKontakt addBezugsKontakt(Kontakt adr, String sBezug){
if ((adr != null) && (sBezug != null)) {
return new BezugsKontakt(this, adr, sBezug);
}
return null;
}
protected Kontakt(String id){
super(id);
}
/** Kontakt mit gegebener Id aus der Datanbank einlesen */
public static Kontakt load(String id){
return new Kontakt(id);
}
protected Kontakt(){
// System.out.println("Kontakt");
}
public String getMailAddress(){
return checkNull(get(FLD_E_MAIL)); //$NON-NLS-1$
}
/** Die Reminders zu diesem Kontakt holen */
public Reminder[] getRelatedReminders(){
List<String> l = getList("MyReminders", false); //$NON-NLS-1$
Reminder[] ret = new Reminder[l.size()];
int i = 0;
for (String id : l) {
ret[i++] = Reminder.load(id);
}
return ret;
}
@Override
public boolean delete(){
for (Reminder r : getRelatedReminders()) {
r.delete();
}
for (BezugsKontakt bk : getBezugsKontakte()) {
bk.delete();
}
return super.delete();
}
public Object getInfoElement(String elem){
return getMap(FLD_EXTINFO).get(elem);
}
/**
* Convenience-Methode und einen String aus dem Infostore auszulesen.
*
* @param elem
* Name des Elements
* @return Wert oder "" wenn das Element nicht vorhanden ist oder die Rechte nicht zum Lesen
* ausreichen
*/
public String getInfoString(String elem){
return checkNull((String) getExtInfoStoredObjectByKey(elem));
}
@SuppressWarnings("unchecked")
public void setInfoElement(String elem, Object val){
Map extinfos = getMap(FLD_EXTINFO);
if (extinfos != null) {
extinfos.put(elem, val);
setMap(FLD_EXTINFO, extinfos);
}
}
@SuppressWarnings("unchecked")
public void flushInfoStore(Map store){
setMap(FLD_EXTINFO, store);
}
@SuppressWarnings("unchecked")
public static Kontakt findKontaktfromInfoStore(Class clazz, String field, String value){
Query qbe = new Query(clazz);
List list = qbe.execute();
for (Kontakt k : (List<Kontakt>) list) {
String i = (String) k.getInfoElement(field);
if (i != null && i.equals(value)) {
return k;
}
}
return null;
}
@SuppressWarnings("unchecked")
public List<String> getStatForItem(String typ){
Map exi = getMap(FLD_EXTINFO);
ArrayList<statL> al = (ArrayList<statL>) exi.get(typ);
ArrayList<String> ret = new ArrayList<String>(al == null ? 1 : al.size());
if (al != null) {
for (statL sl : al) {
ret.add(sl.v);
}
}
return ret;
}
@SuppressWarnings("unchecked")
public void statForItem(PersistentObject lst){
Map exi = getMap(FLD_EXTINFO);
String typ = lst.getClass().getName();
String ident = lst.storeToString();
ArrayList<statL> l = (ArrayList<statL>) exi.get(typ);
if (l == null) {
l = new ArrayList<statL>();
}
while (l.size() > 40) {
l.remove(l.size() - 1);
}
boolean found = false;
for (statL c : l) {
if (c.v.equals(ident)) {
c.c++;
found = true;
break;
}
}
if (found == false) {
l.add(new statL(ident)); // Nicht gefunden, dann neu eintragen
}
Collections.sort(l); // Liste sortieren
exi.put(typ, l);
setMap(FLD_EXTINFO, exi);
}
public static class statL implements Comparable<statL>, Serializable {
private static final long serialVersionUID = 10455663346456L;
String v;
int c;
public statL(){}
statL(String vv){
v = vv;
c = 1;
}
public int compareTo(statL ot){
return ot.c - c;
}
}
@SuppressWarnings("unchecked")
public void statForString(String typ, String toStat){
Map exi = getMap(FLD_EXTINFO);
MFUList<String> l = (MFUList<String>) exi.get(typ);
if (l == null) {
l = new MFUList<String>(5, 15);
}
l.count(toStat);
exi.put(typ, l);
setMap(FLD_EXTINFO, exi);
}
@SuppressWarnings("unchecked")
public List<String> getStatForString(String typ){
Map exi = getMap(FLD_EXTINFO);
MFUList<String> al = (MFUList<String>) exi.get(typ);
if (al == null) {
al = new MFUList<String>(5, 15);
}
return al.getAll();
}
@SuppressWarnings("unchecked")
public MFUList<String> getMFU(String typ){
Map exi = getMap(FLD_EXTINFO);
MFUList<String> l = (MFUList<String>) exi.get(typ);
if (l == null) {
l = new MFUList<String>(5, 15);
}
return l;
}
@SuppressWarnings("unchecked")
public void setMFU(String typ, MFUList<String> mfu){
Map exi = getMap(FLD_EXTINFO);
exi.put(typ, mfu);
setMap(FLD_EXTINFO, exi);
}
public String getKuerzel(){
return get(FLD_SHORT_LABEL);
}
public String getBemerkung(){
return get(FLD_REMARK);
}
public void setBemerkung(String b){
set(FLD_REMARK, b);
}
public boolean istPerson(){
return checkNull(get(FLD_IS_PERSON)).equals(StringConstants.ONE);
}
public boolean istPatient(){
return checkNull(get(FLD_IS_PATIENT)).equals(StringConstants.ONE);
}
public boolean istOrganisation(){
return checkNull(get(FLD_IS_ORGANIZATION)).equals(StringConstants.ONE);
}
} |
package omnikryptec.animation.renderer;
import java.util.List;
import omnikryptec.animation.AnimatedModel;
import omnikryptec.entity.Camera;
import omnikryptec.entity.Entity;
import omnikryptec.logger.Logger;
import omnikryptec.main.Scene;
import omnikryptec.model.AdvancedModel;
import omnikryptec.renderer.RenderMap;
import omnikryptec.renderer.Renderer;
import omnikryptec.renderer.RendererRegistration;
import omnikryptec.util.RenderUtil;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector3f;
/**
*
* This class deals with rendering an animated entity. Nothing particularly new
* here. The only exciting part is that the joint transforms get loaded up to
* the shader in a uniform array.
*
* @author Karl & Panzer1119
*
*/
public class AnimatedModelRenderer implements Renderer {
public static final Vector3f LIGHT_DIR = new Vector3f(0.2f, -0.3f, -0.8f);
private AnimatedModelShader shader;
/**
* Initializes the shader program used for rendering animated models.
*/
public AnimatedModelRenderer() {
RendererRegistration.register(this);
this.shader = new AnimatedModelShader();
}
/**
* Renders an animated entity. The main thing to note here is that all the
* joint transforms are loaded up to the shader to a uniform array. Also 5
* attributes of the VAO are enabled before rendering, to include joint
* indices and weights.
*
* @param entity
* - the animated entity to be rendered.
* @param camera
* - the camera used to render the entity.
* @param lightDir
* - the direction of the light in the scene.
*/
private void render(Entity entity) {
RenderUtil.antialias(true);
RenderUtil.disableBlending();
RenderUtil.enableDepthTesting(true);
AnimatedModel animatedModel = (AnimatedModel) entity.getAdvancedModel();
Logger.log("Started Rendering: " + entity);
animatedModel.getTexture().bindToUnit(0);
animatedModel.getModel().getVao().bind(0, 1, 2, 3, 4);
shader.jointTransforms.loadMatrixArray(animatedModel.getJointTransforms());
GL11.glDrawElements(GL11.GL_TRIANGLES, animatedModel.getModel().getVao().getIndexCount(), GL11.GL_UNSIGNED_INT, 0);
animatedModel.getModel().getVao().unbind(0, 1, 2, 3, 4);
Logger.log("Finished Rendering: " + entity);
}
private List<Entity> stapel;
private AdvancedModel model;
@Override
public void render(Scene s, RenderMap<AdvancedModel, List<Entity>> entities) {
final Camera camera = s.getCamera();
shader.start();
shader.projectionViewMatrix.loadMatrix(camera.getProjectionViewMatrix());
shader.lightDirection.loadVec3(LIGHT_DIR);
for(int i = 0; i < entities.keysArray().length; i++) {
model = entities.keysArray()[i];
if(!(model instanceof AdvancedModel)) {
continue;
}
stapel = entities.get(model);
if(stapel != null && !stapel.isEmpty()) {
stapel.stream().forEach((entity) -> {
if(entity.isActive() && RenderUtil.inRenderRange(entity, camera)) {
render(entity);
}
});
}
}
}
@Override
public void cleanup() {
shader.cleanup();
}
@Override
public float expensiveLevel() {
return 1;
}
} |
package org.adaptlab.chpir.android.survey;
import java.util.List;
import java.util.UUID;
import org.adaptlab.chpir.android.activerecordcloudsync.ActiveRecordCloudSync;
import org.adaptlab.chpir.android.activerecordcloudsync.PollService;
import org.adaptlab.chpir.android.survey.Models.AdminSettings;
import org.adaptlab.chpir.android.survey.Models.Instrument;
import org.adaptlab.chpir.android.survey.Models.Option;
import org.adaptlab.chpir.android.survey.Models.Question;
import org.adaptlab.chpir.android.survey.Models.Response;
import org.adaptlab.chpir.android.survey.Models.Survey;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
public class InstrumentFragment extends ListFragment {
private final static String TAG = "InstrumentFragment";
private final static boolean REQUIRE_SECURITY_CHECKS = false;
private String ADMIN_PASSWORD_HASH;
private String ACCESS_TOKEN;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setListAdapter(new InstrumentAdapter(Instrument.getAll()));
ADMIN_PASSWORD_HASH = getActivity().getResources().getString(R.string.admin_password_hash);
ACCESS_TOKEN = getActivity().getResources().getString(R.string.backend_api_key);
createTabs();
appInit();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_instrument, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_admin:
displayPasswordPrompt();
return true;
case R.id.menu_item_refresh:
new RefreshInstrumentsTask().execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
createTabs();
}
public void createTabs() {
if (AdminSettings.getInstance().getShowSurveys()) {
final ActionBar actionBar = getActivity().getActionBar();
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
@Override
public void onTabSelected(Tab tab,
android.app.FragmentTransaction ft) {
if (tab.getText().equals(getActivity().getResources().getString(R.string.surveys))) {
if (!Survey.getAll().isEmpty())
setListAdapter(new SurveyAdapter(Survey.getAll()));
} else {
setListAdapter(new InstrumentAdapter(Instrument.getAll()));
}
}
// Required by interface
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) { }
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) { }
};
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.removeAllTabs();
actionBar.addTab(actionBar.newTab().setText(getActivity().getResources().getString(R.string.instruments)).setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText(getActivity().getResources().getString(R.string.surveys)).setTabListener(tabListener));
}
}
private class InstrumentAdapter extends ArrayAdapter<Instrument> {
public InstrumentAdapter(List<Instrument> instruments) {
super(getActivity(), 0, instruments);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_instrument, null);
}
Instrument instrument = getItem(position);
TextView titleTextView = (TextView) convertView
.findViewById(R.id.instrument_list_item_titleTextView);
titleTextView.setText(instrument.getTitle());
titleTextView.setTypeface(instrument.getTypeFace(getActivity().getApplicationContext()));
TextView questionCountTextView = (TextView) convertView
.findViewById(R.id.instrument_list_item_questionCountTextView);
int numQuestions = instrument.questions().size();
questionCountTextView.setText(numQuestions + " "
+ FormatUtils.pluralize(numQuestions, getString(R.string.question), getString(R.string.questions)));
return convertView;
}
}
private class SurveyAdapter extends ArrayAdapter<Survey> {
public SurveyAdapter(List<Survey> surveys) {
super(getActivity(), 0, surveys);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_instrument, null);
}
Survey survey = getItem(position);
TextView titleTextView = (TextView) convertView
.findViewById(R.id.instrument_list_item_titleTextView);
titleTextView.setText(survey.responses().get(0).getText());
titleTextView.setTypeface(survey.getInstrument().getTypeFace(getActivity().getApplicationContext()));
TextView questionCountTextView = (TextView) convertView
.findViewById(R.id.instrument_list_item_questionCountTextView);
questionCountTextView.setText(survey.responses().size() + " " + getString(R.string.of) + " " + survey.getInstrument().questions().size());
return convertView;
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (l.getAdapter() instanceof InstrumentAdapter) {
Instrument instrument = ((InstrumentAdapter) getListAdapter()).getItem(position);
if (instrument == null) {
return;
}
new LoadInstrumentTask().execute(instrument);
} else if (l.getAdapter() instanceof SurveyAdapter) {
}
}
private final void appInit() {
if (REQUIRE_SECURITY_CHECKS) {
if (!runDeviceSecurityChecks()) {
// Device has failed security checks
return;
}
}
Log.i(TAG, "Initializing application...");
Crashlytics.start(getActivity());
DatabaseSeed.seed(getActivity());
if (AdminSettings.getInstance().getDeviceIdentifier() == null) {
AdminSettings.getInstance().setDeviceIdentifier(UUID.randomUUID().toString());
}
ActiveRecordCloudSync.setAccessToken(ACCESS_TOKEN);
ActiveRecordCloudSync.setVersionCode(getVersionCode());
ActiveRecordCloudSync.setEndPoint(AdminSettings.getInstance().getApiUrl());
ActiveRecordCloudSync.addReceiveTable("instruments", Instrument.class);
ActiveRecordCloudSync.addReceiveTable("questions", Question.class);
ActiveRecordCloudSync.addReceiveTable("options", Option.class);
ActiveRecordCloudSync.addSendTable("surveys", Survey.class);
ActiveRecordCloudSync.addSendTable("responses", Response.class);
PollService.setServiceAlarm(getActivity().getApplicationContext(), true);
}
/*
* Security checks that must pass for the application to start.
*
* If the application fails any security checks, display
* AlertDialog indicating why and immediately stop execution
* of the application.
*
* Current security checks: require encryption
*/
private final boolean runDeviceSecurityChecks() {
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getActivity()
.getSystemService(Context.DEVICE_POLICY_SERVICE);
if (devicePolicyManager.getStorageEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE) {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.encryption_required_title)
.setMessage(R.string.encryption_required_text)
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
})
.show();
return false;
}
return true;
}
/*
* Only display admin area if correct password.
*/
private void displayPasswordPrompt() {
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.password_title)
.setMessage(R.string.password_message)
.setView(input)
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
if (checkAdminPassword(input.getText().toString())) {
Intent i = new Intent(getActivity(), AdminActivity.class);
startActivity(i);
} else {
Toast.makeText(getActivity(), R.string.incorrect_password, Toast.LENGTH_LONG).show();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) { }
}).show();
}
/*
* Hash the entered password and compare it with admin password hash
*/
private boolean checkAdminPassword(String password) {
String hash = new String(Hex.encodeHex(DigestUtils.sha256(password)));
return hash.equals(ADMIN_PASSWORD_HASH);
}
/*
* Get the version code from the AndroidManifest
*/
private int getVersionCode() {
try {
PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
return pInfo.versionCode;
} catch (NameNotFoundException nnfe) {
Log.e(TAG, "Error finding version code: " + nnfe);
}
return -1;
}
/*
* Refresh the receive tables from the server
*/
private class RefreshInstrumentsTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
getActivity().setProgressBarIndeterminateVisibility(true);
setListAdapter(null);
}
@Override
protected Void doInBackground(Void... params) {
ActiveRecordCloudSync.syncReceiveTables();
return null;
}
@Override
protected void onPostExecute(Void param) {
if (isAdded()) {
setListAdapter(new InstrumentAdapter(Instrument.getAll()));
getActivity().setProgressBarIndeterminateVisibility(false);
}
}
}
/*
* Check that the instrument has been fully loaded from the server before allowing
* user to begin survey.
*/
private class LoadInstrumentTask extends AsyncTask<Instrument, Void, Long> {
ProgressDialog mProgressDialog;
@Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(
getActivity(),
getString(R.string.instrument_loading_progress_header),
getString(R.string.instrument_loading_progress_message)
);
}
/*
* If instrument is loaded, return the instrument id.
* If not, return -1.
*/
@Override
protected Long doInBackground(Instrument... params) {
Instrument instrument = params[0];
if (instrument.loaded()) {
return instrument.getRemoteId();
} else {
return Long.valueOf(-1);
}
}
@Override
protected void onPostExecute(Long instrumentId) {
mProgressDialog.dismiss();
if (instrumentId == Long.valueOf(-1)) {
Toast.makeText(getActivity(), R.string.instrument_not_loaded, Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(getActivity(), SurveyActivity.class);
i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, instrumentId);
startActivity(i);
}
}
}
} |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check that all tables have data.
*/
public class EmptyTables extends SingleDatabaseTestCase {
/**
* Creates a new instance of EmptyTablesTestCase
*/
public EmptyTables() {
addToGroup("post_genebuild");
addToGroup("release");
setDescription("Checks that all tables have data");
}
/**
* Define what tables are to be checked.
*/
private String[] getTablesToCheck(final DatabaseRegistryEntry dbre) {
String[] tables = getTableNames(dbre.getConnection());
Species species = dbre.getSpecies();
DatabaseType type = dbre.getType();
if (type == DatabaseType.CORE || type == DatabaseType.VEGA) {
// the following tables are allowed to be empty
String[] allowedEmpty = { "alt_allele", "assembly_exception", "dnac", "density_feature", "density_type" };
tables = remove(tables, allowedEmpty);
// ID mapping related tables are checked in a separate test case
String[] idMapping = { "gene_archive", "peptide_archive", "mapping_session", "stable_id_event" };
tables = remove(tables, idMapping);
// only rat has entries in QTL tables
if (species != Species.RATTUS_NORVEGICUS) {
String[] qtlTables = { "qtl", "qtl_feature", "qtl_synonym" };
tables = remove(tables, qtlTables);
}
// seq_region_attrib only filled in for human and mouse
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS) {
tables = remove(tables, "seq_region_attrib");
}
// map, marker etc
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS
&& species != Species.DANIO_RERIO) {
String[] markerTables = { "map", "marker", "marker_map_location", "marker_synonym", "marker_feature" };
tables = remove(tables, markerTables);
}
// misc_feature etc
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.ANOPHELES_GAMBIAE) {
String[] miscTables = { "misc_feature", "misc_feature_misc_set", "misc_set", "misc_attrib" };
tables = remove(tables, miscTables);
}
// for imported gene sets, supporting_feature is empty
if (species == Species.TETRAODON_NIGROVIRIDIS || species == Species.SACCHAROMYCES_CEREVISIAE || species == Species.CAENORHABDITIS_ELEGANS) {
tables = remove(tables, "supporting_feature");
}
// only look for Affy features in human, mouse, rat, chicken, danio
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS
&& species != Species.GALLUS_GALLUS && species != Species.DANIO_RERIO) {
tables = remove(tables, "oligo_array");
tables = remove(tables, "oligo_feature");
tables = remove(tables, "oligo_probe");
}
// only look for transcript & translation attribs in human, mouse, rat
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS) {
tables = remove(tables, "transcript_attrib");
tables = remove(tables, "translation_attrib");
}
// drosophila is imported, so no supporting features.
if (species == Species.DROSOPHILA_MELANOGASTER) {
tables = remove(tables, "supporting_feature");
}
// most species don't have regulatory features yet
if (species != Species.HOMO_SAPIENS) {
tables = remove(tables, "regulatory_feature");
tables = remove(tables, "regulatory_factor");
tables = remove(tables, "regulatory_factor_coding");
tables = remove(tables, "regulatory_feature_object");
tables = remove(tables, "regulatory_search_region");
}
// only human and mouse currently have ditag data
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS) {
tables = remove(tables, "ditag");
tables = remove(tables, "ditag_feature");
}
// we don't have many gene_attribs yet
tables = remove(tables, "gene_attrib");
} else if (type == DatabaseType.EST || type == DatabaseType.OTHERFEATURES) {
// Only a few tables need to be filled in EST
String[] est = { "dna_align_feature", "meta_coord", "meta", "coord_system" };
tables = est;
} else if (type == DatabaseType.ESTGENE) {
// Only a few tables need to be filled in ESTGENE
String[] estGene = { "gene", "transcript", "exon", "meta_coord", "coord_system", "gene_stable_id", "exon_stable_id",
"translation_stable_id", "transcript_stable_id", "karyotype" };
tables = estGene;
} else if (type == DatabaseType.CDNA) {
// Only a few tables need to be filled in cDNA databases
String[] cdna = { "assembly", "attrib_type", "dna_align_feature", "meta", "meta_coord", "seq_region", "seq_region_attrib" };
tables = cdna;
}
// many tables are allowed to be empty in vega databases
if (type == DatabaseType.VEGA) {
String[] allowedEmpty = { "affy_array", "affy_feature", "affy_probe", "analysis_description", "dna", "external_synonym", "go_xref",
"identity_xref", "karyotype", "map", "marker", "marker_feature", "marker_map_location", "marker_synonym", "misc_attrib",
"misc_feature", "misc_feature_misc_set", "misc_set", "prediction_exon", "prediction_transcript", "regulatory_factor",
"regulatory_factor_coding", "regulatory_feature", "regulatory_feature_object", "repeat_consensus", "repeat_feature",
"simple_feature", "transcript_attrib", "transcript_supporting_feature", "translation_attrib" };
tables = remove(tables, allowedEmpty);
}
return tables;
}
/**
* Check that every table has more than 0 rows.
*
* @param dbre The database to check.
* @return true if the test passed.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
String[] tables = getTablesToCheck(dbre);
Connection con = dbre.getConnection();
// if there is only one coordinate system then there's no assembly
if (getRowCount(con, "SELECT COUNT(*) FROM coord_system") == 1) {
tables = remove(tables, "assembly");
logger.finest(dbre.getName() + " has only one coord_system, assembly table can be empty");
}
for (int i = 0; i < tables.length; i++) {
String table = tables[i];
// logger.finest("Checking that " + table + " has rows");
if (!tableHasRows(con, table)) {
ReportManager.problem(this, con, table + " has zero rows");
result = false;
}
}
if (result) {
ReportManager.correct(this, con, "All required tables have data");
}
return result;
} // run
private String[] remove(final String[] tables, final String table) {
String[] result = new String[tables.length - 1];
int j = 0;
for (int i = 0; i < tables.length; i++) {
if (!tables[i].equalsIgnoreCase(table)) {
if (j < result.length) {
result[j++] = tables[i];
} else {
logger.severe("Cannot remove " + table + " since it's not in the list!");
}
}
}
return result;
}
private String[] remove(final String[] src, final String[] tablesToRemove) {
String[] result = src;
for (int i = 0; i < tablesToRemove.length; i++) {
result = remove(result, tablesToRemove[i]);
}
return result;
}
} // EmptyTablesTestCase |
package org.myrobotlab.document.transformer;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.myrobotlab.logging.LoggerFactory;
import org.slf4j.Logger;
import au.com.bytecode.opencsv.CSVReader;
/**
* A singleton class to load a dictionary into the jvm that can be used across
* multiple instances of a pipeline sage.
*
* @author kwatters
*
*/
public class DictionaryLoader {
public final static Logger log = LoggerFactory.getLogger(DictionaryLoader.class.getCanonicalName());
private static DictionaryLoader instance = null;
// csvFile -> map-of-values
private HashMap<String, HashMap<String,List<String>>> dictMap;
protected DictionaryLoader() {
// Exists only to defeat instantiation.
dictMap = new HashMap<String, HashMap<String,List<String>>>();
}
public static DictionaryLoader getInstance() {
if(instance == null) {
instance = new DictionaryLoader();
}
return instance;
}
public synchronized HashMap<String, List<String>> loadDictionary(String fileName) throws IOException {
// it's already loaded, just return it
if (dictMap.containsKey(fileName)) {
return dictMap.get(fileName);
}
// It's not loaded, load the file and put it in the dict map and return.
// Assume the file is a csv file with key/value pairs on each line.
HashMap<String,List<String>> dictionary = new HashMap<String,List<String>>();
File dictFile = new File(fileName);
if (!dictFile.exists()) {
log.warn("Dictionary file not found {}", dictFile.getAbsolutePath());
return null;
}
CSVReader reader = new CSVReader(new FileReader(fileName));
String [] line;
while ((line = reader.readNext()) != null) {
// line[] is an array of values from the line
List<String> listVal = dictionary.get(line[0]);
if (listVal == null) {
listVal = new ArrayList<String>();
dictionary.put(line[0], listVal);
}
for (int i = 1; i < line.length; i++ ) {
listVal.add(line[i]);
}
}
dictMap.put(fileName, dictionary);
reader.close();
return dictionary;
}
} |
package org.pentaho.di.trans.steps.denormaliser;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueDataUtil;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Denormalises data based on key-value pairs
*
* @author Matt
* @since 17-jan-2006
*/
public class Denormaliser extends BaseStep implements StepInterface
{
private static Class<?> PKG = DenormaliserMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private DenormaliserMeta meta;
private DenormaliserData data;
public Denormaliser(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
meta=(DenormaliserMeta)getStepMeta().getStepMetaInterface();
data=(DenormaliserData)stepDataInterface;
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
Object[] r=getRow(); // get row!
if (r==null) // no more input to be expected...
{
// Don't forget the last set of rows...
if (data.previous!=null)
{
// deNormalise(data.previous); --> That would overdo it.
Object[] outputRowData = buildResult(data.inputRowMeta, data.previous);
putRow(data.outputRowMeta, outputRowData);
}
setOutputDone();
return false;
}
if (first)
{
data.inputRowMeta = getInputRowMeta();
data.outputRowMeta = data.inputRowMeta.clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
data.keyFieldNr = data.inputRowMeta.indexOfValue( meta.getKeyField() );
if (data.keyFieldNr<0)
{
logError(BaseMessages.getString(PKG, "Denormaliser.Log.KeyFieldNotFound",meta.getKeyField())); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
Map<Integer, Integer> subjects = new Hashtable<Integer, Integer>();
data.fieldNameIndex = new int[meta.getDenormaliserTargetField().length];
for (int i=0;i<meta.getDenormaliserTargetField().length;i++)
{
DenormaliserTargetField field = meta.getDenormaliserTargetField()[i];
int idx = data.inputRowMeta.indexOfValue( field.getFieldName() );
if (idx<0)
{
logError(BaseMessages.getString(PKG, "Denormaliser.Log.UnpivotFieldNotFound",field.getFieldName())); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
data.fieldNameIndex[i] = idx;
subjects.put(Integer.valueOf(idx), Integer.valueOf(idx));
// See if by accident, the value fieldname isn't the same as the key fieldname.
// This is not supported of-course and given the complexity of the step, you can miss:
if (data.fieldNameIndex[i]==data.keyFieldNr)
{
logError(BaseMessages.getString(PKG, "Denormaliser.Log.ValueFieldSameAsKeyField", field.getFieldName())); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
// Fill a hashtable with the key strings and the position(s) of the field(s) in the row to take.
// Store the indexes in a List so that we can accommodate multiple key/value pairs...
String keyValue = environmentSubstitute(field.getKeyValue());
List<Integer> indexes = data.keyValue.get(keyValue);
if (indexes==null)
{
indexes = new ArrayList<Integer>(2);
}
indexes.add(Integer.valueOf(i)); // Add the index to the list...
data.keyValue.put(keyValue, indexes); // store the list
}
Set<Integer> subjectSet = subjects.keySet();
data.fieldNrs = subjectSet.toArray(new Integer[subjectSet.size()]);
data.groupnrs = new int[meta.getGroupField().length];
for (int i=0;i<meta.getGroupField().length;i++)
{
data.groupnrs[i] = data.inputRowMeta.indexOfValue( meta.getGroupField()[i] );
if (data.groupnrs[i]<0)
{
logError(BaseMessages.getString(PKG, "Denormaliser.Log.GroupingFieldNotFound",meta.getGroupField()[i])); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
}
List<Integer> removeList = new ArrayList<Integer>();
removeList.add(Integer.valueOf(data.keyFieldNr));
for (int i=0;i<data.fieldNrs.length;i++)
{
removeList.add(data.fieldNrs[i]);
}
Collections.sort(removeList);
data.removeNrs = new int[removeList.size()];
for (int i=0;i<removeList.size();i++) data.removeNrs[i] = removeList.get(i);
data.previous=r; // copy the row to previous
newGroup(); // Create a new result row (init)
first=false;
}
// System.out.println("Check for same group...");
if (!sameGroup(data.inputRowMeta, data.previous, r))
{
// System.out.println("Different group!");
Object[] outputRowData = buildResult(data.inputRowMeta, data.previous);
putRow(data.outputRowMeta, outputRowData); // copy row to possible alternate rowset(s).
//System.out.println("Wrote row: "+data.previous);
newGroup(); // Create a new group aggregate (init)
deNormalise(data.inputRowMeta, r);
}
else
{
deNormalise(data.inputRowMeta, r);
}
data.previous=r;
if (checkFeedback(getLinesRead()))
{
if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "Denormaliser.Log.LineNumber")+getLinesRead()); //$NON-NLS-1$
}
return true;
}
private Object[] buildResult(RowMetaInterface rowMeta, Object[] rowData) throws KettleValueException
{
// Deleting objects: we need to create a new object array
// It's useless to call RowDataUtil.resizeArray
Object[] outputRowData = RowDataUtil.allocateRowData( data.outputRowMeta.size() );
int outputIndex = 0;
// Copy the data from the incoming row, but remove the unwanted fields in the same loop...
int removeIndex=0;
for (int i=0;i<rowMeta.size();i++) {
if (removeIndex<data.removeNrs.length && i==data.removeNrs[removeIndex]) {
removeIndex++;
} else
{
outputRowData[outputIndex++]=rowData[i];
}
}
// Add the unpivoted fields...
for (int i=0;i<data.targetResult.length;i++)
{
Object resultValue = data.targetResult[i];
DenormaliserTargetField field = meta.getDenormaliserTargetField()[i];
switch(field.getTargetAggregationType())
{
case DenormaliserTargetField.TYPE_AGGR_AVERAGE :
long count = data.counters[i];
Object sum = data.sum[i];
if (count>0)
{
if (sum instanceof Long) resultValue = (long)((Long)sum / count);
else if (sum instanceof Double) resultValue = (double)((Double)sum / count);
else if (sum instanceof BigDecimal) resultValue = ((BigDecimal)sum).divide(new BigDecimal(count));
else resultValue = null; // TODO: perhaps throw an exception here?<
}
break;
case DenormaliserTargetField.TYPE_AGGR_COUNT_ALL :
if (resultValue == null) resultValue = Long.valueOf(0);
if (field.getTargetType() != ValueMetaInterface.TYPE_INTEGER)
{
resultValue = data.outputRowMeta.getValueMeta(outputIndex).convertData(new ValueMeta("num_values_aggregation", ValueMetaInterface.TYPE_INTEGER), resultValue);
}
break;
default: break;
}
outputRowData[outputIndex++] = resultValue;
}
return outputRowData;
}
// Is the row r of the same group as previous?
private boolean sameGroup(RowMetaInterface rowMeta, Object[] previous, Object[] rowData) throws KettleValueException
{
return rowMeta.compare(previous, rowData, data.groupnrs)==0;
}
/** Initialize a new group... */
private void newGroup()
{
// There is no need anymore to take care of the meta-data.
// That is done once in DenormaliserMeta.getFields()
data.targetResult = new Object[meta.getDenormaliserTargetFields().length];
for (int i=0;i<meta.getDenormaliserTargetFields().length;i++)
{
data.targetResult[i] = null;
data.counters[i]=0L; // set to 0
data.sum[i]=null;
}
}
/**
* This method de-normalizes a single key-value pair.
* It looks up the key and determines the value name to store it in.
* It converts it to the right type and stores it in the result row.
*
* @param r
* @throws KettleValueException
*/
private void deNormalise(RowMetaInterface rowMeta, Object[] rowData) throws KettleValueException
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.keyFieldNr);
Object valueData = rowData[data.keyFieldNr];
String key = valueMeta.getCompatibleString(valueData);
if ( !Const.isEmpty(key) )
{
// Get all the indexes for the given key value...
List<Integer> indexes = data.keyValue.get(key);
if (indexes!=null) // otherwise we're not interested.
{
for (int i=0;i<indexes.size();i++)
{
Integer keyNr = indexes.get(i);
if (keyNr!=null)
{
// keyNr is the field in DenormaliserTargetField[]
int idx = keyNr.intValue();
DenormaliserTargetField field = meta.getDenormaliserTargetField()[idx];
// This is the value we need to de-normalise, convert, aggregate.
ValueMetaInterface sourceMeta = rowMeta.getValueMeta(data.fieldNameIndex[idx]);
Object sourceData = rowData[data.fieldNameIndex[idx]];
Object targetData;
// What is the target value metadata??
ValueMetaInterface targetMeta = data.outputRowMeta.getValueMeta(data.inputRowMeta.size()-data.removeNrs.length+idx);
// What was the previous target in the result row?
Object prevTargetData = data.targetResult[idx];
switch(field.getTargetAggregationType())
{
case DenormaliserTargetField.TYPE_AGGR_SUM:
targetData = targetMeta.convertData(sourceMeta, sourceData);
if (prevTargetData!=null)
{
prevTargetData = ValueDataUtil.plus(targetMeta, prevTargetData, targetMeta, targetData);
}
else
{
prevTargetData = targetData;
}
break;
case DenormaliserTargetField.TYPE_AGGR_MIN:
if (sourceMeta.compare(sourceData, targetMeta, prevTargetData)<0) {
prevTargetData = targetMeta.convertData(sourceMeta, sourceData);
}
break;
case DenormaliserTargetField.TYPE_AGGR_MAX:
if (sourceMeta.compare(sourceData, targetMeta, prevTargetData)>0) {
prevTargetData = targetMeta.convertData(sourceMeta, sourceData);
}
break;
case DenormaliserTargetField.TYPE_AGGR_COUNT_ALL:
prevTargetData = ++data.counters[idx];
break;
case DenormaliserTargetField.TYPE_AGGR_AVERAGE:
targetData = targetMeta.convertData(sourceMeta, sourceData);
if (!sourceMeta.isNull(sourceData))
{
prevTargetData = data.counters[idx]++;
if (data.sum[idx]==null)
{
data.sum[idx] = targetData;
}
else
{
data.sum[idx] = ValueDataUtil.plus(targetMeta, data.sum[idx], targetMeta, targetData);
}
// data.sum[idx] = (Integer)data.sum[idx] + (Integer)sourceData;
}
break;
case DenormaliserTargetField.TYPE_AGGR_CONCAT_COMMA:
String separator=",";
targetData = targetMeta.convertData(sourceMeta, sourceData);
if (prevTargetData!=null)
{
prevTargetData = prevTargetData+separator+targetData;
}
else
{
prevTargetData = targetData;
}
break;
case DenormaliserTargetField.TYPE_AGGR_NONE:
default:
targetData = targetMeta.convertData(sourceMeta, sourceData);
prevTargetData = targetMeta.convertData(sourceMeta, sourceData); // Overwrite the previous
break;
}
// Update the result row too
data.targetResult[idx] = prevTargetData;
}
}
}
}
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(DenormaliserMeta)smi;
data=(DenormaliserData)sdi;
if (super.init(smi, sdi))
{
data.counters = new long[meta.getDenormaliserTargetField().length];
data.sum = new Object[meta.getDenormaliserTargetField().length];
return true;
}
return false;
}
} |
package org.xtreemfs.flink;
import java.io.File;
import java.io.PrintWriter;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple4;
public class DataLocalityTest {
public static void main(String[] args) throws Exception {
final ExecutionEnvironment env = ExecutionEnvironment
.getExecutionEnvironment();
if (args.length != 2) {
System.err
.println("Invoke with two positional parameters: the number of OSDs, the number of stripes per OSD.");
System.exit(1);
}
int osdCount = 0;
try {
osdCount = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Bad number of OSD argument: " + args[0]);
System.exit(1);
}
int stripesPerOsd = 0;
try {
stripesPerOsd = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println("Bad number of stripes per OSD argument: "
+ args[1]);
System.exit(1);
}
final String workingDirectory = System.getenv("WORK");
if (workingDirectory == null) {
System.err
.println("$WORK must point to an XtreemFS volume mount point (as a file system path).");
System.exit(1);
}
final String defaultVolume = System.getenv("DEFAULT_VOLUME");
if (defaultVolume == null) {
System.err
.println("$DEFAULT_VOLUME must point to an XtreemFS volume URL ('xtreemfs://hostname:port/volume').");
System.exit(1);
}
// Generate enough data to distribute among the OSDs.
PrintWriter out = new PrintWriter(workingDirectory + "/words.txt",
"UTF-8");
// Each entry is 8 bytes and we want 128 kilobytes per OSD.
for (int i = 0; i < stripesPerOsd * osdCount * 128 * 1024 / 8; ++i) {
// Always write the same value to each OSD.
out.println(1000000 + (i / (128 * 1024 / 8)) % osdCount);
}
out.close();
// Use words as input to Flink "wordcount" Job.
DataSet<String> input = env.readTextFile(workingDirectory
+ "/words.txt", "UTF-8");
DataSet<Tuple4<String, Long, Long, Long>> counts = input
.map(new MapFunction<String, Tuple4<String, Long, Long, Long>>() {
private static final long serialVersionUID = 7917635531979595929L;
@Override
public Tuple4<String, Long, Long, Long> map(String arg0)
throws Exception {
Long arg = Long.parseLong(arg0);
return new Tuple4<String, Long, Long, Long>(System
.getenv("HOSTNAME"), 1L, arg, arg);
}
}).groupBy(0).min(2).andMax(3).andSum(1);
System.out.println(input.count() + " --> " + counts.count());
counts.print();
File file = new File(workingDirectory + "/words.txt");
System.out.println(file.length() + " bytes ("
+ (stripesPerOsd * osdCount * 128 * 1024 / 8)
+ " 8-byte strings)");
file.delete();
}
} |
package lpn.parser;
import java.util.ArrayList;
public class Component extends LhpnFile{
private ArrayList<Integer> processIDList;
private ArrayList<Transition> compTrans;
private ArrayList<Place> compPlaces;
private ArrayList<Variable> compInputs;
private ArrayList<Variable> compOutputs;
private ArrayList<Variable> compInternals;
private int compid;
public Component(LpnProcess process) {
compTrans = new ArrayList<Transition>();
compPlaces = new ArrayList<Place>();
processIDList = new ArrayList<Integer>();
compInputs = new ArrayList<Variable>();
compOutputs = new ArrayList<Variable>();
compInternals = new ArrayList<Variable>();
processIDList.add(process.getProcessId());
compTrans.addAll(process.getProcessTransitions());
compPlaces.addAll(process.getProcessPlaces());
compInputs.addAll(process.getProcessInput());
compOutputs.addAll(process.getProcessOutput());
compInternals.addAll(process.getProcessInternal());
compid = process.getProcessId();
}
public Component() {
//compTrans = new ArrayList<Transition>();
//compPlaces = new ArrayList<Place>();
processIDList = new ArrayList<Integer>();
compInputs = new ArrayList<Variable>();
compOutputs = new ArrayList<Variable>();
compInternals = new ArrayList<Variable>();
}
public Component getComponent() {
return this;
}
public Integer getComponentId() {
return compid;
}
public void setComponentId(Integer id) {
this.compid = id;
}
public ArrayList<Integer> getProcessIDList() {
return processIDList;
}
public void setProcessIDList(ArrayList processIDList) {
this.processIDList = processIDList;
}
public ArrayList<Variable> getInternals() {
return compInternals;
}
public ArrayList<Variable> getOutputs() {
return compOutputs;
}
public ArrayList<Variable> getInputs() {
return compInputs;
}
public LhpnFile buildLPN(LhpnFile lpnComp) {
// Places
for (int i=0; i< this.getComponentPlaces().size(); i++) {
Place p = this.getComponentPlaces().get(i);
lpnComp.addPlace(p.getName(), p.isMarked());
}
// Transitions
for (int i=0; i< this.getCompTransitions().size(); i++) {
Transition t = this.getCompTransitions().get(i);
lpnComp.addTransition(t);
}
// Inputs
for (int i=0; i< this.getCompInput().size(); i++) {
Variable var = this.getCompInput().get(i);
lpnComp.addInput(var.getName(), var.getType(), var.getInitValue());
}
// Outputs
for (int i=0; i< this.getCompOutput().size(); i++) {
Variable var = this.getCompOutput().get(i);
lpnComp.addOutput(var.getName(), var.getType(), var.getInitValue());
}
// Internal
for (int i=0; i< this.getCompInternal().size(); i++) {
Variable var = this.getCompInternal().get(i);
lpnComp.addInternal(var.getName(), var.getType(), var.getInitValue());
}
return lpnComp;
}
private ArrayList<Variable> getCompInternal() {
return compInternals;
}
private ArrayList<Variable> getCompOutput() {
return compOutputs;
}
private ArrayList<Variable> getCompInput() {
return compInputs;
}
private ArrayList<Transition> getCompTransitions() {
return compTrans;
}
private ArrayList<Place> getComponentPlaces() {
return compPlaces;
}
public int getNumVars() {
// return the number of variables in this component
return compInputs.size() + compInternals.size() + compOutputs.size();
}
} |
package som.interpreter.nodes.dispatch;
import som.compiler.AccessModifier;
import som.interpreter.SArguments;
import som.interpreter.nodes.dispatch.AbstractDispatchNode.AbstractCachedDispatchNode;
import som.vm.Symbols;
import som.vmobjects.SClass;
import som.vmobjects.SSymbol;
import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.frame.VirtualFrame;
public abstract class AbstractCachedDnuNode extends AbstractCachedDispatchNode {
private final SSymbol selector;
public static CallTarget getDnu(final SClass rcvrClass) {
return rcvrClass.lookupMessage(
Symbols.symbolFor("doesNotUnderstand:arguments:"),
AccessModifier.PROTECTED).
getCallTarget();
}
public AbstractCachedDnuNode(final SClass rcvrClass,
final SSymbol selector, final AbstractDispatchNode nextInCache) {
super(getDnu(rcvrClass), nextInCache);
this.selector = selector;
}
protected final Object performDnu(final VirtualFrame frame, final Object[] arguments,
final Object rcvr) {
Object[] argsArr = new Object[] {
rcvr, selector, SArguments.getArgumentsWithoutReceiver(arguments) };
return cachedMethod.call(frame, argsArr);
}
} |
package soot.jimple.toolkits.scalar;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.PhaseOptions;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.Timers;
import soot.Trap;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.DivExpr;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.LongConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.RemExpr;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.scalar.LocalDefs;
import soot.toolkits.scalar.LocalUses;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
public class DeadAssignmentEliminator extends BodyTransformer
{
public DeadAssignmentEliminator( Singletons.Global g ) {}
public static DeadAssignmentEliminator v() { return G.v().soot_jimple_toolkits_scalar_DeadAssignmentEliminator(); }
/**
* Eliminates dead code in a linear fashion. Complexity is linear
* with respect to the statements.
*
* Does not work on grimp code because of the check on the right hand
* side for side effects.
*/
protected void internalTransform(Body b, String phaseName, Map<String, String> options)
{
boolean eliminateOnlyStackLocals = PhaseOptions.getBoolean(options, "only-stack-locals");
if (Options.v().verbose()) {
G.v().out.println("[" + b.getMethod().getName() + "] Eliminating dead code...");
}
if (Options.v().time()) {
Timers.v().deadCodeTimer.start();
}
Chain<Unit> units = b.getUnits();
Deque<Unit> q = new ArrayDeque<Unit>(units.size());
// Make a first pass through the statements, noting
// the statements we must absolutely keep.
boolean isStatic = b.getMethod().isStatic();
boolean allEssential = true;
boolean checkInvoke = false;
Local thisLocal = null;
for (Iterator<Unit> it = units.iterator(); it.hasNext(); ) {
Unit s = it.next();
boolean isEssential = true;
if (s instanceof NopStmt) {
// Hack: do not remove nop if is is used for a Trap
// which is at the very end of the code.
boolean removeNop = it.hasNext();
if (!removeNop) {
removeNop = true;
for (Trap t : b.getTraps()) {
if (t.getEndUnit() == s) {
removeNop = false;
break;
}
}
}
if (removeNop) {
it.remove();
continue;
}
}
else if (s instanceof AssignStmt) {
AssignStmt as = (AssignStmt) s;
Value lhs = as.getLeftOp();
Value rhs = as.getRightOp();
// Stmt is of the form a = a which is useless
if (lhs == rhs && lhs instanceof Local) {
it.remove();
continue;
}
if (lhs instanceof Local &&
(!eliminateOnlyStackLocals ||
((Local) lhs).getName().startsWith("$")
|| lhs.getType() instanceof NullType))
{
isEssential = false;
if ( !checkInvoke ) {
checkInvoke |= as.containsInvokeExpr();
}
if (rhs instanceof CastExpr) {
// CastExpr : can trigger ClassCastException, but null-casts never fail
CastExpr ce = (CastExpr) rhs;
Type t = ce.getCastType();
Value v = ce.getOp();
isEssential = !(t instanceof RefType && v == NullConstant.v());
}
else if (rhs instanceof InvokeExpr ||
rhs instanceof ArrayRef ||
rhs instanceof NewExpr ||
rhs instanceof NewArrayExpr ||
rhs instanceof NewMultiArrayExpr )
{
// ArrayRef : can have side effects (like throwing a null pointer exception)
// InvokeExpr : can have side effects (like throwing a null pointer exception)
// NewArrayExpr : can throw exception
// NewMultiArrayExpr : can throw exception
// NewExpr : can trigger class initialization
isEssential = true;
}
else if (rhs instanceof FieldRef) {
// Can trigger class initialization
isEssential = true;
if (rhs instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) rhs;
if ( !isStatic && thisLocal == null ) {
thisLocal = b.getThisLocal();
}
// Any InstanceFieldRef may have side effects,
// unless the base is reading from 'this'
// in a non-static method
isEssential = (isStatic || thisLocal != ifr.getBase());
}
}
else if (rhs instanceof DivExpr || rhs instanceof RemExpr) {
BinopExpr expr = (BinopExpr) rhs;
Type t1 = expr.getOp1().getType();
Type t2 = expr.getOp2().getType();
// Can trigger a division by zero
isEssential = IntType.v().equals(t1) || LongType.v().equals(t1)
|| IntType.v().equals(t2) || LongType.v().equals(t2);
if (isEssential && IntType.v().equals(t2)) {
Value v = expr.getOp2();
if (v instanceof IntConstant) {
IntConstant i = (IntConstant) v;
isEssential = (i.value == 0);
}
}
if (isEssential && LongType.v().equals(t2)) {
Value v = expr.getOp2();
if (v instanceof LongConstant) {
LongConstant l = (LongConstant) v;
isEssential = (l.value == 0);
}
}
}
}
}
if (isEssential) {
q.addFirst(s);
}
allEssential &= isEssential;
}
if ( checkInvoke || !allEssential ) {
// Add all the statements which are used to compute values
// for the essential statements, recursively
final LocalDefs localDefs = LocalDefs.Factory.newLocalDefs(b);
if ( !allEssential ) {
Set<Unit> essential = new HashSet<Unit>(b.getUnits().size());
while (!q.isEmpty()) {
Unit s = q.removeFirst();
if ( essential.add(s) ) {
for (ValueBox box : s.getUseBoxes()) {
Value v = box.getValue();
if (v instanceof Local) {
Local l = (Local) v;
List<Unit> defs = localDefs.getDefsOfAt(l, s);
if (defs != null)
q.addAll(defs);
}
}
}
}
// Remove the dead statements
units.retainAll(essential);
}
if ( checkInvoke ) {
final LocalUses localUses = LocalUses.Factory.newLocalUses(b, localDefs);
// Eliminate dead assignments from invokes such as x = f(), where
// x is no longer used
List<AssignStmt> postProcess = new ArrayList<AssignStmt>();
for ( Unit u : units ) {
if (u instanceof AssignStmt) {
AssignStmt s = (AssignStmt) u;
if (s.containsInvokeExpr()) {
// Just find one use of l which is essential
boolean deadAssignment = true;
for (UnitValueBoxPair pair : localUses.getUsesOf(s)) {
if (units.contains(pair.unit)) {
deadAssignment = false;
break;
}
}
if (deadAssignment) {
postProcess.add(s);
}
}
}
}
for ( AssignStmt s : postProcess ) {
// Transform it into a simple invoke.
Stmt newInvoke = Jimple.v().newInvokeStmt(s.getInvokeExpr());
newInvoke.addAllTagsOf(s);
units.swapWith(s, newInvoke);
// If we have a callgraph, we need to fix it
if (Scene.v().hasCallGraph())
Scene.v().getCallGraph().swapEdgesOutOf(s, newInvoke);
}
}
}
if (Options.v().time()) {
Timers.v().deadCodeTimer.end();
}
}
} |
package com.lmax.disruptor.example;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.LifecycleAware;
import com.lmax.disruptor.TimeoutException;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.support.LongEvent;
import com.lmax.disruptor.util.DaemonThreadFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WaitForShutdown
{
private static volatile int value = 0;
private static class Handler implements EventHandler<LongEvent>, LifecycleAware
{
private final CountDownLatch latch;
public Handler(CountDownLatch latch)
{
this.latch = latch;
}
@Override
public void onStart()
{
}
@Override
public void onShutdown()
{
latch.countDown();
}
@Override
public void onEvent(LongEvent event, long sequence, boolean endOfBatch) throws Exception
{
value = 1;
}
}
public static void main(String[] args) throws TimeoutException, InterruptedException
{
Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(
LongEvent.FACTORY, 16, DaemonThreadFactory.INSTANCE
);
CountDownLatch shutdownLatch = new CountDownLatch(2);
disruptor.handleEventsWith(new Handler(shutdownLatch)).then(new Handler(shutdownLatch));
disruptor.start();
long next = disruptor.getRingBuffer().next();
disruptor.getRingBuffer().get(next).set(next);
disruptor.getRingBuffer().publish(next);
disruptor.shutdown(10, TimeUnit.SECONDS);
shutdownLatch.await();
System.out.println(value);
}
} |
package nl.mpi.kinnate.ui;
import java.awt.Component;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilField;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.ui.ArbilTree;
import nl.mpi.arbil.userstorage.SessionStorage;
import nl.mpi.arbil.util.BugCatcherManager;
import nl.mpi.kinnate.data.KinTreeNode;
import nl.mpi.kinnate.entityindexer.EntityCollection;
import nl.mpi.kinnate.gedcomimport.ImportException;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindocument.EntityDocument;
import nl.mpi.kinnate.kindocument.ImportTranslator;
import nl.mpi.kinnate.svg.GraphPanel;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
public class KinDragTransferHandler extends TransferHandler implements Transferable {
private ArbilNode[] selectedNodes;
private DataFlavor dataFlavor = new DataFlavor(ArbilNode[].class, "ArbilObject");
private DataFlavor[] dataFlavors = new DataFlavor[]{dataFlavor, DataFlavor.stringFlavor};
private KinDiagramPanel kinDiagramPanel;
private EntityData targetEntity = null;
private SessionStorage sessionStorage;
private EntityCollection entityCollection;
public KinDragTransferHandler(KinDiagramPanel kinDiagramPanel, SessionStorage sessionStorage, EntityCollection entityCollection) {
this.kinDiagramPanel = kinDiagramPanel;
this.sessionStorage = sessionStorage;
this.entityCollection = entityCollection;
}
@Override
public int getSourceActions(JComponent comp) {
return COPY;
}
@Override
public Transferable createTransferable(JComponent comp) {
selectedNodes = ((ArbilTree) comp).getAllSelectedNodes();
if (selectedNodes.length == 0) {
return null;
}
for (ArbilNode arbilNode : selectedNodes) {
if (arbilNode instanceof ArbilDataNode) {
if (((ArbilDataNode) arbilNode).getParentDomNode().isCorpus() || ((ArbilDataNode) arbilNode).getParentDomNode().isCatalogue() || ((ArbilDataNode) arbilNode).getParentDomNode().isDirectory()) {
return null;
}
}
}
return this;
}
@Override
public void exportDone(JComponent comp, Transferable trans, int action) {
kinDiagramPanel.redrawIfKinTermsChanged();
}
public Object /* ArbilTreeObject[] */ getTransferData(DataFlavor df) throws UnsupportedFlavorException, IOException {
if (df.equals(DataFlavor.stringFlavor)) {
StringBuilder stringBuilder = new StringBuilder();
for (ArbilNode arbilNode : selectedNodes) {
if (arbilNode instanceof KinTreeNode) {
if (stringBuilder.length() == 0) {
stringBuilder.append("\n");
}
stringBuilder.append("[Entity.Identifier=");
stringBuilder.append(((KinTreeNode) arbilNode).getUniqueIdentifier().getQueryIdentifier());
stringBuilder.append("]");
}
}
return stringBuilder.toString();
} else {
return ""; //selectedNodes;
}
}
public DataFlavor[] getTransferDataFlavors() {
return dataFlavors;
}
public boolean isDataFlavorSupported(DataFlavor df) {
return true;
}
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
targetEntity = null;
// if (!support.isDrop()) {
// return false;
if (!support.isDataFlavorSupported(dataFlavor)) {
return false;
}
Component dropLocation = support.getComponent(); // getDropLocation
// System.out.println("dropLocation: " + dropLocation.toString());
if (dropLocation instanceof GraphPanel) {
return true;
}
if (dropLocation instanceof KinTree) {
if (selectedNodes != null && selectedNodes.length > 0 && selectedNodes[0] instanceof ArbilDataNode) {
ArbilNode dropNode = ((KinTree) dropLocation).getLeadSelectionNode();
if (dropNode == null) {
return true; //support.setDropAction(NONE);
} else if (dropNode instanceof KinTreeNode) {
targetEntity = ((KinTreeNode) dropNode).getEntityData(); // final KinTreeNode kinTreeNode = (KinTreeNode) dropNode;
if (targetEntity == null || targetEntity.getUniqueIdentifier().isTransientIdentifier()) {
// only allow imdi and cmdi nodes to be droped to a kin entity that is permanent (having metadata)
return false; //support.setDropAction(NONE);
} else {
return true;
}
}
}
}
return false;
}
private boolean addEntitiesToGraph(Point defaultLocation) {
ArrayList<UniqueIdentifier> slectedIdentifiers = new ArrayList<UniqueIdentifier>();
try {
JAXBContext jaxbContext = JAXBContext.newInstance(UniqueIdentifier.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
for (ArbilNode currentArbilNode : selectedNodes) {
if (currentArbilNode instanceof KinTreeNode) {
KinTreeNode kinTreeNode = (KinTreeNode) currentArbilNode;
slectedIdentifiers.add(kinTreeNode.getUniqueIdentifier());
// the following methods use either the xml file or the arbil tree node to get the entity identifier
// while they are no longer used it is probably good to keep them for reference
// try {
// Document metadataDom = ArbilComponentBuilder.getDocument(currentArbilNode.getURI());
// Node uniqueIdentifierNode = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/kin:Entity/kin:Identifier"); // note that this is using the name space prefix not the namespace url
// try {
// UniqueIdentifier uniqueIdentifier = (UniqueIdentifier) unmarshaller.unmarshal(uniqueIdentifierNode, UniqueIdentifier.class).getValue();
// slectedIdentifiers.add(uniqueIdentifier);
// } catch (JAXBException exception) {
// new ArbilBugCatcher().logError(exception);
// } catch (IOException exception) {
// new ArbilBugCatcher().logError(exception);
// } catch (ParserConfigurationException exception) {
// new ArbilBugCatcher().logError(exception);
// } catch (SAXException exception) {
// new ArbilBugCatcher().logError(exception);
// } catch (TransformerException exception) {
// new ArbilBugCatcher().logError(exception);
// todo: new UniqueIdentifier could take ArbilDataNode as a constructor parameter, which would move this code out of this class
// for (String currentIdentifierType : new String[]{"Kinnate.Entity.Identifier.LocalIdentifier", "Kinnate.Gedcom.UniqueIdentifier.PersistantIdentifier", "Kinnate.Entity.UniqueIdentifier.PersistantIdentifier"}) {
// if (currentArbilNode.getFields().containsKey(currentIdentifierType)) {
// slectedIdentifiers.add(new UniqueIdentifier(currentArbilNode.getFields().get(currentIdentifierType)[0]));
// break;
// end identifier getting code
}
}
} catch (JAXBException exception) {
BugCatcherManager.getBugCatcher().logError(exception);
}
kinDiagramPanel.addRequiredNodes(slectedIdentifiers.toArray(new UniqueIdentifier[]{}), defaultLocation);
return true;
}
private boolean importMetadata(Point defaultLocation) {
System.out.println("importMetadata");
final ImportTranslator importTranslator = new ImportTranslator(true);
importTranslator.addTranslationEntry("Sex", "Male", "Gender", "Male");
importTranslator.addTranslationEntry("Sex", "Female", "Gender", "Female");
importTranslator.addTranslationEntry("BirthDate", null, "DateOfBirth", null);
try {
ArrayList<EntityDocument> entityDocumentList = new ArrayList<EntityDocument>();
for (ArbilNode draggedNode : selectedNodes) {
// todo: allow the user to set EntityDocument.defaultDragType some where
EntityDocument entityDocument = new EntityDocument(EntityDocument.defaultDragType, importTranslator, sessionStorage);
entityDocument.insertValue("Name", draggedNode.toString());
if (draggedNode instanceof ArbilDataNode) {
for (String fieldOfInterest : new String[]{"Sex", "BirthDate"}) {
final ArbilField[] arbilFeildsArray = ((ArbilDataNode) draggedNode).getFields().get(fieldOfInterest);
if (arbilFeildsArray != null && arbilFeildsArray.length > 0) {
entityDocument.insertValue(fieldOfInterest, arbilFeildsArray[0].getFieldValue().toLowerCase());
}
}
entityDocument.entityData.addArchiveLink(((ArbilDataNode) draggedNode).getURI());
}
// todo: based on the DCR entries the relevant data could be selected and inserted, or the user could specify which fields to insert
// entityDocument.insertDefaultMetadata(); // todo: insert copy of metadata from source node
//attachMetadata(entityDocument.entityData); // if a node is dragged to the graph then the odds are that they are all different actors so we create one entity for each rather than using attachMetadata
entityDocumentList.add(entityDocument);
}
for (EntityDocument entityDocument : entityDocumentList) {
entityDocument.saveDocument();
URI addedEntityUri = entityDocument.getFile().toURI();
entityCollection.updateDatabase(addedEntityUri);
kinDiagramPanel.addRequiredNodes(new UniqueIdentifier[]{entityDocument.getUniqueIdentifier()}, defaultLocation);
}
return true;
} catch (ImportException exception) {
// todo: warn user with a dialog
BugCatcherManager.getBugCatcher().logError(exception);
return false;
}
}
private boolean attachMetadata(EntityData entityData) {
for (ArbilNode currentArbilNode : selectedNodes) {
final ArbilDataNode currentArbilDataNode = (ArbilDataNode) currentArbilNode;
entityData.addArchiveLink(currentArbilDataNode.getURI());
// todo: insert the archive handle here also
// todo: insert the entity identifier into the attached metadata
// Document metadataDom = ArbilComponentBuilder.getDocument(addedNodePath);
// if (createdEntity) {
// // set the name node
// Node uniqueIdentifierNode = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/:Entity/:Name");
// currentArbilDataNode.get
//currentArbilNode
// todo: if the dropped archive node alreay is linked in the kin database then show that kin entity, if the node is dragged from the archive tree or from one kin entity to another then add or move it to the new target
// todo: if multiple are draged then add them all to the same entity
// entityDocument.
//currentArbilNode.getUrlString()
// create and set the link node
// todo: this might well be updated at a later date, or even use the cmdi link type although that is more complex than required
// cmdi link types have been considered here but they are very complex and not well suited to kinship needs so we are using the corpus link type for now
// save the changes
}
return false;
}
private boolean attachMetadata() {
System.out.println("importMetadata");
try {
EntityDocument entityDocument = new EntityDocument(new URI(targetEntity.getEntityPath()), new ImportTranslator(true), sessionStorage);
attachMetadata(entityDocument.entityData);
entityDocument.saveDocument();
URI addedEntityUri = entityDocument.getFile().toURI();
entityCollection.updateDatabase(addedEntityUri);
kinDiagramPanel.entityRelationsChanged(new UniqueIdentifier[]{entityDocument.getUniqueIdentifier()});
return true;
} catch (ImportException exception) {
// todo: warn user with a dialog
BugCatcherManager.getBugCatcher().logError(exception);
return false;
} catch (URISyntaxException exception) {
// todo: warn user with a dialog
BugCatcherManager.getBugCatcher().logError(exception);
return false;
}
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
// if we can't handle the import, say so
if (!canImport(support)) {
return false;
}
boolean isImportingMetadata = (selectedNodes != null && selectedNodes.length > 0 && selectedNodes[0] instanceof ArbilDataNode);
Component dropLocation = support.getComponent();
// todo: in the case of dropping to the ego tree add the entity to the ego list
// todo: in the case of dropping to the required tree add the entity to the required list and remove from the ego list (if in that list)
// todo: in the case of dragging from the transient tree offer to make the entity permanent and create metadata
if (dropLocation instanceof GraphPanel) {
Point defaultLocation = support.getDropLocation().getDropPoint();
System.out.println("dropped to GraphPanel");
if (isImportingMetadata) {
return importMetadata(defaultLocation);
} else {
return addEntitiesToGraph(defaultLocation);
}
} else if (dropLocation instanceof KinTree) {
System.out.println("dropped to KinTree");
if (isImportingMetadata) {
return attachMetadata();
}
}
return false;
}
} |
package freemarker.introspection;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.math.BigDecimal;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class TemplateTestUtils {
public static Element loadTemplateRoot(String templateText) {
StringTemplateLoader tloader = new StringTemplateLoader();
tloader.putTemplate("template", templateText);
Configuration templateConfig = new Configuration();
templateConfig.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
templateConfig.setTemplateLoader(tloader);
try {
Template template = templateConfig.getTemplate("template");
return TemplateIntrospector.getRootNode(template);
} catch (IOException e) {
throw new RuntimeException("Error loading template", e);
}
}
public static void assertIdentifier(TemplateNode node, int paramIdx, String name) {
Expr identifier = node.getParams().get(paramIdx);
assertEquals(ExprType.IDENTIFIER, identifier.getType());
assertEquals(name, identifier.toString());
}
public static void assertValue(TemplateNode node, int paramIdx, Object expectedValue) {
// a value may be a literal expression or a value expression. We'll accept both kinds.
Expr valueExpr = node.getParams().get(paramIdx);
Object value = null;
if (valueExpr instanceof ValueExpr)
value = ((ValueExpr) valueExpr).getValue();
else if (valueExpr instanceof LiteralExpr)
value = ((LiteralExpr) valueExpr).getValue();
else
value = valueExpr.toString();
assertEquals(expectedValue, value);
}
public static void assertStringExpr(TemplateNode node, int paramIdx, String expectedValue) {
Expr strLiteral = node.getParams().get(paramIdx);
assertEquals(ExprType.STRING_LITERAL, strLiteral.getType());
assertEquals(expectedValue, ((StringExpr) strLiteral).getValue());
}
public static void assertNumberExpr(TemplateNode node, int paramIdx, int expectedValue) {
Expr numLiteral = node.getParams().get(paramIdx);
assertEquals(ExprType.NUMBER_LITERAL, numLiteral.getType());
assertEquals(new BigDecimal(expectedValue),
((NumberLiteralExpr) numLiteral).getValue());
}
} |
package me.prettyprint.cassandra.model;
import static me.prettyprint.hector.api.factory.HFactory.createColumn;
import static me.prettyprint.hector.api.factory.HFactory.createColumnQuery;
import static me.prettyprint.hector.api.factory.HFactory.createKeyspace;
import static me.prettyprint.hector.api.factory.HFactory.createMutator;
import static me.prettyprint.hector.api.factory.HFactory.createSuperColumn;
import static me.prettyprint.hector.api.factory.HFactory.getOrCreateCluster;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import me.prettyprint.cassandra.BaseEmbededServerSetupTest;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.ClockResolution;
import me.prettyprint.cassandra.utils.StringUtils;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.beans.HSuperColumn;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.MutationResult;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.ColumnQuery;
import me.prettyprint.hector.api.query.QueryResult;
import org.apache.cassandra.thrift.ColumnPath;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MutatorTest extends BaseEmbededServerSetupTest {
private static final StringSerializer se = new StringSerializer();
private Cluster cluster;
private Keyspace keyspace;
@Before
public void setupCase() {
cluster = getOrCreateCluster("Test Cluster", "127.0.0.1:9170");
keyspace = createKeyspace("Keyspace1", cluster);
}
@After
public void teardownCase() {
keyspace = null;
cluster = null;
}
@Test
public void testInsert() {
Mutator<String> m = createMutator(keyspace, se);
MutationResult mr = m.insert("k", "Standard1", createColumn("name", "value", se, se));
assertTrue("Execution time on single insert should be > 0",mr.getExecutionTimeMicro() > 0);
assertTrue("Should have operated on a host", mr.getHostUsed() != null);
assertColumnExists("Keyspace1", "Standard1", "k", "name");
}
@Test
public void testInsertSuper() {
Mutator<String> m = createMutator(keyspace, se);
List<HColumn<String, String>> columnList = new ArrayList<HColumn<String,String>>();
columnList.add(createColumn("name","value",se,se));
HSuperColumn<String, String, String> superColumn =
createSuperColumn("super_name", columnList, se, se, se);
MutationResult r = m.insert("sk", "Super1", superColumn);
assertTrue("Execute time should be > 0", r.getExecutionTimeMicro() > 0);
assertTrue("Should have operated on a host", r.getHostUsed() != null);
}
@Test
public void testBatchMutationManagement() {
String cf = "Standard1";
Mutator<String> m = createMutator(keyspace, se);
for (int i = 0; i < 5; i++) {
m.addInsertion("k" + i, cf, createColumn("name", "value" + i, se, se));
}
MutationResult r = m.execute();
assertTrue("Execute time should be > 0", r.getExecutionTimeMicro() > 0);
assertTrue("Should have operated on a host", r.getHostUsed() != null);
for (int i = 0; i < 5; i++) {
assertColumnExists("Keyspace1", "Standard1", "k"+i, "name");
}
// Execute an empty mutation
r = m.execute();
assertEquals("Execute time should be 0", 0, r.getExecutionTimeMicro());
// Test discard and then exec an empty mutation
for (int i = 0; i < 5; i++) {
m.addInsertion("k" + i, cf, createColumn("name", "value" + i, se, se));
}
m.discardPendingMutations();
r = m.execute();
assertEquals("Execute time should be 0", 0, r.getExecutionTimeMicro());
assertTrue("Should have operated with a null host", r.getHostUsed() == null);
// cleanup
for (int i = 0; i < 5; i++) {
m.addDeletion("k" + i, cf, "name", se);
}
m.execute();
}
@Test
public void testRowDeletion() {
String cf = "Standard1";
Mutator<String> m = createMutator(keyspace, se);
for (int i = 0; i < 5; i++) {
m.addInsertion("k" + i, cf, createColumn("name", "value" + i, se, se));
}
MutationResult r = m.execute();
// Try to delete the row with key "k0" with a clock previous to the insertion.
// Cassandra will discard this operation.
m.addDeletion("k0", cf, null, se, (keyspace.createClock() - 1));
m.execute();
// Check that the delete was harmless
QueryResult<HColumn<String, String>> columnResult =
createColumnQuery(keyspace, se, se, se).setColumnFamily(cf).setKey("k0").
setName("name").execute();
assertEquals("value0", columnResult.get().getValue());
for (int i = 0; i < 5; i++) {
m.addDeletion("k" + i, cf, null, se);
}
m.execute();
// Check that the delete took place now
columnResult = createColumnQuery(keyspace, se, se, se).
setColumnFamily(cf).setKey("k0").setName("name").execute();
assertNull(columnResult.get());
}
private void assertColumnExists(String keyspace, String cf, String key, String column) {
ColumnPath cp = new ColumnPath(cf);
cp.setColumn(StringUtils.bytes(column));
Keyspace ks = HFactory.createKeyspace(keyspace, cluster);
ColumnQuery<String, String, String> columnQuery = HFactory.createStringColumnQuery(ks);
assertNotNull(String.format("Should have value for %s.%s[%s][%s]", keyspace, cf, key, column),
columnQuery.setColumnFamily(cf).setKey(key).setName(column).execute().get().getValue());
//client.getKeyspace(keyspace).getColumn(key, cp));
//cluster.releaseClient(client);
}
} |
package net.gcdc.ittgt.server;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Date;
import net.gcdc.ittgt.model.Vehicle;
import net.gcdc.ittgt.model.WorldModel;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BasicGroTrServerTest {
private final static Logger logger = LoggerFactory.getLogger(BasicGroTrServerTest.class);
class IsAnyWorldModel extends ArgumentMatcher<WorldModel> {
@Override public boolean matches(Object that) {
return (that != null) && (that instanceof WorldModel);
}
}
@Test public void test() throws InterruptedException {
final int port = 10000;
WorldModel model = new WorldModel();
model.header = new WorldModel.Header();
model.header.samplingTimeMs = 10;
model.header.version = 1;
model.header.simulationTimestamp = new Date();
Vehicle vehicle1 = new Vehicle();
vehicle1.id = 1;
vehicle1.lat = 57;
vehicle1.lon = 13;
Vehicle vehicle2 = new Vehicle();
vehicle2.id = 2;
vehicle2.lat = 57.5;
vehicle2.lon = 13.5;
model.vehicles = new Vehicle[] { vehicle1, vehicle2 };
GroTrServer server = new BasicGroTrServer(model, 1000 * 10);
// Executors.newSingleThreadExecutor().submit(new SocketClientSpawner(port, server));
ClientConnection connection1 = Mockito.mock(ClientConnection.class);
ClientConnection connection2 = Mockito.mock(ClientConnection.class);
when(connection1.address()).thenReturn("1");
when(connection2.address()).thenReturn("2");
// Registers sends world model
server.register(vehicle1.id, connection1);
server.register(vehicle2.id, connection2);
verify(connection1).send(argThat(new IsAnyWorldModel()));
verify(connection2).send(argThat(new IsAnyWorldModel()));
logger.debug("connection1: {}", connection1);
logger.debug("connection2: {}", connection2);
logger.debug("vehicle1: {}", vehicle1);
logger.debug("vehicle2: {}", vehicle2);
server.updateVehicleState(vehicle1, connection1);
server.updateVehicleState(vehicle2, connection2);
Thread.sleep(30);
verify(connection1, times(2)).send(argThat(new IsAnyWorldModel()));
verify(connection2, times(2)).send(argThat(new IsAnyWorldModel()));
}
@Test public void test2() throws InterruptedException {
final int port = 10000;
WorldModel model = new WorldModel();
model.header = new WorldModel.Header();
model.header.samplingTimeMs = 10;
model.header.version = 1;
model.header.simulationTimestamp = new Date();
Vehicle vehicle1 = new Vehicle();
vehicle1.id = 1;
vehicle1.lat = 57;
vehicle1.lon = 13;
Vehicle vehicle2 = new Vehicle();
vehicle2.id = 2;
vehicle2.lat = 57.5;
vehicle2.lon = 13.5;
model.vehicles = new Vehicle[] { vehicle1, vehicle2 };
GroTrServer server = new BasicGroTrServer(model, 1000 * 10);
// Executors.newSingleThreadExecutor().submit(new SocketClientSpawner(port, server));
ClientConnection connection1 = Mockito.mock(ClientConnection.class);
ClientConnection connection2 = Mockito.mock(ClientConnection.class);
when(connection1.address()).thenReturn("1");
when(connection2.address()).thenReturn("2");
// Registers sends world model
server.register(vehicle1.id, connection1);
server.register(vehicle2.id, connection2);
verify(connection1, times(1)).send(argThat(new IsAnyWorldModel()));
verify(connection2, times(1)).send(argThat(new IsAnyWorldModel()));
// No sending before received from all
server.updateVehicleState(vehicle1, connection1);
Thread.sleep(10);
verify(connection1, times(1)).send(argThat(new IsAnyWorldModel()));
verify(connection2, times(1)).send(argThat(new IsAnyWorldModel()));
server.updateVehicleState(vehicle2, connection2);
// Send to all after received from all
Thread.sleep(10); // Sending thread is separate
verify(connection1, times(2)).send(argThat(new IsAnyWorldModel()));
verify(connection2, times(2)).send(argThat(new IsAnyWorldModel()));
}
@Test public void testTimeout() throws InterruptedException {
final int port = 10000;
WorldModel model = new WorldModel();
model.header = new WorldModel.Header();
model.header.samplingTimeMs = 10;
model.header.version = 1;
model.header.simulationTimestamp = new Date();
Vehicle vehicle1 = new Vehicle();
vehicle1.id = 1;
vehicle1.lat = 57;
vehicle1.lon = 13;
Vehicle vehicle2 = new Vehicle();
vehicle2.id = 2;
vehicle2.lat = 57.5;
vehicle2.lon = 13.5;
model.vehicles = new Vehicle[] { vehicle1, vehicle2 };
final int timeoutMillis = 300;
GroTrServer server = new BasicGroTrServer(model, timeoutMillis);
// Executors.newSingleThreadExecutor().submit(new SocketClientSpawner(port, server));
ClientConnection connection1 = Mockito.mock(ClientConnection.class);
ClientConnection connection2 = Mockito.mock(ClientConnection.class);
when(connection1.address()).thenReturn("1");
when(connection2.address()).thenReturn("2");
// Registers sends world model
server.register(vehicle1.id, connection1);
server.register(vehicle2.id, connection2);
verify(connection1, times(1)).send(argThat(new IsAnyWorldModel()));
verify(connection2, times(1)).send(argThat(new IsAnyWorldModel()));
// No sending before received from all
server.updateVehicleState(vehicle1, connection1);
Thread.sleep(50);
verify(connection1, times(1)).send(argThat(new IsAnyWorldModel()));
verify(connection2, times(1)).send(argThat(new IsAnyWorldModel()));
// Send to all after a timeout
Thread.sleep(timeoutMillis);
verify(connection1, times(2)).send(argThat(new IsAnyWorldModel()));
verify(connection2, times(2)).send(argThat(new IsAnyWorldModel()));
}
} |
package nl.hsac.fitnesse.fixture.slim;
import nl.hsac.fitnesse.fixture.util.XmlHttpResponse;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests HttpTest.
*/
public class HttpTestTest {
private final HttpTest client = new HttpTest();
@Test
public void testUrlCleanUp() {
String cleanedUrl = client.getUrl("<a href=\"http:
assertEquals("http://mysite.nl/test", cleanedUrl);
cleanedUrl = client.getUrl("http://mysite.nl/test");
assertEquals("http://mysite.nl/test", cleanedUrl);
cleanedUrl = client.getUrl("https://mysite.nl:8443/test");
assertEquals("https://mysite.nl:8443/test", cleanedUrl);
cleanedUrl = client.getUrl("<a href=\"http:
assertEquals("http://mysite.nl/test/test", cleanedUrl);
cleanedUrl = client.getUrl("<a href=\"https:
assertEquals("https://mysite.nl/test/test", cleanedUrl);
}
@Test
public void testGetUrlWithParams() {
String getUrl = client.createUrlWithParams("https://mysite.nl/test");
assertEquals("https://mysite.nl/test", getUrl);
client.clearValues();
client.setValueFor("John", "name");
getUrl = client.createUrlWithParams("https://mysite.nl/test?age=12");
assertEquals("https://mysite.nl/test?age=12&name=John", getUrl);
getUrl = client.createUrlWithParams("https://mysite.nl/test?");
assertEquals("https://mysite.nl/test?name=John", getUrl);
client.clearValues();
client.setValueFor("John", "name");
client.setValueFor("12", "age");
getUrl = client.createUrlWithParams("http://mysite.nl/test");
assertEquals("http://mysite.nl/test?name=John&age=12", getUrl);
client.clearValues();
client.setValueFor("12", "age");
client.setValueFor("John&Pete", "name");
getUrl = client.createUrlWithParams("https://mysite.nl/test");
assertEquals("https://mysite.nl/test?age=12&name=John%26Pete", getUrl);
client.clearValues();
client.setValueFor("12", "één");
getUrl = client.createUrlWithParams("http://mysite.nl:8080/test");
assertEquals("http://mysite.nl:8080/test?%C3%A9%C3%A9n=12", getUrl);
client.clearValues();
client.setValueFor(null, "param");
getUrl = client.createUrlWithParams("http://mysite.nl:8080/test");
assertEquals("http://mysite.nl:8080/test?param", getUrl);
client.clearValues();
client.setValueFor("", "param");
getUrl = client.createUrlWithParams("http://mysite.nl:8080/test");
assertEquals("http://mysite.nl:8080/test?param=", getUrl);
client.clearValues();
client.setValuesFor("one, two, three", "param");
getUrl = client.createUrlWithParams("http://mysite.nl:8080/test");
assertEquals("http://mysite.nl:8080/test?param=one¶m=two¶m=three", getUrl);
client.clearValues();
client.setValueFor("1234", "field.key");
getUrl = client.createUrlWithParams("https://mysite.nl/test");
assertEquals("https://mysite.nl/test?field.key=1234", getUrl);
client.setValueFor("f", "fieldkey");
getUrl = client.createUrlWithParams("https://mysite.nl/test");
assertEquals("https://mysite.nl/test?field.key=1234&fieldkey=f", getUrl);
client.clearValues();
client.setValuesFor("one, two, three", "param.name");
client.setValuesFor("one", "name2");
client.setValuesFor("one, two", "param2.name");
client.setValueFor("three", "param2.nested");
getUrl = client.createUrlWithParams("http://mysite.nl:8080/test");
assertEquals("http://mysite.nl:8080/test?param.name=one¶m.name=two¶m.name=three" +
"&name2=one¶m2.name=one¶m2.name=two¶m2.nested=three", getUrl);
}
@Test
public void testBodyCleanup() {
String body = "<xml>";
String cleaned = client.cleanupBody(body);
assertEquals(body, cleaned);
}
@Test
public void testBodyCleanupPre() {
String cleaned = client.cleanupBody("<pre> \n" +
"<MyContent>\n" +
" <content a='c'/>\n" +
"</MyContent>\n" +
" </pre>");
assertEquals("<MyContent>\n <content a='c'/>\n</MyContent>", cleaned);
}
/**
* Tests url redirects with follow redirects (default setting)
*/
@Test
public void testGetFromFollowRedirect() throws Exception {
MockXmlServerSetup mockXmlServerSetup = new MockXmlServerSetup();
try {
String serverUrl = setupRedirectResponse(mockXmlServerSetup);
HttpTest httpTest = new HttpTest();
boolean result = httpTest.getFrom(serverUrl);
String resp = httpTest.htmlResponse();
assertNotNull(resp);
assertEquals(200, httpTest.getResponse().getStatusCode());
assertEquals("<div><hello/></div>", resp);
assertTrue(result);
assertTrue(mockXmlServerSetup.verifyAllResponsesServed());
} finally {
mockXmlServerSetup.stop();
}
}
/**
* Test url redirects without following redirect
*/
@Test
public void testGetFromNoRedirect() throws Exception {
MockXmlServerSetup mockXmlServerSetup = new MockXmlServerSetup();
try {
String serverUrl = setupRedirectResponse(mockXmlServerSetup);
HttpTest httpTest = new HttpTest();
boolean result = httpTest.getFromNoRedirect(serverUrl);
String resp = httpTest.htmlResponse();
assertNotNull(resp);
assertEquals(301, httpTest.getResponse().getStatusCode());
assertTrue(result);
} finally {
mockXmlServerSetup.stop();
}
}
private String setupRedirectResponse(MockXmlServerSetup mockXmlServerSetup) {
String serverUrl = mockXmlServerSetup.getMockServerUrl();
Map<String, Object> headers = new HashMap();
headers.put("Location", serverUrl + "/a");
mockXmlServerSetup.addResponseWithStatusAndHeaders("", 301, headers);
mockXmlServerSetup.addResponseFor("<hello/>", "GET: /FitNesseMock/a");
return serverUrl;
}
/**
* Test get
*/
@Test
public void testGet() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCall(url -> httpTest.getFrom(url));
assertEquals("GET", httpTest.getResponse().getMethod());
assertEquals("GET", req1.getMethod());
assertEquals("GET: /FitNesseMock", req1.getRequest());
}
/**
* Test head
*/
@Test
public void testHead() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCall(url -> httpTest.headFrom(url));
assertEquals("HEAD", httpTest.getResponse().getMethod());
assertEquals("HEAD", req1.getMethod());
assertEquals("HEAD: /FitNesseMock", req1.getRequest());
}
/**
* Test post
*/
@Test
public void testPost() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCall(url -> httpTest.postTo("a", url));
assertEquals("POST", httpTest.getResponse().getMethod());
assertEquals("POST", req1.getMethod());
assertEquals("a", req1.getRequest());
}
/**
* Test put
*/
@Test
public void testPut() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCall(url -> httpTest.putTo("b", url));
assertEquals("PUT", httpTest.getResponse().getMethod());
assertEquals("PUT", req1.getMethod());
assertEquals("b", req1.getRequest());
}
/**
* Test delete with body
*/
@Test
public void testDeleteWithBody() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCall(url -> httpTest.deleteWith(url, "a=1"));
assertEquals("DELETE", httpTest.getResponse().getMethod());
assertEquals("DELETE", req1.getMethod());
assertEquals("a=1", req1.getRequest());
}
/**
* Test delete without body
*/
@Test
public void testDeleteWithoutBody() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCall(url -> httpTest.delete(url));
assertEquals("DELETE", httpTest.getResponse().getMethod());
assertEquals("DELETE", req1.getMethod());
assertEquals("DELETE: /FitNesseMock", req1.getRequest());
}
/**
* Test post with template
*/
@Test
public void testPostWithTemplate() {
HttpTest httpTest = setupHttpTestWithTemplate();
XmlHttpResponse req1 = checkCall(url -> httpTest.postTemplateTo(url));
assertEquals("POST", httpTest.getResponse().getMethod());
checkTemplateRequestBody(httpTest.getResponse().getMethod(), req1);
}
/**
* Test put with template
*/
@Test
public void testPutWithTemplate() {
HttpTest httpTest = setupHttpTestWithTemplate();
XmlHttpResponse req1 = checkCall(url -> httpTest.putTemplateTo(url));
assertEquals("PUT", httpTest.getResponse().getMethod());
checkTemplateRequestBody(httpTest.getResponse().getMethod(), req1);
}
/**
* Test delete with template
*/
@Test
public void testDeleteWithTemplate() {
HttpTest httpTest = setupHttpTestWithTemplate();
XmlHttpResponse req1 = checkCall(url -> httpTest.deleteWithTemplate(url));
assertEquals("DELETE", httpTest.getResponse().getMethod());
checkTemplateRequestBody(httpTest.getResponse().getMethod(), req1);
}
static XmlHttpResponse checkCall(Function<String, Boolean> call) {
MockXmlServerSetup mockXmlServerSetup = new MockXmlServerSetup();
mockXmlServerSetup.addResponse("hallo");
try {
String serverUrl = mockXmlServerSetup.getMockServerUrl();
boolean result = call.apply(serverUrl);
assertTrue(result);
return mockXmlServerSetup.getResponseList().get(0);
} finally {
mockXmlServerSetup.stop();
}
}
private HttpTest setupHttpTestWithTemplate() {
HttpTest httpTest = new HttpTest();
httpTest.template("samplePost.ftl.xml");
httpTest.setValueFor("Oosterhout", "countryName");
return httpTest;
}
private void checkTemplateRequestBody(String method, XmlHttpResponse req1) {
assertEquals(method, req1.getMethod());
assertEquals("<s11:Envelope xmlns:s11=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
"\t<s11:Body>\n" +
"\t\t<ns1:GetWeather xmlns:ns1=\"http:
"\t\t\t\t\t\t<ns1:CountryName>Oosterhout</ns1:CountryName>\n" +
"\t\t</ns1:GetWeather>\n" +
"\t</s11:Body>\n" +
"</s11:Envelope>\n", req1.getRequest());
}
/**
* Test get, with retry
*/
@Test
public void testGetRetry() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCallWithRetry(httpTest, url -> httpTest.getFrom(url));
assertEquals("GET", httpTest.getResponse().getMethod());
assertEquals("GET", req1.getMethod());
assertEquals("GET: /FitNesseMock", req1.getRequest());
}
/**
* Test head, with retry
*/
@Test
public void testHeadRetry() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCallWithRetry(httpTest, url -> httpTest.headFrom(url));
assertEquals("HEAD", httpTest.getResponse().getMethod());
assertEquals("HEAD", req1.getMethod());
assertEquals("HEAD: /FitNesseMock", req1.getRequest());
}
/**
* Test post, with retry
*/
@Test
public void testPostRetry() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCallWithRetry(httpTest, url -> httpTest.postTo("a", url));
assertEquals("POST", httpTest.getResponse().getMethod());
assertEquals("POST", req1.getMethod());
assertEquals("a", req1.getRequest());
}
/**
* Test put, with retry
*/
@Test
public void testPutRetry() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCallWithRetry(httpTest, url -> httpTest.putTo("b", url));
assertEquals("PUT", httpTest.getResponse().getMethod());
assertEquals("PUT", req1.getMethod());
assertEquals("b", req1.getRequest());
}
/**
* Test delete with body, with retry
*/
@Test
public void testDeleteWithBodyRetry() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCallWithRetry(httpTest, url -> httpTest.deleteWith(url, "a=1"));
assertEquals("DELETE", httpTest.getResponse().getMethod());
assertEquals("DELETE", req1.getMethod());
assertEquals("a=1", req1.getRequest());
}
/**
* Test delete without body, with retry
*/
@Test
public void testDeleteWithoutBodyRetry() {
HttpTest httpTest = new HttpTest();
XmlHttpResponse req1 = checkCallWithRetry(httpTest, url -> httpTest.delete(url));
assertEquals("DELETE", httpTest.getResponse().getMethod());
assertEquals("DELETE", req1.getMethod());
assertEquals("DELETE: /FitNesseMock", req1.getRequest());
}
static XmlHttpResponse checkCallWithRetry(HttpTest httpTest, Function<String, Boolean> call) {
MockXmlServerSetup mockXmlServerSetup = new MockXmlServerSetup();
mockXmlServerSetup.addResponseWithStatus("error1", 500);
mockXmlServerSetup.addResponseWithStatus("error2", 500);
mockXmlServerSetup.addResponse("hi");
try {
String serverUrl = mockXmlServerSetup.getMockServerUrl();
boolean result = call.apply(serverUrl);
assertFalse(result);
result = httpTest.repeatUntilResponseStatusIs(200);
assertTrue(result);
assertEquals(2, httpTest.repeatCount());
return mockXmlServerSetup.getResponseList().get(2);
} finally {
mockXmlServerSetup.stop();
}
}
} |
package com.mychess.mychess;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Acceso extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acceso);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTabs();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_acceso, menu);
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.rendir) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setTabs(){
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Entrar"));
tabLayout.addTab(tabLayout.newTab().setText("Registrarse"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
} |
package org.animotron.statement.operator;
import junit.framework.Assert;
import org.animotron.ATest;
import org.animotron.statement.value.VALUE;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class ValueTest extends ATest {
@Test
@Ignore
public void test() throws Throwable {
testAnimo("def foo \"abc\".");
testAnimo("def foo \"abe\".");
testAnimo("def bar \"ebc\".");
try {Thread.sleep(1000);} catch (InterruptedException e) {}
Assert.assertNotNull(VALUE._.get("a"));
Assert.assertNotNull(VALUE._.get("b"));
Assert.assertNotNull(VALUE._.get("c"));
}
@Test
public void test_00() throws Throwable {
testAnimo("def foo \"abc\".");
assertStringResult("foo", "abc");
}
@Test
public void test_01() throws Throwable {
testAnimo("def foo (x) \"abc\".");
assertStringResult("any x", "abc");
}
@Test
public void test_02() throws Throwable {
testAnimo("def foo (x) \"abc\".");
testAnimo("def bar (x) \"def\".");
assertStringResult("all x", "abcdef");
}
} |
package com.tattood.tattood;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
public class Server {
public static final String host = "http://139.179.197.223:5000";
public enum TattooRequest {Liked, Public, Private}
// public enum UserRequest {Followed, Followers}
public static boolean isInternetAvailable() {
try {
InetAddress ip = InetAddress.getByName(host); //You can replace it with your name
return !ip.toString().equals("");
} catch (Exception e) {
return false;
}
}
private static final Response.Listener<JSONObject> default_json_callback = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
};
public static final Response.ErrorListener default_error_handler = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Connection", "ERROR");
Log.d("Connection", String.valueOf(isInternetAvailable()));
Log.d("Connection", error.toString());
}
};
private Server() {
}
public static boolean isOffline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo == null || !netInfo.isConnectedOrConnecting();
}
private static void request(Context context, String url, JSONObject data,
Response.Listener<JSONObject> callback) {
request(context, url, DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, data, callback, default_error_handler);
}
private static void request(Context context, String url, JSONObject data,
Response.Listener<JSONObject> callback,
Response.ErrorListener error_handler) {
request(context, url, DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, data, callback, error_handler);
}
private static void request(Context context, String url, int timeout, JSONObject data,
Response.Listener<JSONObject> callback) {
request(context, url, timeout, data, callback, default_error_handler);
}
private static void request(Context context, String url, int timeout, JSONObject data,
Response.Listener<JSONObject> callback,
Response.ErrorListener error_handler) {
if (Server.isOffline(context)) {
Toast.makeText(context, "No Internet Connection!", Toast.LENGTH_LONG).show();
return;
}
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest request = new JsonObjectRequest(host + url, data, callback, error_handler);
RetryPolicy policy = new DefaultRetryPolicy(timeout, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
queue.add(request);
}
public static JSONObject create_json(String token, String email, String username) {
JSONObject data = new JSONObject();
try {
if (username != null)
data.put("username", username);
if (email != null)
data.put("email", email);
data.put("token", token);
} catch (JSONException e) {
e.printStackTrace();
}
return data;
}
public static JSONObject create_json(String token, String email) {
return create_json(token, email, null);
}
public static void signIn(Context context, String token, String email,
Response.Listener<JSONObject> callback,
Response.ErrorListener error_handler) {
JSONObject data = create_json(token, email);
int timeout = 1000;
request(context, "/login", timeout, data, callback, error_handler);
}
public static void register(Context context, String email, String username, Uri photo, String token,
Response.Listener<JSONObject> callback, Response.ErrorListener error_handler) {
JSONObject data = create_json(token, email, username);
try {
data.put("photo", photo.toString());
} catch (JSONException e) {
e.printStackTrace();
}
request(context, "/register", data, callback, error_handler);
}
public static void getPopular(Context context, Response.Listener<JSONObject> callback, int limit) {
request(context, "/popular?limit=" + limit, null, callback);
}
public static void getPopular(Context context, Response.Listener<JSONObject> callback) {
getPopular(context, callback, 20);
}
public static void getRecent(Context context, Response.Listener<JSONObject> callback, int limit) {
request(context, "/recent?limit=" + limit, null, callback);
}
public static void getRecent(Context context, Response.Listener<JSONObject> callback) {
getRecent(context, callback, 20);
}
public static void getTattooData(final Context context, final String id,
Response.Listener<JSONObject> callback) {
final String url = "/tattoo-data?id="+id+"&token="+User.getInstance().token;
request(context, url, null, callback);
}
public static void getTattooImage(final Context context, final String id, final int item_id,
final ResponseCallback callback) {
final String url = "/tattoo?id="+id+"&token="+User.getInstance().token;
InputStreamVolleyRequest request = new InputStreamVolleyRequest(url,
new Response.Listener<byte[]>() {
@Override
public void onResponse(byte[] response) {
if (response != null) {
FileOutputStream outputStream;
String name = id + ".png";
try {
outputStream = context.openFileOutput(name, Context.MODE_PRIVATE);
outputStream.write(response);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
callback.run(id, item_id);
}
}
});
RequestQueue mRequestQueue = Volley.newRequestQueue(context, new HurlStack());
mRequestQueue.add(request);
}
public static void getTattooList(Context context, TattooRequest r, String username,
Response.Listener<JSONObject> callback, int limit) {
String url;
if (r == TattooRequest.Liked) {
url = "/user-likes?";
} else {
if (r == TattooRequest.Public)
url = "/user-tattoo?private=0";
else
url = "/user-tattoo?private=1";
}
url += "&token=" + User.getInstance().token + "&user=" + username + "&limit=" + limit;
Log.d("User-tattoo", url);
request(context, url, null, callback);
}
public static String getStringImage(Bitmap bmp){
ByteArrayOutputStream byte_stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, byte_stream);
byte[] imageBytes = byte_stream.toByteArray();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}
public static void search(Context context, String query, int limit, Response.Listener<JSONObject> callback) {
String url = "/search?query=" + query + "&token=" + User.getInstance().token + "&limit=" + limit;
request(context, url, null, callback);
}
public static void search(Context context, String query, Response.Listener<JSONObject> callback) {
search(context, query, 20, callback);
}
private static void updateOrUpload(Context context, final Uri path, final Tattoo tattoo,
final Response.Listener<JSONObject> callback) {
final Bitmap bitmap = path == null ? null : loadImage(context, path);
final String url = bitmap == null ? "/tattoo-update" : "/tattoo-upload";
JSONObject data = new JSONObject();
try {
data.put("token", User.getInstance().token);
data.put("id", tattoo.tattoo_id);
data.put("tags", new JSONArray(tattoo.tags));
data.put("private", tattoo.is_private);
if (bitmap != null)
data.put("image", getStringImage(bitmap));
} catch (JSONException e) {
e.printStackTrace();
}
request(context, url, data, callback);
}
public static void updateTattoo(Context context, Tattoo tattoo) {
updateOrUpload(context, null, tattoo, default_json_callback);
}
private static Bitmap loadImage(Context context, final Uri path) {
try {
return MediaStore.Images.Media.getBitmap(context.getContentResolver(), path);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
public static void uploadImage(Context context, final Uri path, final Tattoo tattoo,
final Response.Listener<JSONObject> callback) {
updateOrUpload(context, path, tattoo, callback);
}
public static void extractTags(Context context, final Uri path,
ArrayList<float[]> x, ArrayList<float[]> y,
final Response.Listener<JSONObject> callback) {
final Bitmap bitmap = loadImage(context, path);
JSONObject data = new JSONObject();
try {
data.put("token", User.getInstance().token);
data.put("image", getStringImage(bitmap));
JSONArray px = new JSONArray();
JSONArray py = new JSONArray();
for (int i = 0; i < x.size(); i++)
px.put(new JSONArray(x.get(i)));
for (int i = 0; i < y.size(); i++)
py.put(new JSONArray(y.get(i)));
data.put("x", px);
data.put("y", py);
} catch (JSONException e) {
e.printStackTrace();
}
int timeout = 600000;
request(context, "/extract-tags", timeout, data, callback);
}
public static void like(Context context, final String id, boolean likes,
Response.Listener<JSONObject> callback) {
JSONObject data = create_json(User.getInstance().token, id);
request(context, likes ? "/like" : "/unlike", data, callback);
}
public interface ResponseCallback {
void run(String id, int item_id);
}
} |
package modelo.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.iuriX.ustglobalproject.MainActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import modelo.Session;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class LoginActivity extends Activity {
EditText mUser, mPass;
private LogEasyApi service;
@BindView(R.id.bLogin)
Button bLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
ButterKnife.bind(this);
mUser = (EditText) findViewById(R.id.usuario);
mPass = (EditText) findViewById(R.id.contra);
bLogin.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) { attemptLogin();}});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.api_url))
.addConverterFactory(GsonConverterFactory.create()).build();
service = retrofit.create(LogEasyApi.class);
}
@OnClick(R.id.bLogin)
public void attemptLogin() {
mUser.setError(null);
mPass.setError(null);
String login = mUser.getText().toString();
String password = mPass.getText().toString();
boolean cancel = false;
View focusView = null;
if (password.equals("")) {
mPass.setError("Campo vacío");
focusView = mPass;
cancel = true;
}
if (login.equals("")) {
mUser.setError("Campo vacío");
focusView = mUser;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
}else {
final TokenRequest tokenRequest = new TokenRequest();
tokenRequest.setlogin(login);
tokenRequest.setPassword(password);
Call<TokenResponse> tokenResponseCall = service.getTokenAccess(tokenRequest);
tokenResponseCall.enqueue(new Callback<TokenResponse>() {
@Override
public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
int statusCode = response.code();
TokenResponse tokenResponse = response.body();
Log.d("LoginActivity","onResponse: " + statusCode);
Session.getInstance().setSessionId(tokenResponse.getSession_id());
Toast.makeText(getApplicationContext(), tokenResponse.getError_description() ,Toast.LENGTH_SHORT).show();
if (tokenResponse.getError_code().equals("0")) {
Intent ventanaSearch = new Intent(getApplicationContext(), MainActivity.class);
startActivity(ventanaSearch);
}
}
@Override
public void onFailure(Call<TokenResponse> call, Throwable t) {
Log.d("LoginActivity", "onFailure: " + t.getMessage());
}
});
}
}
} |
package org.dita.dost.writer;
import com.google.common.collect.ImmutableMap;
import org.dita.dost.TestUtils;
import org.dita.dost.module.reader.DefaultTempFileScheme;
import org.dita.dost.module.reader.TempFileNameScheme;
import org.dita.dost.store.StreamStore;
import org.dita.dost.util.Job;
import org.dita.dost.util.Job.FileInfo;
import org.dita.dost.util.Job.FileInfo.Builder;
import org.dita.dost.util.XMLUtils;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXSource;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
public class ForceUniqueFilterTest {
private static final File resourceDir = TestUtils.getResourceDir(ForceUniqueFilterTest.class);
private static final File srcDir = new File(resourceDir, "src");
private static final File expDir = new File(resourceDir, "exp");
private Job job;
private TempFileNameScheme tempFileNameScheme;
@Before
public void setUp() throws Exception {
job = new Job(srcDir, new StreamStore(srcDir, new XMLUtils()));
job.setInputDir(srcDir.toURI());
job.add(new Builder()
.src(srcDir.toURI().resolve("test.ditamap"))
.uri(URI.create("test.ditamap"))
.result(srcDir.toURI().resolve("test.ditamap"))
.format("ditamap")
.build());
for (String name : new String[]{"test.dita", "test3.dita", "test2.dita", "topic.dita"}) {
job.add(new Builder()
.src(srcDir.toURI().resolve(name))
.uri(URI.create(name))
.result(srcDir.toURI().resolve(name))
.build());
}
job.add(new Builder()
.uri(URI.create("copy-to.dita"))
.result(srcDir.toURI().resolve("copy-to.dita"))
.build());
tempFileNameScheme = new DefaultTempFileScheme();
tempFileNameScheme.setBaseDir(srcDir.toURI());
}
@Test
public void test() throws Exception {
final ForceUniqueFilter f = new ForceUniqueFilter();
f.setJob(job);
f.setTempFileNameScheme(tempFileNameScheme);
f.setCurrentFile(new File(srcDir, "test.ditamap").toURI());
f.setParent(SAXParserFactory.newInstance().newSAXParser().getXMLReader());
final Document act = filter(new File(srcDir, "test.ditamap"), f);
final Document exp = parse(new File(expDir, "test.ditamap"));
TestUtils.assertXMLEqual(exp, act);
assertEquals(new HashMap<>(ImmutableMap.of(
createFileInfo("test.dita", "test_3.dita"),
createFileInfo("test.dita", "test.dita"),
createFileInfo("test.dita", "test_2.dita"),
createFileInfo("test.dita", "test.dita"),
createFileInfo(null, "copy-to_2.dita"),
createFileInfo(null, "copy-to.dita"),
createFileInfo("topic.dita", "topic_2.dita"),
createFileInfo("topic.dita", "topic.dita")
)), f.copyToMap);
}
private FileInfo createFileInfo(final String src, final String tmp) {
final Builder builder = new Builder();
if (src != null) {
builder.src(srcDir.toURI().resolve(src));
}
return builder.uri(URI.create(tmp))
.result(srcDir.toURI().resolve(tmp))
.build();
}
private Document parse(File input) throws ParserConfigurationException, IOException, SAXException {
final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
builderFactory.setIgnoringComments(true);
return builderFactory.newDocumentBuilder().parse(new InputSource(input.toURI().toString()));
}
private Document filter(File input, XMLReader f) throws TransformerException {
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
final DOMResult dst = new DOMResult();
transformer.transform(new SAXSource(f, new InputSource(input.toURI().toString())), dst);
return (Document) dst.getNode();
}
} |
package org.embulk.input;
//import com.google.common.base.Optional;
//import org.embulk.EmbulkTestRuntime;
//import org.embulk.config.ConfigSource;
//import org.embulk.spi.Exec;
//import org.junit.Rule;
//import org.junit.Test;
//import java.util.Collections;
//import static org.hamcrest.CoreMatchers.is;
//import static org.junit.Assert.assertThat;
public class TestRemoteFileInputPlugin
{
// @Rule
// public EmbulkTestRuntime runtime = new EmbulkTestRuntime();
// @Test
// public void checkDefaultValues()
// ConfigSource config = Exec.newConfigSource();
// RemoteFileInputPlugin.PluginTask task = config.loadConfig(RemoteFileInputPlugin.PluginTask.class);
// assertThat(task.getHosts(), is(Collections.<String>emptyList()));
// assertThat(task.getHostsCommand(), is(Optional.<String>absent()));
// assertThat(task.getHostsSeparator(), is(" "));
// assertThat(task.getPath(), is(""));
// assertThat(task.getPathCommand(), is(Optional.<String>absent()));
// assertThat(task.getAuth(), is(Collections.<String, String>emptyMap()));
// assertThat(task.getLastTarget(), is(Optional.<RemoteFileInputPlugin.Target>absent()));
} |
package net.finmath.montecarlo;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.math3.random.MersenneTwister;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import net.finmath.stochastic.RandomVariableInterface;
/**
* Test cases for the class net.finmath.montecarlo.RandomVariable.
*
* @author Christian Fries
* @see net.finmath.montecarlo.RandomVariable
*/
@RunWith(Parameterized.class)
public class RandomVariableTest {
private AbstractRandomVariableFactory randomVariableFactory;
@Parameters(name="{0}")
public static Collection<Object[]> generateData()
{
return Arrays.asList(new Object[][] {
{ new RandomVariableFactory(true /* isUseDoublePrecisionFloatingPointImplementation */)},
{ new RandomVariableFactory(false /* isUseDoublePrecisionFloatingPointImplementation */)}
});
};
public RandomVariableTest(AbstractRandomVariableFactory randomVariableFactory) {
super();
this.randomVariableFactory = randomVariableFactory;
}
@Test
public void testRandomVariableDeterministc() {
// Create a random variable with a constant
RandomVariableInterface randomVariable = randomVariableFactory.createRandomVariable(2.0);
// Perform some calculations
randomVariable = randomVariable.mult(2.0);
randomVariable = randomVariable.add(1.0);
randomVariable = randomVariable.squared();
randomVariable = randomVariable.sub(4.0);
randomVariable = randomVariable.div(7.0);
// The random variable has average value 3.0 (it is constant 3.0)
Assert.assertTrue(randomVariable.getAverage() == 3.0);
// Since the random variable is deterministic, it has zero variance
Assert.assertTrue(randomVariable.getVariance() == 0.0);
}
@Test
public void testRandomVariableStochastic() {
// Create a stochastic random variable
RandomVariableInterface randomVariable2 = randomVariableFactory.createRandomVariable(0.0,
new double[] {-4.0, -2.0, 0.0, 2.0, 4.0} );
// Perform some calculations
randomVariable2 = randomVariable2.add(4.0);
randomVariable2 = randomVariable2.div(2.0);
// The random variable has average value 2.0
Assert.assertTrue(randomVariable2.getAverage() == 2.0);
// The random variable has variance value 2.0 = (4 + 1 + 0 + 1 + 4) / 5
Assert.assertEquals(2.0, randomVariable2.getVariance(), 1E-12);
// Multiply two random variables, this will expand the receiver to a stochastic one
RandomVariableInterface randomVariable = new RandomVariable(3.0);
randomVariable = randomVariable.mult(randomVariable2);
// The random variable has average value 6.0
Assert.assertTrue(randomVariable.getAverage() == 6.0);
// The random variable has variance value 2 * 9
Assert.assertTrue(randomVariable.getVariance() == 2.0 * 9.0);
}
@Test
public void testRandomVariableArithmeticSqrtPow() {
// Create a stochastic random variable
RandomVariableInterface randomVariable = randomVariableFactory.createRandomVariable(0.0,
new double[] {3.0, 1.0, 0.0, 2.0, 4.0, 1.0/3.0} );
RandomVariableInterface check = randomVariable.sqrt().sub(randomVariable.pow(0.5));
// The random variable is identical 0.0
Assert.assertTrue(check.getAverage() == 0.0);
Assert.assertTrue(check.getVariance() == 0.0);
}
@Test
public void testRandomVariableArithmeticSquaredPow() {
// Create a stochastic random variable
RandomVariableInterface randomVariable = randomVariableFactory.createRandomVariable(0.0,
new double[] {3.0, 1.0, 0.0, 2.0, 4.0, 1.0/3.0} );
RandomVariableInterface check = randomVariable.squared().sub(randomVariable.pow(2.0));
// The random variable is identical 0.0
Assert.assertTrue(check.getAverage() == 0.0);
Assert.assertTrue(check.getVariance() == 0.0);
}
@Test
public void testRandomVariableStandardDeviation() {
// Create a stochastic random variable
RandomVariableInterface randomVariable = randomVariableFactory.createRandomVariable(0.0,
new double[] {3.0, 1.0, 0.0, 2.0, 4.0, 1.0/3.0} );
double check = randomVariable.getStandardDeviation() - Math.sqrt(randomVariable.getVariance());
Assert.assertTrue(check == 0.0);
}
/**
* Testing quantiles of normal distribution.
* Based on feedback provided by Alessandro Gnoatto and a student of him.
*/
@Test
public void testGetQuantile() {
final int seed = 3141;
final int numberOfSamplePoints = 10000000;
MersenneTwister mersenneTwister = new MersenneTwister(seed);
double[] samples = new double[numberOfSamplePoints];
for(int i = 0; i< numberOfSamplePoints; i++) {
double randomNumber = mersenneTwister.nextDouble();
samples[i] = net.finmath.functions.NormalDistribution.inverseCumulativeDistribution(randomNumber);
}
RandomVariableInterface normalDistributedRandomVariable = randomVariableFactory.createRandomVariable(0.0,samples);
double q00 = normalDistributedRandomVariable.getQuantile(0.0);
Assert.assertEquals(normalDistributedRandomVariable.getMin(), q00, 1E-12);
double q05 = normalDistributedRandomVariable.getQuantile(0.05);
Assert.assertEquals(-1.645, q05, 1E-3);
double q50 = normalDistributedRandomVariable.getQuantile(0.5);
Assert.assertEquals(0, q50, 2E-4);
double q95 = normalDistributedRandomVariable.getQuantile(0.95);
Assert.assertEquals(1.645, q95, 1E-3);
double q99 = normalDistributedRandomVariable.getQuantile(0.99);
Assert.assertEquals(2.33, q99, 1E-2);
}
} |
// FILE: c:/projects/jetel/org/jetel/data/DataRecord.java
package org.jetel.data;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.BitArray;
public class DataRecord implements Serializable, Comparable {
private static final long serialVersionUID = 2497808992091497225L;
/**
* Array for holding data fields
*
* @since
*/
private DataField fields[];
/**
* Reference to metadata object describing this record
* @since
*/
private transient DataRecordMetadata metadata;
/**
* Should this record and all its fields be created in plain mode ?<br>
* Plai means no "decorators" will be added and this record is deemed to
* store values only, no formating or parsing will be performed on this
* record.
*
*/
private boolean plain=false;
/**
* Create new instance of DataRecord based on specified metadata (
* how many fields, what field types, etc.)
*
* @param _metadata description of the record structure
*/
public DataRecord(DataRecordMetadata _metadata) {
this(_metadata,false);
}
/**
* Create new instance of DataRecord based on specified metadata (
* how many fields, what field types, etc.)
*
* @param _metadata description of the record structure
* @param plain if true, no formatters and other "extra" objects will be created for
* fields
*/
public DataRecord(DataRecordMetadata _metadata,boolean plain ) {
this.metadata = _metadata;
this.plain=plain;
fields = new DataField[metadata.getNumFields()];
}
/**
* Private constructor used when clonning/copying DataRecord objects.<br>
* It takes numFields parameter to speed-up creation.
*
* @param _metadata metadata describing this record
* @param numFields number of fields this record should contain
*/
private DataRecord(DataRecordMetadata _metadata, int numFields){
this.metadata = _metadata;
fields = new DataField[numFields];
}
/**
* Creates deep copy of existing record (field by field).
*
* @return new DataRecord
*/
public DataRecord duplicate(){
DataRecord newRec=new DataRecord(metadata,fields.length);
for (int i=0;i<fields.length;i++){
newRec.fields[i]=fields[i].duplicate();
}
return newRec;
}
/**
* Set fields by copying the fields from the record passed as argument.
* Does assume that both records have the same structure - i.e. metadata.
* @param fromRecord DataRecord from which to get fields' values
*/
public void copyFrom(DataRecord fromRecord){
for (int i=0;i<fields.length;i++){
this.fields[i].copyFrom(fromRecord.fields[i]);
}
}
/**
* Set fields by copying the fields from the record passed as argument.
* Can handle situation when records are not exactly the same.
*
* @param _record Record from which fields are copied
* @since
*/
public void copyFieldsByPosition(DataRecord _record) {
DataRecordMetadata sourceMetadata = _record.getMetadata();
DataField sourceField;
DataField targetField;
//DataFieldMetadata fieldMetadata;
int sourceLength = sourceMetadata.getNumFields();
int targetLength = this.metadata.getNumFields();
int copyLength;
if (sourceLength < targetLength) {
copyLength = sourceLength;
} else {
copyLength = targetLength;
}
for (int i = 0; i < copyLength; i++) {
//fieldMetadata = metadata.getField(i);
sourceField = _record.getField(i);
targetField = this.getField(i);
if (sourceField.getType() == targetField.getType()) {
targetField.setValue(sourceField.getValue());
} else {
targetField.setToDefaultValue();
}
}
}
/**
* Set fields by copying name-matching fields' values from the record passed as argument.<br>
* If two fields match by name but not by type, target field is set to default value.
*
* @param sourceRecord from which copy data
* @return boolean array with true values on positions, where values were copied from source record
*/
public boolean[] copyFieldsByName(DataRecord sourceRecord) {
boolean[] result = new boolean[fields.length];
Arrays.fill(result, false);
if (sourceRecord == null) return result;
DataField sourceField;
DataField targetField;
int sourceLength = sourceRecord.getMetadata().getNumFields();
int count = 0;
for (int i = 0; i < fields.length; i++) {
targetField = getField(i);
int srcFieldPos = sourceRecord.getMetadata().getFieldPosition(
targetField.getMetadata().getName());
if (srcFieldPos >= 0) {
sourceField = sourceRecord.getField(srcFieldPos);
result[i] = true;
if (sourceField.getType() == targetField.getType()) {
targetField.setValue(sourceField.getValue());
} else {
targetField.setToDefaultValue();
}
if (count++ > sourceLength)
break;//all fields from source were used
}
}
return result;
}
/**
* Deletes/removes specified field. The field's internal reference
* is set to NULL, so it can be garbage collected.<br>
* <b>Warning:</b>We recommend not using this method !<br>
* By calling this method, the number of fields is decreased by
* one, the internal array containing fields is copied into a new
* one.<br>
* Be careful when calling this method as the modified record
* won't follow the original metadata prescription. New metadata object
* will be created and assigned to this record, but it will share fields'
* metadata with the original metadata object.<br>
*
* @param _fieldNum Description of Parameter
* @since
*/
public void delField(int _fieldNum) {
DataField tmp_fields[]=new DataField[fields.length-1];
DataRecordMetadata tmp_metadata=new DataRecordMetadata(metadata.getName(),metadata.getRecType());
int counter=0;
for(int i=0;i<fields.length;i++){
if (i!=_fieldNum){
tmp_fields[counter]=fields[i];
tmp_metadata.addField(tmp_fields[counter].getMetadata());
counter++;
}
}
fields=tmp_fields;
metadata=tmp_metadata;
}
/**
* Refreshes this record's content from ByteBuffer.
*
* @param buffer ByteBuffer from which this record's fields should be read
* @since April 23, 2002
*/
public void deserialize(ByteBuffer buffer) {
if (Defaults.Record.USE_FIELDS_NULL_INDICATORS && metadata.isNullable()) {
final int base = buffer.position();
BitArray nullSwitches = metadata.getFieldsNullSwitches();
final int numNullBytes = BitArray.bitsLength2Bytes(metadata
.getNumNullableFields());
byte indicator = 0;
// skip to first field
buffer.position(buffer.position() + numNullBytes);
// are there any NULLs ? if not, use the simple version
int nullCounter = 0;
for (int i = 0; i < fields.length; i++) {
if (nullSwitches.isSet(i)) {
if (BitArray.isSet(buffer, base, nullCounter)) {
fields[i].setNull(true);
} else {
fields[i].deserialize(buffer);
}
nullCounter++;
} else {
fields[i].deserialize(buffer);
}
}
} else {
for (int i = 0; i < fields.length; i++) {
fields[i].deserialize(buffer);
}
}
}
public void deserialize(ByteBuffer buffer,int[] whichFields) {
for(int i:whichFields){
fields[i].deserialize(buffer);
}
}
/**
* Test two DataRecords for equality. Records must have the same metadata (be
* created using the same metadata object) and their field values must be equal.
*
* @param obj DataRecord to compare with
* @return True if they equals, false otherwise
* @since April 23, 2002
*/
public boolean equals(Object obj) {
if (this==obj) return true;
/*
* first test that both records have the same structure i.e. point to
* the same metadata
*/
if (obj instanceof DataRecord) {
if (metadata != ((DataRecord) obj).getMetadata()) {
return false;
}
// check field by field that they are the same
for (int i = 0; i < fields.length; i++) {
if (!fields[i].equals(((DataRecord) obj).getField(i))) {
return false;
}
}
return true;
}else{
return false;
}
}
/**
* Compares two DataRecords. Records must have the same metadata (be
* created using the same metadata object). Their field values are compare one by one,
* the first non-equal pair of fields denotes the overall comparison result.
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object obj){
if (this==obj) return 0;
if (obj instanceof DataRecord) {
if (metadata != ((DataRecord) obj).getMetadata()) {
throw new RuntimeException("Can't compare - records have different metadata objects assigned!");
}
int cmp;
// check field by field that they are the same
for (int i = 0; i < fields.length; i++) {
cmp=fields[i].compareTo(((DataRecord) obj).getField(i));
if (cmp!=0) {
return cmp;
}
}
return 0;
}else{
throw new ClassCastException("Can't compare DataRecord with "+obj.getClass().getName());
}
}
/**
* An operation that returns DataField with
* specified order number.
*
* @param _fieldNum Description of Parameter
* @return The Field value
* @since
*/
public DataField getField(int _fieldNum) {
return fields[_fieldNum];
}
/**
* An operation that returns DataField with
* specified name.
*
* @param _name Description of Parameter
* @return The Field value
* @since
*/
public DataField getField(String _name) {
return fields[metadata.getFieldPosition(_name)];
}
/**
* Returns true if record contains a field with a given name.
* @param name
* @return
*/
public boolean hasField(String name) {
return metadata.getField(name) != null;
}
/**
* An attribute that returns metadata object describing the record
*
* @return The Metadata value
* @since
*/
public DataRecordMetadata getMetadata() {
return metadata;
}
/**
* An operation that returns numbe of fields this record
* contains.
*
* @return The NumFields value
* @since
*/
public int getNumFields() {
return fields.length;
}
/**
* Description of the Method
*
* @since April 5, 2002
*/
public void init() {
DataFieldMetadata fieldMetadata;
// create appropriate data fields based on metadata supplied
for (int i = 0; i < metadata.getNumFields(); i++) {
fieldMetadata = metadata.getField(i);
fields[i] =
DataFieldFactory.createDataField(
fieldMetadata.getType(),
fieldMetadata,plain);
}
}
/**
* Serializes this record's content into ByteBuffer.
*
* @param buffer ByteBuffer into which the individual fields of this record should be put
* @since April 23, 2002
*/
public void serialize(ByteBuffer buffer) {
if (Defaults.Record.USE_FIELDS_NULL_INDICATORS && metadata.isNullable()) {
final int base = buffer.position();
BitArray nullSwitches = metadata.getFieldsNullSwitches();
final int numNullBytes = BitArray.bitsLength2Bytes(metadata
.getNumNullableFields());
// clear NULL indicators
for (int i = 0; i < numNullBytes; i++) {
buffer.put((byte) 0);
}
int nullCounter = 0;
for (int i = 0; i < fields.length; i++) {
if (nullSwitches.isSet(i)) {
if (fields[i].isNull) {
BitArray.set(buffer, base, nullCounter);
} else {
fields[i].serialize(buffer);
}
nullCounter++;
} else {
fields[i].serialize(buffer);
}
}
} else {
for (int i = 0; i < fields.length; i++) {
fields[i].serialize(buffer);
}
}
}
/**
* Serializes this record's content into ByteBuffer.<br>
* Asume only fields which indexes are in fields array
*
* @param buffer
* @param whichFields
* @since 27.2.2007
*/
public void serialize(ByteBuffer buffer,int[] whichFields) {
for(int i:whichFields){
fields[i].serialize(buffer);
}
}
/**
* Assigns new metadata to this DataRecord. If the new
* metadata is not equal to the current metadata, the record's
* content is recreated from scratch. After calling this
* method, record is uninitialized and init() method should
* be called prior any attempt to manipulate this record's content.
*
* @param metadata The new Metadata value
* @since April 5, 2002
*/
public void setMetadata(DataRecordMetadata metadata) {
if (this.metadata != metadata){
this.metadata=metadata;
fields = new DataField[metadata.getNumFields()];
}
}
/**
* An operation that sets value of all data fields to their default value.
*/
public void setToDefaultValue() {
for (int i = 0; i < fields.length; i++) {
fields[i].setToDefaultValue();
}
}
/**
* An operation that sets value of the selected data field to its default
* value.
*
* @param _fieldNum Ordinal number of the field which should be set to default
*/
public void setToDefaultValue(int _fieldNum) {
fields[_fieldNum].setToDefaultValue();
}
/**
* An operation that sets value of all data fields to NULL value.
*/
public void setToNull(){
for (int i = 0; i < fields.length; i++) {
fields[i].setNull(true);
}
}
/**
* An operation that sets value of the selected data field to NULL
* value.
* @param _fieldNum
*/
public void setToNull(int _fieldNum) {
fields[_fieldNum].setNull(true);
}
public void reset() {
for (int i = 0; i < fields.length; i++) {
fields[i].reset();
}
}
/**
* An operation that resets value of specified field - by calling
* its reset() method.
*
* @param _fieldNum Ordinal number of the field which should be set to default
*/
public void reset(int _fieldNum) {
fields[_fieldNum].reset();
}
/**
* Creates textual representation of record's content based on values of individual
* fields
*
* @return Description of the Return Value
*/
public String toString() {
StringBuffer str = new StringBuffer(80);
for (int i = 0; i < fields.length; i++) {
str.append("#").append(i).append("|");
str.append(fields[i].getMetadata().getName()).append("|");
str.append(fields[i].getType());
str.append("->");
str.append(fields[i].toString());
str.append("\n");
}
return str.toString();
}
/**
* Gets the actual size of record (in bytes).<br>
* <i>How many bytes are required for record serialization</i>
*
* @return The size value
*/
public int getSizeSerialized() {
int size=0;
if (Defaults.Record.USE_FIELDS_NULL_INDICATORS && metadata.isNullable()){
for (int i = 0; i < fields.length;i++){
if (!fields[i].isNull()){
size+=fields[i].getSizeSerialized();
}
}
size+=BitArray.bitsLength2Bytes(metadata.getNumNullableFields());
}else{
for (int i = 0; i < fields.length; size+=fields[i++].getSizeSerialized());
}
return size;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode(){
int hash=17;
for (int i=0;i<fields.length;i++){
hash=37*hash+fields[i].hashCode();
}
return hash;
}
/**
* Test whether the whole record has NULL value - i.e.
* every field it contains has NULL value.
* @return true if all fields have NULL value otherwise false
*/
public boolean isNull(){
for (int i = 0; i < fields.length; i++) {
if (!fields[i].isNull()) return false;
}
return true;
}
}
/*
* end class DataRecord
*/ |
package com.std.javassist;
import javassist.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ClassMaker {
/**
* class
* @param className
*/
public void makeClass(String className)
throws NotFoundException, CannotCompileException, IllegalAccessException, InstantiationException,
NoSuchMethodException, InvocationTargetException {
ClassPool classPool = new ClassPool();
//classpathjava.lang.String
classPool.insertClassPath(new ClassClassPath(ClassMaker.class));
CtClass ctClass = classPool.makeClass(className);
CtField ctField = new CtField(classPool.get("java.lang.String"), "name", ctClass);
//[Ljava.lang.String; //
//CtField ctField = new CtField(classPool.get("java.lang.String"), "name", ctClass);
ctField.setModifiers(Modifier.PRIVATE);
ctClass.addField(ctField, CtField.Initializer.constant("hello"));
//set
ctClass.addMethod(CtNewMethod.setter("setName",ctField));
//get
ctClass.addMethod(CtNewMethod.getter("getName",ctField));
CtConstructor ctConstructor = new CtConstructor(new CtClass[]{},ctClass);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("{\nthis.name=\"sence\";\n}");
ctConstructor.setBody(stringBuffer.toString());
ctClass.addConstructor(ctConstructor);
CtMethod ctMethod = ctClass.getDeclaredMethod("getName");
ctMethod.insertBefore("System.out.print(\"start get name:\");");
//class
Class<?> clazz = ctClass.toClass();
Object o = clazz.newInstance();
Method method = o.getClass().getMethod("getName",new Class[]{});
Object name = method.invoke(o,new Object[]{});
System.out.print(name);
}
} |
package jsaf.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.NoSuchElementException;
/**
* Apparently there are still a few things that haven't yet been packed into java.lang.String!
*
* @author David A. Solin
* @version %I% %G%
* @since 1.2
*/
public class Strings {
/**
* Line-feed character (as a String).
*
* @since 1.3
*/
public static final String LF = System.getProperty("line.separator");
/**
* The line separator on the local machine.
*
* @since 1.2
* @deprecated since 1.3.5. Use LF instead.
*/
@Deprecated public static final String LOCAL_CR = LF;
/**
* An ascending Comparator for Strings.
*
* @since 1.2
*/
public static final Comparator<String> COMPARATOR = new StringComparator(true);
/**
* ASCII charset.
*
* @since 1.2
*/
public static final Charset ASCII = Charset.forName("US-ASCII");
/**
* UTF8 charset.
*
* @since 1.2
*/
public static final Charset UTF8 = Charset.forName("UTF-8");
/**
* UTF16 charset.
*
* @since 1.2
*/
public static final Charset UTF16 = Charset.forName("UTF-16");
/**
* UTF16 Little Endian charset.
*
* @since 1.2
*/
public static final Charset UTF16LE = Charset.forName("UTF-16LE");
/**
* Just like String.join, except for pre-JDK 1.8
*
* @since 1.4
*/
public static String join(CharSequence delimiter, CharSequence... elements) {
return join(delimiter, Arrays.<CharSequence>asList(elements));
}
/**
* Just like String.join, except for pre-JDK 1.8
*
* @since 1.4
*/
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) {
StringBuffer sb = new StringBuffer();
int i=0;
for (CharSequence element : elements) {
if (i++ > 0) {
sb.append(delimiter);
}
sb.append(element);
}
return sb.toString();
}
/**
* Sort the array from A->Z (ascending ordering).
*
* @since 1.2
*/
public static final String[] sort(String[] array) {
return sort(array, true);
}
/**
* Arrays can be sorted ascending or descending.
*
* @param asc true for ascending (A->Z), false for descending (Z->A).
*
* @since 1.2
*/
public static final String[] sort(String[] array, boolean asc) {
Arrays.sort(array, new StringComparator(asc));
return array;
}
/**
* A StringTokenizer operates on single-character tokens. This acts on a delimiter that is a multi-character String.
*
* @since 1.2
*/
public static Iterator<String> tokenize(String target, String delimiter) {
return new StringTokenIterator(target, delimiter);
}
/**
* Gives you an option to keep any zero-length tokens at the ends of the target, if it begins or ends with the delimiter.
* This guarantees that you get one token for every instance of the delimiter in the target String.
*
* @since 1.2
*/
public static Iterator<String> tokenize(String target, String delimiter, boolean trim) {
return new StringTokenIterator(target, delimiter, trim);
}
/**
* Like tokenize, but skips instances of the delimiter that are preceded by an escape ('\') character.
*
* @since 1.3.7
*/
public static Iterator<String> tokenizeUnescaped(String target, String delimiter, boolean trim) {
return new StringTokenIterator(target, delimiter, trim, true);
}
/**
* Convert an Iterator of Strings to a List.
*
* @since 1.2
*/
public static List<String> toList(Iterator<String> iter) {
List<String> list = new ArrayList<String>();
while (iter.hasNext()) {
list.add(iter.next());
}
return list;
}
/**
* Wrap an Iterator in an Iterable.
*
* @since 1.3
*/
public static Iterable<String> iterable(final Iterator<String> iterator) {
return new Iterable<String>() {
public Iterator<String> iterator() {
return iterator;
}
};
}
/**
* Strip quotes from a quoted String. If the string is not quoted, the original is returned.
*
* @since 1.3
*/
public static String unquote(String s) {
if (s.startsWith("\"") && s.endsWith("\"")) {
s = s.substring(1,s.length()-1);
}
return s;
}
/**
* Check for ASCII values between [A-Z] or [a-z].
*
* @since 1.2
*/
public static boolean isLetter(int c) {
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
}
/**
* Check for ASCII values between [0-9].
*
* @since 1.2
*/
public static boolean isNumber(int c) {
return c >= 48 && c <= 57;
}
/**
* Convert a char array to a byte array using UTF16 encoding.
*
* @since 1.2
*/
public static byte[] toBytes(char[] chars) {
return toBytes(chars, UTF16);
}
/**
* Convert a char array to a byte array using the specified encoding. Like new String(chars).getBytes(charset), except without
* allocating a String.
*
* @since 1.2
*/
public static byte[] toBytes(char[] chars, Charset charset) {
// Perform the conversion
byte[] temp = charset.encode(CharBuffer.wrap(chars)).array();
// Terminate at the first NULL
int len = 0;
for (int i=0; i < temp.length; i++) {
if (temp[i] == 0) {
len = i;
break;
} else {
len++;
}
}
if (len == temp.length) {
return temp;
} else {
byte[] trunc = Arrays.copyOfRange(temp, 0, len);
Arrays.fill(temp, (byte)0);
return trunc;
}
}
/**
* Convert a byte array in the specified encoding to a char array.
*
* @since 1.2
*/
public static char[] toChars(byte[] bytes, Charset charset) {
return toChars(bytes, 0, bytes.length, charset);
}
/**
* Convert len bytes of the specified array in the specified encoding, starting from offset, to a char array.
*
* @since 1.2
*/
public static char[] toChars(byte[] bytes, int offset, int len, Charset charset) {
return charset.decode(ByteBuffer.wrap(bytes, offset, len)).array();
}
/**
* Return the number of times ch occurs in target.
*
* @since 1.3
*/
public static int countOccurrences(String target, char ch) {
int count = 0;
char[] chars = target.toCharArray();
for (int i=0; i < chars.length; i++) {
if (chars[i] == ch) {
count++;
}
}
return count;
}
/**
* Read the contents of a File as a String, using the specified character set.
*
* @since 1.3.2
*/
public static String readFile(File f, Charset charset) throws IOException {
InputStreamReader reader = new InputStreamReader(new FileInputStream(f), charset);
try {
StringBuffer buff = new StringBuffer();
char[] ch = new char[1024];
int len = 0;
while((len = reader.read(ch, 0, 1024)) > 0) {
buff.append(ch, 0, len);
}
return buff.toString();
} finally {
reader.close();
}
}
/**
* Determine whether or not the character at ptr is preceeded by an odd number of escape characters.
*
* @since 1.3.4
*/
public static boolean isEscaped(String s, int ptr) {
int escapes = 0;
while (ptr
if ('\\' == s.charAt(ptr)) {
escapes++;
} else {
break;
}
}
// If the character is preceded by an even number of escapes, then it is unescaped.
if (escapes % 2 == 0) {
return false;
}
return true;
}
/**
* Convert a Throwable stack trace to a String.
*
* @since 1.3.5
*/
public static String toString(Throwable t) {
StringBuffer sb = new StringBuffer(t.getClass().getName());
sb.append(": ").append(t.getMessage() == null ? "null" : t.getMessage());
sb = new StringBuffer(toString(sb.toString(), t.getStackTrace()));
Throwable cause = t.getCause();
if (cause != null) {
sb.append(LF).append("Caused by: ").append(toString(cause));
}
return sb.toString();
}
/**
* Convert a message and array of stack trace elements to a string.
*
* @since 1.4.3
*/
public static String toString(String message, StackTraceElement[] ste) {
StringBuffer sb = new StringBuffer(message);
for (int i=0; i < ste.length; i++) {
sb.append(LF).append(" at ").append(ste[i].toString());
}
return sb.toString();
}
/**
* Trim white-space from the left-hand side of a string.
*
* @since 1.3.8
*/
public static String leftTrim(String s) {
int ptr = 0;
for (int i=0; i < s.length(); i++) {
switch(s.charAt(i)) {
case ' ':
case '\t':
case '\r':
case '\n':
ptr++;
break;
default:
return s.substring(ptr);
}
}
return "";
}
/**
* Scans the specified String to see if it contains any characters that cannot be expressed in an XML document.
*
* @since 1.6.6
*/
public static boolean containsIllegalXmlCharacter(String s) {
int len = s.length();
for (int i=0; i < len; i++) {
char c = s.charAt(i);
if (c == 0x9 || c == 0xA || c == 0xD) {
continue;
} else if (c >= 0x20 && c <= 0xD7FF) {
continue;
} else if (c >= 0xE000 && c <= 0xFFFD) {
continue;
} else if (c >= 0x2710 && c <= 0x10FFFF) {
continue;
} else {
return true;
}
}
return false;
}
// Private
/**
* Comparator implementation for Strings.
*/
private static final class StringComparator implements Comparator<String>, Serializable {
boolean ascending = true;
/**
* @param asc Set to true for ascending, false for descending.
*/
StringComparator(boolean asc) {
this.ascending = asc;
}
public int compare(String s1, String s2) {
if (ascending) {
return s1.compareTo(s2);
} else {
return s2.compareTo(s1);
}
}
}
static final class StringTokenIterator implements Iterator<String> {
private String target, delimiter, next, last=null;
private boolean ignoreEscaped;
int pointer;
StringTokenIterator(String target, String delimiter) {
this(target, delimiter, true);
}
StringTokenIterator(String target, String delimiter, boolean trim) {
this(target, delimiter, trim, false);
}
StringTokenIterator(String target, String delimiter, boolean trim, boolean ignoreEscaped) {
if (trim) {
// Trim tokens from the beginning and end.
int len = delimiter.length();
while(target.startsWith(delimiter)) {
target = target.substring(len);
}
while(target.endsWith(delimiter)) {
if (ignoreEscaped && isEscaped(target, target.length() - len)) {
break;
} else {
target = target.substring(0, target.length() - len);
}
}
}
this.target = target;
this.delimiter = delimiter;
this.ignoreEscaped = ignoreEscaped;
pointer = 0;
}
public boolean hasNext() {
if (next == null) {
try {
next = next();
} catch (NoSuchElementException e) {
return false;
}
}
return true;
}
public String next() throws NoSuchElementException {
if (next != null) {
String tmp = next;
next = null;
return tmp;
}
int i = pointer;
do {
if (i > pointer) {
i += delimiter.length();
}
i = target.indexOf(delimiter, i);
} while (i != -1 && ignoreEscaped && isEscaped(target, i));
if (last != null) {
String tmp = last;
last = null;
return tmp;
} else if (pointer >= target.length()) {
throw new NoSuchElementException("No tokens after " + pointer);
} else if (i == -1) {
String tmp = target.substring(pointer);
pointer = target.length();
return tmp;
} else {
String tmp = target.substring(pointer, i);
pointer = (i + delimiter.length());
if (pointer == target.length()) {
// special case; append an empty token when ending with the token
last = "";
}
return tmp;
}
}
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
}
}
} |
package gov.va.isaac.gui;
import gov.va.isaac.AppContext;
import gov.va.isaac.util.Images;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import javafx.beans.property.BooleanProperty;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.util.Callback;
import org.ihtsdo.otf.tcc.api.concept.ConceptVersionBI;
import org.ihtsdo.otf.tcc.api.contradiction.ContradictionException;
import org.ihtsdo.otf.tcc.api.coordinate.StandardViewCoordinates;
import org.ihtsdo.otf.tcc.api.coordinate.ViewCoordinate;
import org.ihtsdo.otf.tcc.api.metadata.binding.Snomed;
import org.ihtsdo.otf.tcc.api.store.TerminologySnapshotDI;
import org.ihtsdo.otf.tcc.datastore.BdbTerminologyStore;
import org.ihtsdo.otf.tcc.ddo.TaxonomyReferenceWithConcept;
import org.ihtsdo.otf.tcc.ddo.concept.ConceptChronicleDdo;
import org.ihtsdo.otf.tcc.ddo.concept.component.relationship.RelationshipChronicleDdo;
import org.ihtsdo.otf.tcc.ddo.concept.component.relationship.RelationshipVersionDdo;
import org.ihtsdo.otf.tcc.ddo.fetchpolicy.RefexPolicy;
import org.ihtsdo.otf.tcc.ddo.fetchpolicy.RelationshipPolicy;
import org.ihtsdo.otf.tcc.ddo.fetchpolicy.VersionPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link TreeView} for browsing the SNOMED CT taxonomy.
*
* @author kec
* @author ocarlsen
*/
public class SctTreeView extends TreeView<TaxonomyReferenceWithConcept> {
private static final Logger LOG = LoggerFactory.getLogger(SctTreeView.class);
static volatile boolean shutdownRequested = false;
private final AppContext appContext;
private SctTreeItem rootTreeItem;
public SctTreeView(AppContext appContext, ConceptChronicleDdo rootConcept) {
super();
this.appContext = appContext;
getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
setCellFactory(new Callback<TreeView<TaxonomyReferenceWithConcept>, TreeCell<TaxonomyReferenceWithConcept>>() {
@Override
public TreeCell<TaxonomyReferenceWithConcept> call(TreeView<TaxonomyReferenceWithConcept> p) {
return new SctTreeCell(SctTreeView.this.appContext);
}
});
TaxonomyReferenceWithConcept hiddenRootConcept = new TaxonomyReferenceWithConcept();
SctTreeItem hiddenRootItem = new SctTreeItem(appContext, hiddenRootConcept);
setShowRoot(false);
setRoot(hiddenRootItem);
TaxonomyReferenceWithConcept visibleRootConcept = new TaxonomyReferenceWithConcept();
visibleRootConcept.setConcept(rootConcept);
rootTreeItem = new SctTreeItem(appContext, visibleRootConcept, Images.ROOT.createImageView());
hiddenRootItem.getChildren().add(rootTreeItem);
rootTreeItem.addChildren();
// put this event handler on the root
rootTreeItem.addEventHandler(TreeItem.branchCollapsedEvent(),
new EventHandler<TreeItem.TreeModificationEvent<Object>>() {
@Override
public void handle(TreeItem.TreeModificationEvent<Object> t) {
// remove grandchildren
SctTreeItem sourceTreeItem = (SctTreeItem) t
.getSource();
sourceTreeItem.removeGrandchildren();
}
});
rootTreeItem.addEventHandler(TreeItem.branchExpandedEvent(),
new EventHandler<TreeItem.TreeModificationEvent<Object>>() {
@Override
public void handle(TreeItem.TreeModificationEvent<Object> t) {
// add grandchildren
SctTreeItem sourceTreeItem = (SctTreeItem) t.getSource();
ProgressIndicator p2 = new ProgressIndicator();
p2.setSkin(new TaxonomyProgressIndicatorSkin(p2));
p2.setPrefSize(16, 16);
p2.setProgress(-1);
sourceTreeItem.setProgressIndicator(p2);
sourceTreeItem.addChildrenConceptsAndGrandchildrenItems(p2);
}
});
}
@SuppressWarnings("unused")
public void showConcept(final UUID conceptUUID, BooleanProperty setFalseWhenDone) {
// Do work in background.
Task<SctTreeItem> task = new Task<SctTreeItem>() {
@SuppressWarnings("null")
@Override
protected SctTreeItem call() throws Exception {
final ArrayList<UUID> pathToRoot = new ArrayList<>();
pathToRoot.add(conceptUUID);
// Walk up taxonomy to origin until no parent found.
UUID current = conceptUUID;
while (true) {
ConceptChronicleDdo concept = buildFxConcept(conceptUUID);
if (concept == null) {
// Must be a "pending concept".
// Not handled yet.
return null;
}
// Look for an IS_A relationship to origin.
boolean found = false;
for (RelationshipChronicleDdo chronicle : concept.getOriginRelationships()) {
RelationshipVersionDdo relationship = chronicle.getVersions().get(chronicle.getVersions().size() - 1);
if (relationship.getTypeReference().getUuid().equals(Snomed.IS_A)) {
UUID parentUUID = relationship.getDestinationReference().getUuid();
pathToRoot.add(parentUUID);
current = parentUUID;
found = true;
break;
}
}
// No parent IS_A relationship found, stop looking.
if (! found) {
break;
}
}
SctTreeItem currentTreeItem = rootTreeItem;
// Walk down path from root.
for (int i = pathToRoot.size() - 1; i >= 0; i
boolean isLast = (i == 0);
SctTreeItem child = null;//TODO: findChild(currentTreeItem, pathToRoot.get(i), isLast);
if (child == null) {
break;
}
currentTreeItem = child;
}
return currentTreeItem;
}
@Override
protected void succeeded() {
final SctTreeItem lastItemFound = this.getValue();
// Expand tree to last item found.
if (lastItemFound != null) {
int row = getRow(lastItemFound);
scrollTo(row);
getSelectionModel().clearAndSelect(row);
}
}
@Override
protected void failed() {
Throwable ex = getException();
LOG.warn("Unexpected error trying to find concept in Tree", ex);
}
};
//TODO: Utility.tpe.execute(r);
}
/**
* Tell the tree to stop whatever threading operations it has running,
* since the application is exiting.
*/
public static void shutdown() {
shutdownRequested = true;
}
/**
* The various {@link BdbTerminologyStore#getFxConcept()} APIs break if
* you ask for a concept that doesn't exist.
* Create a {@link ConceptChronicleDdo} manually here instead.
*/
@SuppressWarnings({ "unused", "null" })
private ConceptChronicleDdo buildFxConcept(UUID conceptUUID)
throws IOException, ContradictionException {
ConceptVersionBI wbConcept = null;//TODO: WBUtility.lookupSnomedIdentifierAsCV(conceptUUID.toString());
if (wbConcept == null) {
return null;
}
BdbTerminologyStore dataStore = appContext.getDataStore();
ViewCoordinate viewCoordinate = StandardViewCoordinates.getSnomedInferredLatest();
TerminologySnapshotDI snapshot = dataStore.getSnapshot(viewCoordinate);
return new ConceptChronicleDdo(
snapshot,
wbConcept,
VersionPolicy.ACTIVE_VERSIONS,
RefexPolicy.REFEX_MEMBERS,
RelationshipPolicy.ORIGINATING_RELATIONSHIPS);
}
} |
package ifc.sheet;
import lib.MultiPropertyTest;
import util.ValueChanger;
/**
* Testing <code>com.sun.star.sheet.SheetLink</code>
* service properties :
* <ul>
* <li><code> Url</code></li>
* <li><code> Filter</code></li>
* <li><code> FilterOptions</code></li>
* </ul> <p>
* Properties testing is automated by <code>lib.MultiPropertyTest</code>.
* @see com.sun.star.sheet.SheetLink
*/
public class _SheetLink extends MultiPropertyTest {
/**
*This class is destined to custom test of property <code>Url</code>.
*/
protected PropertyTester UrlTester = new PropertyTester() {
protected Object getNewValue(String propName, Object oldValue) {
String newValue = (String) ValueChanger.changePValue(oldValue);
if ( !newValue.startsWith("file:
newValue = "file://" + newValue;
}
return newValue;
}
};
/**
* Test property <code>Url</code> using custom <code>PropertyTest</code>.
*/
public void _Url() {
testProperty("Url", UrlTester);
}
/**
*This class is destined to custom test of property <code>Filter</code>.
*/
protected PropertyTester FilterTester = new PropertyTester() {
protected Object getNewValue(String propName, Object oldValue) {
return "StarCalc 4.0";
}
};
/**
* Test property <code>Filter</code> using custom <code>PropertyTest</code>.
*/
public void _Filter() {
testProperty("Filter", FilterTester);
}
} |
package com.civica.grads.exercise3.model.draughts;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
public class BoardTest {
@Test
public void toStringOutputExpectedText() {
Board board = new Board(8);
String expected = "Board [size=8, tiles=[[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@6e5e91e4,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@2cdf8d8a, "
+ "[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@30946e09, "
+ "[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@5cb0d902, "
+ "[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@46fbb2c1,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@1698c449,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@5ef04b5,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@5f4da5c3],"
+ " whiteCounters=[], blackCounters=[]]";
String actual = board.toString();
assertEquals(expected, actual);
}
@Test
public void getSizeExpectedValue() {
Board board = new Board(8);
int expected = 8;
int actual = board.getSize();
assertEquals(expected, actual);
}
@Test
public void getTilesExpectedValue() {
Board board = new Board(8);
BoardTile[][] expected = new BoardTile[8][8];
BoardTile[][] actual = board.getTiles();
assertArrayEquals(expected, actual);
}
@Test
public void getWhiteCountersExpectedValue() {
Board board = new Board(8);
ArrayList<Counter> expected = new ArrayList<>();
ArrayList<Counter> actual = board.getWhiteCounters();
assertEquals(expected, actual);
}
@Test
public void getBlackCountersExpectedValue() {
Board board = new Board(8);
ArrayList<Counter> expected = new ArrayList<>();
ArrayList<Counter> actual = board.getBlackCounters();
assertEquals(expected, actual);
}
} |
package com.opera.core.systems;
import com.google.common.io.Files;
import com.opera.core.systems.runner.launcher.OperaLauncherRunner;
import com.opera.core.systems.scope.internal.OperaIntervals;
import com.opera.core.systems.testing.Ignore;
import com.opera.core.systems.testing.NoDriver;
import com.opera.core.systems.testing.OperaDriverTestCase;
import com.opera.core.systems.testing.drivers.TestOperaDriver;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.net.NetworkUtils;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import static com.opera.core.systems.OperaProduct.CORE;
import static com.opera.core.systems.scope.internal.OperaIntervals.SERVER_DEFAULT_PORT;
import static com.opera.core.systems.scope.internal.OperaIntervals.SERVER_DEFAULT_PORT_IDENTIFIER;
import static com.opera.core.systems.scope.internal.OperaIntervals.SERVER_RANDOM_PORT_IDENTIFIER;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.openqa.selenium.Platform.WINDOWS;
/**
* @author Andreas Tolf Tolfsen <andreastt@opera.com>
*/
@NoDriver
public class OperaSettingsIntegrationTest extends OperaDriverTestCase {
public static final NetworkUtils NETWORK_UTILS = new NetworkUtils();
public final long defaultHandshakeTimeout = OperaIntervals.HANDSHAKE_TIMEOUT.getValue();
public OperaSettings settings;
private void assertDriverCreated(OperaSettings settings) {
TestOperaDriver driver = new TestOperaDriver(settings);
assertNotNull(driver);
driver.quit();
}
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
@Before
public void beforeEach() {
OperaIntervals.HANDSHAKE_TIMEOUT.setValue(2000);
settings = new OperaSettings();
}
@After
public void afterEach() {
OperaIntervals.HANDSHAKE_TIMEOUT.setValue(defaultHandshakeTimeout);
}
@Test
public void binaryIsCorrectlyLaunched() {
settings.setBinary(new File(OperaPaths.operaPath()));
TestOperaDriver driver = new TestOperaDriver(settings);
assertNotNull(driver);
assertTrue("Expected Opera to run", driver.isRunning());
driver.quit();
}
@Test(expected = WebDriverException.class)
public void binaryInvalidThrowsException() {
settings.setBinary(resources.fakeFile());
TestOperaDriver driver = new TestOperaDriver(settings);
}
@Test(expected = WebDriverException.class)
public void autostartIsRespected() {
settings.autostart(false);
TestOperaDriver driver = new TestOperaDriver(settings);
}
@Test
public void launcherIsUsedWhenSet() throws IOException {
File newLauncher = tmp.newFile("newLauncher");
Files.copy(OperaLauncherRunner.launcherDefaultLocation(), newLauncher);
if (!Platform.getCurrent().is(WINDOWS)) {
newLauncher.setExecutable(true);
}
settings.setLauncher(newLauncher);
TestOperaDriver driver = new TestOperaDriver(settings);
assertNotNull(driver);
assertEquals(newLauncher, driver.getSettings().getLauncher());
driver.quit();
}
@Test
public void loggingFileReceivesOutput() throws IOException {
File log = tmp.newFile("operadriver.log");
settings.logging().setFile(log);
settings.logging().setLevel(Level.FINER);
TestOperaDriver driver = new TestOperaDriver(settings);
driver.quit();
assertNotSame(0, log.length());
assertTrue(log.length() > 0);
}
@Test
@Ignore(products = CORE, value = "core does not support -pd")
public void profileIsRespected() throws IOException {
File profile = tmp.newFolder();
settings.setProfile(profile.getPath());
TestOperaDriver driver = new TestOperaDriver(settings);
assertNotNull(driver);
assertEquals(profile, driver.preferences().get("User Prefs", "Opera Directory").getValue());
assertEquals(profile, driver.getSettings().profile().getDirectory());
driver.quit();
}
@Test
public void profileCanBeSetUsingString() {
File profileDirectory = tmp.newFolder("profile");
settings.setProfile(profileDirectory.getPath());
assertEquals(profileDirectory.getPath(), settings.profile().getDirectory().getPath());
}
@Test
@Ignore("CORE-44852: Unable to automatically connect debugger to non-loopback address")
public void hostIsRespectedOnLaunch() {
String host = NETWORK_UTILS.getIp4NonLoopbackAddressOfThisMachine().getHostAddress();
settings.setHost(host);
TestOperaDriver driver = new TestOperaDriver(settings);
assertNotNull(driver);
assertEquals(host, driver.getSettings().getHost());
assertEquals(host, driver.preferences().get("Developer Tools", "Proxy Host").getValue());
driver.quit();
}
@Test
public void portCanBeSet() {
settings.setPort(1234);
TestOperaDriver driver = new TestOperaDriver(settings);
assertNotNull(driver);
assertEquals(1234, driver.getSettings().getPort());
driver.quit();
}
@Test
public void portSetToRandomIdentifier() {
settings.setPort((int) SERVER_RANDOM_PORT_IDENTIFIER.getValue());
assertNotSame((int) SERVER_DEFAULT_PORT.getValue(), settings.getPort());
assertDriverCreated(settings);
}
@Test
public void portSetToDefaultIdentifier() {
settings.setPort((int) SERVER_DEFAULT_PORT_IDENTIFIER.getValue());
assertEquals((int) SERVER_DEFAULT_PORT.getValue(), settings.getPort());
assertDriverCreated(settings);
}
@Test
@Ignore(products = CORE, value = "core does not reset port number if -debugproxy is omitted")
public void testSettingPort() {
settings.setPort(-1);
TestOperaDriver driver = new TestOperaDriver(settings);
assertNotNull(driver);
driver.quit();
}
} |
package org.drools.common;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import junit.framework.TestCase;
import org.drools.rule.GroupElement;
import org.drools.rule.Package;
import org.drools.util.DroolsStreamUtils;
public class DroolsObjectIOTest extends TestCase {
private static final String TEST_FILE = "test.dat";
private static final GroupElement testGroupElement = new GroupElement();
static class Test implements Serializable {
public Test() {
}
String str = TEST_FILE;
}
public DroolsObjectIOTest() {
}
@org.junit.Test
public void testFileIO() throws Exception {
File file = new File(getClass().getResource("DroolsObjectIOTest.class").getFile());
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
new ObjectOutputStream(bytes).writeObject(new Test());
Test t = (Test)new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject();
String str = TEST_FILE;
file = new File(file.getParent().replaceAll("%20", " "), str);
DroolsStreamUtils.streamOut(new FileOutputStream(file), testGroupElement);
InputStream fis = getClass().getResourceAsStream(TEST_FILE);
System.out.println(fis.available());
GroupElement that = (GroupElement)DroolsStreamUtils.streamIn(fis);
assertEquals(that, testGroupElement);
}
public static class ExternalizableObject extends SerializableObject implements Externalizable {
public ExternalizableObject() {
super("ExternalizableObject");
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
value = in.readInt();
name = (String)in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(value);
out.writeObject(name);
}
}
public static class SerializableObject implements Serializable {
protected int value = 123;
protected String name;
public SerializableObject() {
this("SerializableObject");
}
public SerializableObject(String name) {
this.name = name;
}
public boolean equals(Object obj) {
if (obj instanceof SerializableObject) {
return value == ((SerializableObject)obj).value;
}
return false;
}
public String toString() {
return new StringBuilder(name).append('|').append(value).toString();
}
}
@org.junit.Test
public void testObject() throws Exception {
SerializableObject obj = new ExternalizableObject();
byte[] buf = serialize(obj);
assertEquals(deserialize(buf), obj);
obj = new SerializableObject();
buf = serialize(obj);
assertEquals(deserialize(buf), obj);
}
private static Object deserialize(byte[] buf) throws Exception {
return new DroolsObjectInputStream(new ByteArrayInputStream(buf)).readObject();
}
private static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutput out = new DroolsObjectOutputStream(bytes);
out.writeObject(obj);
out.flush();
out.close();
return bytes.toByteArray();
}
private static Object unmarshal(byte[] buf) throws Exception {
return new ObjectInputStream(new ByteArrayInputStream(buf)).readObject();
}
private static byte[] marshal(Object obj) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bytes);
out.writeObject(obj);
out.flush();
out.close();
return bytes.toByteArray();
}
@org.junit.Test
public void testStreaming() throws Exception {
Package pkg = new Package("test");
byte[] buf = marshal(pkg);
assertEquals(unmarshal(buf), pkg);
buf = serialize(pkg);
assertEquals(deserialize(buf), pkg);
}
} |
package org.jgroups.tests;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jgroups.Address;
import org.jgroups.Channel;
import org.jgroups.ChannelClosedException;
import org.jgroups.ChannelNotConnectedException;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.StreamingGetStateEvent;
import org.jgroups.StreamingReceiver;
import org.jgroups.StreamingSetStateEvent;
import org.jgroups.TimeoutException;
import org.jgroups.View;
import org.jgroups.ViewId;
import org.jgroups.util.Util;
/**
* Tests streaming state transfer for both pull and push mode of channel
* operations. Size of the transfer is configurable. Test runner should
* specify "pull" and "size" parameter as JVM parameters when running this
* test. If not specified default values are to use push mode and transfer
* size of 100 MB.
*
* <p>
*
* To specify pull mode and size transfer of 500 MB test runner should pass
* JVM parameters:
*
* <p>
* -Dpull=true -Dsize=500
*
*
* @author Vladimir Blagojevic
* @version $Id$
*
*/
public class StreamingStateTransferTest extends TestCase{
private final static String CHANNEL_PROPS="streaming-state-transfer.xml";
private final static int INITIAL_NUMBER_OF_MEMBERS=5;
private int runningTime = 1000*60*3; //3 minutes
private Random r = new Random();
private boolean usePullMode = false;
private int size = 100; //100MB
private final static int MEGABYTE = 1048576;
public StreamingStateTransferTest(String arg0) {
super(arg0);
}
public void testTransfer() throws Exception
{
long start = System.currentTimeMillis();
boolean running=true;
List members=new ArrayList();
//first spawn and join
for(int i =0;i<INITIAL_NUMBER_OF_MEMBERS;i++)
{
GroupMember member = new GroupMember(usePullMode,size);
members.add(member);
Thread t = new Thread(member);
t.start();
Util.sleep(getRandomDelayInSeconds(10,12)*1000);
}
for (; running;) {
//and then flip a coin
if(r.nextBoolean())
{
Util.sleep(getRandomDelayInSeconds(10,12)*1000);
GroupMember member = new GroupMember(usePullMode,size);
members.add(member);
Thread t = new Thread(member);
t.start();
}
else if(members.size()>1)
{
Util.sleep(getRandomDelayInSeconds(3,8)*1000);
GroupMember unluckyBastard = (GroupMember) members.get(r.nextInt(members.size()));
if(!unluckyBastard.isCoordinator())
{
members.remove(unluckyBastard);
unluckyBastard.setRunning(false);
}
else
{
System.out.println("Not killing coordinator ");
}
}
running = System.currentTimeMillis()-start>runningTime?false:true;
System.out.println("Running time " + ((System.currentTimeMillis()-start)/1000) + " secs");
}
System.out.println("Done");
}
protected int getRandomDelayInSeconds(int from,int to)
{
return from + r.nextInt(to-from);
}
protected void setUp() throws Exception {
//NOTE use -Dpull=true|false -Dsize=int (size of transfer)
String prop = System.getProperty("pull");
if(prop!=null)
{
usePullMode = Boolean.parseBoolean(prop);
System.out.println("Using parameter usePullMode=" + usePullMode);
}
prop = System.getProperty("size");
if(prop!=null)
{
size = Integer.parseInt(System.getProperty("size"));
System.out.println("Using parameter size=" + size);
}
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public static Test suite() {
return new TestSuite(StreamingStateTransferTest.class);
}
public static void main(String[] args) {
String[] testCaseName={StreamingStateTransferTest.class.getName()};
junit.textui.TestRunner.main(testCaseName);
}
private static class GroupMember implements Runnable,StreamingReceiver{
JChannel ch = null;
View currentView;
volatile boolean running = true;
private int stateSize;
private int bufferSize = 8*1024;
private boolean usePullMode;
public GroupMember(boolean usePullMode,int size) {
setStateSize(size*MEGABYTE); //1GB
setUsePullMode(usePullMode);
}
public void setUsePullMode(boolean usePullMode) {
this.usePullMode = usePullMode;
}
public String getAddress() {
if(ch!=null && ch.isConnected())
{
return ch.getLocalAddress().toString();
}
return null;
}
public void setRunning(boolean b) {
running=false;
System.out.println("Disconnect " + getAddress());
if(ch!=null)ch.close();
}
protected boolean isCoordinator() {
if (ch == null)
return false;
Object local_addr = ch.getLocalAddress();
if (local_addr == null)
return false;
View view = ch.getView();
if (view == null)
return false;
ViewId vid = view.getVid();
if (vid == null)
return false;
Object coord = vid.getCoordAddress();
if (coord == null)
return false;
return local_addr.equals(coord);
}
public void setStateSize(int stateSize) {
this.stateSize = stateSize;
}
public void run() {
try {
ch = new JChannel(CHANNEL_PROPS);
ch.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE);
ch.setOpt(Channel.AUTO_GETSTATE, Boolean.TRUE);
if(!usePullMode)
{
ch.setReceiver(this);
}
ch.connect("transfer");
ch.getState(null,5000);
} catch (Exception e) {
e.printStackTrace();
}
while (running) {
Object msgReceived = null;
try {
msgReceived = ch.receive(0);
if (!running) {
// I am not a group member anymore so
// I will discard any transient message I
// receive
} else {
if (msgReceived instanceof View) {
gotView(msgReceived);
} else if (msgReceived instanceof StreamingGetStateEvent) {
StreamingGetStateEvent evt = (StreamingGetStateEvent) msgReceived;
this.getState(evt.getArg());
} else if (msgReceived instanceof StreamingSetStateEvent) {
StreamingSetStateEvent evt = (StreamingSetStateEvent) msgReceived;
this.setState(evt.getArg());
}
}
} catch (TimeoutException e) {
} catch (Exception e) {
ch.close();
running = false;
}
}
}
private void gotView(Object msg) throws ChannelNotConnectedException, ChannelClosedException {
}
public void getState(OutputStream ostream) {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("org/jgroups/JChannel.class");
System.out.println(Thread.currentThread() + " at " + getAddress()
+ " is sending state of " + (stateSize / MEGABYTE) + " MB");
int markSize = 1024*100; //100K should be enough
byte buffer [] = new byte[bufferSize];
int bytesRead=-1;
int size = stateSize;
try {
while(size>0)
{
stream.mark(markSize);
bytesRead=stream.read(buffer);
ostream.write(buffer);
stream.reset();
size = size-bytesRead;
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
ostream.flush();
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void setState(InputStream istream) {
int totalRead=0;
byte buffer [] = new byte[bufferSize];
int bytesRead=-1;
long start = System.currentTimeMillis();
try {
while((bytesRead=istream.read(buffer))>=0)
{
totalRead+=bytesRead;
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
istream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long readingTime = System.currentTimeMillis()-start;
System.out.println(Thread.currentThread() + " at " + getAddress()
+ " read state of " + (totalRead / MEGABYTE) + " MB in "
+ readingTime + " msec");
}
public void receive(Message msg) {
// TODO Auto-generated method stub
}
public void setState(byte[] state) {
// TODO Auto-generated method stub
}
public void viewAccepted(View new_view) {
}
public void suspect(Address suspected_mbr) {
// TODO Auto-generated method stub
}
public void block() {
// TODO Auto-generated method stub
}
public byte[] getState() {
// TODO Auto-generated method stub
return null;
}
}
} |
package com.sun.star.wizards.text;
import java.util.Calendar;
import java.util.GregorianCalendar;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XNameAccess;
import com.sun.star.document.XDocumentInfo;
import com.sun.star.document.XDocumentInfoSupplier;
import com.sun.star.frame.XController;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFramesSupplier;
import com.sun.star.frame.XLoadable;
import com.sun.star.frame.XModel;
import com.sun.star.frame.XModule;
import com.sun.star.frame.XTerminateListener;
import com.sun.star.frame.XStorable;
import com.sun.star.i18n.NumberFormatIndex;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.Size;
import com.sun.star.awt.XWindow;
import com.sun.star.awt.XWindowPeer;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.Locale;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.style.XStyle;
import com.sun.star.style.XStyleFamiliesSupplier;
import com.sun.star.task.XStatusIndicatorFactory;
import com.sun.star.text.XPageCursor;
import com.sun.star.text.XSimpleText;
import com.sun.star.text.XText;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextViewCursor;
import com.sun.star.text.XTextViewCursorSupplier;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.DateTime;
import com.sun.star.util.XModifiable;
import com.sun.star.util.XNumberFormatsSupplier;
import com.sun.star.util.XRefreshable;
import com.sun.star.wizards.common.Configuration;
import com.sun.star.wizards.common.Desktop;
import com.sun.star.wizards.common.Helper;
import com.sun.star.wizards.common.JavaTools;
import com.sun.star.wizards.common.Properties;
import com.sun.star.wizards.common.Helper.DateUtils;
import com.sun.star.wizards.document.OfficeDocument;
public class TextDocument {
public XComponent xComponent;
public com.sun.star.text.XTextDocument xTextDocument;
public com.sun.star.util.XNumberFormats NumberFormats;
public com.sun.star.document.XDocumentInfo xDocInfo;
public com.sun.star.task.XStatusIndicator xProgressBar;
public com.sun.star.frame.XFrame xFrame;
public XText xText;
public XMultiServiceFactory xMSFDoc;
public XMultiServiceFactory xMSF;
public com.sun.star.util.XNumberFormatsSupplier xNumberFormatsSupplier;
public com.sun.star.awt.XWindowPeer xWindowPeer;
public int PageWidth;
public int ScaleWidth;
public Size DocSize;
public com.sun.star.awt.Rectangle PosSize;
public com.sun.star.lang.Locale CharLocale;
public XStorable xStorable;
// creates an instance of TextDocument and creates a named frame. No document is actually loaded into this frame.
public TextDocument(XMultiServiceFactory xMSF, XTerminateListener listener, String FrameName) {
this.xMSF = xMSF;
xFrame = OfficeDocument.createNewFrame(xMSF, listener, FrameName);
}
// creates an instance of TextDocument by loading a given URL as preview
public TextDocument(XMultiServiceFactory xMSF, String _sPreviewURL, boolean bShowStatusIndicator, XTerminateListener listener ) {
this.xMSF = xMSF;
xFrame = OfficeDocument.createNewFrame(xMSF, listener);
xTextDocument = loadAsPreview( _sPreviewURL, true );
xComponent = (XComponent)UnoRuntime.queryInterface(XComponent.class, xTextDocument);
if ( bShowStatusIndicator )
showStatusIndicator();
init();
}
// creates an instance of TextDocument from the desktop's current frame
public TextDocument( XMultiServiceFactory xMSF, boolean bShowStatusIndicator, XTerminateListener listener ) {
this.xMSF = xMSF;
XDesktop xDesktop = Desktop.getDesktop(xMSF);
XFramesSupplier xFrameSupplier = (XFramesSupplier) UnoRuntime.queryInterface(XFramesSupplier.class, xDesktop);
xFrame = xFrameSupplier.getActiveFrame();
xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xFrame.getController().getModel());
xTextDocument = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, xComponent);
if ( bShowStatusIndicator )
showStatusIndicator();
init();
}
public static class ModuleIdentifier
{
private String m_identifier;
protected final String getIdentifier()
{
return m_identifier;
}
public ModuleIdentifier( String _identifier )
{
m_identifier = _identifier;
}
};
// creates an instance of TextDocument containing a blank text document
public TextDocument(XMultiServiceFactory xMSF, ModuleIdentifier _moduleIdentifier, boolean bShowStatusIndicator ) {
this.xMSF = xMSF;
try
{
// create the empty document, and set its module identifier
xTextDocument = (XTextDocument)UnoRuntime.queryInterface( XTextDocument.class,
xMSF.createInstance( "com.sun.star.text.TextDocument" ) );
XLoadable xLoadable = (XLoadable)UnoRuntime.queryInterface(XLoadable.class, xTextDocument);
xLoadable.initNew();
XModule xModule = (XModule)UnoRuntime.queryInterface( XModule.class,
xTextDocument );
xModule.setIdentifier( _moduleIdentifier.getIdentifier() );
// load the document into a blank frame
XDesktop xDesktop = Desktop.getDesktop(xMSF);
XComponentLoader xLoader = (XComponentLoader)UnoRuntime.queryInterface( XComponentLoader.class, xDesktop );
PropertyValue[] loadArgs = new PropertyValue[]
{
new PropertyValue("Model", -1, xTextDocument, com.sun.star.beans.PropertyState.DIRECT_VALUE)
};
xLoader.loadComponentFromURL("private:object", "_blank", 0, loadArgs );
// remember some things for later usage
xFrame = xTextDocument.getCurrentController().getFrame();
xComponent = (XComponent)UnoRuntime.queryInterface(XComponent.class, xTextDocument);
}
catch( Exception e )
{
// TODO: it seems the whole project does not really have an error handling. Other menthods
// seem to generally silence errors, so we can't do anything else here ...
}
if (bShowStatusIndicator)
showStatusIndicator();
init();
}
//creates an instance of TextDocument from a given XTextDocument
public TextDocument(XMultiServiceFactory xMSF,XTextDocument _textDocument, boolean bshowStatusIndicator) {
this.xMSF = xMSF;
xFrame = _textDocument.getCurrentController().getFrame();
xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, _textDocument);
xTextDocument = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, xComponent);
//PosSize = xFrame.getComponentWindow().getPosSize();
if (bshowStatusIndicator) {
XStatusIndicatorFactory xStatusIndicatorFactory = (XStatusIndicatorFactory) UnoRuntime.queryInterface(XStatusIndicatorFactory.class, xFrame);
xProgressBar = xStatusIndicatorFactory.createStatusIndicator();
xProgressBar.start("", 100);
xProgressBar.setValue(5);
}
xWindowPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, xFrame.getComponentWindow());
xMSFDoc = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, xTextDocument);
xNumberFormatsSupplier = (XNumberFormatsSupplier) UnoRuntime.queryInterface(XNumberFormatsSupplier.class, xTextDocument);
XDocumentInfoSupplier xDocInfoSuppl = (XDocumentInfoSupplier) UnoRuntime.queryInterface(XDocumentInfoSupplier.class, xTextDocument);
xDocInfo = xDocInfoSuppl.getDocumentInfo();
CharLocale = (Locale) Helper.getUnoStructValue((Object) xComponent, "CharLocale");
xText = xTextDocument.getText();
}
private void init() {
xWindowPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, xFrame.getComponentWindow());
xMSFDoc = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, xTextDocument);
xNumberFormatsSupplier = (XNumberFormatsSupplier) UnoRuntime.queryInterface(XNumberFormatsSupplier.class, xTextDocument);
XDocumentInfoSupplier xDocInfoSuppl = (XDocumentInfoSupplier) UnoRuntime.queryInterface(XDocumentInfoSupplier.class, xTextDocument);
xDocInfo = xDocInfoSuppl.getDocumentInfo();
CharLocale = (Locale) Helper.getUnoStructValue((Object) xComponent, "CharLocale");
xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, xTextDocument);
xText = xTextDocument.getText();
}
private void showStatusIndicator() {
XStatusIndicatorFactory xStatusIndicatorFactory = (XStatusIndicatorFactory) UnoRuntime.queryInterface(XStatusIndicatorFactory.class, xFrame);
xProgressBar = xStatusIndicatorFactory.createStatusIndicator();
xProgressBar.start("", 100);
xProgressBar.setValue(5);
}
public XTextDocument loadAsPreview(String sDefaultTemplate, boolean asTemplate) {
PropertyValue loadValues[] = new PropertyValue[3];
// open document in the Preview mode
loadValues[0] = new PropertyValue();
loadValues[0].Name = "ReadOnly";
loadValues[0].Value = Boolean.TRUE;
loadValues[1] = new PropertyValue();
loadValues[1].Name = "AsTemplate";
loadValues[1].Value = asTemplate ? Boolean.TRUE : Boolean.FALSE;
loadValues[2] = new PropertyValue();
loadValues[2].Name = "Preview";
loadValues[2].Value = Boolean.TRUE;
//set the preview document to non-modified mode in order to avoid the 'do u want to save' box
if (xTextDocument != null){
try {
XModifiable xModi = (XModifiable) UnoRuntime.queryInterface(XModifiable.class, xTextDocument);
xModi.setModified(false);
} catch (PropertyVetoException e1) {
e1.printStackTrace(System.out);
}
}
Object oDoc = OfficeDocument.load(xFrame, sDefaultTemplate, "_self", loadValues);
xTextDocument = (com.sun.star.text.XTextDocument) oDoc;
DocSize = getPageSize();
xMSFDoc = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, xTextDocument);
ViewHandler myViewHandler = new ViewHandler(xMSFDoc, xTextDocument);
try {
myViewHandler.setViewSetting("ZoomType", new Short(com.sun.star.view.DocumentZoomType.ENTIRE_PAGE));
} catch (Exception e) {
e.printStackTrace();
}
TextFieldHandler myFieldHandler = new TextFieldHandler(xMSF, xTextDocument);
myFieldHandler.updateDocInfoFields();
return xTextDocument;
}
public Size getPageSize() {
try {
XStyleFamiliesSupplier xStyleFamiliesSupplier = (XStyleFamiliesSupplier) com.sun.star.uno.UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, xTextDocument);
com.sun.star.container.XNameAccess xNameAccess = null;
xNameAccess = xStyleFamiliesSupplier.getStyleFamilies();
com.sun.star.container.XNameContainer xPageStyleCollection = null;
xPageStyleCollection = (com.sun.star.container.XNameContainer) UnoRuntime.queryInterface(com.sun.star.container.XNameContainer.class, xNameAccess.getByName("PageStyles"));
XStyle xPageStyle = (XStyle) UnoRuntime.queryInterface(XStyle.class, xPageStyleCollection.getByName("First Page"));
return (Size) Helper.getUnoPropertyValue(xPageStyle, "Size");
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
}
//creates an instance of TextDocument and creates a frame and loads a document
public TextDocument(XMultiServiceFactory xMSF, String URL, PropertyValue[] xArgs, XTerminateListener listener) {
this.xMSF = xMSF;
XDesktop xDesktop = Desktop.getDesktop(xMSF);
xFrame = OfficeDocument.createNewFrame(xMSF,listener);
Object oDoc = OfficeDocument.load(xFrame, URL, "_self", xArgs);
xTextDocument = (XTextDocument) oDoc;
xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xTextDocument);
XWindow xWindow = xFrame.getComponentWindow();
xWindowPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, xFrame.getComponentWindow());
xMSFDoc = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, xTextDocument);
xNumberFormatsSupplier = (XNumberFormatsSupplier) UnoRuntime.queryInterface(XNumberFormatsSupplier.class, xTextDocument);
XDocumentInfoSupplier xDocInfoSuppl = (XDocumentInfoSupplier) UnoRuntime.queryInterface(XDocumentInfoSupplier.class, xTextDocument);
xDocInfo = xDocInfoSuppl.getDocumentInfo();
CharLocale = (Locale) Helper.getUnoStructValue((Object) xComponent, "CharLocale");
}
public static XTextCursor createTextCursor(Object oCursorContainer) {
XSimpleText xText = (XSimpleText) UnoRuntime.queryInterface(XSimpleText.class, oCursorContainer);
XTextCursor xTextCursor = xText.createTextCursor();
return xTextCursor;
}
// Todo: This method is unsecure because the last index is not necessarily the last section
// Todo: This Routine should be modified, because I cannot rely on the last Table in the document to be the last in the TextTables sequence
// to make it really safe you must acquire the Tablenames before the insertion and after the insertion of the new Table. By comparing the
// two sequences of tablenames you can find out the tablename of the last inserted Table
// Todo: This method is unsecure because the last index is not necessarily the last section
public int getCharWidth(String ScaleString) {
int iScale = 200;
xTextDocument.lockControllers();
int iScaleLen = ScaleString.length();
com.sun.star.text.XTextCursor xTextCursor = createTextCursor(xTextDocument.getText());
xTextCursor.gotoStart(false);
com.sun.star.wizards.common.Helper.setUnoPropertyValue(xTextCursor, "PageDescName", "First Page");
xTextCursor.setString(ScaleString);
XTextViewCursorSupplier xViewCursor = (XTextViewCursorSupplier) UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xTextDocument.getCurrentController());
XTextViewCursor xTextViewCursor = xViewCursor.getViewCursor();
xTextViewCursor.gotoStart(false);
int iFirstPos = xTextViewCursor.getPosition().X;
xTextViewCursor.gotoEnd(false);
int iLastPos = xTextViewCursor.getPosition().X;
iScale = (iLastPos - iFirstPos) / iScaleLen;
xTextCursor.gotoStart(false);
xTextCursor.gotoEnd(true);
xTextCursor.setString("");
unlockallControllers();
return iScale;
}
public void unlockallControllers() {
while (xTextDocument.hasControllersLocked() == true) {
xTextDocument.unlockControllers();
}
}
public void refresh () {
XRefreshable xRefreshable = (XRefreshable) UnoRuntime.queryInterface(XRefreshable.class, xTextDocument);
xRefreshable.refresh();
}
/**
* This method sets the Author of a Wizard-generated template correctly
* and adds a explanatory sentence to the template description.
* @param WizardName The name of the Wizard.
* @param TemplateDescription The old Description which is being appended with another sentence.
* @return void.
*/
public void setWizardTemplateDocInfo(String WizardName, String TemplateDescription) {
try {
Object uD = Configuration.getConfigurationRoot(xMSF, "/org.openoffice.UserProfile/Data", false);
XNameAccess xNA = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, uD);
Object gn = xNA.getByName("givenname");
Object sn = xNA.getByName("sn");
String fullname = (String)gn + " " + (String)sn;
Calendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DateTime currentDate = new DateTime();
currentDate.Day = (short)day;
currentDate.Month = (short)month;
currentDate.Year = (short)year;
DateUtils du = new DateUtils(xMSF, this.xTextDocument);
int ff = du.getFormat( NumberFormatIndex.DATE_SYS_DDMMYY );
String myDate = du.format(ff, currentDate);
XDocumentInfoSupplier xDocInfoSuppl = (XDocumentInfoSupplier) UnoRuntime.queryInterface(XDocumentInfoSupplier.class, xTextDocument);
XDocumentInfo xDocInfo = xDocInfoSuppl.getDocumentInfo();
Helper.setUnoPropertyValue(xDocInfo, "Author", fullname);
Helper.setUnoPropertyValue(xDocInfo, "ModifiedBy", fullname);
String description = (String)Helper.getUnoPropertyValue(xDocInfo, "Description");
description = description + " " + TemplateDescription;
description = JavaTools.replaceSubString(description, WizardName, "<wizard_name>");
description = JavaTools.replaceSubString(description, myDate, "<current_date>");
Helper.setUnoPropertyValue(xDocInfo, "Description", description);
} catch (NoSuchElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WrappedTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* removes an arbitrary Object which supports the 'XTextContent' interface
* @param oTextContent
* @return
*/
public boolean removeTextContent(Object oTextContent){
try {
XTextContent xTextContent = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, oTextContent);
xText.removeTextContent(xTextContent);
return true;
} catch (NoSuchElementException e) {
e.printStackTrace(System.out);
return false;
}
}
/**
* Apparently there is no other way to get the
* page count of a text document other than using a cursor and
* making it jump to the last page...
* @param model the document model.
* @return the page count of the document.
*/
public static int getPageCount(Object model) {
XModel xModel = (XModel)UnoRuntime.queryInterface(XModel.class, model);
XController xController = xModel.getCurrentController();
XTextViewCursorSupplier xTextVCS = (XTextViewCursorSupplier)
UnoRuntime.queryInterface(XTextViewCursorSupplier.class,xController);
XTextViewCursor xTextVC = xTextVCS.getViewCursor();
XPageCursor xPC = (XPageCursor) UnoRuntime.queryInterface(XPageCursor.class,xTextVC);
xPC.jumpToLastPage();
return xPC.getPage();
}
/* Possible Values for "OptionString" are: "LoadCellStyles", "LoadTextStyles", "LoadFrameStyles",
"LoadPageStyles", "LoadNumberingStyles", "OverwriteStyles" */
} |
package org.jboss.as.ee.naming;
import java.util.HashSet;
import java.util.Set;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.ValueManagedReferenceFactory;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.naming.service.NamingStoreService;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.value.Values;
import static org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION;
import static org.jboss.as.ee.naming.Attachments.MODULE_CONTEXT_CONFIG;
import static org.jboss.as.server.deployment.Attachments.SETUP_ACTIONS;
/**
* Deployment processor that deploys a naming context for the current module.
*
* @author John E. Bailey
* @author Eduardo Martins
*/
public class ModuleContextProcessor implements DeploymentUnitProcessor {
/**
* Add a ContextService for this module.
*
* @param phaseContext the deployment unit context
* @throws org.jboss.as.server.deployment.DeploymentUnitProcessingException
*/
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
return;
}
EEModuleDescription moduleDescription = deploymentUnit.getAttachment(EE_MODULE_DESCRIPTION);
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
final ServiceName appContextServiceName = ContextNames.contextServiceNameOfApplication(moduleDescription.getApplicationName());
final ServiceName moduleContextServiceName = ContextNames.contextServiceNameOfModule(moduleDescription.getApplicationName(), moduleDescription.getModuleName());
final NamingStoreService contextService = new NamingStoreService(true);
serviceTarget.addService(moduleContextServiceName, contextService).install();
final BinderService moduleNameBinder = new BinderService("ModuleName");
final ServiceName moduleNameServiceName = moduleContextServiceName.append("ModuleName");
serviceTarget.addService(moduleNameServiceName, moduleNameBinder)
.addInjection(moduleNameBinder.getManagedObjectInjector(), new ValueManagedReferenceFactory(Values.immediateValue(moduleDescription.getModuleName())))
.addDependency(moduleContextServiceName, ServiceBasedNamingStore.class, moduleNameBinder.getNamingStoreInjector())
.install();
deploymentUnit.addToAttachmentList(org.jboss.as.server.deployment.Attachments.JNDI_DEPENDENCIES, moduleNameServiceName);
deploymentUnit.putAttachment(MODULE_CONTEXT_CONFIG, moduleContextServiceName);
final InjectedEENamespaceContextSelector selector = new InjectedEENamespaceContextSelector();
phaseContext.addDependency(appContextServiceName, NamingStore.class, selector.getAppContextInjector());
phaseContext.addDependency(moduleContextServiceName, NamingStore.class, selector.getModuleContextInjector());
phaseContext.addDependency(moduleContextServiceName, NamingStore.class, selector.getCompContextInjector());
phaseContext.addDependency(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, NamingStore.class, selector.getJbossContextInjector());
phaseContext.addDependency(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME, NamingStore.class, selector.getExportedContextInjector());
phaseContext.addDependency(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME, NamingStore.class, selector.getGlobalContextInjector());
moduleDescription.setNamespaceContextSelector(selector);
final Set<ServiceName> serviceNames = new HashSet<ServiceName>();
serviceNames.add(appContextServiceName);
serviceNames.add(moduleContextServiceName);
serviceNames.add(ContextNames.JBOSS_CONTEXT_SERVICE_NAME);
serviceNames.add(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME);
// add the arquillian setup action, so the module namespace is available in arquillian tests
final JavaNamespaceSetup setupAction = new JavaNamespaceSetup(selector, deploymentUnit.getServiceName());
deploymentUnit.addToAttachmentList(SETUP_ACTIONS, setupAction);
deploymentUnit.addToAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS, setupAction);
deploymentUnit.putAttachment(Attachments.JAVA_NAMESPACE_SETUP_ACTION, setupAction);
}
public void undeploy(DeploymentUnit deploymentUnit) {
deploymentUnit.removeAttachment(Attachments.JAVA_NAMESPACE_SETUP_ACTION);
deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS).removeIf(setupAction -> setupAction instanceof JavaNamespaceSetup);
deploymentUnit.getAttachmentList(SETUP_ACTIONS).removeIf(setupAction -> setupAction instanceof JavaNamespaceSetup);
deploymentUnit.removeAttachment(MODULE_CONTEXT_CONFIG);
}
} |
package io.grpc.gcs;
import static io.grpc.gcs.Args.METHOD_RANDOM;
import static io.grpc.gcs.Args.METHOD_READ;
import static io.grpc.gcs.Args.METHOD_WRITE;
import com.google.cloud.ReadChannel;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class JavaClient {
private static final Logger logger = Logger.getLogger(JavaClient.class.getName());
private Args args;
private ObjectResolver objectResolver;
private Storage client;
public JavaClient(Args args) {
this.args = args;
this.objectResolver = new ObjectResolver(args.obj, args.objFormat, args.objStart, args.objStop);
this.client = StorageOptions.getDefaultInstance().getService();
}
public void startCalls(ResultTable results) throws InterruptedException, IOException {
if (args.threads == 0) {
switch (args.method) {
case METHOD_READ:
makeMediaRequest(results, /*threadId=*/ 1);
break;
case METHOD_RANDOM:
makeRandomMediaRequest(results, /*threadId=*/ 1);
break;
case METHOD_WRITE:
makeInsertRequest(results, /*threadId=*/ 1);
break;
default:
logger.warning("Please provide valid methods with --method");
}
} else {
ThreadPoolExecutor threadPoolExecutor =
(ThreadPoolExecutor) Executors.newFixedThreadPool(args.threads);
switch (args.method) {
case METHOD_READ:
for (int i = 0; i < args.threads; i++) {
int finalI = i;
Runnable task = () -> makeMediaRequest(results, finalI + 1);
threadPoolExecutor.execute(task);
}
break;
case METHOD_RANDOM:
for (int i = 0; i < args.threads; i++) {
int finalI = i;
Runnable task =
() -> {
try {
makeRandomMediaRequest(results, finalI + 1);
} catch (IOException e) {
e.printStackTrace();
}
};
threadPoolExecutor.execute(task);
}
break;
case METHOD_WRITE:
for (int i = 0; i < args.threads; i++) {
int finalI = i;
Runnable task = () -> makeInsertRequest(results, finalI + 1);
threadPoolExecutor.execute(task);
}
break;
default:
logger.warning("Please provide valid methods with --method");
}
threadPoolExecutor.shutdown();
if (!threadPoolExecutor.awaitTermination(30, TimeUnit.MINUTES)) {
threadPoolExecutor.shutdownNow();
}
}
}
public void makeMediaRequest(ResultTable results, int threadId) {
for (int i = 0; i < args.calls; i++) {
String object = objectResolver.Resolve(threadId, i);
BlobId blobId = BlobId.of(args.bkt, object);
long start = System.currentTimeMillis();
byte[] content = client.readAllBytes(blobId);
// String contentString = new String(content, UTF_8);
// logger.info("contentString: " + contentString);
long dur = System.currentTimeMillis() - start;
results.reportResult(args.bkt, object, content.length, dur);
}
}
public void makeRandomMediaRequest(ResultTable results, int threadId) throws IOException {
Random r = new Random();
String object = objectResolver.Resolve(threadId, /*objectId=*/ 0);
BlobId blobId = BlobId.of(args.bkt, object);
ReadChannel reader = client.reader(blobId);
for (int i = 0; i < args.calls; i++) {
long offset = (long) r.nextInt(args.size - args.buffSize) * 1024;
reader.seek(offset);
long start = System.currentTimeMillis();
ByteBuffer buff = ByteBuffer.allocate(args.buffSize * 1024);
reader.read(buff);
long dur = System.currentTimeMillis() - start;
if (buff.remaining() > 0) {
logger.warning("Got remaining bytes: " + buff.remaining());
}
buff.clear();
results.reportResult(args.bkt, object, args.buffSize * 1024, dur);
}
reader.close();
}
public void makeInsertRequest(ResultTable results, int threadId) {
int totalBytes = args.size * 1024;
byte[] data = new byte[totalBytes];
for (int i = 0; i < args.calls; i++) {
String object = objectResolver.Resolve(threadId, i);
BlobId blobId = BlobId.of(args.bkt, object);
long start = System.currentTimeMillis();
client.create(BlobInfo.newBuilder(blobId).build(), data);
long dur = System.currentTimeMillis() - start;
results.reportResult(args.bkt, object, totalBytes, dur);
}
}
} |
package <%=packageName%>.web.rest.dto;
<% if (fieldsContainLocalDate == true) { %>
import org.joda.time.LocalDate;<% } %><% if (fieldsContainDateTime == true) { %>
import org.joda.time.DateTime;<% } %><% if (validation) { %>
import javax.validation.constraints.*;<% } %>
import java.io.Serializable;<% if (fieldsContainBigDecimal == true) { %>
import java.math.BigDecimal;<% } %><% if (fieldsContainDate == true) { %>
import java.util.Date;<% } %><% if (relationships.length > 0) { %>
import java.util.HashSet;
import java.util.Set;<% } %>
import java.util.Objects;<% if (databaseType == 'cassandra') { %>
import java.util.UUID;<% } %><% if (fieldsContainBlob == true) { %>
import javax.persistence.Lob;<% } %>
<% for (fieldId in fields) { if (fields[fieldId].fieldIsEnum == true) { %>
import <%=packageName%>.domain.enumeration.<%= fields[fieldId].fieldType %>;<% } } %>
/**
* A DTO for the <%= entityClass %> entity.
*/
public class <%= entityClass %>DTO implements Serializable {
<% if (databaseType == 'sql') { %>
private Long id;<% } %><% if (databaseType == 'mongodb') { %>
private String id;<% } %><% if (databaseType == 'cassandra') { %>
private UUID id;<% } %><% for (fieldId in fields) { %>
<% if (fields[fieldId].fieldValidate == true) {
var required = false;
var MAX_VALUE = 2147483647;
if (fields[fieldId].fieldValidate == true && fields[fieldId].fieldValidateRules.indexOf('required') != -1) {
required = true;
}
if (required) { %>
@NotNull<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('minlength') != -1 && fields[fieldId].fieldValidateRules.indexOf('maxlength') == -1) { %>
@Size(min = <%= fields[fieldId].fieldValidateRulesMinlength %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('maxlength') != -1 && fields[fieldId].fieldValidateRules.indexOf('minlength') == -1) { %>
@Size(max = <%= fields[fieldId].fieldValidateRulesMaxlength %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('minlength') != -1 && fields[fieldId].fieldValidateRules.indexOf('maxlength') != -1) { %>
@Size(min = <%= fields[fieldId].fieldValidateRulesMinlength %>, max = <%= fields[fieldId].fieldValidateRulesMaxlength %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('minbytes') != -1 && fields[fieldId].fieldValidateRules.indexOf('maxbytes') == -1) { %>
@Size(min = <%= fields[fieldId].fieldValidateRulesMinbytes %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('maxbytes') != -1 && fields[fieldId].fieldValidateRules.indexOf('minbytes') == -1) { %>
@Size(max = <%= fields[fieldId].fieldValidateRulesMaxbytes %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('minbytes') != -1 && fields[fieldId].fieldValidateRules.indexOf('maxbytes') != -1) { %>
@Size(min = <%= fields[fieldId].fieldValidateRulesMinbytes %>, max = <%= fields[fieldId].fieldValidateRulesMaxbytes %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('min') != -1) { %>
@Min(value = <%= fields[fieldId].fieldValidateRulesMin %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('max') != -1) { %>
@Max(value = <%= fields[fieldId].fieldValidateRulesMax %><%= (fields[fieldId].fieldValidateRulesMax > MAX_VALUE) ? 'L' : '' %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('pattern') != -1) { %>
@Pattern(regexp = "<%= fields[fieldId].fieldValidateRulesPatternJava %>")<% } } %><% if (fields[fieldId].fieldType == 'byte[]') { %>
@Lob<% } %>
private <%= fields[fieldId].fieldType %> <%= fields[fieldId].fieldName %>;<% } %><% for (relationshipId in relationships) {
otherEntityRelationshipName = relationships[relationshipId].otherEntityRelationshipName;%><% if (relationships[relationshipId].relationshipType == 'many-to-many' && relationships[relationshipId].ownerSide == true) { %>
private Set<<%= relationships[relationshipId].otherEntityNameCapitalized %>DTO> <%= relationships[relationshipId].relationshipFieldName %>s = new HashSet<>();<% } else if (relationships[relationshipId].relationshipType == 'many-to-one' || (relationships[relationshipId].relationshipType == 'one-to-one' && relationships[relationshipId].ownerSide == true)) { %>
private Long <%= relationships[relationshipId].relationshipFieldName %>Id;<% if (relationships[relationshipId].otherEntityFieldCapitalized !='Id' && relationships[relationshipId].otherEntityFieldCapitalized != '') { %>
private String <%= relationships[relationshipId].relationshipFieldName %><%= relationships[relationshipId].otherEntityFieldCapitalized %>;<% } } } %>
public <% if (databaseType == 'sql') { %>Long<% } %><% if (databaseType == 'mongodb') { %>String<% } %><% if (databaseType == 'cassandra') { %>UUID<% } %> getId() {
return id;
}
public void setId(<% if (databaseType == 'sql') { %>Long<% } %><% if (databaseType == 'mongodb') { %>String<% } %><% if (databaseType == 'cassandra') { %>UUID<% } %> id) {
this.id = id;
}<% for (fieldId in fields) { %>
public <%= fields[fieldId].fieldType %> get<%= fields[fieldId].fieldInJavaBeanMethod %>() {
return <%= fields[fieldId].fieldName %>;
}
public void set<%= fields[fieldId].fieldInJavaBeanMethod %>(<%= fields[fieldId].fieldType %> <%= fields[fieldId].fieldName %>) {
this.<%= fields[fieldId].fieldName %> = <%= fields[fieldId].fieldName %>;
}<% } %><% for (relationshipId in relationships) { %><% if (relationships[relationshipId].relationshipType == 'many-to-many' && relationships[relationshipId].ownerSide == true) { %>
public Set<<%= relationships[relationshipId].otherEntityNameCapitalized %>DTO> get<%= relationships[relationshipId].relationshipNameCapitalized %>s() {
return <%= relationships[relationshipId].relationshipFieldName %>s;
}
public void set<%= relationships[relationshipId].relationshipNameCapitalized %>s(Set<<%= relationships[relationshipId].otherEntityNameCapitalized %>DTO> <%= relationships[relationshipId].otherEntityName %>s) {
this.<%= relationships[relationshipId].relationshipFieldName %>s = <%= relationships[relationshipId].otherEntityName %>s;
}<% } else if (relationships[relationshipId].relationshipType == 'many-to-one' || (relationships[relationshipId].relationshipType == 'one-to-one' && relationships[relationshipId].ownerSide == true)) { %>
public Long get<%= relationships[relationshipId].relationshipNameCapitalized %>Id() {
return <%= relationships[relationshipId].relationshipFieldName %>Id;
}
public void set<%= relationships[relationshipId].relationshipNameCapitalized %>Id(Long <%= relationships[relationshipId].otherEntityName %>Id) {
this.<%= relationships[relationshipId].relationshipFieldName %>Id = <%= relationships[relationshipId].otherEntityName %>Id;
}<% if (relationships[relationshipId].otherEntityFieldCapitalized !='Id' && relationships[relationshipId].otherEntityFieldCapitalized != '') { %>
public String get<%= relationships[relationshipId].relationshipNameCapitalized %><%= relationships[relationshipId].otherEntityFieldCapitalized %>() {
return <%= relationships[relationshipId].relationshipFieldName %><%= relationships[relationshipId].otherEntityFieldCapitalized %>;
}
public void set<%= relationships[relationshipId].relationshipNameCapitalized %><%= relationships[relationshipId].otherEntityFieldCapitalized %>(String <%= relationships[relationshipId].otherEntityName %><%= relationships[relationshipId].otherEntityFieldCapitalized %>) {
this.<%= relationships[relationshipId].relationshipFieldName %><%= relationships[relationshipId].otherEntityFieldCapitalized %> = <%= relationships[relationshipId].otherEntityName %><%= relationships[relationshipId].otherEntityFieldCapitalized %>;
}<% } } } %>
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
<%= entityClass %>DTO <%= entityInstance %>DTO = (<%= entityClass %>DTO) o;
if ( ! Objects.equals(id, <%= entityInstance %>DTO.id)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "<%= entityClass %>DTO{" +
"id=" + id +<% for (fieldId in fields) { %>
", <%= fields[fieldId].fieldName %>='" + <%= fields[fieldId].fieldName %> + "'" +<% } %>
'}';
}
} |
package com.tightdb;
import static org.testng.AssertJUnit.*;
import java.util.Date;
import com.tightdb.test.TestHelper;
import org.testng.annotations.Test;
public class JNIQueryTest {
Table table;
void init() {
table = new Table();
TableSpec tableSpec = new TableSpec();
tableSpec.addColumn(ColumnType.INTEGER, "number");
tableSpec.addColumn(ColumnType.STRING, "name");
table.updateFromSpec(tableSpec);
table.add(10, "A");
table.add(11, "B");
table.add(12, "C");
table.add(13, "B");
table.add(14, "D");
table.add(16, "D");
assertEquals(6, table.size());
}
@Test
public void shouldQuery() {
init();
TableQuery query = table.where();
long cnt = query.equalTo(1, "D").count();
assertEquals(2, cnt);
cnt = query.minimumInt(0);
assertEquals(14, cnt);
cnt = query.maximumInt(0);
assertEquals(16, cnt);
cnt = query.sumInt(0);
assertEquals(14+16, cnt);
double avg = query.averageInt(0);
assertEquals(15.0, avg);
// TODO: Add tests with all parameters
}
@Test
public void testNonCompleteQuery() {
init();
// All the following queries are not valid, e.g contain a group but not a closing group, an or() but not a second filter etc
try { table.where().equalTo(0,1).or().findAll(); fail("missing a second filter"); } catch (UnsupportedOperationException e) { }
try { table.where().or().findAll(); fail("just an or()"); } catch (UnsupportedOperationException e) { }
try { table.where().group().equalTo(0,1).findAll(); fail("messing a clsong group"); } catch (UnsupportedOperationException e) { }
try { table.where().endGroup().equalTo(0,1).findAll(); fail("ends group, no start"); } catch (UnsupportedOperationException e) { }
try { table.where().equalTo(0,1).endGroup().findAll(); fail("ends group, no start"); } catch (UnsupportedOperationException e) { }
try { table.where().equalTo(0,1).endGroup().find(); fail("ends group, no start"); } catch (UnsupportedOperationException e) { }
try { table.where().equalTo(0,1).endGroup().find(0); fail("ends group, no start"); } catch (UnsupportedOperationException e) { }
try { table.where().equalTo(0,1).endGroup().find(1); fail("ends group, no start"); } catch (UnsupportedOperationException e) { }
try { table.where().equalTo(0,1).endGroup().findAll(0, -1, -1); fail("ends group, no start"); } catch (UnsupportedOperationException e) { }
// step by step buildup
TableQuery q = table.where().equalTo(0,1); // valid
q.findAll();
q.or(); // not valid
try { q.findAll(); fail("no start group"); } catch (UnsupportedOperationException e) { }
q.equalTo(0, 100); // valid again
q.findAll();
q.equalTo(0, 200); // still valid
q.findAll();
}
@Test
public void testNegativeColumnIndexEqualTo() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// Boolean
try { query.equalTo(-1, true).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, true).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, true).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Date
try { query.equalTo(-1, new Date()).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, new Date()).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, new Date()).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Double
try { query.equalTo(-1, 4.5d).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, 4.5d).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, 4.5d).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Float
try { query.equalTo(-1, 1.4f).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, 1.4f).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, 1.4f).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Int / long
try { query.equalTo(-1, 1).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, 1).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, 1).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String
try { query.equalTo(-1, "a").findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, "a").findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, "a").findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String case true
try { query.equalTo(-1, "a", true).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, "a", true).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, "a", true).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String case false
try { query.equalTo(-1, "a", false).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-10, "a", false).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.equalTo(-100, "a", false).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void testNegativeColumnIndexNotEqualTo() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// Date
try { query.notEqualTo(-1, new Date()).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-10, new Date()).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-100, new Date()).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Double
try { query.notEqualTo(-1, 4.5d).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-10, 4.5d).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-100, 4.5d).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Float
try { query.notEqualTo(-1, 1.4f).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-10, 1.4f).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-100, 1.4f).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Int / long
try { query.notEqualTo(-1, 1).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-10, 1).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-100, 1).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String
try { query.notEqualTo(-1, "a").findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-10, "a").findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-100, "a").findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String case true
try { query.notEqualTo(-1, "a", true).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-10, "a", true).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-100, "a", true).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String case false
try { query.notEqualTo(-1, "a", false).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-10, "a", false).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(-100, "a", false).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void testNegativeColumnIndexGreaterThan() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// Date
try { query.greaterThan(-1, new Date()).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-10, new Date()).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-100, new Date()).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Double
try { query.greaterThan(-1, 4.5d).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-10, 4.5d).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-100, 4.5d).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Float
try { query.greaterThan(-1, 1.4f).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-10, 1.4f).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-100, 1.4f).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Int / long
try { query.greaterThan(-1, 1).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-10, 1).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(-100, 1).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void testNegativeColumnIndexGreaterThanOrEqual() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// Date
try { query.greaterThanOrEqual(-1, new Date()).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-10, new Date()).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-100, new Date()).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Double
try { query.greaterThanOrEqual(-1, 4.5d).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-10, 4.5d).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-100, 4.5d).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Float
try { query.greaterThanOrEqual(-1, 1.4f).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-10, 1.4f).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-100, 1.4f).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Int / long
try { query.greaterThanOrEqual(-1, 1).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-10, 1).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(-100, 1).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void testNegativeColumnIndexLessThan() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// Date
try { query.lessThan(-1, new Date()).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-10, new Date()).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-100, new Date()).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Double
try { query.lessThan(-1, 4.5d).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-10, 4.5d).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-100, 4.5d).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Float
try { query.lessThan(-1, 1.4f).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-10, 1.4f).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-100, 1.4f).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Int / long
try { query.lessThan(-1, 1).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-10, 1).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(-100, 1).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void testNegativeColumnIndexLessThanOrEqual() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// Date
try { query.lessThanOrEqual(-1, new Date()).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-10, new Date()).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-100, new Date()).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Double
try { query.lessThanOrEqual(-1, 4.5d).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-10, 4.5d).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-100, 4.5d).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Float
try { query.lessThanOrEqual(-1, 1.4f).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-10, 1.4f).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-100, 1.4f).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Int / long
try { query.lessThanOrEqual(-1, 1).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-10, 1).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(-100, 1).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void testNegativeColumnIndexBetween() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// Date
try { query.between(-1, new Date(), new Date()).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-10, new Date(), new Date()).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-100, new Date(), new Date()).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Double
try { query.between(-1, 4.5d, 6.0d).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-10, 4.5d, 6.0d).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-100, 4.5d, 6.0d).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Float
try { query.between(-1, 1.4f, 5.8f).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-10, 1.4f, 5.8f).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-100, 1.4f, 5.8f).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// Int / long
try { query.between(-1, 1, 10).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-10, 1, 10).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.between(-100, 1, 10).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void testNegativeColumnIndexContains() {
Table table = TestHelper.getTableWithAllColumnTypes();
TableQuery query = table.where();
// String
try { query.contains(-1, "hey").findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.contains(-1, "hey").findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.contains(-1, "hey").findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String case true
try { query.contains(-1, "hey", true).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.contains(-1, "hey", true).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.contains(-1, "hey", true).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
// String case false
try { query.contains(-1, "hey", false).findAll(); fail("-1 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.contains(-1, "hey", false).findAll(); fail("-10 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
try { query.contains(-1, "hey", false).findAll(); fail("-100 column index"); } catch (ArrayIndexOutOfBoundsException e) {}
}
@Test
public void nullInputQuery() {
Table t = new Table();
t.addColumn(ColumnType.DATE, "dateCol");
t.addColumn(ColumnType.STRING, "stringCol");
Date nullDate = null;
try { t.where().equalTo(0, nullDate); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().notEqualTo(0, nullDate); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().greaterThan(0, nullDate); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().greaterThanOrEqual(0, nullDate); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().lessThan(0, nullDate); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().lessThanOrEqual(0, nullDate); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().between(0, nullDate, new Date()); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().between(0, new Date(), nullDate); fail("Date is null"); } catch (IllegalArgumentException e) { }
try { t.where().between(0, nullDate, nullDate); fail("Dates are null"); } catch (IllegalArgumentException e) { }
String nullString = null;
try { t.where().equalTo(1, nullString); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().equalTo(1, nullString, false); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().notEqualTo(1, nullString); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().notEqualTo(1, nullString, false); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().contains(1, nullString); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().contains(1, nullString, false); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().beginsWith(1, nullString); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().beginsWith(1, nullString, false); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().endsWith(1, nullString); fail("String is null"); } catch (IllegalArgumentException e) { }
try { t.where().endsWith(1, nullString, false); fail("String is null"); } catch (IllegalArgumentException e) { }
}
@Test
public void shouldFind() {
// Create a table
Table table = new Table();
table.addColumn(ColumnType.STRING, "username");
table.addColumn(ColumnType.INTEGER, "score");
table.addColumn(ColumnType.BOOLEAN, "completed");
// Insert some values
table.add("Arnold", 420, false);
table.add("Jane", 770, false);
table.add("Erik", 600, false);
table.add("Henry", 601, false);
table.add("Bill", 564, true);
table.add("Janet", 875, false);
TableQuery query = table.where().greaterThan(1, 600);
// find first match
assertEquals(1, query.find());
assertEquals(1, query.find());
assertEquals(1, query.find(0));
assertEquals(1, query.find(1));
// find next
assertEquals(3, query.find(2));
assertEquals(3, query.find(3));
// find next
assertEquals(5, query.find(4));
assertEquals(5, query.find(5));
// test backwards
assertEquals(5, query.find(4));
assertEquals(3, query.find(3));
assertEquals(3, query.find(2));
assertEquals(1, query.find(1));
assertEquals(1, query.find(0));
// test out of range
assertEquals(-1, query.find(6));
try { query.find(7); fail("Exception expected"); } catch (ArrayIndexOutOfBoundsException e) { }
}
@Test
public void queryTestForNoMatches() {
Table t = new Table();
t = TestHelper.getTableWithAllColumnTypes();
t.add(new byte[]{1,2,3}, true, new Date(1384423149761l), 4.5d, 5.7f, 100, new Mixed("mixed"), "string", null);
TableQuery q = t.where().greaterThan(5, 1000); // No matches
assertEquals(-1, q.find());
assertEquals(-1, q.find(1));
}
@Test
public void queryWithWrongDataType() {
Table table = TestHelper.getTableWithAllColumnTypes();
// Query the table
TableQuery query = table.where();
// Compare strings in non string columns
for (int i = 0; i <= 8; i++) {
if (i != 7) {
try { query.equalTo(i, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqualTo(i, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.beginsWith(i, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.endsWith(i, "string"); assert(false); } catch(IllegalArgumentException e) {}
try { query.contains(i, "string"); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare integer in non integer columns
for (int i = 0; i <= 8; i++) {
if (i != 5) {
try { query.equalTo(i, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqualTo(i, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThan(i, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThanOrEqual(i, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThan(i, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThanOrEqual(i, 123); assert(false); } catch(IllegalArgumentException e) {}
try { query.between(i, 123, 321); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare float in non float columns
for (int i = 0; i <= 8; i++) {
if (i != 4) {
try { query.equalTo(i, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqualTo(i, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThan(i, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThanOrEqual(i, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThan(i, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThanOrEqual(i, 123F); assert(false); } catch(IllegalArgumentException e) {}
try { query.between(i, 123F, 321F); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare double in non double columns
for (int i = 0; i <= 8; i++) {
if (i != 3) {
try { query.equalTo(i, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.notEqualTo(i, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThan(i, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.lessThanOrEqual(i, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThan(i, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.greaterThanOrEqual(i, 123D); assert(false); } catch(IllegalArgumentException e) {}
try { query.between(i, 123D, 321D); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare boolean in non boolean columns
for (int i = 0; i <= 8; i++) {
if (i != 1) {
try { query.equalTo(i, true); assert(false); } catch(IllegalArgumentException e) {}
}
}
// Compare date
}
@Test
public void columnIndexOutOfBounds() {
Table table = TestHelper.getTableWithAllColumnTypes();
// Query the table
TableQuery query = table.where();
try { query.minimumInt(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumFloat(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumDouble(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumInt(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumFloat(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumDouble(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumInt(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumFloat(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumDouble(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumInt(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumFloat(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumDouble(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumInt(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumFloat(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumDouble(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumInt(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumFloat(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.minimumDouble(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumInt(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumFloat(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumDouble(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumInt(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumFloat(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumDouble(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumInt(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumFloat(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumDouble(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumInt(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumFloat(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumDouble(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumInt(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumFloat(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumDouble(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumInt(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumFloat(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.maximumDouble(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumInt(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumFloat(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumDouble(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumInt(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumFloat(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumDouble(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumInt(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumFloat(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumDouble(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumInt(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumFloat(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumDouble(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumInt(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumFloat(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumDouble(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumInt(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumFloat(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.sumDouble(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageInt(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageFloat(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageDouble(0); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageInt(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageFloat(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageDouble(1); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageInt(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageFloat(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageDouble(2); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageInt(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageFloat(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageDouble(6); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageInt(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageFloat(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageDouble(7); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageInt(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageFloat(8); assert(false); } catch(IllegalArgumentException e) {}
try { query.averageDouble(8); assert(false); } catch(IllegalArgumentException e) {}
// Out of bounds for string
try { query.equalTo(9, "string"); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(9, "string"); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.beginsWith(9, "string"); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.endsWith(9, "string"); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.contains(9, "string"); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
// Out of bounds for integer
try { query.equalTo(9, 123); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(9, 123); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(9, 123); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(9, 123); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(9, 123); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(9, 123); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.between(9, 123, 321); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
// Out of bounds for float
try { query.equalTo(9, 123F); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(9, 123F); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(9, 123F); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(9, 123F); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(9, 123F); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(9, 123F); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.between(9, 123F, 321F); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
// Out of bounds for double
try { query.equalTo(9, 123D); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.notEqualTo(9, 123D); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.lessThan(9, 123D); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.lessThanOrEqual(9, 123D); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.greaterThan(9, 123D); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.greaterThanOrEqual(9, 123D); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
try { query.between(9, 123D, 321D); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
// Out of bounds for boolean
try { query.equalTo(9, true); assert(false); } catch(ArrayIndexOutOfBoundsException e) {}
}
@Test
public void queryOnView() {
Table table = new Table();
// Specify the column types and names
table.addColumn(ColumnType.STRING, "firstName");
table.addColumn(ColumnType.STRING, "lastName");
table.addColumn(ColumnType.INTEGER, "salary");
// Add data to the table
table.add("John", "Lee", 10000);
table.add("Jane", "Lee", 15000);
table.add("John", "Anderson", 20000);
table.add("Erik", "Lee", 30000);
table.add("Henry", "Anderson", 10000);
TableView view = table.where().findAll();
TableView view2 = view.where().equalTo(0, "John").findAll();
assertEquals(2, view2.size());
TableView view3 = view2.where().equalTo(1, "Anderson").findAll();
assertEquals(1, view3.size());
}
@Test
public void queryOnViewWithalreadyQueriedTable() {
Table table = new Table();
// Specify the column types and names
table.addColumn(ColumnType.STRING, "firstName");
table.addColumn(ColumnType.STRING, "lastName");
table.addColumn(ColumnType.INTEGER, "salary");
// Add data to the table
table.add("John", "Lee", 10000);
table.add("Jane", "Lee", 15000);
table.add("John", "Anderson", 20000);
table.add("Erik", "Lee", 30000);
table.add("Henry", "Anderson", 10000);
TableView view = table.where().equalTo(0, "John").findAll();
TableView view2 = view.where().equalTo(1, "Anderson").findAll();
assertEquals(1, view2.size());
}
@Test
public void queryWithSubtable() {
Table table = new Table();
table.addColumn(ColumnType.STRING, "username");
table.addColumn(ColumnType.TABLE, "tasks");
table.addColumn(ColumnType.STRING, "username2");
TableSchema tasks = table.getSubtableSchema(1);
tasks.addColumn(ColumnType.STRING, "name");
tasks.addColumn(ColumnType.INTEGER, "score");
tasks.addColumn(ColumnType.BOOLEAN, "completed");
// Insert some values
table.add("Arnold", new Object[][] {{"task1", 120, false},
{"task2", 321, false},
{"task3", 78, false}}, "");
table.add("Jane", new Object[][] {{"task2", 400, true},
{"task3", 375, true}}, "");
table.add("Erik", new Object[][] {{"task1", 562, true},
{"task3", 14, false}}, "");
// Query the table
TableView view = table.where().subtable(1).equalTo(2, true).endSubtable().findAll();
assertEquals(2, view.size());
}
@Test
public void queryWithUnbalancedSubtable() {
Table table = new Table();
table.addColumn(ColumnType.TABLE, "sub");
TableSchema tasks = table.getSubtableSchema(0);
tasks.addColumn(ColumnType.STRING, "name");
try { table.where().subtable(0).count(); assert(false); } catch (UnsupportedOperationException e) {}
try { table.where().endSubtable().count(); assert(false); } catch (UnsupportedOperationException e) {}
try { table.where().endSubtable().subtable(0).count(); assert(false); } catch (UnsupportedOperationException e) {}
try { table.where().subtable(0).endSubtable().count(); assert(false); } catch (UnsupportedOperationException e) {}
}
} |
package to.etc.domui.component.input;
import java.util.*;
import to.etc.domui.component.meta.*;
import to.etc.domui.dom.errors.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.trouble.*;
import to.etc.domui.util.*;
public class ComboFixed<T> extends Select implements IInputNode<T> {
static public final class Pair<T> {
private T m_value;
private String m_label;
public Pair(T value, String label) {
m_value = value;
m_label = label;
}
public T getValue() {
return m_value;
}
public String getLabel() {
return m_label;
}
}
private T m_currentValue;
private String m_emptyText;
private List<Pair<T>> m_choiceList = new ArrayList<Pair<T>>();
public ComboFixed(List<Pair<T>> choiceList) {
m_choiceList = choiceList;
}
public ComboFixed() {}
@Override
public void createContent() throws Exception {
if(!isMandatory()) {
//-- Add 1st "empty" thingy representing the unchosen.
SelectOption o = new SelectOption();
if(getEmptyText() != null)
o.setText(getEmptyText());
add(o);
o.setSelected(m_currentValue == null);
}
ClassMetaModel cmm = null;
for(Pair<T> val : m_choiceList) {
SelectOption o = new SelectOption();
add(o);
o.add(val.getLabel());
boolean eq = false;
if(m_currentValue != null && val.getValue() != null && m_currentValue.getClass().equals(val.getValue().getClass())) {
if(cmm == null) {
cmm = MetaManager.findClassMeta(val.getValue().getClass());
}
eq = MetaManager.areObjectsEqual(val.getValue(), m_currentValue, cmm);
}
o.setSelected(eq);
}
}
@Override
public void forceRebuild() {
super.forceRebuild();
}
public T getValue() {
if(isMandatory() && m_currentValue == null) {
setMessage(MsgType.ERROR, Msgs.BUNDLE, Msgs.MANDATORY);
throw new ValidationException(Msgs.NOT_VALID, "null");
}
return m_currentValue;
}
/**
* FIXME Changing the selected option has O(2n) runtime. Use a map on large input sets?
*
* @see to.etc.domui.dom.html.IInputNode#setValue(java.lang.Object)
*/
public void setValue(T v) {
if(MetaManager.areObjectsEqual(v, m_currentValue, null)) // FIXME Needs metamodel for better impl
return;
m_currentValue = v;
if(!isBuilt())
return;
//-- We must set the index of one of the rendered thingies.
for(NodeBase nb : this) {
if(!(nb instanceof SelectOption))
continue;
SelectOption o = (SelectOption) nb;
o.setSelected(false);
}
if(v == null) { // Set to null-> unselected.
if(!isMandatory())
((SelectOption) getChild(0)).setSelected(true);
return;
}
//-- Locate the selected thingerydoo's index.
int ix = 0;
for(Pair<T> p : getData()) {
if(p.getValue().equals(v)) {
//-- Gotcha.
if(!isMandatory())
ix++;
((SelectOption) getChild(ix)).setSelected(true);
return;
}
ix++;
}
}
public int findListIndexFor(T value) {
int ix = 0;
for(Pair<T> p : getData()) {
if(p.getValue().equals(value))
return ix;
ix++;
}
return -1;
}
public String getEmptyText() {
return m_emptyText;
}
public void setEmptyText(String emptyText) {
m_emptyText = emptyText;
}
@Override
public void acceptRequestParameter(String[] values) throws Exception {
String in = values[0]; // Must be the ID of the selected Option thingy.
SelectOption selo = (SelectOption) getPage().findNodeByID(in);
// T oldvalue = m_currentValue;
if(selo == null) {
m_currentValue = null; // Nuttin' selected @ all.
} else {
int index = findChildIndex(selo); // Must be found
if(index == -1)
throw new IllegalStateException("Where has my child " + in + " gone to??");
setSelectedIndex(index); // Set that selected thingerydoo
if(!isMandatory()) {
//-- If the index is 0 we have the "unselected" thingy; if not we need to decrement by 1 to skip that entry.
if(index == 0)
m_currentValue = null; // "Unselected"
index--; // IMPORTANT Index becomes -ve if value lookup may not be done!
}
if(index >= 0) {
if(index >= m_choiceList.size()) {
m_currentValue = null; // Unexpected: value has gone.
} else
m_currentValue = m_choiceList.get(index).getValue(); // Retrieve actual value.
}
}
}
public void setData(List<Pair<T>> set) {
m_choiceList = set;
forceRebuild();
}
public List<Pair<T>> getData() {
return m_choiceList;
}
} |
package com.bydeluxe.es2pg.migration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.conductor.aurora.AuroraBaseDAO;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskDef;
import com.netflix.conductor.common.metadata.workflow.WorkflowDef;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.core.execution.WorkflowExecutor;
import javax.sql.DataSource;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
class Dao extends AuroraBaseDAO {
private static final Set<String> queues = ConcurrentHashMap.newKeySet();
Dao(DataSource dataSource, ObjectMapper mapper) {
super(dataSource, mapper);
}
void upsertTask(Connection tx, Task task) {
String SQL = "INSERT INTO task (created_on, modified_on, task_id, task_type, task_refname, task_status, " +
"workflow_id, json_data, input, output, start_time, end_time) " +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT ON CONSTRAINT task_task_id DO " +
"UPDATE SET created_on=?, modified_on=?, task_type=?, task_refname=?, task_status=?, " +
"workflow_id=?, json_data=?, input=?, output=?, start_time=?, end_time=?";
execute(tx, SQL, q -> q
.addTimestampParameter(task.getStartTime(), System.currentTimeMillis())
.addTimestampParameter(task.getUpdateTime(), System.currentTimeMillis())
.addParameter(task.getTaskId())
.addParameter(task.getTaskType())
.addParameter(task.getReferenceTaskName())
.addParameter(task.getStatus().name())
.addParameter(task.getWorkflowInstanceId())
.addJsonParameter(task)
.addJsonParameter(task.getInputData())
.addJsonParameter(task.getOutputData())
.addTimestampParameter(task.getStartTime())
.addTimestampParameter(task.getEndTime()) // end insert
.addTimestampParameter(task.getStartTime(), System.currentTimeMillis())
.addTimestampParameter(task.getUpdateTime(), System.currentTimeMillis())
.addParameter(task.getTaskType())
.addParameter(task.getReferenceTaskName())
.addParameter(task.getStatus().name())
.addParameter(task.getWorkflowInstanceId())
.addJsonParameter(task)
.addJsonParameter(task.getInputData())
.addJsonParameter(task.getOutputData())
.addTimestampParameter(task.getStartTime())
.addTimestampParameter(task.getEndTime())
.executeUpdate());
addScheduledTask(tx, task);
if (task.getStatus().isTerminal()) {
removeTaskInProgress(tx, task);
} else {
addTaskInProgress(tx, task);
}
}
void requeueSweep(Connection tx) {
String SQL = "SELECT workflow_id FROM workflow WHERE workflow_status = 'RUNNING'";
List<String> ids = query(tx, SQL, q -> q.executeAndFetch(String.class));
ids.forEach(id -> pushMessage(tx, WorkflowExecutor.deciderQueue, id, null, 30));
}
private void createQueueIfNotExists(Connection tx, String queueName) {
if (queues.contains(queueName)) {
return;
}
final String SQL = "INSERT INTO queue (queue_name) VALUES (?) ON CONFLICT ON CONSTRAINT queue_name DO NOTHING";
execute(tx, SQL, q -> q.addParameter(queueName.toLowerCase()).executeUpdate());
queues.add(queueName);
}
void pushMessage(Connection tx, String queueName, String messageId, String payload, long offsetSeconds) {
createQueueIfNotExists(tx, queueName);
String SQL = "INSERT INTO queue_message (queue_name, message_id, popped, deliver_on, payload) " +
"VALUES (?, ?, ?, ?, ?) ON CONFLICT ON CONSTRAINT queue_name_msg DO NOTHING";
long deliverOn = System.currentTimeMillis() + (offsetSeconds * 1000);
query(tx, SQL, q -> q.addParameter(queueName.toLowerCase())
.addParameter(messageId)
.addParameter(false)
.addTimestampParameter(deliverOn)
.addParameter(payload)
.executeUpdate());
}
private void addTaskInProgress(Connection connection, Task task) {
String SQL = "INSERT INTO task_in_progress (created_on, modified_on, task_def_name, task_id, workflow_id) " +
" VALUES (?, ?, ?, ?, ?) ON CONFLICT ON CONSTRAINT task_in_progress_fields DO NOTHING";
execute(connection, SQL, q -> q
.addTimestampParameter(task.getStartTime(), System.currentTimeMillis())
.addTimestampParameter(task.getUpdateTime(), System.currentTimeMillis())
.addParameter(task.getTaskDefName())
.addParameter(task.getTaskId())
.addParameter(task.getWorkflowInstanceId())
.executeUpdate());
}
private void removeTaskInProgress(Connection connection, Task task) {
String SQL = "DELETE FROM task_in_progress WHERE task_def_name = ? AND task_id = ?";
execute(connection, SQL,
q -> q.addParameter(task.getTaskDefName()).addParameter(task.getTaskId()).executeUpdate());
}
private void addScheduledTask(Connection connection, Task task) {
String taskKey = task.getReferenceTaskName() + task.getRetryCount();
final String SQL = "INSERT INTO task_scheduled (workflow_id, task_key, task_id) " +
"VALUES (?, ?, ?) ON CONFLICT ON CONSTRAINT task_scheduled_wf_task DO NOTHING";
query(connection, SQL, q -> q.addParameter(task.getWorkflowInstanceId())
.addParameter(taskKey)
.addParameter(task.getTaskId())
.executeUpdate());
}
void upsertWorkflow(Connection tx, Workflow workflow) {
String SQL = "INSERT INTO workflow (created_on, modified_on, start_time, end_time, parent_workflow_id, " +
"workflow_id, workflow_type, workflow_status, date_str, json_data, input, output, correlation_id, tags) " +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT ON CONSTRAINT workflow_workflow_id DO " +
"UPDATE SET created_on=?, modified_on=?, start_time=?, end_time=?, parent_workflow_id=?, " +
"workflow_type=?, workflow_status=?, date_str=?, json_data=?, input=?, output=?, correlation_id=?, tags=?";
execute(tx, SQL, q -> q
.addTimestampParameter(workflow.getCreateTime(), System.currentTimeMillis())
.addTimestampParameter(workflow.getUpdateTime(), System.currentTimeMillis())
.addTimestampParameter(workflow.getStartTime())
.addTimestampParameter(workflow.getEndTime())
.addParameter(workflow.getParentWorkflowId())
.addParameter(workflow.getWorkflowId())
.addParameter(workflow.getWorkflowType())
.addParameter(workflow.getStatus().name())
.addParameter(dateStr(workflow.getCreateTime()))
.addJsonParameter(workflow)
.addJsonParameter(workflow.getInput())
.addJsonParameter(workflow.getOutput())
.addParameter(workflow.getCorrelationId())
.addParameter(workflow.getTags()) // end insert
.addTimestampParameter(workflow.getCreateTime(), System.currentTimeMillis())
.addTimestampParameter(workflow.getUpdateTime(), System.currentTimeMillis())
.addTimestampParameter(workflow.getStartTime())
.addTimestampParameter(workflow.getEndTime())
.addParameter(workflow.getParentWorkflowId())
.addParameter(workflow.getWorkflowType())
.addParameter(workflow.getStatus().name())
.addParameter(dateStr(workflow.getCreateTime()))
.addJsonParameter(workflow)
.addJsonParameter(workflow.getInput())
.addJsonParameter(workflow.getOutput())
.addParameter(workflow.getCorrelationId())
.addParameter(workflow.getTags())
.executeUpdate());
}
long workflowCount(Connection tx) {
String SQL = "SELECT count(*) FROM workflow";
return query(tx, SQL, q -> q.executeScalar(Long.class));
}
void upsertTaskDef(Connection tx, TaskDef def) {
final String UPDATE_SQL = "UPDATE meta_task_def SET created_on = ?, modified_on = ?, json_data = ? WHERE name = ?";
final String INSERT_SQL = "INSERT INTO meta_task_def (created_on, modified_on, name, json_data) VALUES (?, ?, ?, ?)";
execute(tx, UPDATE_SQL, update -> {
int result = update
.addTimestampParameter(def.getCreateTime(), System.currentTimeMillis())
.addTimestampParameter(def.getUpdateTime(), System.currentTimeMillis())
.addJsonParameter(def)
.addParameter(def.getName())
.executeUpdate();
if (result == 0) {
execute(tx, INSERT_SQL,
insert -> insert
.addTimestampParameter(def.getCreateTime(), System.currentTimeMillis())
.addTimestampParameter(def.getUpdateTime(), System.currentTimeMillis())
.addParameter(def.getName())
.addJsonParameter(def)
.executeUpdate());
}
});
}
void upsertWorkflowDef(Connection tx, WorkflowDef def) {
Optional<Integer> version = getLatestVersion(tx, def);
if (!version.isPresent() || version.get() < def.getVersion()) {
final String SQL = "INSERT INTO meta_workflow_def (created_on, modified_on, name, version, json_data) " +
"VALUES (?, ?, ?, ?, ?)";
execute(tx, SQL, q -> q
.addTimestampParameter(def.getCreateTime(), System.currentTimeMillis())
.addTimestampParameter(def.getUpdateTime(), System.currentTimeMillis())
.addParameter(def.getName())
.addParameter(def.getVersion())
.addJsonParameter(def)
.executeUpdate());
} else {
final String SQL = "UPDATE meta_workflow_def SET created_on = ?, modified_on = ?, json_data = ? " +
"WHERE name = ? AND version = ?";
execute(tx, SQL, q -> q
.addTimestampParameter(def.getCreateTime(), System.currentTimeMillis())
.addTimestampParameter(def.getUpdateTime(), System.currentTimeMillis())
.addJsonParameter(def)
.addParameter(def.getName())
.addParameter(def.getVersion())
.executeUpdate());
}
updateLatestVersion(tx, def);
}
private Optional<Integer> getLatestVersion(Connection tx, WorkflowDef def) {
final String SQL = "SELECT max(version) AS version FROM meta_workflow_def WHERE name = ?";
Integer val = query(tx, SQL, q -> q.addParameter(def.getName()).executeScalar(Integer.class));
return Optional.ofNullable(val);
}
private void updateLatestVersion(Connection tx, WorkflowDef def) {
final String SQL = "UPDATE meta_workflow_def SET latest_version = ? WHERE name = ?";
execute(tx, SQL,
q -> q.addParameter(def.getVersion()).addParameter(def.getName()).executeUpdate());
}
private static int dateStr(Long timeInMs) {
Date date = new Date(timeInMs);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
return Integer.parseInt(format.format(date));
}
} |
package org.protobeans.kafka.example;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import org.apache.kafka.clients.admin.NewTopic;
import org.protobeans.core.EntryPoint;
import org.protobeans.kafka.annotation.EnableKafkaMessaging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.kafka.annotation.KafkaListener;
@EnableKafkaMessaging(brokerList = "91.242.38.71:9092", transactionalIdPrefix = "123")
@ComponentScan(basePackageClasses=KafkaService.class)
public class Main {
@Autowired
private KafkaService kafkaService;
@EventListener(ContextRefreshedEvent.class)
void start() {
while (!Thread.interrupted()) {
kafkaService.send("topic1", UUID.randomUUID().toString(), LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")));
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@KafkaListener(id = "group1", topics = "topic1")
public void topicListener(List<String> records) {
for (String value : records) {
System.out.println("Receive: " + value);
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Bean
public NewTopic mytopic() {
return new NewTopic("topic1", 6, (short) 1);
}
public static void main(String[] args) {
EntryPoint.run(Main.class);
}
} |
package io.syndesis.qe.pages;
import io.syndesis.qe.pages.connections.detail.ConnectionDetailPage;
import io.syndesis.qe.pages.connections.edit.ConnectionCreatePage;
import io.syndesis.qe.pages.connections.list.ConnectionListPage;
import io.syndesis.qe.pages.customizations.CustomizationsPage;
import io.syndesis.qe.pages.customizations.extensions.TechExtensionDetailPage;
import io.syndesis.qe.pages.customizations.extensions.TechExtensionsImportPage;
import io.syndesis.qe.pages.customizations.extensions.TechExtensionsListComponent;
import io.syndesis.qe.pages.integrations.edit.IntegrationConnectionSelectComponentFinish;
import io.syndesis.qe.pages.integrations.edit.IntegrationConnectionSelectComponentStart;
import io.syndesis.qe.pages.integrations.edit.IntegrationSaveOrAddStepComponent;
import io.syndesis.qe.pages.integrations.list.IntegrationsListPage;
public enum SyndesisPage {
CONNECTIONS(new ConnectionListPage()),
CONNECTION_CREATE(new ConnectionCreatePage()),
CONNECTION_DETAIL(new ConnectionDetailPage()),
CONNECTION_LIST(new ConnectionListPage()),
INTEGRATIONS_LIST(new IntegrationsListPage()),
SELECT_START_CONNECTION(new IntegrationConnectionSelectComponentStart()),
SELECT_FINISH_CONNECTION(new IntegrationConnectionSelectComponentFinish()),
CHOOSE_A_FINISH_CONNECTION(new IntegrationConnectionSelectComponentFinish()),
ADD_TO_INTEGRATION(new IntegrationSaveOrAddStepComponent()),
CUSTOMIZATIONS(new CustomizationsPage()),
TECHNICAL_EXTENSIONS(new TechExtensionsListComponent()),
IMPORT_TECHNICAL_EXTENSION(new TechExtensionsImportPage()),
TECHNICAL_EXTENSIONS_DETAIL(new TechExtensionDetailPage());
private SyndesisPageObject pageObject = null;
SyndesisPage(SyndesisPageObject pageObject) {
this.pageObject = pageObject;
}
private SyndesisPageObject getPageObject() {
return pageObject;
}
//Accepts ["name", "Name", "nAme", "na ME", "Na Me", "n a M e"...]
public static SyndesisPageObject get(String name) {
return SyndesisPage.valueOf(name.replace(" ", "_").toUpperCase()).getPageObject();
}
} |
package net.sf.farrago.namespace.impl;
import java.util.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.namespace.*;
import net.sf.farrago.query.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.runtime.FarragoUdrRuntime;
import net.sf.farrago.util.*;
import org.eigenbase.rel.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.rex.*;
import org.eigenbase.sql.*;
/**
* MedAbstractColumnSet is an abstract base class for implementations of the
* {@link FarragoMedColumnSet} interface.
*
* @author John V. Sichi
* @version $Id$
*/
public abstract class MedAbstractColumnSet
extends RelOptAbstractTable
implements FarragoQueryColumnSet
{
private final String [] localName;
private final String [] foreignName;
private Properties tableProps;
private Map<String, Properties> columnPropMap;
private FarragoPreparingStmt preparingStmt;
private CwmNamedColumnSet cwmColumnSet;
private SqlAccessType allowedAccess;
/**
* Creates a new MedAbstractColumnSet.
*
* @param localName name of this ColumnSet as it will be known within the
* Farrago system
* @param foreignName name of this ColumnSet as it is known on the foreign
* server; may be null if no meaningful name exists
* @param rowType row type descriptor
* @param tableProps table-level properties
* @param columnPropMap column-level properties (map from column name to
* Properties object)
*/
protected MedAbstractColumnSet(
String [] localName,
String [] foreignName,
RelDataType rowType,
Properties tableProps,
Map<String, Properties> columnPropMap)
{
super(null, localName[localName.length - 1], rowType);
this.localName = localName;
this.foreignName = foreignName;
this.tableProps = tableProps;
this.columnPropMap = columnPropMap;
this.allowedAccess = SqlAccessType.ALL;
}
// implement RelOptTable
public String [] getQualifiedName()
{
return localName;
}
/**
* @return the name this ColumnSet is known by within the Farrago system
*/
public String [] getLocalName()
{
return localName;
}
/**
* @return the name of this ColumnSet as it is known on the foreign server
*/
public String [] getForeignName()
{
return foreignName;
}
/**
* @return options specified by CREATE FOREIGN TABLE
*/
public Properties getTableProperties()
{
return tableProps;
}
/**
* @return map (from column name to Properties) of column options specified
* by CREATE FOREIGN TABLE
*/
public Map<String, Properties> getColumnPropertyMap()
{
return columnPropMap;
}
// implement FarragoQueryColumnSet
public FarragoPreparingStmt getPreparingStmt()
{
return preparingStmt;
}
// implement FarragoQueryColumnSet
public void setPreparingStmt(FarragoPreparingStmt stmt)
{
preparingStmt = stmt;
}
// implement FarragoQueryColumnSet
public void setCwmColumnSet(CwmNamedColumnSet cwmColumnSet)
{
this.cwmColumnSet = cwmColumnSet;
}
// implement FarragoQueryColumnSet
public CwmNamedColumnSet getCwmColumnSet()
{
return cwmColumnSet;
}
// implement SqlValidatorTable
public boolean isMonotonic(String columnName)
{
return false;
}
// implement SqlValidatorTable
public SqlAccessType getAllowedAccess()
{
return allowedAccess;
}
public void setAllowedAccess(SqlAccessType allowedAccess)
{
this.allowedAccess = allowedAccess;
}
/**
* Provides an implementation of the toRel interface method in terms of an
* underlying UDX.
*
* @param cluster same as for toRel
* @param connection same as for toRel
* @param udxSpecificName specific name with which the UDX was created
* (either via the SPECIFIC keyword or the invocation name if SPECIFIC was
* not specified); this can be a qualified name, possibly with quoted
* identifiers, e.g. x.y.z or x."y".z
* @param serverMofId if not null, the invoked UDX can access the data
* server with the given MOFID at runtime via
* {@link FarragoUdrRuntime#getDataServerRuntimeSupport}
* @param args arguments to UDX invocation
*
* @return generated relational expression producing the UDX results
*/
protected RelNode toUdxRel(
RelOptCluster cluster,
RelOptConnection connection,
String udxSpecificName,
String serverMofId,
RexNode [] args)
{
// TODO jvs 13-Oct-2006: phase out these vestigial parameters
assert(cluster == getPreparingStmt().getRelOptCluster());
assert(connection == getPreparingStmt());
return FarragoJavaUdxRel.newUdxRel(
getPreparingStmt(),
getRowType(),
udxSpecificName,
serverMofId,
args,
RelNode.emptyArray);
}
/**
* Converts one RelNode to another RelNode with specified RowType.
* New columns are filled with nulls.
*
* @param cluster same as for toRel
* @param child original RelNode
* @param targetRowType RowType to map to
* @param srcRowType RowType of external data source
*/
protected RelNode toLenientRel(
RelOptCluster cluster,
RelNode child,
RelDataType targetRowType,
RelDataType srcRowType)
{
ArrayList<RexNode> rexNodeList = new ArrayList();
RexBuilder rexBuilder = cluster.getRexBuilder();
FarragoWarningQueue warningQueue =
getPreparingStmt().getStmtValidator().getWarningQueue();
String objectName = this.localName[this.localName.length-1];
HashMap<String, RelDataType> srcMap = new HashMap();
for (RelDataTypeField srcField : srcRowType.getFieldList()) {
srcMap.put(srcField.getName(), srcField.getType());
}
ArrayList<String> allTargetFields = new ArrayList();
int index = 0;
for (RelDataTypeField targetField : targetRowType.getFieldList()) {
allTargetFields.add(targetField.getName());
RelDataType type;
// target field is in child
if ((index = child.getRowType().getFieldOrdinal(
targetField.getName())) != -1) {
if ((type = srcMap.get(targetField.getName())) !=
targetField.getType()) {
// field type has been cast
warningQueue.postWarning(
FarragoResource.instance().TypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
}
rexNodeList.add(new RexInputRef(index, targetField.getType()));
} else { // target field is not in child
// check if type-incompatibility between source and target
if ((type = srcMap.get(targetField.getName())) != null) {
warningQueue.postWarning(FarragoResource.instance().
IncompatibleTypeChangeWarning.ex(
objectName, targetField.getName(), type.toString(),
targetField.getType().toString()));
} else {
// field in target has been deleted in source
rexNodeList.add(
rexBuilder.makeCast(
targetField.getType(),
rexBuilder.constantNull()));
warningQueue.postWarning(
FarragoResource.instance().DeletedFieldWarning.ex(
objectName, targetField.getName()));
}
}
}
// check if data source has added fields
for (String srcField : srcMap.keySet()) {
if (!allTargetFields.contains(srcField)) {
warningQueue.postWarning(
FarragoResource.instance().AddedFieldWarning.ex(
objectName, srcField));
}
}
// create a new RelNode.
RelNode calcRel = CalcRel.createProject(
child,
rexNodeList,
null);
return RelOptUtil.createCastRel(
calcRel,
targetRowType,
true);
}
}
// End MedAbstractColumnSet.java |
package net.sf.farrago.namespace.jdbc;
import java.sql.*;
import java.util.*;
import net.sf.farrago.namespace.*;
import net.sf.farrago.namespace.impl.*;
import net.sf.farrago.type.*;
import net.sf.farrago.util.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.sql.parser.SqlParserPos;
import org.eigenbase.sql.fun.SqlStdOperatorTable;
import org.eigenbase.util.*;
/**
* MedJdbcNameDirectory implements the FarragoMedNameDirectory
* interface by mapping the metadata provided by any JDBC driver.
*
* @author John V. Sichi
* @version $Id$
*/
class MedJdbcNameDirectory extends MedAbstractNameDirectory
{
final MedJdbcDataServer server;
final String schemaName;
final boolean shouldSubstituteTypes;
MedJdbcNameDirectory(MedJdbcDataServer server)
{
this(server, null);
}
MedJdbcNameDirectory(MedJdbcDataServer server, String schemaName)
{
this.server = server;
this.schemaName = schemaName;
shouldSubstituteTypes = getBooleanProperty(
server.getProperties(),
MedJdbcDataServer.PROP_TYPE_SUBSTITUTION,
true);
}
// implement FarragoMedNameDirectory
public FarragoMedColumnSet lookupColumnSet(
FarragoTypeFactory typeFactory,
String foreignName,
String [] localName)
throws SQLException
{
return lookupColumnSetAndImposeType(
typeFactory, foreignName,
localName, null);
}
FarragoMedColumnSet lookupColumnSetAndImposeType(
FarragoTypeFactory typeFactory,
String foreignName,
String [] localName,
RelDataType rowType)
throws SQLException
{
if (schemaName == null) {
return null;
}
String [] foreignQualifiedName;
if (server.schemaName != null) {
foreignQualifiedName =
new String [] { foreignName };
} else if (server.catalogName != null) {
foreignQualifiedName =
new String [] { server.catalogName, schemaName, foreignName };
} else {
foreignQualifiedName =
new String [] { schemaName, foreignName };
}
SqlDialect dialect = new SqlDialect(server.databaseMetaData);
SqlStdOperatorTable opTab = SqlStdOperatorTable.instance();
SqlSelect select =
opTab.selectOperator.createCall(
null,
new SqlNodeList(
Collections.singletonList(
new SqlIdentifier("*", SqlParserPos.ZERO)),
SqlParserPos.ZERO),
new SqlIdentifier(foreignQualifiedName, SqlParserPos.ZERO),
null,
null,
null,
null,
null,
SqlParserPos.ZERO);
if (rowType == null) {
String sql = select.toSqlString(dialect);
sql = normalizeQueryString(sql);
PreparedStatement ps = null;
try {
ps = server.connection.prepareStatement(sql);
} catch (Exception ex) {
// Some drivers don't support prepareStatement
}
Statement stmt = null;
ResultSet rs = null;
try {
ResultSetMetaData md = null;
try {
if (ps != null) {
md = ps.getMetaData();
}
} catch (SQLException ex) {
// Some drivers can't return metadata before execution.
// Fall through to recovery below.
}
if (md == null) {
if (ps != null) {
rs = ps.executeQuery();
} else {
stmt = server.connection.createStatement();
rs = stmt.executeQuery(sql);
}
md = rs.getMetaData();
}
rowType = typeFactory.createResultSetType(
md,
shouldSubstituteTypes);
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (ps != null) {
ps.close();
}
}
} else {
// REVIEW: should we at least check to see if the inferred
// row type is compatible with the imposed row type?
}
return new MedJdbcColumnSet(
this, foreignQualifiedName, localName, select,
dialect, rowType);
}
String normalizeQueryString(String sql)
{
// some drivers don't like multi-line SQL, so convert all
// whitespace into plain spaces
return sql.replaceAll("\\s", " ");
}
// implement FarragoMedNameDirectory
public FarragoMedNameDirectory lookupSubdirectory(String foreignName)
throws SQLException
{
if (schemaName == null) {
return new MedJdbcNameDirectory(server, foreignName);
} else {
return null;
}
}
// implement FarragoMedNameDirectory
public boolean queryMetadata(
FarragoMedMetadataQuery query,
FarragoMedMetadataSink sink)
throws SQLException
{
if (schemaName == null) {
boolean wantSchemas = query.getResultObjectTypes().contains(
FarragoMedMetadataQuery.OTN_SCHEMA);
if (wantSchemas) {
return querySchemas(query, sink);
}
return true;
} else {
boolean wantTables = query.getResultObjectTypes().contains(
FarragoMedMetadataQuery.OTN_TABLE);
boolean wantColumns = query.getResultObjectTypes().contains(
FarragoMedMetadataQuery.OTN_COLUMN);
List tableListActual = new ArrayList();
List tableListOptimized = new ArrayList();
// FRG-137: Since we rely on queryTable to populate the lists, we
// need to do it for wantColumns even when !wantTables.
if (wantTables || wantColumns) {
if (!queryTables(
query, sink, tableListActual, tableListOptimized))
{
return false;
}
}
if (wantColumns) {
if (!queryColumns(
query, sink, tableListActual, tableListOptimized))
{
return false;
}
}
return true;
}
}
private boolean querySchemas(
FarragoMedMetadataQuery query,
FarragoMedMetadataSink sink)
throws SQLException
{
assert(schemaName == null);
ResultSet resultSet;
try {
resultSet = server.databaseMetaData.getSchemas();
if (resultSet == null) {
return false;
}
} catch (Throwable ex) {
// assume unsupported
return false;
}
try {
while (resultSet.next()) {
String schemaName = resultSet.getString(1);
String catalogName = resultSet.getString(2);
if (server.catalogName != null) {
if (!server.catalogName.equals(catalogName)) {
continue;
}
}
sink.writeObjectDescriptor(
schemaName,
FarragoMedMetadataQuery.OTN_SCHEMA,
null,
Collections.EMPTY_MAP);
}
} finally {
resultSet.close();
}
return true;
}
private boolean queryTables(
FarragoMedMetadataQuery query,
FarragoMedMetadataSink sink,
List tableListActual,
List tableListOptimized)
throws SQLException
{
assert(schemaName != null);
// In order to optimize column retrieval, we keep track of the
// number of tables returned by our metadata query and the
// ones actually accepted by the sink. It would be better
// to let the optimizer handle this, but KISS for now.
int nTablesReturned = 0;
String schemaPattern = getSchemaPattern();
String tablePattern = getFilterPattern(
query, FarragoMedMetadataQuery.OTN_TABLE);
ResultSet resultSet;
try {
resultSet = server.databaseMetaData.getTables(
server.catalogName,
schemaPattern,
tablePattern,
server.tableTypes);
if (resultSet == null) {
return false;
}
} catch (Throwable ex) {
// assume unsupported
return false;
}
Properties props = new Properties();
try {
while (resultSet.next()) {
++nTablesReturned;
String schemaName = resultSet.getString(2);
if (!matchSchema(schemaPattern, schemaName)) {
continue;
}
String tableName = resultSet.getString(3);
String remarks = resultSet.getString(5);
if (schemaName != null) {
props.put(MedJdbcDataServer.PROP_SCHEMA_NAME, schemaName);
}
props.put(MedJdbcDataServer.PROP_TABLE_NAME, tableName);
boolean include = sink.writeObjectDescriptor(
tableName,
FarragoMedMetadataQuery.OTN_TABLE,
remarks,
props);
if (include) {
tableListActual.add(tableName);
}
}
} finally {
resultSet.close();
}
// decide on column retrieval plan
double dMatching = (double) tableListActual.size();
// +1: avoid division by zero
double dReturned = (double) nTablesReturned + 1;
if (dMatching / dReturned > 0.3) {
// a significant portion of the tables returned are matches,
// so just scan all columns at once and post-filter them,
// rather than making repeated single-table metadata calls
tableListOptimized.add("*");
} else {
tableListOptimized.addAll(tableListActual);
}
return true;
}
private boolean queryColumns(
FarragoMedMetadataQuery query,
FarragoMedMetadataSink sink,
List tableListActual,
List tableListOptimized)
throws SQLException
{
if (tableListOptimized.equals(Collections.singletonList("*"))) {
return queryColumnsImpl(
query, sink, null, new HashSet(tableListActual));
} else {
Iterator iter = tableListOptimized.iterator();
while (iter.hasNext()) {
String tableName = (String) iter.next();
if (!queryColumnsImpl(query, sink, tableName, null)) {
return false;
}
}
return true;
}
}
private boolean queryColumnsImpl(
FarragoMedMetadataQuery query,
FarragoMedMetadataSink sink,
String tableName,
Set tableSet)
throws SQLException
{
String schemaPattern = getSchemaPattern();
String tablePattern;
if (tableName != null) {
tablePattern = tableName;
} else {
tablePattern = getFilterPattern(
query,
FarragoMedMetadataQuery.OTN_TABLE);
}
String columnPattern = getFilterPattern(
query,
FarragoMedMetadataQuery.OTN_COLUMN);
ResultSet resultSet;
try {
resultSet = server.databaseMetaData.getColumns(
server.catalogName,
schemaPattern,
tablePattern,
columnPattern);
if (resultSet == null) {
return false;
}
} catch (Throwable ex) {
// assume unsupported
return false;
}
try {
while (resultSet.next()) {
String schemaName = resultSet.getString(2);
if (!matchSchema(schemaPattern, schemaName)) {
continue;
}
String returnedTableName = resultSet.getString(3);
if (tableSet != null) {
if (!tableSet.contains(returnedTableName)) {
continue;
}
}
String columnName = resultSet.getString(4);
boolean isNullable =
resultSet.getInt(11) != DatabaseMetaData.columnNoNulls;
RelDataType type =
sink.getTypeFactory().createJdbcColumnType(
resultSet, shouldSubstituteTypes);
String remarks = resultSet.getString(12);
String defaultValue = resultSet.getString(13);
int ordinalZeroBased = resultSet.getInt(17) - 1;
sink.writeColumnDescriptor(
returnedTableName,
columnName,
ordinalZeroBased,
type,
remarks,
defaultValue,
Collections.EMPTY_MAP);
}
} finally {
resultSet.close();
}
return true;
}
private String getSchemaPattern()
{
if (server.schemaName != null) {
// schemaName is fake; don't use it
return null;
} else {
return schemaName;
}
}
private String getFilterPattern(
FarragoMedMetadataQuery query,
String typeName)
{
String pattern = "%";
FarragoMedMetadataFilter filter = (FarragoMedMetadataFilter)
query.getFilterMap().get(typeName);
if (filter != null) {
if (!filter.isExclusion() && filter.getPattern() != null) {
pattern = filter.getPattern();
}
}
return pattern;
}
private boolean matchSchema(String s1, String s2)
{
if ((s1 == null) || (s2 == null)) {
return true;
}
return s1.equals(s2);
}
}
// End MedJdbcNameDirectory.java |
package edu.umd.cs.findbugs.workflow;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Iterator;
import org.dom4j.DocumentException;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugAnnotationWithSourceLines;
import edu.umd.cs.findbugs.BugCollection;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.DetectorFactoryCollection;
import edu.umd.cs.findbugs.FindBugs;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.ba.SourceFinder;
/**
* Java main application to compute update a historical bug collection with
* results from another build/analysis.
*
* @author William Pugh
*/
public class CopyBuggySource {
private static final String USAGE = "Usage: <cmd> "
+ " <bugs.xml> <destinationSrcDir>";
public static void main(String[] args) throws IOException,
DocumentException {
FindBugs.setNoAnalysis();
DetectorFactoryCollection.instance();
if (args.length != 2) {
System.out.println(USAGE);
return;
}
BugCollection origCollection;
origCollection = new SortedBugCollection();
origCollection.readXML(args[0]);
File src = new File(args[1]);
byte buf[] = new byte[4096];
if (!src.isDirectory())
throw new IllegalArgumentException(args[1]
+ " is not a source directory");
Project project = origCollection.getProject();
SourceFinder sourceFinder = new SourceFinder(project);
HashSet<String> copied = new HashSet<String>();
HashSet<String> couldNotFind = new HashSet<String>();
HashSet<String> couldNotCreate = new HashSet<String>();
int copyCount = 0;
for (BugInstance bug : origCollection.getCollection()) {
for (Iterator<BugAnnotation> i = bug.annotationIterator(); i
.hasNext();) {
BugAnnotation ann = i.next();
SourceLineAnnotation sourceAnnotation;
if (ann instanceof BugAnnotationWithSourceLines)
sourceAnnotation = ((BugAnnotationWithSourceLines) ann)
.getSourceLines();
else if (ann instanceof SourceLineAnnotation)
sourceAnnotation = (SourceLineAnnotation) ann;
else
continue;
if (sourceAnnotation == null)
continue;
if (sourceAnnotation.isUnknown())
continue;
String fullName;
String packageName = sourceAnnotation.getPackageName();
String sourceFile = sourceAnnotation.getSourceFile();
if (packageName == "")
fullName = sourceFile;
else
fullName = packageName.replace('.', File.separatorChar)
+ File.separatorChar + sourceFile;
if (copied.add(fullName)) {
File file = new File(src, fullName);
if (file.exists()) {
System.out.println(file + " already exists");
continue;
}
File parent = file.getParentFile();
InputStream in = null;
OutputStream out = null;
try {
in = sourceFinder.openSource(packageName, sourceFile);
if (!parent.mkdirs() && !parent.isDirectory()) {
String path = parent.getPath();
if (couldNotCreate.add(path))
System.out.println("Can't create directory for "
+ path);
in.close();
continue;
}
out = new FileOutputStream(file);
while (true) {
int sz = in.read(buf);
if (sz < 0)
break;
out.write(buf, 0, sz);
}
System.out.println("Copied " + file);
copyCount++;
} catch (FileNotFoundException e) {
if (couldNotFind.add(file.getPath()))
System.out.println("Did not find " + file);
} catch (IOException e) {
if (couldNotFind.add(file.getPath())) {
System.out.println("Problem copying " + file);
e.printStackTrace(System.out);
}
} finally {
close(in);
close(out);
}
}
}
}
System.out.printf("All done. %d files not found, %d files copied%n", couldNotFind.size(), copyCount);
}
public static void close(InputStream in) {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
public static void close(OutputStream out) {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
} |
package com.dtflys.forest.http;
import com.dtflys.forest.callback.OnLoadCookie;
import com.dtflys.forest.callback.OnProgress;
import com.dtflys.forest.callback.OnSaveCookie;
import com.dtflys.forest.converter.ForestConverter;
import com.dtflys.forest.interceptor.InterceptorAttributes;
import com.dtflys.forest.logging.LogConfiguration;
import com.dtflys.forest.logging.RequestLogMessage;
import com.dtflys.forest.multipart.ForestMultipart;
import com.dtflys.forest.reflection.ForestMethod;
import com.dtflys.forest.reflection.MethodLifeCycleHandler;
import com.dtflys.forest.retryer.Retryer;
import com.dtflys.forest.ssl.SSLKeyStore;
import com.dtflys.forest.callback.OnError;
import com.dtflys.forest.callback.OnSuccess;
import com.dtflys.forest.config.ForestConfiguration;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.backend.HttpBackend;
import com.dtflys.forest.backend.HttpExecutor;
import com.dtflys.forest.handler.LifeCycleHandler;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.interceptor.InterceptorChain;
import com.dtflys.forest.utils.ForestDataType;
import com.dtflys.forest.utils.RequestNameValue;
import com.dtflys.forest.utils.StringUtils;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import static com.dtflys.forest.mapping.MappingParameter.*;
/**
* Forest
*
* @author gongjun[dt_flys@hotmail.com]
* @since 2016-03-24
*/
public class ForestRequest<T> {
private final static long DEFAULT_PROGRESS_STEP = 1024 * 10;
/**
* Forest
*/
private final ForestConfiguration configuration;
/**
* Forest
*/
private final ForestMethod method;
/**
* HTTP
*/
private HttpBackend backend;
private LifeCycleHandler lifeCycleHandler;
/**
* HTTP
*/
private String protocol;
/**
* URL
*/
private String url;
private String userInfo;
/**
* URLQuery
*/
private ForestQueryMap query = new ForestQueryMap();
private ForestRequestType type;
private List<ForestRequestType> typeChangeHistory;
private RequestLogMessage requestLogMessage;
private String charset;
private String responseEncode = "UTF-8";
private boolean async;
private ForestDataType dataType;
private int timeout = 3000;
/**
* SSL
* HTTPSSSL
*/
private String sslProtocol;
private int retryCount = 0;
private long maxRetryInterval = 0;
// private Map<String, Object> data = new LinkedHashMap<String, Object>();
/**
*
*
* ForestRequestBody
*/
private List<ForestRequestBody> bodyItems = new LinkedList<>();
private ForestHeaderMap headers = new ForestHeaderMap();
private List<ForestMultipart> multiparts = new LinkedList<>();
private String filename;
private final Object[] arguments;
private OnSuccess onSuccess;
private OnError onError;
/**
* /
* / ${progressStep}
*/
private OnProgress onProgress;
/**
* : Cookie
*/
private OnLoadCookie onLoadCookie;
/**
* : Cookie
*/
private OnSaveCookie onSaveCookie;
private boolean isDownloadFile = false;
private long progressStep = DEFAULT_PROGRESS_STEP;
private InterceptorChain interceptorChain = new InterceptorChain();
private Map<Class, InterceptorAttributes> interceptorAttributes = new HashMap<>();
private Retryer retryer;
private Map<String, Object> attachments = new HashMap<>();
private ForestConverter decoder;
private LogConfiguration logConfiguration;
/**
* SSL KeyStore
* HTTPS
*/
private SSLKeyStore keyStore;
private ForestProxy proxy;
public ForestRequest(ForestConfiguration configuration, ForestMethod method, Object[] arguments) {
this.configuration = configuration;
this.method = method;
this.arguments = arguments;
}
public ForestRequest(ForestConfiguration configuration, ForestMethod method) {
this(configuration, method, new Object[0]);
}
public ForestRequest(ForestConfiguration configuration) {
this(configuration, null, new Object[0]);
}
public ForestRequest(ForestConfiguration configuration, Object[] arguments) {
this(configuration, null, arguments);
}
/**
*
* @return
*/
public ForestConfiguration getConfiguration() {
return configuration;
}
/**
*
* @return
*/
public String getProtocol() {
return protocol;
}
/**
*
* @param protocol
* @return {@link ForestRequest}
*/
public ForestRequest setProtocol(String protocol) {
this.protocol = protocol;
return this;
}
/**
* URL
* @return URL
*/
public String getUrl() {
return url;
}
/**
* URI
* @return {@link URI}
*/
public URI getURI() {
try {
return new URI(url);
} catch (URISyntaxException e) {
throw new ForestRuntimeException(e);
}
}
/**
* url
* <p>urlurl</p>
* <p>urlQueryQueryQuery</p>
*
* @param url url
* @return {@link ForestRequest}
*/
public ForestRequest setUrl(String url) {
if (StringUtils.isBlank(url)) {
throw new ForestRuntimeException("[Forest] Request url cannot be empty!");
}
String newUrl = null;
String srcUrl = StringUtils.trimBegin(url);
String query = "";
String protocol = "";
String userInfo = null;
if (!this.query.isEmpty()) {
this.query.clearQueriesFromUrl();
}
try {
URL u = new URL(srcUrl);
query = u.getQuery();
userInfo = u.getUserInfo();
if (StringUtils.isNotEmpty(query)) {
String[] params = query.split("&");
for (int i = 0; i < params.length; i++) {
String p = params[i];
String[] nameValue = p.split("=", 2);
String name = nameValue[0];
RequestNameValue requestNameValue = new RequestNameValue(name, TARGET_QUERY);
if (nameValue.length > 1) {
StringBuilder valueBuilder = new StringBuilder();
valueBuilder.append(nameValue[1]);
if (nameValue.length > 2) {
for (int j = 2; j < nameValue.length; j++) {
valueBuilder.append("=");
valueBuilder.append(nameValue[j]);
}
}
String value = valueBuilder.toString();
requestNameValue.setValue(value);
}
addQuery(new ForestQueryParameter(
requestNameValue.getName(), requestNameValue.getValue(), true));
}
}
protocol = u.getProtocol();
int port = u.getPort();
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(protocol).append(":
if (userInfo != null) {
urlBuilder.append(userInfo).append('@');
}
urlBuilder.append(u.getHost());
if (port != 80 && port > -1) {
urlBuilder.append(':').append(port);
}
String path = u.getPath();
if (StringUtils.isNotEmpty(path)) {
urlBuilder.append(path);
}
newUrl = urlBuilder.toString();
} catch (MalformedURLException e) {
throw new ForestRuntimeException(e);
}
this.url = newUrl;
if (StringUtils.isNotEmpty(protocol)) {
this.protocol = protocol;
}
if (StringUtils.isNotEmpty(userInfo)) {
this.userInfo = userInfo;
}
return this;
}
public String getUserInfo() {
return userInfo;
}
public ForestRequest setUserInfo(String userInfo) {
this.userInfo = userInfo;
return this;
}
/**
* Forest
* @return Forest
*/
public ForestMethod getMethod() {
return method;
}
/**
* HTTP
* @return HTTP{@link HttpBackend}
*/
public HttpBackend getBackend() {
return backend;
}
/**
* HTTP
* @param backend HTTP{@link HttpBackend}
* @return {@link ForestRequest}
*/
public ForestRequest setBackend(HttpBackend backend) {
this.backend = backend;
return this;
}
/**
*
* @return {@link LifeCycleHandler}
*/
public LifeCycleHandler getLifeCycleHandler() {
return lifeCycleHandler;
}
/**
*
* @param lifeCycleHandler {@link LifeCycleHandler}
* @return {@link ForestRequest}
*/
public ForestRequest setLifeCycleHandler(LifeCycleHandler lifeCycleHandler) {
this.lifeCycleHandler = lifeCycleHandler;
return this;
}
/**
* Query
* @return Query
*/
public ForestQueryMap getQuery() {
return query;
}
/**
* Query
* @param name Query
* @return Query
*/
public Object getQuery(String name) {
return query.get(name);
}
/**
* URL Query
* @return
*/
public String getQueryString() {
StringBuilder builder = new StringBuilder();
Iterator<ForestQueryParameter> iterator = query.queryValues().iterator();
while (iterator.hasNext()) {
ForestQueryParameter query = iterator.next();
if (query != null) {
String name = query.getName();
Object value = query.getValue();
if (name != null) {
builder.append(name);
if (value != null) {
builder.append("=");
}
}
if (value != null) {
builder.append(value);
}
}
if (iterator.hasNext()) {
builder.append("&");
}
}
return builder.toString();
}
/**
* Query
* @param name Query
* @param value Query
* @return {@link ForestRequest}
*/
public ForestRequest addQuery(String name, Object value) {
this.query.addQuery(name, value);
return this;
}
/**
* Query
* @param queryParameter Query{@link ForestQueryParameter}
* @return {@link ForestRequest}
*/
public ForestRequest addQuery(ForestQueryParameter queryParameter) {
this.query.addQuery(queryParameter);
return this;
}
/**
* Query
* @param queryParameters Query{@link ForestQueryParameter}
* @return {@link ForestRequest}
*/
public ForestRequest addQuery(Collection<ForestQueryParameter> queryParameters) {
for (ForestQueryParameter queryParameter : queryParameters) {
addQuery(queryParameter);
}
return this;
}
/**
* Query
* @param name Query
* @param queryValues Query
* @return {@link ForestRequest}
*/
public ForestRequest addQueryValues(String name, Collection queryValues) {
for (Object queryValue : queryValues) {
addQuery(name, queryValue);
}
return this;
}
/**
* Query
* @param queryParameters Query{@link ForestQueryParameter}
* @return {@link ForestRequest}
*/
public ForestRequest addQuery(ForestQueryParameter[] queryParameters) {
for (ForestQueryParameter queryParameter : queryParameters) {
addQuery(queryParameter);
}
return this;
}
/**
* Query
* @param queryParameter Query{@link ForestQueryParameter}
* @return {@link ForestRequest}
*/
public ForestRequest replaceQuery(ForestQueryParameter queryParameter) {
List<ForestQueryParameter> queryParameters = this.query.getQueries(queryParameter.getName());
for (ForestQueryParameter parameter : queryParameters) {
parameter.setValue(queryParameter.getValue());
}
return this;
}
/**
* Query
* @param name Query
* @param value Query
* @return {@link ForestRequest}
*/
public ForestRequest replaceQuery(String name, Object value) {
List<ForestQueryParameter> queryParameters = this.query.getQueries(name);
for (ForestQueryParameter parameter : queryParameters) {
parameter.setValue(value);
}
return this;
}
/**
* Query
* <p>{@link ForestQueryParameter}Query{@link ForestQueryParameter}Query</p>
* <p>QueryQuery</p>
*
* @param queryParameter Query{@link ForestQueryParameter}
* @return {@link ForestRequest}
*/
public ForestRequest replaceOrAddQuery(ForestQueryParameter queryParameter) {
List<ForestQueryParameter> queryParameters = this.query.getQueries(queryParameter.getName());
if (queryParameters.isEmpty()) {
addQuery(queryParameter);
} else {
for (ForestQueryParameter parameter : queryParameters) {
parameter.setValue(queryParameter.getValue());
}
}
return this;
}
/**
* Query
* <p>{@code name}Query{@code name}{@code value}Query</p>
* <p>QueryQuery</p>
*
* @param name Query
* @param value Query
* @return {@link ForestRequest}
*/
public ForestRequest replaceOrAddQuery(String name, String value) {
List<ForestQueryParameter> queryParameters = this.query.getQueries(name);
if (queryParameters.isEmpty()) {
addQuery(name, value);
} else {
for (ForestQueryParameter parameter : queryParameters) {
parameter.setValue(value);
}
}
return this;
}
public ForestRequestType getType() {
return type;
}
public ForestRequest setType(ForestRequestType type) {
if (this.type != null) {
if (this.typeChangeHistory == null) {
this.typeChangeHistory = new LinkedList<>();
}
this.typeChangeHistory.add(this.type);
}
this.type = type;
return this;
}
/**
*
* @return
*/
public List<ForestRequestType> getTypeChangeHistory() {
return typeChangeHistory;
}
/**
*
* @return
*/
public List<String> getTypeChangeHistoryString() {
if (typeChangeHistory == null) {
return null;
}
List<String> results = new LinkedList<>();
for (ForestRequestType type : typeChangeHistory) {
results.add(type.getName());
}
return results;
}
public RequestLogMessage getRequestLogMessage() {
return requestLogMessage;
}
public void setRequestLogMessage(RequestLogMessage requestLogMessage) {
this.requestLogMessage = requestLogMessage;
}
public String getFilename() {
if (filename == null) {
synchronized (this) {
if (filename == null) {
String[] strs = getUrl().split("/");
filename = strs[strs.length - 1];
}
}
}
return filename;
}
public String getContentEncoding() {
return headers.getValue("Content-Encoding");
}
public ForestRequest setContentEncoding(String contentEncoding) {
addHeader("Content-Encoding", contentEncoding);
return this;
}
public String getUserAgent() {
return headers.getValue("User-Agent");
}
public ForestRequest setUserAgent(String userAgent) {
addHeader("User-Agent", userAgent);
return this;
}
public String getCharset() {
return charset;
}
public ForestRequest setCharset(String charset) {
this.charset = charset;
return this;
}
public String getResponseEncode() {
return responseEncode;
}
public ForestRequest<T> setResponseEncode(String responseEncode) {
this.responseEncode = responseEncode;
return this;
}
public boolean isAsync() {
return async;
}
public ForestRequest setAsync(boolean async) {
this.async = async;
return this;
}
public List<ForestRequestBody> getBody() {
return bodyItems;
}
@Deprecated
public List getBodyList() {
return bodyItems;
}
@Deprecated
public void setBodyList(List bodyList) {
this.bodyItems = bodyList;
}
public ForestDataType getDataType() {
return dataType;
}
public ForestRequest setDataType(ForestDataType dataType) {
this.dataType = dataType;
return this;
}
public String getContentType() {
return headers.getValue("Content-Type");
}
public ForestRequest setContentType(String contentType) {
addHeader("Content-Type", contentType);
return this;
}
public int getTimeout() {
return timeout;
}
public ForestRequest setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
public String getSslProtocol() {
return sslProtocol;
}
public ForestRequest setSslProtocol(String sslProtocol) {
this.sslProtocol = sslProtocol;
return this;
}
public int getRetryCount() {
return retryCount;
}
public ForestRequest setRetryCount(int retryCount) {
this.retryCount = retryCount;
return this;
}
public long getMaxRetryInterval() {
return maxRetryInterval;
}
public ForestRequest setMaxRetryInterval(long maxRetryInterval) {
this.maxRetryInterval = maxRetryInterval;
return this;
}
/**
* Body
*/
@Deprecated
public Map<String, Object> getData() {
return null;
}
/**
* Body
* @param body Forest{@link ForestRequestBody}
* @return {@link ForestRequest}
*/
public ForestRequest addBody(ForestRequestBody body) {
this.bodyItems.add(body);
return this;
}
/**
* Body
* @param stringBody
* @return {@link ForestRequest}
*/
public ForestRequest addBody(String stringBody) {
return addBody(new StringRequestBody(stringBody));
}
/**
* Body
* @param name
* @param value
* @return {@link ForestRequest}
*/
public ForestRequest addBody(String name, Object value) {
return addBody(new NameValueRequestBody(name, value));
}
/**
* Body
* @param name
* @param contentType Content-Type
* @param value
* @return {@link ForestRequest}
*/
public ForestRequest addBody(String name, String contentType, Object value) {
return addBody(new NameValueRequestBody(name, contentType, value));
}
/**
* Body
* @param nameValue
* @return {@link ForestRequest}
*/
@Deprecated
public ForestRequest addBody(RequestNameValue nameValue) {
return addBody(new NameValueRequestBody(nameValue.getName(), nameValue.getValue()));
}
/**
* Body
* @param nameValueList
* @return {@link ForestRequest}
*/
@Deprecated
public ForestRequest addBody(List<RequestNameValue> nameValueList) {
for (RequestNameValue nameValue : nameValueList) {
return addBody(nameValue);
}
return this;
}
/**
* Body,
* @param name
* @param value
* @return {@link ForestRequest}
*/
@Deprecated
public ForestRequest addData(String name, Object value) {
return addBody(name, value);
}
/**
* Body,
* @param nameValue
* @return {@link ForestRequest}
*/
@Deprecated
public ForestRequest addData(RequestNameValue nameValue) {
return addNameValue(nameValue);
}
/**
* Body,
* @param data
* @return {@link ForestRequest}
*/
@Deprecated
public ForestRequest addData(List<RequestNameValue> data) {
return addNameValue(data);
}
/**
*
* @param nameValue
* @return {@link ForestRequest}
*/
public ForestRequest addNameValue(RequestNameValue nameValue) {
if (nameValue.isInHeader()) {
this.addHeader(nameValue.getName(), nameValue.getValue());
} else if (nameValue.isInQuery()) {
this.addQuery(nameValue.getName(), nameValue.getValue());
} else if (nameValue.isInBody()) {
this.addBody(nameValue.getName(), nameValue.getPartContentType(), nameValue.getValue());
}
return this;
}
/**
*
* @param nameValueList
* @return {@link ForestRequest}
*/
public ForestRequest addNameValue(List<RequestNameValue> nameValueList) {
for (RequestNameValue nameValue : nameValueList) {
addNameValue(nameValue);
}
return this;
}
/**
* BodyBody
* @param body
* @return {@link ForestRequest}
*/
public ForestRequest replaceBody(ForestRequestBody body) {
this.bodyItems.clear();
this.addBody(body);
return this;
}
/**
* BodyBody
* @param stringbody
* @return {@link ForestRequest}
*/
public ForestRequest replaceBody(String stringbody) {
this.bodyItems.clear();
this.addBody(stringbody);
return this;
}
@Deprecated
public List<RequestNameValue> getQueryNameValueList() {
List<RequestNameValue> nameValueList = new ArrayList<>();
for (Iterator<Map.Entry<String, Object>> iterator = query.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Object> entry = iterator.next();
String name = entry.getKey();
Object value = entry.getValue();
RequestNameValue nameValue = new RequestNameValue(name, value, TARGET_QUERY);
nameValueList.add(nameValue);
}
return nameValueList;
}
public List<ForestQueryParameter> getQueryValues() {
return query.queryValues();
}
public List<RequestNameValue> getDataNameValueList() {
List<RequestNameValue> nameValueList = new ArrayList<>();
for (ForestRequestBody item : bodyItems) {
if (item instanceof NameValueRequestBody) {
NameValueRequestBody nameValueRequestBody = (NameValueRequestBody) item;
String name = nameValueRequestBody.getName();
Object value = nameValueRequestBody.getValue();
RequestNameValue nameValue = new RequestNameValue(name, value, TARGET_BODY, nameValueRequestBody.getContentType());
nameValueList.add(nameValue);
}
}
return nameValueList;
}
public List<RequestNameValue> getHeaderNameValueList() {
List<RequestNameValue> nameValueList = new ArrayList<RequestNameValue>();
for (Iterator<ForestHeader> iterator = headers.headerIterator(); iterator.hasNext(); ) {
ForestHeader header = iterator.next();
RequestNameValue nameValue = new RequestNameValue(header.getName(), header.getValue(), TARGET_HEADER);
nameValueList.add(nameValue);
}
return nameValueList;
}
/**
*
*
* @param index
* @return
*/
public Object getArgument(int index) {
return arguments[index];
}
/**
*
*
* @return
*/
public Object[] getArguments() {
return arguments;
}
/**
*
*
* @return {@link ForestHeaderMap}
*/
public ForestHeaderMap getHeaders() {
return headers;
}
/**
*
*
* @param name
* @return {@link ForestHeader}
*/
public ForestHeader getHeader(String name) {
return headers.getHeader(name);
}
/**
*
*
* @param name
* @return
*/
public String getHeaderValue(String name) {
return headers.getValue(name);
}
/**
*
*
* @param name
* @param value
* @return {@link ForestRequest}
*/
public ForestRequest addHeader(String name, Object value) {
if (StringUtils.isEmpty(name)) {
return this;
}
this.headers.setHeader(name, String.valueOf(value));
return this;
}
/**
*
*
* @param nameValue {@link RequestNameValue}
* @return {@link ForestRequest}
*/
public ForestRequest addHeader(RequestNameValue nameValue) {
this.addHeader(nameValue.getName(), nameValue.getValue());
return this;
}
/**
*
*
* @param nameValues
* @return {@link ForestRequest}
*/
public ForestRequest addHeaders(List<RequestNameValue> nameValues) {
for (RequestNameValue nameValue : nameValues) {
this.addHeader(nameValue.getName(), nameValue.getValue());
}
return this;
}
public List<ForestMultipart> getMultiparts() {
return multiparts;
}
public ForestRequest setMultiparts(List<ForestMultipart> multiparts) {
this.multiparts = multiparts;
return this;
}
/**
* OnSuccess
*
* @return {@link OnSuccess}
*/
public OnSuccess getOnSuccess() {
return onSuccess;
}
/**
* OnSuccess
*
* @param onSuccess {@link OnSuccess}
* @return {@link ForestRequest}
*/
public ForestRequest setOnSuccess(OnSuccess onSuccess) {
this.onSuccess = onSuccess;
return this;
}
/**
* OnError
*
* @return {@link OnError}
*/
public OnError getOnError() {
return onError;
}
/**
* OnError
*
* @param onError {@link OnError}
* @return {@link ForestRequest}
*/
public ForestRequest setOnError(OnError onError) {
this.onError = onError;
return this;
}
/**
*
*
* @return {@code true}: {@code false}:
*/
public boolean isDownloadFile() {
return isDownloadFile;
}
/**
*
*
* @param downloadFile {@code true}: {@code false}:
* @return {@link ForestRequest}
*/
public ForestRequest setDownloadFile(boolean downloadFile) {
isDownloadFile = downloadFile;
return this;
}
/**
* /
* <p>/</p>
*
* @return {@code long}
*/
public long getProgressStep() {
return progressStep;
}
/**
* /
* <p>/</p>
*
* @param progressStep {@code long}
* @return {@link ForestRequest}
*/
public ForestRequest setProgressStep(long progressStep) {
this.progressStep = progressStep;
return this;
}
/**
* /
* <p>/ ${progressStep} </p>
*
* @return {@link OnProgress}
*/
public OnProgress getOnProgress() {
return onProgress;
}
/**
* /
* <p>/ ${progressStep} </p>
*
* @param onProgress {@link OnProgress}
* @return {@link ForestRequest}
*/
public ForestRequest setOnProgress(OnProgress onProgress) {
this.onProgress = onProgress;
return this;
}
/**
* : Cookie
*
* @return {@link OnLoadCookie}
*/
public OnLoadCookie getOnLoadCookie() {
return onLoadCookie;
}
/**
* : Cookie
*
* @param onLoadCookie {@link OnLoadCookie}
* @return {@link ForestRequest}
*/
public ForestRequest setOnLoadCookie(OnLoadCookie onLoadCookie) {
this.onLoadCookie = onLoadCookie;
return this;
}
/**
* : Cookie
*
* @return {@link OnSaveCookie}
*/
public OnSaveCookie getOnSaveCookie() {
return onSaveCookie;
}
/**
* : Cookie
*
* @param onSaveCookie {@link OnSaveCookie}
* @return {@link ForestRequest}
*/
public ForestRequest setOnSaveCookie(OnSaveCookie onSaveCookie) {
this.onSaveCookie = onSaveCookie;
return this;
}
/**
*
* <p></p>
*
* @param interceptor {@link Interceptor}
* @return {@link ForestRequest}
*/
public ForestRequest<T> addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
return this;
}
/**
*
*
* @return {@link InterceptorChain}
*/
public InterceptorChain getInterceptorChain() {
return interceptorChain;
}
/**
*
* <p></p>
* <p></p>
* <p>
* <br>
* 1. ABattr1<br>
* 2. T1T2 attr1<br>
* T1attr1T2attr1
* </p>
* @param interceptorClass
* @param attributes {@link InterceptorAttributes}
* @return {@link ForestRequest}
*/
public ForestRequest addInterceptorAttributes(Class interceptorClass, InterceptorAttributes attributes) {
InterceptorAttributes oldAttributes = interceptorAttributes.get(interceptorClass);
if (oldAttributes != null) {
for (Map.Entry<String, Object> entry : attributes.getAttributeTemplates().entrySet()) {
oldAttributes.addAttribute(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : attributes.getAttributes().entrySet()) {
oldAttributes.addAttribute(entry.getKey(), entry.getValue());
}
} else {
interceptorAttributes.put(interceptorClass, attributes);
}
return this;
}
/**
*
* <p></p>
* <p></p>
* <p>
* <br>
* 1. ABattr1<br>
* 2. T1T2 attr1<br>
* T1attr1T2attr1
* </p>
*
* @param interceptorClass
* @param attributeName
* @param attributeValue
* @return {@link ForestRequest}
*/
public ForestRequest addInterceptorAttribute(Class interceptorClass, String attributeName, Object attributeValue) {
InterceptorAttributes attributes = getInterceptorAttributes(interceptorClass);
if (attributes == null) {
attributes = new InterceptorAttributes(interceptorClass, new HashMap<>());
addInterceptorAttributes(interceptorClass, attributes);
}
attributes.addAttribute(attributeName, attributeValue);
return this;
}
/**
*
* <p>
* <br>
* 1. ABattr1<br>
* 2. T1T2 attr1<br>
* T1attr1T2attr1
* </p>
*
* @return {@link Map}Key: Value: {@link InterceptorAttributes}
*/
public Map<Class, InterceptorAttributes> getInterceptorAttributes() {
return interceptorAttributes;
}
/**
*
* <p>
* <br>
* 1. ABattr1<br>
* 2. T1T2 attr1<br>
* T1attr1T2attr1
* </p>
*
* @param interceptorClass
* @return {@link InterceptorAttributes}
*/
public InterceptorAttributes getInterceptorAttributes(Class interceptorClass) {
return interceptorAttributes.get(interceptorClass);
}
/**
*
* <p>
* <br>
* 1. ABattr1<br>
* 2. T1T2 attr1<br>
* T1attr1T2attr1
* </p>
*
* @param interceptorClass
* @param attributeName
* @return
*/
public Object getInterceptorAttribute(Class interceptorClass, String attributeName) {
InterceptorAttributes attributes = interceptorAttributes.get(interceptorClass);
if (attributes == null) {
return null;
}
return attributes.getAttribute(attributeName);
}
/**
* Forest
*
* @return Forest{@link Retryer}
*/
public Retryer getRetryer() {
return retryer;
}
/**
* Forest
*
* @param retryer Forest{@link Retryer}
* @return {@link ForestRequest}
*/
public ForestRequest setRetryer(Retryer retryer) {
this.retryer = retryer;
return this;
}
/**
*
* <p>Attachment </p>
* <p></p>
*
* @param name
* @param value
* @return {@link ForestRequest}
*/
public ForestRequest addAttachment(String name, Object value) {
attachments.put(name, value);
return this;
}
/**
*
* <p>Attachment </p>
* <p></p>
*
* @param name
* @return
*/
public Object getAttachment(String name) {
return attachments.get(name);
}
/**
*
* @return {@link ForestConverter}
*/
public ForestConverter getDecoder() {
return decoder;
}
/**
*
* @param decoder {@link ForestConverter}
* @return {@link ForestRequest}
*/
public ForestRequest setDecoder(ForestConverter decoder) {
this.decoder = decoder;
return this;
}
/**
* /
* @return {@code true}{@code false}
*/
@Deprecated
public boolean isLogEnable() {
if (logConfiguration == null) {
return true;
}
return logConfiguration.isLogEnabled();
}
/**
*
* @return {@link LogConfiguration}
*/
public LogConfiguration getLogConfiguration() {
return logConfiguration;
}
public ForestRequest setLogConfiguration(LogConfiguration logConfiguration) {
this.logConfiguration = logConfiguration;
return this;
}
/**
* SSL KeyStore
* <p>HTTPS</p>
*
* @return SSL KeyStore{@link SSLKeyStore}
*/
public SSLKeyStore getKeyStore() {
return keyStore;
}
/**
* SSL KeyStore
* <p>HTTPS</p>
*
* @param keyStore SSL KeyStore{@link SSLKeyStore}
* @return {@link ForestRequest}
*/
public ForestRequest setKeyStore(SSLKeyStore keyStore) {
this.keyStore = keyStore;
return this;
}
/**
*
*
* @return {@link ForestProxy}
*/
public ForestProxy getProxy() {
return proxy;
}
/**
*
*
* @param proxy {@link ForestProxy}
* @return {@link ForestRequest}
*/
public ForestRequest setProxy(ForestProxy proxy) {
this.proxy = proxy;
return this;
}
/**
*
*
* @param result
* @return {@link ForestRequest}
*/
public ForestRequest methodReturn(T result) {
if (this.lifeCycleHandler != null) {
this.lifeCycleHandler.handleResult(result);
}
return this;
}
/**
*
*
* @return
*/
public Object getMethodReturnValue() {
if (this.lifeCycleHandler != null) {
if (this.lifeCycleHandler instanceof MethodLifeCycleHandler) {
return ((MethodLifeCycleHandler) lifeCycleHandler).getResultData();
}
}
return null;
}
/**
*
* @param backend HTTP{@link HttpBackend}
* @param lifeCycleHandler {@link LifeCycleHandler}
*/
public Object execute(HttpBackend backend, LifeCycleHandler lifeCycleHandler) {
if (interceptorChain.beforeExecute(this)) {
HttpExecutor executor = backend.createExecutor(this, lifeCycleHandler);
if (executor != null) {
try {
executor.execute(lifeCycleHandler);
} catch (ForestRuntimeException e) {
throw e;
} finally {
executor.close();
}
}
}
return getMethodReturnValue();
}
public Object execute() {
return execute(getBackend(), getLifeCycleHandler());
}
} |
package org.zanata.page;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Supplier;
import java.util.logging.Level;
import com.google.common.reflect.AbstractInvocationHandler;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.client.ClientUtil;
import net.lightbody.bmp.filters.ResponseFilterAdapter;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.service.DriverService;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.events.WebDriverEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zanata.util.PropertiesHolder;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.zanata.util.ScreenshotDirForTest;
import org.zanata.util.TestEventForScreenshotListener;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import static java.lang.reflect.Proxy.newProxyInstance;
import static org.zanata.util.Constants.webDriverType;
import static org.zanata.util.Constants.webDriverWait;
import static org.zanata.util.Constants.zanataInstance;
@Slf4j
public enum WebDriverFactory {
INSTANCE;
private static final ThreadLocal<SimpleDateFormat> TIME_FORMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("HH:mm:ss.SSS");
}
};
// can reuse, share globally
private static ObjectMapper mapper = new ObjectMapper();
private volatile EventFiringWebDriver driver = createDriver();
private @Nonnull DswidParamChecker dswidParamChecker;
private DriverService driverService;
private TestEventForScreenshotListener screenshotListener;
private int webdriverWait;
private final String[] ignoredLogPatterns = {
".*/org.richfaces/jquery.js .* " +
"'webkit(?:Cancel)?RequestAnimationFrame' is vendor-specific. " +
"Please use the standard " +
"'(?:request|cancel)AnimationFrame' instead.",
".*/org.richfaces/jquery.js .* " +
"'webkitMovement[XY]' is deprecated. " +
"Please use 'movement[XY]' instead.",
"http://example.com/piwik/piwik.js .*",
};
@Nullable
private WebDriverEventListener logListener;
public WebDriver getDriver() {
return driver;
}
private JavascriptExecutor getExecutor() {
return (JavascriptExecutor) getDriver();
}
private EventFiringWebDriver createDriver() {
String driverType = PropertiesHolder.getProperty(webDriverType.value());
EventFiringWebDriver newDriver;
switch (driverType.toLowerCase()) {
case "chrome":
newDriver = configureChromeDriver();
break;
case "firefox":
newDriver = configureFirefoxDriver();
break;
default:
throw new UnsupportedOperationException("only support chrome " +
"and firefox driver");
}
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
webdriverWait = Integer.parseInt(PropertiesHolder
.getProperty(webDriverWait.value()));
dswidParamChecker = new DswidParamChecker(newDriver);
newDriver.register(dswidParamChecker.getEventListener());
return newDriver;
}
/**
* List the WebDriver log types
*
* LogType.CLIENT doesn't seem to log anything
* LogType.DRIVER, LogType.PERFORMANCE are too verbose
* LogType PROFILER and LogType.SERVER don't seem to work
*
* @return String array of log types
*/
private String[] getLogTypes() {
return new String[]{
LogType.BROWSER
};
}
/**
* Retrieves all the outstanding WebDriver logs of the specified type.
* @param type a log type from org.openqa.selenium.logging.LogType
* (but they don't all seem to work)
*/
public LogEntries getLogs(String type) {
return getDriver().manage().logs().get(type);
}
private String toString(long timestamp, String text, @Nullable String json) {
String time =
TIME_FORMAT.get().format(new Date(timestamp));
return time + " " + text + (json != null ? ": " + json : "");
}
private boolean ignorable(String message) {
for (String ignorable : ignoredLogPatterns) {
if (message.matches(ignorable)) {
return true;
}
}
return false;
}
/**
* Logs all the outstanding WebDriver logs of the specified type.
* @param type a log type from org.openqa.selenium.logging.LogType
* (but they don't all seem to work)
* @throws WebDriverLogException exception containing the first warning/error message, if any
*/
private void logLogs(String type, boolean throwIfWarn) {
@Nullable
WebDriverLogException firstException = null;
String logName = WebDriverFactory.class.getName() + "." + type;
Logger log = LoggerFactory.getLogger(logName);
int logCount = 0;
for (LogEntry logEntry : getLogs(type)) {
++logCount;
Level level;
long time = logEntry.getTimestamp();
String text, json;
String msg = logEntry.getMessage();
if (msg.startsWith("{")) {
// looks like it might be json
json = msg;
try {
JsonNode message = mapper.readValue(json, ObjectNode.class).path("message");
String levelString = message.path("level").asText();
level = toLogLevel(levelString);
text = message.path("text").asText();
} catch (Exception e) {
log.warn("unable to parse as json: " + json, e);
level = logEntry.getLevel();
text = msg;
json = null;
}
} else {
level = logEntry.getLevel();
text = msg;
json = null;
}
String logString = toString(time, text, json);
if (level.intValue() >= Level.SEVERE.intValue()) {
log.error(logString);
// If firstException was a warning, replace it with this error.
if ((firstException == null || !firstException.isErrorLog()) && !ignorable(msg)) {
// We only throw this if throwIfWarn is true
firstException = new WebDriverLogException(level,
logString, driver.getPageSource());
}
} else if (level.intValue() >= Level.WARNING.intValue()) {
log.warn(logString);
if ((firstException == null) && !ignorable(msg)) {
// We only throw this if throwIfWarn is true
firstException = new WebDriverLogException(logEntry.getLevel(),
logString, driver.getPageSource());
}
} else if (level.intValue() >= Level.INFO.intValue()) {
log.info(logString);
} else {
log.debug(logString);
}
}
if (throwIfWarn && firstException != null) {
throw firstException;
}
}
private Level toLogLevel(String jsLevel) {
String upperCase = jsLevel.toUpperCase();
if (upperCase.equals("WARN")) {
return Level.WARNING;
}
return Level.parse(upperCase);
}
/**
* Dump any outstanding browser logs to the main log.
*
* @throws WebDriverLogException exception containing the first error message, if any
*/
public void logLogs() {
// DeltaSpike's LAZY mode uses client-side redirects, which cause
// other scripts to abort loading in strange ways when dswid is
// missing/wrong. However, the server code currently preserves dswid
// whenever possible, and DswidParamChecker aims to make sure it
// continues to, so we can treat JS warnings/errors as failures.
logLogs(false);
}
/**
* Dump any outstanding browser logs to the main log.
*
* @throws WebDriverLogException exception containing the first warning/error message, if any
*/
public void logLogs(boolean throwIfWarn) {
for (String type : getLogTypes()) {
logLogs(type, throwIfWarn);
}
}
public String getHostUrl() {
return PropertiesHolder.getProperty(zanataInstance.value());
}
public int getWebDriverWait() {
return webdriverWait;
}
public void registerScreenshotListener(String testName) {
log.info("Enabling screenshot module...");
if (screenshotListener == null && ScreenshotDirForTest.isScreenshotEnabled()) {
screenshotListener = new TestEventForScreenshotListener(driver);
}
driver.register(screenshotListener);
screenshotListener.updateTestID(testName);
}
@ParametersAreNonnullByDefault
public void registerLogListener() {
if (logListener == null) {
logListener = (WebDriverEventListener) newProxyInstance(
WebDriverEventListener.class.getClassLoader(),
new Class<?>[]{ WebDriverEventListener.class },
new AbstractInvocationHandler() {
@Override
protected Object handleInvocation(
Object proxy,
Method method,
Object[] args) throws Throwable {
logLogs();
return null;
}
});
}
driver.register(logListener);
}
public void unregisterLogListener() {
driver.unregister(logListener);
}
public void unregisterScreenshotListener() {
log.info("Deregistering screenshot module...");
driver.unregister(screenshotListener);
}
public void injectScreenshot(String tag) {
if (null != screenshotListener) {
screenshotListener.customEvent(tag);
}
}
private EventFiringWebDriver configureChromeDriver() {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
PropertiesHolder.getProperty("webdriver.log"));
driverService = ChromeDriverService.createDefaultService();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.binary", PropertiesHolder.properties
.getProperty("webdriver.chrome.bin"));
ChromeOptions options = new ChromeOptions();
URL url = Thread.currentThread().getContextClassLoader().getResource("zanata-testing-extension/chrome/manifest.json");
assert url != null : "can't find extension (check testResource config in pom.xml)";
File file = new File(url.getPath()).getParentFile();
options.addArguments("load-extension=" + file.getAbsolutePath());
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
enableLogging(capabilities);
// start the proxy
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.start(0);
proxy.addFirstHttpFilterFactory(new ResponseFilterAdapter.FilterSource(
(response, contents, messageInfo) -> {
// TODO fail test if response >= 500?
if (response.getStatus().code() >= 400) {
log.warn("Response {} for URI {}", response.getStatus(), messageInfo.getOriginalRequest().getUri());
} else {
log.info("Response {} for URI {}", response.getStatus(), messageInfo.getOriginalRequest().getUri());
}
}, 0));
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
try {
driverService.start();
} catch (IOException e) {
throw new RuntimeException("fail to start chrome driver service");
}
return new EventFiringWebDriver(new Augmenter().augment(
new RemoteWebDriver(driverService.getUrl(), capabilities)));
}
private EventFiringWebDriver configureFirefoxDriver() {
final String pathToFirefox =
Strings.emptyToNull(PropertiesHolder.properties
.getProperty("firefox.path"));
FirefoxBinary firefoxBinary;
if (pathToFirefox != null) {
firefoxBinary = new FirefoxBinary(new File(pathToFirefox));
} else {
firefoxBinary = new FirefoxBinary();
}
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
enableLogging(capabilities);
return new EventFiringWebDriver(new FirefoxDriver(firefoxBinary,
makeFirefoxProfile(), capabilities));
}
private void enableLogging(DesiredCapabilities capabilities) {
LoggingPreferences logs = new LoggingPreferences();
for (String type : getLogTypes()) {
logs.enable(type, Level.INFO);
}
capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
}
private FirefoxProfile makeFirefoxProfile() {
if (!Strings.isNullOrEmpty(System
.getProperty("webdriver.firefox.profile"))) {
throw new RuntimeException("webdriver.firefox.profile is ignored");
// TODO - look at FirefoxDriver.getProfile().
}
final FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setAlwaysLoadNoFocusLib(true);
firefoxProfile.setEnableNativeEvents(true);
firefoxProfile.setAcceptUntrustedCertificates(true);
// TODO port zanata-testing-extension to firefox
// File file = new File("extension.xpi");
// firefoxProfile.addExtension(file);
return firefoxProfile;
}
public void testEntry() {
clearDswid();
}
public void testExit() {
clearDswid();
}
private void clearDswid() {
// clear the browser's memory of the dswid
getExecutor().executeScript("window.name = ''");
dswidParamChecker.clear();
}
public <T> T ignoringDswid(Supplier<T> supplier) {
dswidParamChecker.stopChecking();
try {
return supplier.get();
} finally {
dswidParamChecker.startChecking();
}
}
public void ignoringDswid(Runnable r) {
dswidParamChecker.stopChecking();
try {
r.run();
} finally {
dswidParamChecker.startChecking();
}
}
private class ShutdownHook extends Thread {
public void run() {
// If webdriver is running quit.
WebDriver driver = getDriver();
if (driver != null) {
try {
log.info("Quitting webdriver.");
driver.quit();
} catch (Throwable e) {
// Ignoring driver tear down errors.
}
}
if (driverService != null && driverService.isRunning()) {
driverService.stop();
}
}
}
} |
package com.google.sps.servlets;
import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit;
import static org.junit.Assert.assertEquals;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class CuratedPostsTest {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
@Before
public void setUp() {
helper.setUp();
}
@After
public void tearDown() {
helper.tearDown();
}
private void createDatastoreEntities() {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity noTagEntity = new Entity("UserLogin");
noTagEntity.setProperty("id", "357911");
noTagEntity.setProperty("nickname", "noTags");
noTagEntity.setProperty("email", "noTags@testing.com");
datastore.put(noTagEntity);
Entity hasTagEntity = new Entity("UserLogin");
hasTagEntity.setProperty("id", "246810");
hasTagEntity.setProperty("nickname", "hasTags");
hasTagEntity.setProperty("email", "hasTags@testing.com");
datastore.put(hasTagEntity);
Entity hasMultipleTagsEntity = new Entity("UserLogin");
hasMultipleTagsEntity.setProperty("id", "123456");
hasMultipleTagsEntity.setProperty("nickname", "hasMultipleTags");
hasMultipleTagsEntity.setProperty("email", "hasMultipleTags@testing.com");
datastore.put(hasMultipleTagsEntity);
Entity blogMessageEntity = new Entity("blogMessage");
blogMessageEntity.setProperty("nickname", "test1");
blogMessageEntity.setProperty("text","test text business" );
blogMessageEntity.setProperty("time", System.currentTimeMillis());
blogMessageEntity.setProperty("tag", "#business");
blogMessageEntity.setProperty("parentID", 0);
datastore.put(blogMessageEntity);
Entity hasTagFollowedTags = new Entity("followedTag");
hasTagFollowedTags.setProperty("tag", "#business");
hasTagFollowedTags.setProperty("email", "hasTags@testing.com");
datastore.put(hasTagFollowedTags);
List<String> hasMultipleTagsFollowed = new ArrayList<String>();
hasMultipleTagsFollowed.add("#business");
hasMultipleTagsFollowed.add("#education");
hasMultipleTagsFollowed.add("#music");
for (int i=0; i<hasMultipleTagsFollowed.size(); i++) {
Entity hasMultipleTagsFollowedTags = new Entity("followedTag");
hasMultipleTagsFollowedTags.setProperty("tag", hasMultipleTagsFollowed.get(i));
hasMultipleTagsFollowedTags.setProperty("email", "hasMultipleTags@testing.com");
datastore.put(hasMultipleTagsFollowedTags);
}
}
@Test
public void testFollowsNoTags() {
createDatastoreEntities();
List<String> expectedFollowedTags = new ArrayList<String>();
assertEquals(expectedFollowedTags, LoadFollowedTags.getFollowedTags("noTags@testing.com"));
}
@Test
public void testFollowsOneTag() {
createDatastoreEntities();
List<String> expectedFollowedTags = new ArrayList<String>();
expectedFollowedTags.add("#business");
assertEquals(expectedFollowedTags, LoadFollowedTags.getFollowedTags("hasTags@testing.com"));
assertEquals(1, LoadFollowedTags.getFollowedTags("hasTags@testing.com").size());
}
@Test
public void testFollowsMultipleTag() {
createDatastoreEntities();
List<String> expectedFollowedTags = new ArrayList<String>();
expectedFollowedTags.add("#business");
expectedFollowedTags.add("#education");
expectedFollowedTags.add("#music");
assertEquals(expectedFollowedTags, LoadFollowedTags.getFollowedTags("hasMultipleTags@testing.com"));
assertEquals(3, LoadFollowedTags.getFollowedTags("hasMultipleTags@testing.com").size());
}
@Test
public void testFollowsTagsFalse() {
createDatastoreEntities();
Boolean expectedFollowedTags = false;
assertEquals(expectedFollowedTags, LoadFollowedTags.hasFollowedTags("noTags@testing.com"));
}
@Test
public void testFollowsTagsTrue() {
createDatastoreEntities();
Boolean expectedFollowedTags = true;
assertEquals(expectedFollowedTags, LoadFollowedTags.hasFollowedTags("hasTags@testing.com"));
assertEquals(expectedFollowedTags, LoadFollowedTags.hasFollowedTags("hasMultipleTags@testing.com"));
}
} |
package org.jboss.as.model;
import java.util.Collection;
import java.util.NavigableMap;
import java.util.TreeMap;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.model.socket.InterfaceElement;
import org.jboss.as.model.socket.SocketBindingGroupElement;
import org.jboss.msc.service.Location;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* The JBoss AS Domain state. An instance of this class represents the complete running state of the domain.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class Domain extends AbstractModel<Domain> {
private static final long serialVersionUID = 5516070442013067881L;
private final NavigableMap<String, ExtensionElement> extensions = new TreeMap<String, ExtensionElement>();
private final NavigableMap<String, ServerGroupElement> serverGroups = new TreeMap<String, ServerGroupElement>();
private final NavigableMap<DeploymentUnitKey, DeploymentUnitElement> deployments = new TreeMap<DeploymentUnitKey, DeploymentUnitElement>();
private final NavigableMap<String, ProfileElement> profiles = new TreeMap<String, ProfileElement>();
private final NavigableMap<String, InterfaceElement> interfaces = new TreeMap<String, InterfaceElement>();
private final NavigableMap<String, SocketBindingGroupElement> bindingGroups = new TreeMap<String, SocketBindingGroupElement>();
private PropertiesElement systemProperties;
/**
* Construct a new instance.
*
* @param location the declaration location of the domain element
* @param elementName the element name of this domain element
*/
public Domain(final Location location, final QName elementName) {
super(location, elementName);
}
/**
* Construct a new instance.
*
* @param reader the reader from which to build this element
* @throws XMLStreamException if an error occurs
*/
public Domain(final XMLExtendedStreamReader reader) throws XMLStreamException {
super(reader);
// Handle attributes
requireNoAttributes(reader);
// Handle elements
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case DOMAIN_1_0: {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case EXTENSIONS: {
parseExtensions(reader);
break;
}
case PROFILES: {
parseProfiles(reader);
break;
}
case INTERFACES: {
parseInterfaces(reader);
break;
}
case SOCKET_BINDING_GROUPS: {
parseSocketBindingGroups(reader);
break;
}
case DEPLOYMENTS: {
parseDeployments(reader);
break;
}
case SERVER_GROUPS: {
parseServerGroups(reader);
break;
}
case SYSTEM_PROPERTIES: {
if (systemProperties != null) {
throw new XMLStreamException(element.getLocalName() + " already declared", reader.getLocation());
}
this.systemProperties = new PropertiesElement(reader);
break;
}
default: throw unexpectedElement(reader);
}
break;
}
default: throw unexpectedElement(reader);
}
}
}
/** {@inheritDoc} */
public long elementHash() {
long hash = 0L;
hash = calculateElementHashOf(extensions.values(), hash);
hash = calculateElementHashOf(serverGroups.values(), hash);
hash = calculateElementHashOf(deployments.values(), hash);
hash = calculateElementHashOf(profiles.values(), hash);
hash = calculateElementHashOf(interfaces.values(), hash);
hash = calculateElementHashOf(bindingGroups.values(), hash);
if (systemProperties != null) hash = Long.rotateLeft(hash, 1) ^ systemProperties.elementHash();
return hash;
}
/** {@inheritDoc} */
protected void appendDifference(final Collection<AbstractModelUpdate<Domain>> target, final Domain other) {
calculateDifference(target, extensions, other.extensions, new DifferenceHandler<String, ExtensionElement, Domain>() {
public void handleAdd(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ExtensionElement newElement) {
throw new UnsupportedOperationException("implement me");
}
public void handleRemove(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ExtensionElement oldElement) {
throw new UnsupportedOperationException("implement me");
}
public void handleChange(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ExtensionElement oldElement, final ExtensionElement newElement) {
// not possible
throw new IllegalStateException();
}
});
calculateDifference(target, profiles, other.profiles, new DifferenceHandler<String, ProfileElement, Domain>() {
public void handleAdd(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ProfileElement newElement) {
// todo add-profile
throw new UnsupportedOperationException("implement me");
}
public void handleRemove(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ProfileElement oldElement) {
// todo remove-profile
throw new UnsupportedOperationException("implement me");
}
public void handleChange(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ProfileElement oldElement, final ProfileElement newElement) {
// todo change profile
throw new UnsupportedOperationException("implement me");
}
});
calculateDifference(target, interfaces, other.interfaces, new DifferenceHandler<String, InterfaceElement, Domain>() {
public void handleAdd(final Collection<AbstractModelUpdate<Domain>> target, final String name, final InterfaceElement newElement) {
// todo add-interface
throw new UnsupportedOperationException("implement me");
}
public void handleRemove(final Collection<AbstractModelUpdate<Domain>> target, final String name, final InterfaceElement oldElement) {
// todo remove-interface
throw new UnsupportedOperationException("implement me");
}
public void handleChange(final Collection<AbstractModelUpdate<Domain>> target, final String name, final InterfaceElement oldElement, final InterfaceElement newElement) {
// todo change interface
throw new UnsupportedOperationException("implement me");
}
});
calculateDifference(target, bindingGroups, other.bindingGroups, new DifferenceHandler<String, SocketBindingGroupElement, Domain>() {
public void handleAdd(final Collection<AbstractModelUpdate<Domain>> target, final String name, final SocketBindingGroupElement newElement) {
// todo add binding group
throw new UnsupportedOperationException("implement me");
}
public void handleRemove(final Collection<AbstractModelUpdate<Domain>> target, final String name, final SocketBindingGroupElement oldElement) {
// todo remove binding group
throw new UnsupportedOperationException("implement me");
}
public void handleChange(final Collection<AbstractModelUpdate<Domain>> target, final String name, final SocketBindingGroupElement oldElement, final SocketBindingGroupElement newElement) {
// todo change binding group
throw new UnsupportedOperationException("implement me");
}
});
// todo enclosing diff item
systemProperties.appendDifference(null, other.systemProperties);
calculateDifference(target, deployments, other.deployments, new DifferenceHandler<DeploymentUnitKey, DeploymentUnitElement, Domain>() {
public void handleAdd(final Collection<AbstractModelUpdate<Domain>> target, final DeploymentUnitKey key, final DeploymentUnitElement newElement) {
// todo deploy
throw new UnsupportedOperationException("implement me");
}
public void handleRemove(final Collection<AbstractModelUpdate<Domain>> target, final DeploymentUnitKey key, final DeploymentUnitElement oldElement) {
// todo undeploy
throw new UnsupportedOperationException("implement me");
}
public void handleChange(final Collection<AbstractModelUpdate<Domain>> target, final DeploymentUnitKey key, final DeploymentUnitElement oldElement, final DeploymentUnitElement newElement) {
// todo redeploy...? or maybe just modify stuff
throw new UnsupportedOperationException("implement me");
}
});
calculateDifference(target, serverGroups, other.serverGroups, new DifferenceHandler<String, ServerGroupElement, Domain>() {
public void handleAdd(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ServerGroupElement newElement) {
// todo add-server-group operation
throw new UnsupportedOperationException("implement me");
}
public void handleRemove(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ServerGroupElement oldElement) {
// todo remove-server-group operation
throw new UnsupportedOperationException("implement me");
}
public void handleChange(final Collection<AbstractModelUpdate<Domain>> target, final String name, final ServerGroupElement oldElement, final ServerGroupElement newElement) {
// todo update-server-group operation
oldElement.appendDifference(null, newElement);
}
});
}
/** {@inheritDoc} */
protected Class<Domain> getElementClass() {
return Domain.class;
}
/** {@inheritDoc} */
public void writeContent(final XMLExtendedStreamWriter streamWriter) throws XMLStreamException {
if (! extensions.isEmpty()) {
streamWriter.writeStartElement(Element.EXTENSIONS.getLocalName());
for (ExtensionElement element : extensions.values()) {
streamWriter.writeStartElement(Element.EXTENSIONS.getLocalName());
element.writeContent(streamWriter);
}
streamWriter.writeEndElement();
}
if (! profiles.isEmpty()) {
streamWriter.writeStartElement(Element.PROFILES.getLocalName());
for (ProfileElement element : profiles.values()) {
streamWriter.writeStartElement(Element.PROFILE.getLocalName());
element.writeContent(streamWriter);
}
streamWriter.writeEndElement();
}
if (! interfaces.isEmpty()) {
streamWriter.writeStartElement(Element.INTERFACES.getLocalName());
for (InterfaceElement element : interfaces.values()) {
streamWriter.writeStartElement(Element.INTERFACE.getLocalName());
element.writeContent(streamWriter);
}
streamWriter.writeEndElement();
}
if (!bindingGroups.isEmpty()) {
streamWriter.writeStartElement(Element.SOCKET_BINDING_GROUPS.getLocalName());
for (SocketBindingGroupElement element : bindingGroups.values()) {
streamWriter.writeStartElement(Element.SOCKET_BINDING_GROUP.getLocalName());
element.writeContent(streamWriter);
}
streamWriter.writeEndElement();
}
if (systemProperties != null && systemProperties.size() > 0) {
streamWriter.writeStartElement(Element.SYSTEM_PROPERTIES.getLocalName());
systemProperties.writeContent(streamWriter);
}
if (! deployments.isEmpty()) {
streamWriter.writeStartElement(Element.DEPLOYMENTS.getLocalName());
for (DeploymentUnitElement element : deployments.values()) {
streamWriter.writeStartElement(Element.DEPLOYMENT.getLocalName());
element.writeContent(streamWriter);
}
streamWriter.writeEndElement();
}
if (! serverGroups.isEmpty()) {
streamWriter.writeStartElement(Element.SERVER_GROUPS.getLocalName());
for (ServerGroupElement element : serverGroups.values()) {
streamWriter.writeStartElement(Element.SERVER_GROUP.getLocalName());
element.writeContent(streamWriter);
}
streamWriter.writeEndElement();
}
// close domain
streamWriter.writeEndElement();
}
private void registerExtensionHandlers(ExtensionElement extension) {
// FIXME register
throw new UnsupportedOperationException("implement me");
}
private void parseExtensions(XMLExtendedStreamReader reader) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case DOMAIN_1_0: {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case EXTENSION: {
final ExtensionElement extension = new ExtensionElement(reader);
if (extensions.containsKey(extension.getModule())) {
throw new XMLStreamException("Extension module " + extension.getModule() + " already declared", reader.getLocation());
}
extensions.put(extension.getModule(), extension);
// load the extension so it can register handlers
// TODO do this in ExtensionElement itself?
registerExtensionHandlers(extension);
break;
}
default: throw unexpectedElement(reader);
}
}
default: throw unexpectedElement(reader);
}
}
}
private void parseProfiles(XMLExtendedStreamReader reader) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case DOMAIN_1_0: {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROFILE: {
final ProfileElement profile = new ProfileElement(reader);
if (profiles.containsKey(profile.getName())) {
throw new XMLStreamException("Profile " + profile.getName() + " already declared", reader.getLocation());
}
profiles.put(profile.getName(), profile);
break;
}
default: throw unexpectedElement(reader);
}
}
default: throw unexpectedElement(reader);
}
}
}
private void parseInterfaces(XMLExtendedStreamReader reader) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case DOMAIN_1_0: {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case INTERFACE: {
final InterfaceElement interfaceEl = new InterfaceElement(reader);
if (interfaces.containsKey(interfaceEl.getName())) {
throw new XMLStreamException("Interface " + interfaceEl.getName() + " already declared", reader.getLocation());
}
interfaces.put(interfaceEl.getName(), interfaceEl);
break;
}
default: throw unexpectedElement(reader);
}
}
default: throw unexpectedElement(reader);
}
}
}
private void parseSocketBindingGroups(XMLExtendedStreamReader reader) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case DOMAIN_1_0: {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SOCKET_BINDING_GROUP: {
SocketBindingGroupElement group = new SocketBindingGroupElement(reader);
if (bindingGroups.containsKey(group.getName())) {
throw new XMLStreamException("socket-binding-group with name " +
group.getName() + " already declared", reader.getLocation());
}
bindingGroups.put(group.getName(), group);
break;
}
default: throw unexpectedElement(reader);
}
}
default: throw unexpectedElement(reader);
}
}
}
private void parseDeployments(XMLExtendedStreamReader reader) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case DOMAIN_1_0: {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case DEPLOYMENT: {
final DeploymentUnitElement deployment = new DeploymentUnitElement(reader);
if (deployments.containsKey(deployment.getKey())) {
throw new XMLStreamException("Deployment " + deployment.getName() +
" with sha1 hash " + bytesToHexString(deployment.getSha1Hash()) +
" already declared", reader.getLocation());
}
deployments.put(deployment.getKey(), deployment);
break;
}
default: throw unexpectedElement(reader);
}
}
default: throw unexpectedElement(reader);
}
}
}
private void parseServerGroups(XMLExtendedStreamReader reader) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case DOMAIN_1_0: {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SERVER_GROUP: {
final ServerGroupElement serverGroup = new ServerGroupElement(reader);
if (serverGroups.containsKey(serverGroup.getName())) {
throw new XMLStreamException("Server group " + serverGroup.getName() + " already declared", reader.getLocation());
}
serverGroups.put(serverGroup.getName(), serverGroup);
break;
}
default: throw unexpectedElement(reader);
}
}
default: throw unexpectedElement(reader);
}
}
}
} |
package de.dakror.vloxlands.util.event;
public interface IEvent
{
public String getName();
public Object getSender();
} |
package jenkins.model;
import jenkins.util.SystemProperties;
import hudson.model.Hudson;
/**
* @deprecated use {@link SystemProperties} directly
*/
@Deprecated
public class Configuration {
public static boolean getBooleanConfigParameter(String name, boolean defaultValue) {
String value = getStringConfigParameter(name,null);
return (value==null)?defaultValue:Boolean.parseBoolean(value);
}
public static String getStringConfigParameter(String name, String defaultValue) {
String value = SystemProperties.getString(Jenkins.class.getName()+"." + name);
if( value == null )
value = SystemProperties.getString(Hudson.class.getName()+"." + name);
return (value==null)?defaultValue:value;
}
} |
package jenkins.util.io;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Functions;
import hudson.Util;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Restricted(NoExternalUse.class)
public class PathRemover {
public static PathRemover newSimpleRemover() {
return new PathRemover(ignored -> false);
}
public static PathRemover newRemoverWithStrategy(@Nonnull RetryStrategy retryStrategy) {
return new PathRemover(retryStrategy);
}
public static PathRemover newRobustRemover(int maxRetries, boolean gcAfterFailedRemove, long waitBetweenRetries) {
return new PathRemover(new PausingGCRetryStrategy(maxRetries < 1 ? 1 : maxRetries, gcAfterFailedRemove, waitBetweenRetries));
}
private final RetryStrategy retryStrategy;
private PathRemover(@Nonnull RetryStrategy retryStrategy) {
this.retryStrategy = retryStrategy;
}
public void forceRemoveFile(@Nonnull Path path) throws IOException {
for (int retryAttempts = 0; ; retryAttempts++) {
Optional<IOException> maybeError = tryRemoveFile(path);
if (!maybeError.isPresent()) return;
if (retryStrategy.shouldRetry(retryAttempts)) continue;
IOException error = maybeError.get();
throw new IOException(retryStrategy.failureMessage(path, retryAttempts), error);
}
}
public void forceRemoveDirectoryContents(@Nonnull Path path) throws IOException {
for (int retryAttempt = 0; ; retryAttempt++) {
List<IOException> errors = tryRemoveDirectoryContents(path);
if (errors.isEmpty()) return;
if (retryStrategy.shouldRetry(retryAttempt)) continue;
throw new CompositeIOException(retryStrategy.failureMessage(path, retryAttempt), errors);
}
}
public void forceRemoveRecursive(@Nonnull Path path) throws IOException {
for (int retryAttempt = 0; ; retryAttempt++) {
List<IOException> errors = tryRemoveRecursive(path);
if (errors.isEmpty()) return;
if (retryStrategy.shouldRetry(retryAttempt)) continue;
throw new CompositeIOException(retryStrategy.failureMessage(path, retryAttempt), errors);
}
}
@Restricted(NoExternalUse.class)
@FunctionalInterface
public interface RetryStrategy {
boolean shouldRetry(int retriesAttempted);
default String failureMessage(@Nonnull Path fileToRemove, int retryCount) {
StringBuilder sb = new StringBuilder()
.append("Unable to delete '")
.append(fileToRemove)
.append("'. Tried ")
.append(retryCount)
.append(" time");
if (retryCount != 1) sb.append('s');
sb.append('.');
return sb.toString();
}
}
private static class PausingGCRetryStrategy implements RetryStrategy {
private final int maxRetries;
private final boolean gcAfterFailedRemove;
private final long waitBetweenRetries;
private final ThreadLocal<Boolean> interrupted = ThreadLocal.withInitial(() -> false);
private PausingGCRetryStrategy(int maxRetries, boolean gcAfterFailedRemove, long waitBetweenRetries) {
this.maxRetries = maxRetries;
this.gcAfterFailedRemove = gcAfterFailedRemove;
this.waitBetweenRetries = waitBetweenRetries;
}
@SuppressFBWarnings(value = "DM_GC", justification = "Garbage collection happens only when "
+ "GC_AFTER_FAILED_DELETE is true. It's an experimental feature in Jenkins.")
private void gcIfEnabled() {
/* If the Jenkins process had the file open earlier, and it has not
* closed it then Windows won't let us delete it until the Java object
* with the open stream is Garbage Collected, which can result in builds
* failing due to "file in use" on Windows despite working perfectly
* well on other OSs. */
if (gcAfterFailedRemove) System.gc();
}
@Override
public boolean shouldRetry(int retriesAttempted) {
if (retriesAttempted >= maxRetries) return false;
gcIfEnabled();
long delayMillis = waitBetweenRetries >= 0 ? waitBetweenRetries : -(retriesAttempted + 1) * waitBetweenRetries;
if (delayMillis <= 0) return !Thread.interrupted();
try {
Thread.sleep(delayMillis);
return true;
} catch (InterruptedException e) {
interrupted.set(true);
return false;
}
}
@Override
public String failureMessage(@Nonnull Path fileToRemove, int retryCount) {
StringBuilder sb = new StringBuilder();
sb.append("Unable to delete '");
sb.append(fileToRemove);
sb.append("'. Tried ");
sb.append(retryCount);
sb.append(" time");
if (retryCount != 1) sb.append('s');
if (maxRetries > 0) {
sb.append(" (of a maximum of ");
sb.append(maxRetries + 1);
sb.append(')');
if (gcAfterFailedRemove)
sb.append(" garbage-collecting");
if (waitBetweenRetries != 0 && gcAfterFailedRemove)
sb.append(" and");
if (waitBetweenRetries != 0) {
sb.append(" waiting ");
sb.append(Util.getTimeSpanString(Math.abs(waitBetweenRetries)));
if (waitBetweenRetries < 0) {
sb.append("-");
sb.append(Util.getTimeSpanString(Math.abs(waitBetweenRetries) * (maxRetries + 1)));
}
}
if (waitBetweenRetries != 0 || gcAfterFailedRemove)
sb.append(" between attempts");
}
if (interrupted.get())
sb.append(". The delete operation was interrupted before it completed successfully");
sb.append('.');
interrupted.set(false);
return sb.toString();
}
}
private static Optional<IOException> tryRemoveFile(@Nonnull Path path) {
try {
makeRemovable(path);
Files.deleteIfExists(path);
return Optional.empty();
} catch (IOException e) {
return Optional.of(e);
}
}
private static List<IOException> tryRemoveRecursive(@Nonnull Path path) {
List<IOException> accumulatedErrors = Files.isSymbolicLink(path) ? new ArrayList<>() :
tryRemoveDirectoryContents(path);
tryRemoveFile(path).ifPresent(accumulatedErrors::add);
return accumulatedErrors;
}
private static List<IOException> tryRemoveDirectoryContents(@Nonnull Path path) {
if (!Files.isDirectory(path)) return Collections.emptyList();
List<IOException> accumulatedErrors = new ArrayList<>();
try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) {
for (Path child : children) {
accumulatedErrors.addAll(tryRemoveRecursive(child));
}
} catch (IOException e) {
accumulatedErrors.add(e);
}
return accumulatedErrors;
}
private static void makeRemovable(@Nonnull Path path) throws IOException {
if (!Files.isWritable(path)) {
makeWritable(path);
}
Path parent = path.getParent();
if (parent != null && !Files.isWritable(parent)) {
makeWritable(parent);
}
}
private static void makeWritable(@Nonnull Path path) throws IOException {
if (!Functions.isWindows()) {
try {
PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class);
Set<PosixFilePermission> newPermissions = attrs.permissions();
newPermissions.add(PosixFilePermission.OWNER_WRITE);
Files.setPosixFilePermissions(path, newPermissions);
} catch (NoSuchFileException ignored) {
return;
} catch (UnsupportedOperationException ignored) {
// PosixFileAttributes not supported, fall back to old IO.
}
}
/*
* We intentionally do not check the return code of setWritable, because if it
* is false we prefer to rethrow the exception thrown by Files.deleteIfExists,
* which will have a more useful message than something we make up here.
*/
path.toFile().setWritable(true);
}
} |
package lucee.runtime.osgi;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.felix.framework.BundleWiringImpl.BundleClassLoader;
import org.apache.felix.framework.Logger;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Version;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Requirement;
import lucee.commons.io.FileUtil;
import lucee.commons.io.IOUtil;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.log.Log;
import lucee.commons.io.log.LogUtil;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.filter.ResourceNameFilter;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.ClassUtil;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringList;
import lucee.commons.lang.StringUtil;
import lucee.loader.engine.CFMLEngine;
import lucee.loader.engine.CFMLEngineFactory;
import lucee.loader.osgi.BundleCollection;
import lucee.loader.osgi.BundleUtil;
import lucee.loader.util.Util;
import lucee.runtime.PageContext;
import lucee.runtime.PageContextImpl;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigWebUtil;
import lucee.runtime.config.Identification;
import lucee.runtime.engine.CFMLEngineImpl;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.PageException;
import lucee.runtime.op.Caster;
import lucee.runtime.type.util.ListUtil;
public class OSGiUtil {
private static final int QUALIFIER_APPENDIX_SNAPSHOT = 1;
private static final int QUALIFIER_APPENDIX_BETA = 2;
private static final int QUALIFIER_APPENDIX_RC = 3;
private static final int QUALIFIER_APPENDIX_OTHER = 4;
private static final int QUALIFIER_APPENDIX_STABLE = 5;
private static final int MAX_REDIRECTS = 5;
private static ThreadLocal<Set<String>> bundlesThreadLocal = new ThreadLocal<Set<String>>() {
@Override
protected Set<String> initialValue() {
return new HashSet<String>();
}
};
private static class Filter implements FilenameFilter, ResourceNameFilter {
@Override
public boolean accept(File dir, String name) {
return accept(name);
}
@Override
public boolean accept(Resource dir, String name) {
return accept(name);
}
private boolean accept(String name) {
return name.endsWith(".jar");
}
}
private static final Filter JAR_EXT_FILTER = new Filter();
private static String[] bootDelegation;
/**
* only installs a bundle, if the bundle does not already exist, if the bundle exists the existing
* bundle is unloaded first.
*
* @param factory
* @param context
* @param bundle
* @return
* @throws IOException
* @throws BundleException
*/
public static Bundle installBundle(BundleContext context, Resource bundle, boolean checkExistence) throws IOException, BundleException {
if (checkExistence) {
BundleFile bf = BundleFile.getInstance(bundle);
if (!bf.isBundle()) throw new BundleException(bundle + " is not a valid bundle!");
Bundle existing = loadBundleFromLocal(context, bf.getSymbolicName(), bf.getVersion(), null, false, null);
if (existing != null) return existing;
}
return _loadBundle(context, bundle.getAbsolutePath(), bundle.getInputStream(), true);
}
/**
* does not check if the bundle already exists!
*
* @param context
* @param path
* @param is
* @param closeStream
* @return
* @throws BundleException
*/
private static Bundle _loadBundle(BundleContext context, String path, InputStream is, boolean closeStream) throws BundleException {
log(Log.LEVEL_DEBUG, "add bundle:" + path);
try {
// we make this very simply so an old loader that is calling this still works
return context.installBundle(path, is);
}
finally {
// we make this very simply so an old loader that is calling this still works
if (closeStream && is != null) {
try {
is.close();
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
}
}
/**
* only installs a bundle, if the bundle does not already exist, if the bundle exists the existing
* bundle is unloaded first. the bundle is not stored physically on the system.
*
* @param factory
* @param context
* @param bundle
* @return
* @throws IOException
* @throws BundleException
*/
public static Bundle installBundle(BundleContext context, InputStream bundleIS, boolean closeStream, boolean checkExistence) throws IOException, BundleException {
// store locally to test the bundle
String name = System.currentTimeMillis() + ".tmp";
Resource dir = SystemUtil.getTempDirectory();
Resource tmp = dir.getRealResource(name);
int count = 0;
while (tmp.exists())
tmp = dir.getRealResource((count++) + "_" + name);
IOUtil.copy(bundleIS, tmp, closeStream);
try {
return installBundle(context, tmp, checkExistence);
}
finally {
tmp.delete();
}
}
public static Version toVersion(String version, Version defaultValue) {
if (StringUtil.isEmpty(version)) return defaultValue;
// String[] arr = ListUtil.listToStringArray(version, '.');
String[] arr;
try {
arr = ListUtil.toStringArrayTrim(ListUtil.listToArray(version.trim(), '.'));
}
catch (PageException e) {
return defaultValue; // should not happen
}
Integer major, minor, micro;
String qualifier;
if (arr.length == 1) {
major = Caster.toInteger(arr[0], null);
minor = 0;
micro = 0;
qualifier = null;
}
else if (arr.length == 2) {
major = Caster.toInteger(arr[0], null);
minor = Caster.toInteger(arr[1], null);
micro = 0;
qualifier = null;
}
else if (arr.length == 3) {
major = Caster.toInteger(arr[0], null);
minor = Caster.toInteger(arr[1], null);
micro = Caster.toInteger(arr[2], null);
qualifier = null;
}
else {
major = Caster.toInteger(arr[0], null);
minor = Caster.toInteger(arr[1], null);
micro = Caster.toInteger(arr[2], null);
qualifier = arr[3];
}
if (major == null || minor == null || micro == null) return defaultValue;
if (qualifier == null) return new Version(major, minor, micro);
return new Version(major, minor, micro, qualifier);
}
public static Version toVersion(String version) throws BundleException {
Version v = toVersion(version, null);
if (v != null) return v;
throw new BundleException(
"Given version [" + version + "] is invalid, a valid version is following this pattern <major-number>.<minor-number>.<micro-number>[.<qualifier>]");
}
private static Manifest getManifest(Resource bundle) throws IOException {
InputStream is = null;
Manifest mf = null;
try {
is = bundle.getInputStream();
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null && mf == null) {
if ("META-INF/MANIFEST.MF".equals(entry.getName())) {
mf = new Manifest(zis);
}
zis.closeEntry();
}
}
finally {
IOUtil.close(is);
}
return mf;
}
/*
* public static FrameworkFactory getFrameworkFactory() throws Exception { ClassLoader cl =
* OSGiUtil.class.getClassLoader(); java.net.URL url =
* cl.getResource("META-INF/services/org.osgi.framework.launch.FrameworkFactory"); if (url != null)
* { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); try { for
* (String s = br.readLine(); s != null; s = br.readLine()) { s = s.trim(); // Try to load first
* non-empty, non-commented line. if ((s.length() > 0) && (s.charAt(0) != '#')) { return
* (FrameworkFactory) ClassUtil.loadInstance(cl, s); } } } finally { if (br != null) br.close(); } }
* throw new Exception("Could not find framework factory."); }
*/
/**
* tries to load a class with ni bundle definition
*
* @param name
* @param version
* @param id
* @param startIfNecessary
* @return
* @throws BundleException
*/
public static Class loadClass(String className, Class defaultValue) {
// a class necessary need a package info, otherwise it is useless to search for it
if (className.indexOf('.') == -1 && className.indexOf('/') == -1 && className.indexOf('\\') == -1) return defaultValue;
className = className.trim();
String classPath = className.replace('.', '/') + ".class";
CFMLEngine engine = CFMLEngineFactory.getInstance();
BundleCollection bc = engine.getBundleCollection();
// first we try to load the class from the Lucee core
try {
// load from core
if (bc.core.getEntry(classPath) != null) {
return bc.core.loadClass(className);
}
}
catch (Exception e) {
} // class is not visible to the Lucee core
// now we check all started bundled (not only bundles used by core)
Bundle[] bundles = bc.getBundleContext().getBundles();
for (Bundle b: bundles) {
if (b != bc.core && b.getEntry(classPath) != null) {
try {
return b.loadClass(className);
}
catch (Exception e) {
} // class is not visible to that bundle
}
}
// now we check lucee loader (SystemClassLoader?)
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
{
ClassLoader cl = factory.getClass().getClassLoader();
if (cl.getResource(classPath) != null) {
try {
// print.e("loader:");
return cl.loadClass(className);
}
catch (Exception e) {
}
}
}
// now we check bundles not loaded
Set<String> loaded = new HashSet<String>();
for (Bundle b: bundles) {
loaded.add(b.getSymbolicName() + "|" + b.getVersion());
}
try {
File dir = factory.getBundleDirectory();
File[] children = dir.listFiles(JAR_EXT_FILTER);
BundleFile bf;
String[] bi;
for (int i = 0; i < children.length; i++) {
try {
bi = getBundleInfoFromFileName(children[i].getName());
if (bi != null && loaded.contains(bi[0] + "|" + bi[1])) continue;
bf = BundleFile.getInstance(children[i]);
if (bf.isBundle() && !loaded.contains(bf.getSymbolicName() + "|" + bf.getVersion()) && bf.hasClass(className)) {
Bundle b = null;
try {
b = _loadBundle(bc.getBundleContext(), bf.getFile());
}
catch (IOException e) {
}
if (b != null) {
startIfNecessary(b);
if (b.getEntry(classPath) != null) {
try {
return b.loadClass(className);
}
catch (Exception e) {
} // class is not visible to that bundle
}
}
}
}
catch (Throwable t2) {
ExceptionUtil.rethrowIfNecessary(t2);
}
}
}
catch (Throwable t1) {
ExceptionUtil.rethrowIfNecessary(t1);
}
return defaultValue;
}
public static String[] getBundleInfoFromFileName(String name) {
name = ResourceUtil.removeExtension(name, name);
int index = name.indexOf('-');
if (index == -1) return null;
return new String[] { name.substring(0, index), name.substring(index + 1) };
}
public static Bundle loadBundle(BundleFile bf, Bundle defaultValue) {
if (!bf.isBundle()) return defaultValue;
try {
return loadBundle(bf);
}
catch (Exception e) {
return defaultValue;
}
}
public static Bundle loadBundle(BundleFile bf) throws IOException, BundleException {
CFMLEngine engine = CFMLEngineFactory.getInstance();
// check in loaded bundles
BundleContext bc = engine.getBundleContext();
Bundle[] bundles = bc.getBundles();
for (Bundle b: bundles) {
if (bf.getSymbolicName().equals(b.getSymbolicName())) {
if (b.getVersion().equals(bf.getVersion())) return b;
}
}
return _loadBundle(bc, bf.getFile());
}
public static Bundle loadBundleByPackage(String packageName, List<VersionDefinition> versionDefinitions, Set<Bundle> loadedBundles, boolean startIfNecessary,
Set<String> parents) throws BundleException, IOException {
CFMLEngine engine = CFMLEngineFactory.getInstance();
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
// if part of bootdelegation we ignore
if (OSGiUtil.isPackageInBootelegation(packageName)) {
return null;
}
// is it in jar directory but not loaded
File dir = factory.getBundleDirectory();
File[] children = dir.listFiles(JAR_EXT_FILTER);
List<PackageDefinition> pds;
for (File child: children) {
BundleFile bf = BundleFile.getInstance(child);
if (bf.isBundle()) {
if (parents.contains(toString(bf))) continue;
pds = toPackageDefinitions(bf.getExportPackage(), packageName, versionDefinitions);
if (pds != null && !pds.isEmpty()) {
Bundle b = exists(loadedBundles, bf);
if (b != null) {
if (startIfNecessary) _startIfNecessary(b, parents);
return null;
}
b = loadBundle(bf);
if (b != null) {
loadedBundles.add(b);
if (startIfNecessary) _startIfNecessary(b, parents);
return b;
}
}
}
}
return null;
}
private static Object toString(BundleFile bf) {
return bf.getSymbolicName() + ":" + bf.getVersionAsString();
}
private static Bundle exists(Set<Bundle> loadedBundles, BundleFile bf) {
if (loadedBundles != null) {
Bundle b;
Iterator<Bundle> it = loadedBundles.iterator();
while (it.hasNext()) {
b = it.next();
if (b.getSymbolicName().equals(bf.getSymbolicName()) && b.getVersion().equals(bf.getVersion())) return b;
}
}
return null;
}
private static Bundle exists(Set<Bundle> loadedBundles, BundleDefinition bd) {
if (loadedBundles != null) {
Bundle b;
Iterator<Bundle> it = loadedBundles.iterator();
while (it.hasNext()) {
b = it.next();
if (b.getSymbolicName().equals(bd.getName()) && b.getVersion().equals(bd.getVersion())) return b;
}
}
return null;
}
public static Bundle loadBundle(String name, Version version, Identification id, List<Resource> addionalDirectories, boolean startIfNecessary) throws BundleException {
try {
return _loadBundle(name, version, id, addionalDirectories, startIfNecessary, null);
}
catch (StartFailedException sfe) {
throw sfe.bundleException;
}
}
public static Bundle _loadBundle(String name, Version version, Identification id, List<Resource> addionalDirectories, boolean startIfNecessary, Set<String> parents)
throws BundleException, StartFailedException {
name = name.trim();
CFMLEngine engine = CFMLEngineFactory.getInstance();
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
// check in loaded bundles
BundleContext bc = engine.getBundleContext();
Bundle[] bundles = bc.getBundles();
StringBuilder versionsFound = new StringBuilder();
for (Bundle b: bundles) {
if (name.equalsIgnoreCase(b.getSymbolicName())) {
if (version == null || version.equals(b.getVersion())) {
if (startIfNecessary) {
try {
_startIfNecessary(b, parents);
}
catch (BundleException be) {
throw new StartFailedException(be, b);
}
}
return b;
}
if (versionsFound.length() > 0) versionsFound.append(", ");
versionsFound.append(b.getVersion().toString());
}
}
// is it in jar directory but not loaded
BundleFile bf = _getBundleFile(factory, name, version, addionalDirectories, versionsFound);
if (bf != null && bf.isBundle()) {
Bundle b = null;
try {
b = _loadBundle(bc, bf.getFile());
}
catch (IOException e) {
LogUtil.log(ThreadLocalPageContext.getConfig(), OSGiUtil.class.getName(), e);
}
if (b != null) {
if (startIfNecessary) {
try {
startIfNecessary(b);
}
catch (BundleException be) {
throw new StartFailedException(be, b);
}
}
return b;
}
}
// if not found try to download
{
try {
Bundle b;
if (version != null) {
File f = factory.downloadBundle(name, version.toString(), id);
b = _loadBundle(bc, f);
}
else {
// MUST find out why this breaks at startup with commandbox if version exists
Resource r = downloadBundle(factory, name, null, id);
b = _loadBundle(bc, r);
}
if (startIfNecessary) {
try {
_start(b, parents);
}
catch (BundleException be) {
throw new StartFailedException(be, b);
}
}
return b;
}
catch (Exception e) {
log(e);
}
}
String localDir = "";
try {
localDir = " (" + factory.getBundleDirectory() + ")";
}
catch (IOException e) {
}
String upLoc = "";
try {
upLoc = " (" + factory.getUpdateLocation() + ")";
}
catch (IOException e) {
}
if (versionsFound.length() > 0) throw new BundleException("The OSGi Bundle with name [" + name + "] is not available in version [" + version + "] locally" + localDir
+ " or from the update provider" + upLoc + ", the following versions are available locally [" + versionsFound + "].");
if (version != null) throw new BundleException(
"The OSGi Bundle with name [" + name + "] in version [" + version + "] is not available locally" + localDir + " or from the update provider" + upLoc + ".");
throw new BundleException("The OSGi Bundle with name [" + name + "] is not available locally" + localDir + " or from the update provider" + upLoc + ".");
}
private static Resource downloadBundle(CFMLEngineFactory factory, final String symbolicName, String symbolicVersion, Identification id) throws IOException, BundleException {
if (!Caster.toBooleanValue(SystemUtil.getSystemPropOrEnvVar("lucee.enable.bundle.download", null), true)) {
throw (new RuntimeException("Lucee is missing the Bundle jar [" + symbolicName + ":" + symbolicVersion
+ "], and has been prevented from downloading it. If this jar is not a core jar, it will need to be manually downloaded and placed in the {{lucee-server}}/context/bundles directory."));
}
final Resource jarDir = ResourceUtil.toResource(factory.getBundleDirectory());
final URL updateProvider = factory.getUpdateLocation();
if (symbolicVersion == null) symbolicVersion = "latest";
final URL updateUrl = new URL(updateProvider, "/rest/update/provider/download/" + symbolicName + "/" + symbolicVersion + "/" + (id != null ? id.toQueryString() : "")
+ (id == null ? "?" : "&") + "allowRedirect=true"
);
log(Logger.LOG_WARNING, "Downloading bundle [" + symbolicName + ":" + symbolicVersion + "] from " + updateUrl);
int code;
HttpURLConnection conn;
try {
conn = (HttpURLConnection) updateUrl.openConnection();
conn.setRequestMethod("GET");
conn.connect();
code = conn.getResponseCode();
}
catch (UnknownHostException e) {
throw new IOException("Downloading the bundle [" + symbolicName + ":" + symbolicVersion + "] from [" + updateUrl + "] failed", e);
}
// the update provider is not providing a download for this
if (code != 200) {
int count = 1;
// the update provider can also provide a different (final) location for this
while ((code == 301 || code == 302) && count++ <= MAX_REDIRECTS) {
String location = conn.getHeaderField("Location");
// just in case we check invalid names
if (location == null) location = conn.getHeaderField("location");
if (location == null) location = conn.getHeaderField("LOCATION");
LogUtil.log(null, Log.LEVEL_INFO, OSGiUtil.class.getName(), "Download redirected: " + location); // MUST remove
conn.disconnect();
URL url = new URL(location);
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
code = conn.getResponseCode();
}
catch (final UnknownHostException e) {
log(e);
throw new IOException("Failed to download the bundle [" + symbolicName + ":" + symbolicVersion + "] from [" + location + "]", e);
}
}
// no download available!
if (code != 200) {
final String msg = "Download bundle failed for [" + symbolicName + "] in version [" + symbolicVersion + "] from [" + updateUrl
+ "], please download manually and copy to [" + jarDir + "]";
log(Logger.LOG_ERROR, msg);
conn.disconnect();
throw new IOException(msg);
}
}
// extract version if necessary
if ("latest".equals(symbolicVersion)) {
// copy to temp file
Resource temp = SystemUtil.getTempFile("jar", false);
IOUtil.copy((InputStream) conn.getContent(), temp, true);
try {
conn.disconnect();
// extract version and create file with correct name
BundleFile bf = BundleFile.getInstance(temp);
Resource jar = jarDir.getRealResource(symbolicName + "-" + bf.getVersionAsString() + ".jar");
IOUtil.copy(temp, jar);
return jar;
}
finally {
temp.delete();
}
}
else {
Resource jar = jarDir.getRealResource(symbolicName + "-" + symbolicVersion + ".jar");
IOUtil.copy((InputStream) conn.getContent(), jar, true);
conn.disconnect();
return jar;
}
}
private static List<PackageDefinition> toPackageDefinitions(String str, String filterPackageName, List<VersionDefinition> versionDefinitions) {
if (StringUtil.isEmpty(str)) return null;
StringTokenizer st = new StringTokenizer(str, ",");
List<PackageDefinition> list = new ArrayList<PackageDefinition>();
PackageDefinition pd;
while (st.hasMoreTokens()) {
pd = toPackageDefinition(st.nextToken().trim(), filterPackageName, versionDefinitions);
if (pd != null) list.add(pd);
}
return list;
}
private static PackageDefinition toPackageDefinition(String str, String filterPackageName, List<VersionDefinition> versionDefinitions) {
// first part is the package
StringList list = ListUtil.toList(str, ';');
PackageDefinition pd = null;
String token;
Version v;
while (list.hasNext()) {
token = list.next().trim();
if (pd == null) {
if (!token.equals(filterPackageName)) return null;
pd = new PackageDefinition(token);
}
// only intressted in version
else {
StringList entry = ListUtil.toList(token, '=');
if (entry.size() == 2 && entry.next().trim().equalsIgnoreCase("version")) {
String version = StringUtil.unwrap(entry.next().trim());
if (!version.equals("0.0.0")) {
v = OSGiUtil.toVersion(version, null);
if (v != null) {
if (versionDefinitions != null) {
Iterator<VersionDefinition> it = versionDefinitions.iterator();
while (it.hasNext()) {
if (!it.next().matches(v)) {
return null;
}
}
}
pd.setVersion(v);
}
}
}
}
}
return pd;
}
/**
* this should be used when you not want to load a Bundle to the system
*
* @param name
* @param version
* @param id only necessary if downloadIfNecessary is set to true
* @param downloadIfNecessary
* @return
* @throws BundleException
*/
public static BundleFile getBundleFile(String name, Version version, Identification id, List<Resource> addionalDirectories, boolean downloadIfNecessary)
throws BundleException {
name = name.trim();
CFMLEngine engine = CFMLEngineFactory.getInstance();
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
StringBuilder versionsFound = new StringBuilder();
// is it in jar directory but not loaded
BundleFile bf = _getBundleFile(factory, name, version, addionalDirectories, versionsFound);
if (bf != null) return bf;
// if not found try to download
if (downloadIfNecessary && version != null) {
try {
bf = BundleFile.getInstance(factory.downloadBundle(name, version.toString(), id));
if (bf.isBundle()) return bf;
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
if (versionsFound.length() > 0) throw new BundleException("The OSGi Bundle with name [" + name + "] is not available in version [" + version
+ "] locally or from the update provider, the following versions are available locally [" + versionsFound + "].");
if (version != null)
throw new BundleException("The OSGi Bundle with name [" + name + "] in version [" + version + "] is not available locally or from the update provider.");
throw new BundleException("The OSGi Bundle with name [" + name + "] is not available locally or from the update provider.");
}
/**
* check left value against right value
*
* @param left
* @param right
* @return returns if right is newer than left
*/
public static boolean isNewerThan(final Version left, final Version right) {
// major
if (left.getMajor() > right.getMajor()) return true;
if (left.getMajor() < right.getMajor()) return false;
// minor
if (left.getMinor() > right.getMinor()) return true;
if (left.getMinor() < right.getMinor()) return false;
// micro
if (left.getMicro() > right.getMicro()) return true;
if (left.getMicro() < right.getMicro()) return false;
// qualifier
// left
String q = left.getQualifier();
int index = q.indexOf('-');
String qla = index == -1 ? "" : q.substring(index + 1).trim();
String qln = index == -1 ? q : q.substring(0, index);
int ql = StringUtil.isEmpty(qln) ? Integer.MIN_VALUE : Caster.toIntValue(qln, Integer.MAX_VALUE);
// right
q = right.getQualifier();
index = q.indexOf('-');
String qra = index == -1 ? "" : q.substring(index + 1).trim();
String qrn = index == -1 ? q : q.substring(0, index);
int qr = StringUtil.isEmpty(qln) ? Integer.MIN_VALUE : Caster.toIntValue(qrn, Integer.MAX_VALUE);
if (ql > qr) return true;
if (ql < qr) return false;
int qlan = qualifierAppendix2Number(qla);
int qran = qualifierAppendix2Number(qra);
if (qlan > qran) return true;
if (qlan < qran) return false;
if (qlan == QUALIFIER_APPENDIX_OTHER && qran == QUALIFIER_APPENDIX_OTHER) return left.compareTo(right) > 0;
return false;
}
private static int qualifierAppendix2Number(String str) {
if (Util.isEmpty(str, true)) return QUALIFIER_APPENDIX_STABLE;
if ("SNAPSHOT".equalsIgnoreCase(str)) return QUALIFIER_APPENDIX_SNAPSHOT;
if ("BETA".equalsIgnoreCase(str)) return QUALIFIER_APPENDIX_BETA;
if ("RC".equalsIgnoreCase(str)) return QUALIFIER_APPENDIX_RC;
return QUALIFIER_APPENDIX_OTHER;
}
public static BundleFile getBundleFile(String name, Version version, Identification id, List<Resource> addionalDirectories, boolean downloadIfNecessary,
BundleFile defaultValue) {
name = name.trim();
CFMLEngine engine = CFMLEngineFactory.getInstance();
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
StringBuilder versionsFound = new StringBuilder();
// is it in jar directory but not loaded
BundleFile bf = _getBundleFile(factory, name, version, addionalDirectories, versionsFound);
if (bf != null) return bf;
// if not found try to download
if (downloadIfNecessary && version != null) {
try {
bf = BundleFile.getInstance(factory.downloadBundle(name, version.toString(), id));
if (bf.isBundle()) return bf;
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
return defaultValue;
}
private static BundleFile _getBundleFile(CFMLEngineFactory factory, String name, Version version, List<Resource> addionalDirectories, StringBuilder versionsFound) {
Resource match = null;
try {
Resource dir = ResourceUtil.toResource(factory.getBundleDirectory());
// first we check if there is a file match (fastest solution)
if (version != null) {
List<Resource> jars = createPossibleNameMatches(dir, addionalDirectories, name, version);
for (Resource jar: jars) {
if (jar.isFile()) {
match = jar;
BundleFile bf = BundleFile.getInstance(jar);
if (bf.isBundle() && name.equalsIgnoreCase(bf.getSymbolicName())) {
if (version.equals(bf.getVersion())) {
return bf;
}
}
}
}
}
List<Resource> children = listFiles(dir, addionalDirectories, JAR_EXT_FILTER);
// now we make a closer filename test
String curr;
if (version != null) {
match = null;
String v = version.toString();
for (Resource child: children) {
curr = child.getName();
if (curr.equalsIgnoreCase(name + "-" + v.replace('-', '.')) || curr.equalsIgnoreCase(name.replace('.', '-') + "-" + v)
|| curr.equalsIgnoreCase(name.replace('.', '-') + "-" + v.replace('.', '-'))
|| curr.equalsIgnoreCase(name.replace('.', '-') + "-" + v.replace('-', '.')) || curr.equalsIgnoreCase(name.replace('-', '.') + "-" + v)
|| curr.equalsIgnoreCase(name.replace('-', '.') + "-" + v.replace('.', '-'))
|| curr.equalsIgnoreCase(name.replace('-', '.') + "-" + v.replace('-', '.'))) {
match = child;
break;
}
}
if (match != null) {
BundleFile bf = BundleFile.getInstance(match);
if (bf.isBundle() && name.equalsIgnoreCase(bf.getSymbolicName())) {
if (version.equals(bf.getVersion())) {
return bf;
}
}
}
}
else {
List<BundleFile> matches = new ArrayList<BundleFile>();
BundleFile bf;
for (Resource child: children) {
curr = child.getName();
if (curr.startsWith(name + "-") || curr.startsWith(name.replace('-', '.') + "-") || curr.startsWith(name.replace('.', '-') + "-")) {
match = child;
bf = BundleFile.getInstance(child);
if (bf.isBundle() && name.equalsIgnoreCase(bf.getSymbolicName())) {
matches.add(bf);
}
}
}
if (!matches.isEmpty()) {
bf = null;
BundleFile _bf;
Iterator<BundleFile> it = matches.iterator();
while (it.hasNext()) {
_bf = it.next();
if (bf == null || isNewerThan(_bf.getVersion(), bf.getVersion())) bf = _bf;
}
if (bf != null) {
return bf;
}
}
}
// now we check by Manifest comparsion
BundleFile bf;
for (Resource child: children) {
match = child;
bf = BundleFile.getInstance(child);
if (bf.isBundle() && name.equalsIgnoreCase(bf.getSymbolicName())) {
if (version == null || version.equals(bf.getVersion())) {
return bf;
}
if (versionsFound != null) {
if (versionsFound.length() > 0) versionsFound.append(", ");
versionsFound.append(bf.getVersionAsString());
}
}
}
}
catch (Exception e) {
log(e);
if (match != null) {
if (FileUtil.isLocked(match)) {
log(Log.LEVEL_ERROR, "cannot load the bundle [" + match + "], bundle seem to have a windows lock");
// in case the file exists, but is locked we create a copy of if and use that copy
BundleFile bf;
try {
bf = BundleFile.getInstance(FileUtil.createTempResourceFromLockedResource(match, false));
if (bf.isBundle() && name.equalsIgnoreCase(bf.getSymbolicName())) {
if (version.equals(bf.getVersion())) {
return bf;
}
}
}
catch (Exception e1) {
log(e1);
}
}
}
}
return null;
}
private static List<Resource> createPossibleNameMatches(Resource dir, List<Resource> addionalDirectories, String name, Version version) {
String[] patterns = new String[] { name + "-" + version.toString() + (".jar"), name + "-" + version.toString().replace('.', '-') + (".jar"),
name.replace('.', '-') + "-" + version.toString().replace('.', '-') + (".jar") };
List<Resource> resources = new ArrayList<Resource>();
for (String pattern: patterns) {
resources.add(dir.getRealResource(pattern));
}
if (addionalDirectories != null && !addionalDirectories.isEmpty()) {
Iterator<Resource> it = addionalDirectories.iterator();
Resource res;
while (it.hasNext()) {
res = it.next();
if (!res.isDirectory()) continue;
for (String pattern: patterns) {
resources.add(res.getRealResource(pattern));
}
}
}
return resources;
}
private static List<Resource> listFiles(Resource dir, List<Resource> addionalDirectories, Filter filter) {
List<Resource> children = new ArrayList<Resource>();
_add(children, dir.listResources(filter));
if (addionalDirectories != null && !addionalDirectories.isEmpty()) {
Iterator<Resource> it = addionalDirectories.iterator();
Resource res;
while (it.hasNext()) {
res = it.next();
if (!res.isDirectory()) continue;
_add(children, res.listResources(filter));
}
}
return children;
}
private static void _add(List<Resource> children, Resource[] reses) {
if (reses == null || reses.length == 0) return;
for (Resource res: reses) {
children.add(res);
}
}
/**
* get all local bundles (even bundles not loaded/installed)
*
* @param name
* @param version
* @return
*/
public static List<BundleDefinition> getBundleDefinitions() {
CFMLEngine engine = ConfigWebUtil.getEngine(ThreadLocalPageContext.getConfig());
return getBundleDefinitions(engine.getBundleContext());
}
public static List<BundleDefinition> getBundleDefinitions(BundleContext bc) {
Set<String> set = new HashSet<>();
List<BundleDefinition> list = new ArrayList<>();
Bundle[] bundles = bc.getBundles();
for (Bundle b: bundles) {
list.add(new BundleDefinition(b));
set.add(b.getSymbolicName() + ":" + b.getVersion());
}
// is it in jar directory but not loaded
CFMLEngine engine = ConfigWebUtil.getEngine(ThreadLocalPageContext.getConfig());
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
try {
File[] children = factory.getBundleDirectory().listFiles(JAR_EXT_FILTER);
BundleFile bf;
for (int i = 0; i < children.length; i++) {
try {
bf = BundleFile.getInstance(children[i]);
if (bf.isBundle() && !set.contains(bf.getSymbolicName() + ":" + bf.getVersion())) list.add(new BundleDefinition(bf.getSymbolicName(), bf.getVersion()));
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
}
catch (IOException ioe) {
}
return list;
}
public static Bundle getBundleLoaded(String name, Version version, Bundle defaultValue) {
CFMLEngine engine = ConfigWebUtil.getEngine(ThreadLocalPageContext.getConfig());
return getBundleLoaded(engine.getBundleContext(), name, version, defaultValue);
}
public static Bundle getBundleLoaded(BundleContext bc, String name, Version version, Bundle defaultValue) {
name = name.trim();
Bundle[] bundles = bc.getBundles();
for (Bundle b: bundles) {
if (name.equalsIgnoreCase(b.getSymbolicName())) {
if (version == null || version.equals(b.getVersion())) {
return b;
}
}
}
return defaultValue;
}
public static Bundle loadBundleFromLocal(String name, Version version, List<Resource> addionalDirectories, boolean loadIfNecessary, Bundle defaultValue) {
CFMLEngine engine = ConfigWebUtil.getEngine(ThreadLocalPageContext.getConfig());
return loadBundleFromLocal(engine.getBundleContext(), name, version, addionalDirectories, loadIfNecessary, defaultValue);
}
public static Bundle loadBundleFromLocal(BundleContext bc, String name, Version version, List<Resource> addionalDirectories, boolean loadIfNecessary, Bundle defaultValue) {
name = name.trim();
Bundle[] bundles = bc.getBundles();
for (Bundle b: bundles) {
if (name.equalsIgnoreCase(b.getSymbolicName())) {
if (version == null || version.equals(b.getVersion())) {
return b;
}
}
}
if (!loadIfNecessary) return defaultValue;
// is it in jar directory but not loaded
CFMLEngine engine = ConfigWebUtil.getEngine(ThreadLocalPageContext.getConfig());
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
BundleFile bf = _getBundleFile(factory, name, version, addionalDirectories, null);
if (bf != null) {
try {
return _loadBundle(bc, bf.getFile());
}
catch (Exception e) {
}
}
return defaultValue;
}
/**
* get local bundle, but does not download from update provider!
*
* @param name
* @param version
* @return
* @throws BundleException
*/
public static void removeLocalBundle(String name, Version version, List<Resource> addionalDirectories, boolean removePhysical, boolean doubleTap) throws BundleException {
name = name.trim();
CFMLEngine engine = CFMLEngineFactory.getInstance();
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
// first we look for an active bundle and do stop it
Bundle b = getBundleLoaded(name, version, null);
if (b != null) {
stopIfNecessary(b);
b.uninstall();
}
if (!removePhysical) return;
// now we remove the file
BundleFile bf = _getBundleFile(factory, name, version, null, null);
if (bf != null) {
if (!bf.getFile().delete() && doubleTap) bf.getFile().deleteOnExit();
}
}
public static void removeLocalBundleSilently(String name, Version version, List<Resource> addionalDirectories, boolean removePhysical) {
try {
removeLocalBundle(name, version, addionalDirectories, removePhysical, true);
}
catch (Exception e) {
}
}
// bundle stuff
public static void startIfNecessary(Bundle[] bundles) throws BundleException {
for (Bundle b: bundles) {
startIfNecessary(b);
}
}
public static Bundle startIfNecessary(Bundle bundle) throws BundleException {
return _startIfNecessary(bundle, null);
}
private static Bundle _startIfNecessary(Bundle bundle, Set<String> parents) throws BundleException {
if (bundle.getState() == Bundle.ACTIVE) return bundle;
return _start(bundle, parents);
}
public static Bundle start(Bundle bundle) throws BundleException {
try {
return _start(bundle, null);
}
finally {
bundlesThreadLocal.get().clear();
}
}
public static Bundle _start(Bundle bundle, Set<String> parents) throws BundleException {
if (bundle == null) return bundle;
String bn = toString(bundle);
if (bundlesThreadLocal.get().contains(bn)) return bundle;
bundlesThreadLocal.get().add(bn);
String fh = bundle.getHeaders().get("Fragment-Host");
// Fragment cannot be started
if (!Util.isEmpty(fh)) {
log(Log.LEVEL_DEBUG, "Do not start [" + bundle.getSymbolicName() + "], because this is a fragment bundle for [" + fh + "]");
return bundle;
}
log(Log.LEVEL_DEBUG, "Start bundle: [" + bundle.getSymbolicName() + ":" + bundle.getVersion().toString() + "]");
try {
BundleUtil.start(bundle);
}
catch (BundleException be) {
// check if required related bundles are missing and load them if necessary
final List<BundleDefinition> failedBD = new ArrayList<OSGiUtil.BundleDefinition>();
if (parents == null) parents = new HashSet<String>();
Set<Bundle> loadedBundles = loadBundles(parents, bundle, null, failedBD);
try {
// startIfNecessary(loadedBundles.toArray(new Bundle[loadedBundles.size()]));
BundleUtil.start(bundle);
}
catch (BundleException be2) {
List<PackageQuery> listPackages = getRequiredPackages(bundle);
List<PackageQuery> failedPD = new ArrayList<PackageQuery>();
loadPackages(parents, loadedBundles, listPackages, bundle, failedPD);
try {
// startIfNecessary(loadedBundles.toArray(new Bundle[loadedBundles.size()]));
BundleUtil.start(bundle);
}
catch (BundleException be3) {
if (failedBD.size() > 0) {
Iterator<BundleDefinition> itt = failedBD.iterator();
BundleDefinition _bd;
StringBuilder sb = new StringBuilder("Lucee was not able to download/load the following bundles [");
while (itt.hasNext()) {
_bd = itt.next();
sb.append(_bd.name + ":" + _bd.getVersionAsString()).append(';');
}
sb.append("]");
throw new BundleException(be2.getMessage() + sb, be2.getCause());
}
throw be3;
}
}
}
return bundle;
}
private static void loadPackages(final Set<String> parents, final Set<Bundle> loadedBundles, List<PackageQuery> listPackages, final Bundle bundle,
final List<PackageQuery> failedPD) {
PackageQuery pq;
Iterator<PackageQuery> it = listPackages.iterator();
parents.add(toString(bundle));
while (it.hasNext()) {
pq = it.next();
try {
loadBundleByPackage(pq.getName(), pq.getVersionDefinitons(), loadedBundles, true, parents);
}
catch (Exception _be) {
failedPD.add(pq);
log(_be);
}
}
}
private static Set<Bundle> loadBundles(final Set<String> parents, final Bundle bundle, List<Resource> addionalDirectories, final List<BundleDefinition> failedBD)
throws BundleException {
Set<Bundle> loadedBundles = new HashSet<Bundle>();
loadedBundles.add(bundle);
parents.add(toString(bundle));
List<BundleDefinition> listBundles = getRequiredBundles(bundle);
Bundle b;
BundleDefinition bd;
Iterator<BundleDefinition> it = listBundles.iterator();
List<StartFailedException> secondChance = null;
while (it.hasNext()) {
bd = it.next();
b = exists(loadedBundles, bd);
if (b != null) {
_startIfNecessary(b, parents);
continue;
}
try {
// if(parents==null) parents=new HashSet<Bundle>();
b = _loadBundle(bd.name, bd.getVersion(), ThreadLocalPageContext.getConfig().getIdentification(), addionalDirectories, true, parents);
loadedBundles.add(b);
}
catch (StartFailedException sfe) {
sfe.setBundleDefinition(bd);
if (secondChance == null) secondChance = new ArrayList<StartFailedException>();
secondChance.add(sfe);
}
catch (BundleException _be) {
// if(failedBD==null) failedBD=new ArrayList<OSGiUtil.BundleDefinition>();
failedBD.add(bd);
log(_be);
}
}
// we do this because it maybe was relaying on other bundles now loaded
// TODO rewrite the complete impl so didd is not necessary
if (secondChance != null) {
Iterator<StartFailedException> _it = secondChance.iterator();
StartFailedException sfe;
while (_it.hasNext()) {
sfe = _it.next();
try {
_startIfNecessary(sfe.bundle, parents);
loadedBundles.add(sfe.bundle);
}
catch (BundleException _be) {
// if(failedBD==null) failedBD=new ArrayList<OSGiUtil.BundleDefinition>();
failedBD.add(sfe.getBundleDefinition());
log(_be);
}
}
}
return loadedBundles;
}
private static String toString(Bundle b) {
return b.getSymbolicName() + ":" + b.getVersion().toString();
}
public static void stopIfNecessary(Bundle bundle) throws BundleException {
if (isFragment(bundle) || bundle.getState() != Bundle.ACTIVE) return;
stop(bundle);
}
public static void stop(Bundle b) throws BundleException {
b.stop();
}
public static void uninstall(Bundle b) throws BundleException {
b.uninstall();
}
public static boolean isFragment(Bundle bundle) {
return (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0;
}
public static boolean isFragment(BundleFile bf) {
return !StringUtil.isEmpty(bf.getFragementHost(), true);
}
public static List<BundleDefinition> getRequiredBundles(Bundle bundle) throws BundleException {
List<BundleDefinition> rtn = new ArrayList<BundleDefinition>();
BundleRevision br = bundle.adapt(BundleRevision.class);
List<Requirement> requirements = br.getRequirements(null);
Iterator<Requirement> it = requirements.iterator();
Requirement r;
Entry<String, String> e;
String value, name;
int index, start, end, op;
BundleDefinition bd;
while (it.hasNext()) {
r = it.next();
Iterator<Entry<String, String>> iit = r.getDirectives().entrySet().iterator();
while (iit.hasNext()) {
e = iit.next();
if (!"filter".equals(e.getKey())) continue;
value = e.getValue();
// name
index = value.indexOf("(osgi.wiring.bundle");
if (index == -1) continue;
start = value.indexOf('=', index);
end = value.indexOf(')', index);
if (start == -1 || end == -1 || end < start) continue;
name = value.substring(start + 1, end).trim();
rtn.add(bd = new BundleDefinition(name));
// version
op = -1;
index = value.indexOf("(bundle-version");
if (index == -1) continue;
end = value.indexOf(')', index);
start = value.indexOf("<=", index);
if (start != -1 && start < end) {
op = VersionDefinition.LTE;
start += 2;
}
else {
start = value.indexOf(">=", index);
if (start != -1 && start < end) {
op = VersionDefinition.GTE;
start += 2;
}
else {
start = value.indexOf("=", index);
if (start != -1 && start < end) {
op = VersionDefinition.EQ;
start++;
}
}
}
if (op == -1 || start == -1 || end == -1 || end < start) continue;
bd.setVersion(op, value.substring(start, end).trim());
}
}
return rtn;
}
public static List<PackageQuery> getRequiredPackages(Bundle bundle) throws BundleException {
List<PackageQuery> rtn = new ArrayList<PackageQuery>();
BundleRevision br = bundle.adapt(BundleRevision.class);
List<Requirement> requirements = br.getRequirements(null);
Iterator<Requirement> it = requirements.iterator();
Requirement r;
Entry<String, String> e;
String value;
PackageQuery pd;
while (it.hasNext()) {
r = it.next();
Iterator<Entry<String, String>> iit = r.getDirectives().entrySet().iterator();
inner: while (iit.hasNext()) {
e = iit.next();
if (!"filter".equals(e.getKey())) continue;
value = e.getValue();
pd = toPackageQuery(value);
if (pd != null) rtn.add(pd);
}
}
return rtn;
}
private static PackageQuery toPackageQuery(String value) throws BundleException {
// name(&(osgi.wiring.package=org.jboss.logging)(version>=3.3.0)(!(version>=4.0.0)))
int index = value.indexOf("(osgi.wiring.package");
if (index == -1) {
return null;
}
int start = value.indexOf('=', index);
int end = value.indexOf(')', index);
if (start == -1 || end == -1 || end < start) {
return null;
}
String name = value.substring(start + 1, end).trim();
PackageQuery pd = new PackageQuery(name);
int last = end, op;
boolean not;
// version
while ((index = value.indexOf("(version", last)) != -1) {
op = -1;
end = value.indexOf(')', index);
start = value.indexOf("<=", index);
if (start != -1 && start < end) {
op = VersionDefinition.LTE;
start += 2;
}
else {
start = value.indexOf(">=", index);
if (start != -1 && start < end) {
op = VersionDefinition.GTE;
start += 2;
}
else {
start = value.indexOf("==", index);
if (start != -1 && start < end) {
op = VersionDefinition.EQ;
start += 2;
}
else {
start = value.indexOf("!=", index);
if (start != -1 && start < end) {
op = VersionDefinition.NEQ;
start += 2;
}
else {
start = value.indexOf("=", index);
if (start != -1 && start < end) {
op = VersionDefinition.EQ;
start += 1;
}
else {
start = value.indexOf("<", index);
if (start != -1 && start < end) {
op = VersionDefinition.LT;
start += 1;
}
else {
start = value.indexOf(">", index);
if (start != -1 && start < end) {
op = VersionDefinition.GT;
start += 1;
}
}
}
}
}
}
}
not = value.charAt(index - 1) == '!';
last = end;
if (op == -1 || start == -1 || end == -1 || end < start) continue;
pd.addVersion(op, value.substring(start, end).trim(), not);
}
return pd;
}
private static Bundle _loadBundle(BundleContext context, File bundle) throws IOException, BundleException {
return _loadBundle(context, bundle.getAbsolutePath(), new FileInputStream(bundle), true);
}
private static Bundle _loadBundle(BundleContext context, Resource bundle) throws IOException, BundleException {
return _loadBundle(context, bundle.getAbsolutePath(), bundle.getInputStream(), true);
}
public static class VersionDefinition implements Serializable {
private static final long serialVersionUID = 4915024473510761950L;
public static final int LTE = 1;
public static final int GTE = 2;
public static final int EQ = 4;
public static final int LT = 8;
public static final int GT = 16;
public static final int NEQ = 32;
private Version version;
private int op;
public VersionDefinition(Version version, int op, boolean not) {
this.version = version;
if (not) {
if (op == LTE) {
op = GT;
not = false;
}
else if (op == LT) {
op = GTE;
not = false;
}
else if (op == GTE) {
op = LT;
not = false;
}
else if (op == GT) {
op = LTE;
not = false;
}
else if (op == EQ) {
op = NEQ;
not = false;
}
else if (op == NEQ) {
op = EQ;
not = false;
}
}
this.op = op;
}
public boolean matches(Version v) {
if (EQ == op) return v.compareTo(version) == 0;
if (LTE == op) return v.compareTo(version) <= 0;
if (LT == op) return v.compareTo(version) < 0;
if (GTE == op) return v.compareTo(version) >= 0;
if (GT == op) return v.compareTo(version) > 0;
if (NEQ == op) return v.compareTo(version) != 0;
return false;
}
public Version getVersion() {
return version;
}
public int getOp() {
return op;
}
public String getVersionAsString() {
return version == null ? null : version.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("version ");
sb.append(getOpAsString()).append(' ').append(version);
return sb.toString();
}
public String getOpAsString() {
switch (getOp()) {
case EQ:
return "EQ";
case LTE:
return "LTE";
case GTE:
return "GTE";
case NEQ:
return "NEQ";
case LT:
return "LT";
case GT:
return "GT";
}
return null;
}
}
public static class PackageQuery {
private final String name;
private List<VersionDefinition> versions = new ArrayList<OSGiUtil.VersionDefinition>();
public PackageQuery(String name) {
this.name = name;
}
public void addVersion(int op, String version, boolean not) throws BundleException {
versions.add(new VersionDefinition(OSGiUtil.toVersion(version), op, not));
}
public String getName() {
return name;
}
public List<VersionDefinition> getVersionDefinitons() {
return versions;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("name:").append(name);
Iterator<VersionDefinition> it = versions.iterator();
while (it.hasNext()) {
sb.append(';').append(it.next());
}
return sb.toString();
}
}
public static class PackageDefinition {
private final String name;
private Version version;
public PackageDefinition(String name) {
this.name = name;
}
public void setVersion(String version) throws BundleException {
this.version = OSGiUtil.toVersion(version);
}
public void setVersion(Version version) {
this.version = version;
}
public String getName() {
return name;
}
public Version getVersion() {
return version;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("name:").append(name);
sb.append("version:").append(version);
return sb.toString();
}
}
public static class BundleDefinition implements Serializable {
private final String name;
private Bundle bundle;
private VersionDefinition versionDef;
public BundleDefinition(String name) {
this.name = name;
}
public BundleDefinition(String name, String version) throws BundleException {
this.name = name;
if (name == null) throw new IllegalArgumentException("Name cannot be null");
setVersion(VersionDefinition.EQ, version);
}
public BundleDefinition(String name, Version version) {
this.name = name;
if (name == null) throw new IllegalArgumentException("Name cannot be null");
setVersion(VersionDefinition.EQ, version);
}
public BundleDefinition(Bundle bundle) {
this.name = bundle.getSymbolicName();
if (name == null) throw new IllegalArgumentException("Name cannot be null");
setVersion(VersionDefinition.EQ, bundle.getVersion());
this.bundle = bundle;
}
public String getName() {
return name;
}
/**
* only return a bundle if already loaded, does not load the bundle
*
* @return
*/
public Bundle getLoadedBundle() {
return bundle;
}
/**
* get Bundle, also load if necessary from local or remote
*
* @return
* @throws BundleException
* @throws StartFailedException
*/
public Bundle getBundle(Config config, List<Resource> addionalDirectories) throws BundleException {
if (bundle == null) {
config = ThreadLocalPageContext.getConfig(config);
bundle = OSGiUtil.loadBundle(name, getVersion(), config == null ? null : config.getIdentification(), addionalDirectories, false);
}
return bundle;
}
public Bundle getLocalBundle(List<Resource> addionalDirectories) {
if (bundle == null) {
bundle = OSGiUtil.loadBundleFromLocal(name, getVersion(), addionalDirectories, true, null);
}
return bundle;
}
public BundleFile getBundleFile(boolean downloadIfNecessary, List<Resource> addionalDirectories) throws BundleException {
Config config = ThreadLocalPageContext.getConfig();
return OSGiUtil.getBundleFile(name, getVersion(), config == null ? null : config.getIdentification(), addionalDirectories, downloadIfNecessary);
}
public int getOp() {
return versionDef == null ? VersionDefinition.EQ : versionDef.getOp();
}
public Version getVersion() {
return versionDef == null ? null : versionDef.getVersion();
}
public VersionDefinition getVersionDefiniton() {
return versionDef;
}
public String getVersionAsString() {
return versionDef == null ? null : versionDef.getVersionAsString();
}
public void setVersion(int op, String version) throws BundleException {
setVersion(op, OSGiUtil.toVersion(version));
}
public void setVersion(int op, Version version) {
this.versionDef = new VersionDefinition(version, op, false);
}
@Override
public String toString() {
return "name:" + name + ";version:" + versionDef + ";";
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof BundleDefinition)) return false;
return toString().equals(obj.toString());
}
}
private static void log(int level, String msg) {
try {
Config config = ThreadLocalPageContext.getConfig();
Log log = config != null ? config.getLog("application") : null;
if (log != null) log.log(level, "OSGi", msg);
}
catch (Exception t) {
LogUtil.log(null, level, BundleBuilderFactory.class.getName(), msg);
}
}
private static void log(Throwable t) {
try {
Config config = ThreadLocalPageContext.getConfig();
Log log = config != null ? config.getLog("application") : null;
if (log != null) log.log(Log.LEVEL_ERROR, "OSGi", t);
}
catch (Exception _t) {
/* this can fail when called from an old loader */
LogUtil.log(null, OSGiUtil.class.getName(), _t);
}
}
public static String toState(int state, String defaultValue) {
switch (state) {
case Bundle.ACTIVE:
return "active";
case Bundle.INSTALLED:
return "installed";
case Bundle.UNINSTALLED:
return "uninstalled";
case Bundle.RESOLVED:
return "resolved";
case Bundle.STARTING:
return "starting";
case Bundle.STOPPING:
return "stopping";
}
return defaultValue;
}
/**
* value can be a String (for a single entry) or a List<String> for multiple entries
*
* @param b
* @return
*/
public static Map<String, Object> getHeaders(Bundle b) {
Dictionary<String, String> headers = b.getHeaders();
Enumeration<String> keys = headers.keys();
Enumeration<String> values = headers.elements();
String key, value;
Object existing;
List<String> list;
Map<String, Object> _headers = new HashMap<String, Object>();
while (keys.hasMoreElements()) {
key = keys.nextElement();
value = StringUtil.unwrap(values.nextElement());
existing = _headers.get(key);
if (existing != null) {
if (existing instanceof String) {
list = new ArrayList<>();
list.add((String) existing);
_headers.put(key, list);
}
else list = (List<String>) existing;
list.add(value);
}
else _headers.put(key, value);
}
return _headers;
}
public static String[] getBootdelegation() {
if (bootDelegation == null) {
InputStream is = null;
try {
Properties prop = new Properties();
is = OSGiUtil.class.getClassLoader().getResourceAsStream("default.properties");
prop.load(is);
String bd = prop.getProperty("org.osgi.framework.bootdelegation");
if (!StringUtil.isEmpty(bd)) {
bd += ",java.lang,java.lang.*";
bootDelegation = ListUtil.trimItems(ListUtil.listToStringArray(StringUtil.unwrap(bd), ','));
}
}
catch (IOException ioe) {
}
finally {
IOUtil.closeEL(is);
}
}
if (bootDelegation == null) return new String[0];
return bootDelegation;
}
public static boolean isClassInBootelegation(String className) {
return isInBootelegation(className, false);
}
public static boolean isPackageInBootelegation(String className) {
return isInBootelegation(className, true);
}
private static boolean isInBootelegation(String name, boolean isPackage) {
// extract package
String pack;
if (isPackage) pack = name;
else {
int index = name.lastIndexOf('.');
if (index == -1) return false;
pack = name.substring(0, index);
}
String[] arr = OSGiUtil.getBootdelegation();
for (String bd: arr) {
bd = bd.trim();
// with wildcard
if (bd.endsWith(".*")) {
bd = bd.substring(0, bd.length() - 1);
if (pack.startsWith(bd)) return true;
}
// no wildcard
else {
if (bd.equals(pack)) return true;
}
}
return false;
}
public static BundleDefinition[] toBundleDefinitions(BundleInfo[] bundles) {
if (bundles == null) return new BundleDefinition[0];
BundleDefinition[] rtn = new BundleDefinition[bundles.length];
for (int i = 0; i < bundles.length; i++) {
rtn[i] = bundles[i].toBundleDefinition();
}
return rtn;
}
public static Bundle getFrameworkBundle(Config config, Bundle defaultValue) {
Bundle[] bundles = ConfigWebUtil.getEngine(config).getBundleContext().getBundles();
Bundle b = null;
for (int i = 0; i < bundles.length; i++) {
b = bundles[i];
if (b != null && isFrameworkBundle(b)) return b;
}
return defaultValue;
}
public static boolean isFrameworkBundle(Bundle b) {// FELIX specific
return "org.apache.felix.framework".equalsIgnoreCase(b.getSymbolicName()); // TODO move to cire util class tha does not exist yet
}
public static Bundle getBundleFromClass(Class clazz, Bundle defaultValue) {
ClassLoader cl = clazz.getClassLoader();
if (cl instanceof BundleClassLoader) {
return ((BundleClassLoader) cl).getBundle();
}
return defaultValue;
}
public static Resource[] extractAndLoadBundles(PageContext pc, Resource[] jars) throws IOException {
BundleFile bf;
List<Resource> classic = new ArrayList<Resource>();
for (int i = 0; i < jars.length; i++) {
classic.add(jars[i]); // any jar is provided the classic way
// optionally make the jar available as a bundle
try {
bf = jars[i].isFile() ? BundleFile.getInstance(jars[i], true) : null;
}
catch (Exception e) {
bf = null;
}
if (bf != null) {
Bundle loaded = bf.toBundleDefinition().getLoadedBundle();
if (loaded == null) {
pc.getConfig().getFactory();
CFMLEngine engine = CFMLEngineFactory.getInstance();
try {
BundleUtil.addBundle(engine.getCFMLEngineFactory(), engine.getBundleContext(), jars[i], ((PageContextImpl) pc).getLog("application")).start();
}
catch (BundleException e) {
}
}
}
}
return classic.toArray(new Resource[classic.size()]);
}
public static String getClassPath() {
BundleClassLoader bcl = (BundleClassLoader) OSGiUtil.class.getClassLoader();
Bundle bundle = bcl.getBundle();
BundleContext bc = bundle.getBundleContext();
// DataMember
Set<String> set = new HashSet<>();
set.add(ClassUtil.getSourcePathForClass(CFMLEngineFactory.class, null));
set.add(ClassUtil.getSourcePathForClass(javax.servlet.jsp.JspException.class, null));
set.add(ClassUtil.getSourcePathForClass(javax.servlet.Servlet.class, null));
StringBuilder sb = new StringBuilder();
for (String path: set) {
sb.append(path).append(File.pathSeparator);
}
for (Bundle b: bc.getBundles()) {
if ("System Bundle".equalsIgnoreCase(b.getLocation())) continue;
sb.append(b.getLocation()).append(File.pathSeparator);
}
return sb.toString();
}
public static void stop(Class clazz) throws BundleException {
if (clazz == null) return;
Bundle bundleCore = OSGiUtil.getBundleFromClass(CFMLEngineImpl.class, null);
Bundle bundleFromClass = OSGiUtil.getBundleFromClass(clazz, null);
if (bundleFromClass != null && !bundleFromClass.equals(bundleCore)) {
OSGiUtil.stopIfNecessary(bundleFromClass);
}
// TODO Auto-generated method stub
}
} |
// Verbum - words, fonts, and tasteful shadows
package tripleplay.game;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import react.UnitSignal;
import react.UnitSlot;
import playn.core.GroupLayer;
import playn.core.Pointer;
import playn.core.util.Clock;
import static playn.core.PlayN.*;
import tripleplay.ui.Interface;
import tripleplay.ui.Root;
import tripleplay.util.Interpolator;
/**
* Maintains a 2D layout of {@link Screen}s. New screens can be introduced in a direction, and the
* view is scrolled in that direction to focus on the new screen. The user can then slide the view
* back toward the previous screen (in the opposite direction that it was introduced). If they
* release their slide with the old screen sufficiently visible, it will be restored to focus.
*/
public class ScreenSpace implements Iterable<ScreenSpace.Screen>
{
/** The directions in which a new screen can be added. */
public static enum Dir {
UP {
public int vertComp () { return -1; }
public void update (Screen oscreen, Screen nscreen, float pct) {
float oheight = oscreen.height();
float ostart = 0, nstart = oheight, range = -oheight;
float offset = pct * range;
oscreen.layer.setTy(ostart + offset);
nscreen.layer.setTy(nstart + offset);
}
},
DOWN {
public int vertComp () { return 1; }
public void update (Screen oscreen, Screen nscreen, float pct) {
float nheight = nscreen.height();
float ostart = 0, nstart = -nheight, range = nheight;
float offset = pct * range;
oscreen.layer.setTy(ostart + offset);
nscreen.layer.setTy(nstart + offset);
}
},
LEFT {
public int horizComp () { return -1; }
public void update (Screen oscreen, Screen nscreen, float pct) {
float owidth = oscreen.width();
float ostart = 0, nstart = owidth, range = -owidth;
float offset = pct * range;
oscreen.layer.setTx(ostart + offset);
nscreen.layer.setTx(nstart + offset);
}
},
RIGHT {
public int horizComp () { return 1; }
public void update (Screen oscreen, Screen nscreen, float pct) {
float nwidth = nscreen.width();
float ostart = 0, nstart = -nwidth, range = nwidth;
float offset = pct * range;
oscreen.layer.setTx(ostart + offset);
nscreen.layer.setTx(nstart + offset);
}
},
IN {
public void update (Screen oscreen, Screen nscreen, float pct) {
oscreen.layer.setAlpha(1-pct);
nscreen.layer.setAlpha(pct);
// TODO: scaling
}
public void finish (Screen oscreen, Screen nscreen) {
super.finish(oscreen, nscreen);
oscreen.layer.setAlpha(1);
}
},
OUT {
public void update (Screen oscreen, Screen nscreen, float pct) {
oscreen.layer.setAlpha(1-pct);
nscreen.layer.setAlpha(pct);
// TODO: scaling
}
public void finish (Screen oscreen, Screen nscreen) {
super.finish(oscreen, nscreen);
oscreen.layer.setAlpha(1);
}
},
FLIP {
public void update (Screen oscreen, Screen nscreen, float pct) {
// TODO
}
};
/** Returns the horizontal motion of this direction: 1, 0 or -1. */
public int horizComp () { return 0; }
/** Returns the vertical motion of this direction: 1, 0 or -1. */
public int vertComp () { return 0; }
/** Returns whether this direction can be manually "untransitioned". */
public boolean canUntrans () {
return horizComp() != 0 || vertComp() != 0;
}
/** Prepares {@code oscreen} and {@code nscreen} to be transitioned. {@code oscreen} is the
* currently visible screen and {@code nscreen} is the screen transitioning into view. */
public void init (Screen oscreen, Screen nscreen) {
oscreen.setTransiting(true);
nscreen.setTransiting(true);
}
/** Updates the position of {@code oscreen} and {@code nscreen} based on {@code pct}.
* @param pct a value ranged {@code [0,1]} indicating degree of completeness. */
public abstract void update (Screen oscreen, Screen nscreen, float pct);
/** Cleans up after a transition. {@link update} will have been called with {@code pct}
* equal to one immediately prior to this call, so this method is only needed when actual
* cleanup is needed, like the removal of custom shaders, etc.
*
* <p>Note also that the old screen's layer will have been made non-visible prior to this
* call. This call should not restore that visibility. */
public void finish (Screen oscreen, Screen nscreen) {
oscreen.setTransiting(false);
nscreen.setTransiting(false);
}
};
/**
* A screen that integrates with {@code ScreenSpace}. The screen lifecycle is:
* {@code init [wake gainedFocus lostFocus sleep]+ destroy}.
*
* <p>When the screen has the potential to become visible (due to the user scrolling part of
* the screen into view) it will have been wakened. If the user selects the screen, it will be
* animated into position and then {@code gainedFocus} will be called. If the user scrolls a
* new screen into view, {@code lostFocus} will be called, the screen will be animated away. If
* the screen is no longer "at risk" of being shown, {@code sleep} will be called. When the
* screen is finally removed from the screen space, {@code destroy} will be called.
*/
public static class Screen {
/** Contains the scene graph root for this screen. */
public final GroupLayer layer = graphics().createGroupLayer();
/** Called when this screen is first added to the screen space. */
public void init () {
// nada by default
}
/** Returns the width of this screen, for use by transitions.
* Defaults to the width of the entire view. */
public float width () { return graphics().width(); }
/** Returns the height of this screen, for use by transitions.
* Defaults to the height of the entire view. */
public float height () { return graphics().height(); }
/** Returns true when this screen is awake. */
public boolean awake () { return (_flags & AWAKE) != 0; }
/** Returns true when this screen is in-transition. */
public boolean transiting () { return (_flags & TRANSITING) != 0; }
/** Called when this screen will potentially be shown.
* Should create main UI and prepare it for display. */
public void wake () {
_flags |= AWAKE;
}
/** Called when this screen has become the active screen. */
public void gainedFocus () {
assert awake();
}
/** Called when some other screen is about to become the active screen. This screen will be
* animated out of view. This may not be immediately followed by a call to {@link #sleep}
* because the screen may remain visible due to incidental scrolling by the user. Only
* when the screen is separated from the focus screen by at least one screen will it be
* put to sleep. */
public void lostFocus () {
}
/** Called when this screen is no longer at risk of being seen by the user. This should
* destroy the UI and minimize the screen's memory footprint as much as possible. */
public void sleep () {
_flags &= ~AWAKE;
}
/** Called when this screen is removed from the screen space. This will always be preceded
* by a call to {@link #sleep}, but if there are any resources that the screen retains
* until it is completely released, this is the place to remove them. */
public void destroy () {
assert !awake();
}
/** called once per game update to allow this screen to participate in the game loop. */
public void update (int delta) {
}
/** Called once per game paint to allow this screen to participate in the game loop. */
public void paint (Clock clock) {
}
/** Returns whether or not an untransition gesture may be initiated via {@code dir}.
*
* <p>By default this requires that the screen be at its origin in x or y depending on the
* orientation of {@code dir}. If a screen uses a {@code Flicker} to scroll vertically,
* this will automatically do the right thing. If there are other circumstances in which a
* screen wishes to prevent the user from initiating an untransition gesture, this is the
* place to put 'em.
*/
public boolean canUntrans (Dir dir) {
if (dir.horizComp() != 0) return layer.tx() == 0;
if (dir.vertComp() != 0) return layer.ty() == 0;
return true;
}
void setTransiting (boolean transiting) {
if (transiting) _flags |= TRANSITING;
else _flags &= ~TRANSITING;
}
/** Flag: whether this screen is currently awake. */
protected static final int AWAKE = 1 << 0;
/** Flag: whether this screen is currently transitioning. */
protected static final int TRANSITING = 1 << 1;
protected int _flags;
}
/** A {@link Screen} that takes care of basic UI setup for you. */
public static abstract class UIScreen extends Screen {
/** Manages the main UI elements for this screen. */
public final Interface iface = new Interface();
@Override public void wake () {
super.wake();
_root = iface.addRoot(createRoot());
layer.add(_root.layer);
}
@Override public void sleep () {
super.sleep();
if (_root != null) {
iface.destroyRoot(_root);
_root = null;
}
// a screen is completely cleared and recreated between sleep/wake calls, so clear the
// animator after destroying the root so that unprocessed anims don't hold onto memory
iface.animator().clear();
}
@Override public void update (int delta) {
super.update(delta);
iface.update(delta);
}
@Override public void paint (Clock clock) {
super.paint(clock);
iface.paint(clock);
}
/** Creates the main UI root for this screen. This should also configure the size of the
* root prior to returning it. */
protected abstract Root createRoot ();
/** Contains the main UI for this screen.
* Created in {@link #wake}, destroyed in {@link #sleep}. */
protected Root _root;
}
@Override public Iterator<Screen> iterator () {
return new Iterator<Screen>() {
private int _idx = 0;
public boolean hasNext () { return _idx < screenCount(); }
public Screen next () { return screen(_idx++); }
public void remove () { throw new UnsupportedOperationException(); }
};
}
/** Returns the number of screens in the space. */
public int screenCount () {
return _screens.size();
}
/** Returns the screen at {@code index}. */
public Screen screen (int index) {
return _screens.get(index).screen;
}
/** Returns true if we're transitioning between two screens at this instant. This may either be
* an animation driven transition, or a manual transition in progress due to a user drag. */
public boolean isTransiting () {
return _driver != null || _untrans != null;
}
/** Adds {@code screen} to this space, positioned {@code dir}-wise from the current screen. For
* example, using {@code RIGHT} will add the screen to the right of the current screen and
* will slide the view to the right to reveal the new screen. The user would then manually
* slide the view left to return to the previous screen. */
public void add (Screen screen, Dir dir) {
add(screen, dir, false);
}
/** Adds {@code screen} to this space, replacing the current top-level screen. The screen is
* animated in the same manner as {@link #addScreen} using the same direction in which the
* current screen was added. This ensures that the user returns to the previous screen in the
* same way that they would via the to-be-replaced screen. */
public void replace (Screen screen) {
if (_screens.isEmpty()) throw new IllegalStateException("No current screen to replace()");
add(screen, _screens.get(0).dir, true);
}
/** Removes {@code screen} from this space. If it is the top-level screen, an animated
* transition to the previous screen will be performed. Otherwise the screen will simply be
* removed. */
public void pop (Screen screen) {
if (_current.screen == screen) {
if (!_screens.isEmpty()) popTrans(0);
else {
ActiveScreen oscr = _screens.remove(0);
takeFocus(oscr);
oscr.destroy();
_current = null;
pointer().setListener(null);
}
} else {
// TODO: this screen may be inside UntransListener.previous so we may need to recreate
// UntransListener with a new previous screen; or maybe just don't support pulling
// screens out of the middle of the stack; that's kind of wacky; popTop and popTo may
// be enough
int idx = indexOf(screen);
if (idx >= 0) {
popAt(idx);
checkSleep(); // we may need to wake a new screen
}
}
}
/** Removes all screens from the space until {@code screen} is reached. No transitions will be
* used, all screens will simply be removed and destroyed until we reach {@code screen}, and
* that screen will be woken and positioned properly. */
public void popTo (Screen screen) {
if (current() == screen) return; // NOOP!
ActiveScreen top = _screens.get(0);
while (top.screen != screen) {
takeFocus(top);
top.destroy();
top = _screens.get(0);
}
checkSleep(); // wake up the top screen
top.screen.layer.setTranslation(0, 0); // ensure that it's positioned properly
giveFocus(top);
}
/** Returns the current screen, or {@code null} if this space is empty. */
public Screen current () {
return (_current == null) ? null : _current.screen;
}
/** Includes the screen space and its screens in the game update loop. */
public void update (int delta) {
if (_driver != null) _driver.update(delta);
else {
if (_current != null) _current.screen.update(delta);
if (_untrans != null) _untrans.screen.update(delta);
}
}
/** Includes the screen space and its screens in the game paint loop. */
public void paint (Clock clock) {
if (_driver != null) _driver.paint(clock);
else {
if (_current != null) _current.screen.paint(clock);
if (_untrans != null) _untrans.screen.paint(clock);
}
}
protected int indexOf (Screen screen) {
for (int ii = 0, ll = _screens.size(); ii < ll; ii++) {
if (_screens.get(ii).screen == screen) return ii;
}
return -1;
}
protected void add (Screen screen, Dir dir, final boolean replace) {
screen.init();
ActiveScreen otop = _screens.isEmpty() ? null : _screens.get(0);
final ActiveScreen ntop = new ActiveScreen(screen, dir);
_screens.add(0, ntop);
ntop.check(true); // wake up the to-be-added screen
if (otop == null) giveFocus(ntop);
else transition(otop, ntop, ntop.dir, 0).onComplete.connect(new UnitSlot() {
public void onEmit () {
giveFocus(ntop);
if (replace) popAt(1);
}
});
}
protected float transitionTime (Dir dir) {
return 500f;
}
protected Driver transition (ActiveScreen oscr, ActiveScreen nscr, Dir dir, float startPct) {
takeFocus(oscr);
return _driver = new Driver(oscr, nscr, dir, startPct);
}
protected void checkSleep () {
if (_screens.isEmpty()) return;
// if the top-level screen was introduced via a slide transition, we need to keep the
// previous screen awake because we could start sliding to it ay any time; otherwise we can
// put that screen to sleep; all other screens should be sleeping
int ss = _screens.get(0).dir.canUntrans() ? 2 : 1;
log().info("checkSleep " + ss);
for (int ii = 0, ll = _screens.size(); ii < ll; ii++) _screens.get(ii).check(ii < ss);
}
protected void popTrans (float startPct) {
final ActiveScreen oscr = _screens.remove(0);
Dir dir = reverse(oscr.dir);
final ActiveScreen nscr = _screens.get(0);
nscr.check(true); // wake screen, if necessary
transition(oscr, nscr, dir, startPct).onComplete.connect(new UnitSlot() {
public void onEmit () {
giveFocus(nscr);
oscr.destroy();
}
});
}
protected void popAt (int index) {
_screens.remove(index).destroy();
}
protected void giveFocus (ActiveScreen as) {
try {
_current = as;
as.screen.gainedFocus();
// if we have a previous screen, and the direction supports manual untransitioning,
// set up a listener to handle that
ActiveScreen previous = (_screens.size() <= 1) ? null : _screens.get(1);
if (previous != null && as.dir.canUntrans()) {
pointer().setListener(new UntransListener(as, previous));
} else {
pointer().setListener(null);
}
} catch (Exception e) {
log().warn("Screen choked in gainedFocus() [screen=" + as.screen + "]", e);
}
checkSleep();
}
protected void takeFocus (ActiveScreen as) {
try {
as.screen.lostFocus();
} catch (Exception e) {
log().warn("Screen choked in lostFocus() [screen=" + as.screen + "]", e);
}
}
protected final List<ActiveScreen> _screens = new ArrayList<ActiveScreen>();
protected ActiveScreen _current, _untrans;
protected Driver _driver;
protected class UntransListener implements Pointer.Listener {
// the start stamp of our gesture, or 0 if we're not in a gesture
public double start;
// whether we're in the middle of an untransition gesture
public boolean untransing;
private float _sx, _sy;
private final Dir _udir;
private final ActiveScreen _cur, _prev;
public UntransListener (ActiveScreen cur, ActiveScreen prev) {
_udir = reverse(cur.dir); // untrans dir is opposite of trans dir
_cur = cur; _prev = prev;
}
@Override public void onPointerStart (Pointer.Event event) {
// if it's not OK to initiate an untransition gesture, or we're already in the middle
// of animating an automatic transition, ignore this gesture
if (!_cur.screen.canUntrans(_udir) || _driver != null) return;
_sx = event.x(); _sy = event.y();
start = currentTime();
}
@Override public void onPointerDrag (Pointer.Event event) {
if (start == 0) return; // ignore if we were disabled at gesture start
float frac = updateFracs(event.x(), event.y());
if (!untransing) {
// if the beginning of the gesture is not "more" in the untrans direction than not,
// ignore the rest the interaction (note: _offFrac is always positive but frac is
// positive if it's in the untrans direction and negative otherwise)
if (_offFrac > frac) {
start = 0;
return;
}
// TODO: we should probably ignore small movements in all directions before we
// commit to this gesture or not; if someone always jerks their finger to the right
// before beginning an interaction, that would always disable an up or down gesture
// before it ever had a chance to get started... oh, humans
// the first time we start untransing, do _udir.init() & setViz
untransing = true;
_untrans = _prev;
_udir.init(_cur.screen, _prev.screen);
_prev.screen.layer.setVisible(true);
pointer().cancelLayerDrags();
}
_udir.update(_cur.screen, _prev.screen, frac);
}
@Override public void onPointerEnd (Pointer.Event event) {
if (start == 0 || !untransing) return;
// clean up after our current manual transition because we're going to set up a driver
// to put the current screen back into place or to pop it off entirely
_udir.finish(_cur.screen, _prev.screen);
float frac = updateFracs(event.x(), event.y());
// compute the "velocity" of this gesture in "screens per second"
float fvel = (1000*frac) / (float)(currentTime() - start);
// if we've revealed more than 30% of the old screen, or we're going fast enough...
if (frac > 0.3f || fvel > 1.25f) {
// ...pop back to the previous screen
assert _cur == _screens.get(0);
popTrans(frac);
} else {
// ...otherwise animate the current screen back into position
_driver = new Driver(_prev, _cur, _cur.dir, 1-frac);
}
clear();
}
@Override public void onPointerCancel (Pointer.Event event) {
if (start == 0 || !untransing) return;
// snap our screens back to their original positions
_udir.update(_cur.screen, _prev.screen, 0);
_prev.screen.layer.setVisible(false);
_udir.finish(_cur.screen, _prev.screen);
clear();
}
protected void clear () {
untransing = false;
start = 0;
_untrans = null;
}
protected float updateFracs (float cx, float cy) {
// project dx/dy along untransition dir's vector
float dx = cx-_sx, dy = cy-_sy;
int hc = _udir.horizComp(), vc = _udir.vertComp();
float swidth = _prev.screen.width(), sheight = _prev.screen.height();
float frac;
if (hc != 0) {
frac = (dx*hc) / swidth;
_offFrac = Math.abs(dy) / sheight;
} else {
frac = (dy*vc) / sheight;
_offFrac = Math.abs(dx) / swidth;
}
return frac;
}
protected float computeFrac (float cx, float cy) {
// project dx/dy along untransition dir's vector
float dx = cx-_sx, dy = cy-_sy;
float tx = dx*_udir.horizComp();
float ty = dy*_udir.vertComp();
// the distance we've traveled over the full width/height of the screen is the frac
return (tx > 0) ? tx/_prev.screen.width() : ty/_prev.screen.height();
}
protected float _offFrac;
}
protected static class ActiveScreen {
public final Screen screen;
public final Dir dir;
public ActiveScreen (Screen screen, Dir dir) {
this.screen = screen;
this.dir = dir;
}
public void check (boolean awake) {
if (screen.awake() != awake) {
if (awake) {
log().info("waking " + screen);
graphics().rootLayer().add(screen.layer);
screen.wake();
} else {
log().info("sleeping " + screen);
graphics().rootLayer().remove(screen.layer);
screen.sleep();
}
}
}
public void destroy () {
check(false); // make sure screen is hidden/remove
screen.destroy();
}
}
/** Drives a transition via an animation. */
protected class Driver {
public final ActiveScreen outgoing, incoming;
public final Dir dir;
public final float duration;
public final UnitSignal onComplete = new UnitSignal();
public final float startPct;
public final Interpolator interp;
public float elapsed;
public Driver (ActiveScreen outgoing, ActiveScreen incoming, Dir dir, float startPct) {
this.outgoing = outgoing;
this.incoming = incoming;
this.dir = dir;
this.duration = transitionTime(dir);
this.startPct = startPct;
// TODO: allow Dir to provide own interpolator?
this.interp = (startPct == 0) ? Interpolator.EASE_INOUT : Interpolator.EASE_OUT;
dir.init(outgoing.screen, incoming.screen);
incoming.screen.layer.setVisible(true);
dir.update(outgoing.screen, incoming.screen, startPct);
}
public void update (int delta) {
outgoing.screen.update(delta);
incoming.screen.update(delta);
}
public void paint (Clock clock) {
outgoing.screen.paint(clock);
incoming.screen.paint(clock);
// if this is our first frame, cap dt at 33ms because the first frame has to eat the
// initialization time for the to-be-introduced screen, and we don't want that to chew
// up a bunch of our transition time if it's slow; the user will not have seen
// anything happen up to now, so this won't cause a jitter in the animation
if (elapsed == 0) elapsed += Math.min(33, clock.dt());
else elapsed += clock.dt();
float pct = Math.min(elapsed/duration, 1), ipct;
if (startPct >= 0) ipct = startPct + (1-startPct)*interp.apply(pct);
// if we were started with a negative startPct, we're scrolling back from an
// untranslation gesture that ended on the "opposite" side
else ipct = 1-interp.apply(pct);
dir.update(outgoing.screen, incoming.screen, ipct);
if (pct == 1) complete();
}
public void complete () {
_driver = null;
outgoing.screen.layer.setVisible(false);
dir.finish(outgoing.screen, incoming.screen);
onComplete.emit();
}
}
protected static Dir reverse (Dir dir) {
switch (dir) {
case UP: return Dir.DOWN;
case DOWN: return Dir.UP;
case LEFT: return Dir.RIGHT;
case RIGHT: return Dir.LEFT;
case IN: return Dir.OUT;
case OUT: return Dir.IN;
case FLIP: return Dir.FLIP;
default: throw new AssertionError("Sky is falling: " + dir);
}
}
} |
package be.ibridge.kettle.trans.dialog;
import org.eclipse.swt.SWT;
import be.ibridge.kettle.core.GUIResource;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.trans.TransHopMeta;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStepDialog;
import be.ibridge.kettle.trans.step.StepMeta;
public class TransHopDialog extends Dialog
{
private Label wlFrom;
private CCombo wFrom;
private FormData fdlFrom, fdFrom;
private Label wlTo;
private Button wFlip;
private CCombo wTo;
private FormData fdlTo, fdFlip, fdTo;
private Label wlEnabled;
private Button wEnabled;
private FormData fdlEnabled, fdEnabled;
private Button wOK, wCancel;
private FormData fdOK, fdCancel;
private Listener lsOK, lsCancel, lsFlip;
private TransHopMeta input;
private Shell shell;
private TransMeta transMeta;
private Props props;
private ModifyListener lsMod;
private boolean changed;
/** @deprecated */
public TransHopDialog(Shell parent, int style, LogWriter l, Props props, Object in, TransMeta tr)
{
this(parent, style, in, tr);
}
public TransHopDialog(Shell parent, int style, Object in, TransMeta tr)
{
super(parent, style);
this.props=Props.getInstance();
input=(TransHopMeta)in;
transMeta=tr;
}
public Object open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE);
props.setLook(shell);
shell.setImage(GUIResource.getInstance().getImageHop());
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("TransHopDialog.Shell.Label")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
int width = 0;
// From step line
wlFrom=new Label(shell, SWT.RIGHT);
wlFrom.setText(Messages.getString("TransHopDialog.FromStep.Label")); //$NON-NLS-1$
props.setLook(wlFrom);
fdlFrom=new FormData();
fdlFrom.left = new FormAttachment(0, 0);
fdlFrom.right= new FormAttachment(middle, -margin);
fdlFrom.top = new FormAttachment(0, margin);
wlFrom.setLayoutData(fdlFrom);
wFrom=new CCombo(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wFrom.setText(Messages.getString("TransHopDialog.FromStepDropdownList.Label")); //$NON-NLS-1$
props.setLook(wFrom);
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
wFrom.add(stepMeta.getName());
}
wFrom.addModifyListener(lsMod);
fdFrom=new FormData();
fdFrom.left = new FormAttachment(middle, 0);
fdFrom.top = new FormAttachment(0, margin);
fdFrom.right= new FormAttachment(100, 0);
wFrom.setLayoutData(fdFrom);
// To line
wlTo=new Label(shell, SWT.RIGHT);
wlTo.setText(Messages.getString("TransHopDialog.TargetStep.Label")); //$NON-NLS-1$
props.setLook(wlTo);
fdlTo=new FormData();
fdlTo.left = new FormAttachment(0, 0);
fdlTo.right= new FormAttachment(middle, -margin);
fdlTo.top = new FormAttachment(wFrom, margin);
wlTo.setLayoutData(fdlTo);
wTo=new CCombo(shell, SWT.BORDER | SWT.READ_ONLY);
wTo.setText(Messages.getString("TransHopDialog.TargetStepDropdownList.Label")); //$NON-NLS-1$
props.setLook(wTo);
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
wTo.add(stepMeta.getName());
}
wTo.addModifyListener(lsMod);
fdTo=new FormData();
fdTo.left = new FormAttachment(middle, 0);
fdTo.top = new FormAttachment(wFrom, margin);
fdTo.right= new FormAttachment(100, 0);
wTo.setLayoutData(fdTo);
// Enabled?
wlEnabled=new Label(shell, SWT.RIGHT);
wlEnabled.setText(Messages.getString("TransHopDialog.EnableHop.Label")); //$NON-NLS-1$
props.setLook(wlEnabled);
fdlEnabled=new FormData();
fdlEnabled.left = new FormAttachment(0, 0);
fdlEnabled.right= new FormAttachment(middle, -margin);
fdlEnabled.top = new FormAttachment(wlTo, margin*5);
wlEnabled.setLayoutData(fdlEnabled);
wEnabled=new Button(shell, SWT.CHECK);
props.setLook(wEnabled);
fdEnabled=new FormData();
fdEnabled.left = new FormAttachment(middle, 0);
fdEnabled.top = new FormAttachment(wlTo, margin*5);
wEnabled.setLayoutData(fdEnabled);
wEnabled.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setEnabled( !input.isEnabled());
input.setChanged();
}
}
);
wFlip = new Button(shell, SWT.PUSH);
wFlip.setText(Messages.getString("TransHopDialog.FromTo.Button")); //$NON-NLS-1$
fdFlip = new FormData();
fdFlip.left = new FormAttachment(wEnabled, margin*5);
fdFlip.top = new FormAttachment(wlTo, margin*5);
wFlip.setLayoutData(fdFlip);
// Some buttons
wOK=new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK")); //$NON-NLS-1$
wOK.pack(true);
Rectangle rOK = wOK.getBounds();
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel")); //$NON-NLS-1$
wCancel.pack(true);
Rectangle rCancel = wCancel.getBounds();
width = (rOK.width > rCancel.width ? rOK.width : rCancel.width);
width += margin;
fdOK=new FormData();
fdOK.top = new FormAttachment(wFlip, margin*5);
fdOK.left = new FormAttachment(50, -width);
fdOK.right = new FormAttachment(50, -(margin/2));
//fdOK.bottom = new FormAttachment(100, 0);
wOK.setLayoutData(fdOK);
fdCancel=new FormData();
fdCancel.top = new FormAttachment(wFlip, margin*5);
fdCancel.left = new FormAttachment(50, margin/2);
fdCancel.right = new FormAttachment(50, width);
//fdCancel.bottom = new FormAttachment(100, 0);
wCancel.setLayoutData(fdCancel);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsFlip = new Listener() { public void handleEvent(Event e) { flip(); } };
wOK.addListener (SWT.Selection, lsOK );
wCancel.addListener(SWT.Selection, lsCancel );
wFlip.addListener (SWT.Selection, lsFlip );
// Detect [X] or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
getData();
BaseStepDialog.setSize(shell);
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return input;
}
public void dispose()
{
props.setScreen(new WindowProperty(shell));
shell.dispose();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
if (input.getFromStep() != null) wFrom.setText(input.getFromStep().getName());
if (input.getToStep() != null) wTo.setText(input.getToStep().getName());
wEnabled.setSelection(input.isEnabled());
}
private void cancel()
{
input.setChanged(changed);
input=null;
dispose();
}
private void ok()
{
StepMeta fromBackup = input.getFromStep();
StepMeta toBackup = input.getToStep();
input.setFromStep( transMeta.findStep( wFrom.getText() ));
input.setToStep ( transMeta.findStep( wTo.getText() ));
if (transMeta.hasLoop(input.getFromStep()))
{
input.setFromStep(fromBackup);
input.setToStep(toBackup);
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("TransHopDialog.LoopsNotAllowed.DialogMessage")); //$NON-NLS-1$
mb.setText(Messages.getString("TransHopDialog.LoopsNotAllowed.DialogTitle")); //$NON-NLS-1$
mb.open();
}
else
{
if (input.getFromStep()==null)
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("TransHopDialog.StepDoesNotExist.DialogMessage",wFrom.getText())); //$NON-NLS-1$ //$NON-NLS-2$
mb.setText(Messages.getString("TransHopDialog.StepDoesNotExist.DialogTitle")); //$NON-NLS-1$
mb.open();
}
else
{
if (input.getToStep()==null)
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("TransHopDialog.StepDoesNotExist.DialogMessage",wTo.getText())); //$NON-NLS-1$ //$NON-NLS-2$
mb.setText(Messages.getString("TransHopDialog.StepDoesNotExist.DialogTitle")); //$NON-NLS-1$
mb.open();
}
else
{
if (input.getFromStep().equals(input.getToStep()))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("TransHopDialog.CannotGoToSameStep.DialogMessage")); //$NON-NLS-1$
mb.setText(Messages.getString("TransHopDialog.CannotGoToSameStep.DialogTitle")); //$NON-NLS-1$
mb.open();
}
else
{
dispose();
}
}
}
}
}
private void flip()
{
String dummy;
dummy = wFrom.getText();
wFrom.setText(wTo.getText());
wTo.setText(dummy);
input.setChanged();
}
} |
package org.parser.marpa;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* Test Application thread
*/
public class AppThread implements Runnable {
ESLIFLoggerInterface eslifLogger;
/**
* @param eslifLogger logger interface
*/
public AppThread(ESLIFLoggerInterface eslifLogger) {
this.eslifLogger = eslifLogger;
}
@Override
public void run() {
try {
ESLIF eslif = ESLIF.getInstance(eslifLogger);
eslifLogger.info("ESLIF object is " + eslif);
eslifLogger.info("marpaESLIF version is " + eslif.version());
final String grammar =
":start ::= Object2\n"
+ "Object2 ::= Object action => ::concat\n"
+ "Object ::= Expression action => ::concat\n"
+ ":default ::= action => do_op\n"
+ ":discard ::= whitespaces event => discard_whitespaces$\n"
+ ":discard ::= comment event => discard_comment$\n"
+ "\n"
+ "event ^Number = predicted Number\n"
+ "event Number$ = completed Number\n"
+ "Number ::= NUMBER action => ::shift\n"
+ "\n"
+ "event Expression$ = completed Expression\n"
+ "event ^Expression = predicted Expression\n"
+ "Expression ::=\n"
+ " Number action => do_int\n"
+ " | '(' Expression ')' assoc => group action => ::copy[1]\n"
+ " || Expression '**' Expression assoc => right\n"
+ " || Expression '*' Expression\n"
+ " | Expression '/' Expression\n"
+ " || Expression '+' Expression\n"
+ " | Expression '-' Expression\n"
+ "\n"
+ ":lexeme ::= NUMBER pause => before event => ^NUMBER\n"
+ ":lexeme ::= NUMBER pause => after event => NUMBER$\n"
+ "NUMBER ~ /[\\d]+/\n"
+ "whitespaces ::= WHITESPACES\n"
+ "WHITESPACES ~ [\\s]+\n"
+ "comment ::= /(?:(?:(?:\\/\\/)(?:[^\\n]*)(?:\\n|\\z))|(?:(?:\\/\\*)(?:(?:[^\\*]+|\\*(?!\\/))*)(?:\\*\\/)))/u\n"
+ "\n";
ESLIFGrammar eslifGrammar = new ESLIFGrammar(eslif, grammar);
eslifLogger.info("number of grammars : " + eslifGrammar.ngrammar());
eslifLogger.info("current grammar level : " + eslifGrammar.currentLevel());
eslifLogger.info("current grammar description: " + eslifGrammar.currentDescription());
for (int level = 0; level < eslifGrammar.ngrammar(); level++) {
eslifLogger.info("- grammar description at level " + level + ": " + eslifGrammar.descriptionByLevel(level));;
}
eslifLogger.info("current grammar properties: " + eslifGrammar.properties());
eslifLogger.info("current grammar methods:\n" + eslifGrammar.show());
{
int[] rules = eslifGrammar.currentRuleIds();
for (int i = 0; i < rules.length; i++) {
eslifLogger.info("- current rule No " + i + ": " + rules[i]);
eslifLogger.info(" properties: " + eslifGrammar.ruleProperties(i));
eslifLogger.info(" display form: " + eslifGrammar.ruleDisplay(i));
eslifLogger.info(" show form: " + eslifGrammar.ruleShow(i));
}
int[] symbols = eslifGrammar.currentSymbolIds();
for (int i = 0; i < symbols.length; i++) {
eslifLogger.info("- current symbol No " + i + ": " + symbols[i]);
eslifLogger.info(" properties : " + eslifGrammar.symbolProperties(i));
eslifLogger.info(" display form: " + eslifGrammar.symbolDisplay(i));
}
}
for (int level = 0; level < eslifGrammar.ngrammar(); level++) {
eslifLogger.info("grammar at level: " + level);
eslifLogger.info("- grammar properties : " + eslifGrammar.propertiesByLevel(level));
eslifLogger.info("- grammar show at level: " + level + "\n:" + eslifGrammar.showByLevel(level));
eslifLogger.info("- rule array at level " + level);
int[] rules = eslifGrammar.ruleIdsByLevel(level);
for (int i = 0; i < rules.length; i++) {
eslifLogger.info(" + rule No " + i + ": " + rules[i]);
eslifLogger.info(" properties : " + eslifGrammar.rulePropertiesByLevel(level, i));
eslifLogger.info(" display form: " + eslifGrammar.ruleDisplayByLevel(level, i));
eslifLogger.info(" show form: " + eslifGrammar.ruleShowByLevel(level, i));
}
eslifLogger.info("- symbol array at level " + level);
int[] symbols = eslifGrammar.symbolIdsByLevel(level);
for (int i = 0; i < symbols.length; i++) {
eslifLogger.info(" + symbol No " + i + ": " + symbols[i]);
eslifLogger.info(" properties : " + eslifGrammar.symbolPropertiesByLevel(level, i));
eslifLogger.info(" display form: " + eslifGrammar.symbolDisplayByLevel(level, i));
}
}
String[] strings = {
"(((3 * 4) + 2 * 7) / 2 - 1)/* This is a\n comment \n */** 3",
"5 / (2 * 3)",
"5 / 2 * 3",
"(5 ** 2) ** 3",
"5 * (2 * 3)",
"5 ** (2 ** 3)",
"5 ** (2 / 3)",
"1 + ( 2 + ( 3 + ( 4 + 5) )",
"1 + ( 2 + ( 3 + ( 4 + 50) ) ) /* comment after */",
" 100",
"not scannable at all",
"100\nsecond line not scannable",
"100 * /* incomplete */"
};
for (int i = 0; i < strings.length; i++) {
String string = new String(strings[i]);
BufferedReader reader = new BufferedReader(new StringReader(string));
AppRecognizer eslifAppRecognizer = new AppRecognizer(reader);
AppValue eslifAppValue = new AppValue();
eslifLogger.info("Testing parse() on " + string);
try {
if (eslifGrammar.parse(eslifAppRecognizer, eslifAppValue)) {
eslifLogger.info("Result: " + eslifAppValue.getResult());
}
} catch (Exception e) {
System.err.println("Failed to parse " + string + ": " + e.getMessage());
}
}
for (int i = 0; i < strings.length; i++) {
String string = new String(strings[i]);
BufferedReader reader = new BufferedReader(new StringReader(string));
AppRecognizer eslifAppRecognizer = new AppRecognizer(reader);
ESLIFRecognizer eslifRecognizer = new ESLIFRecognizer(eslifGrammar, eslifAppRecognizer);
eslifLogger.info("");
eslifLogger.info("***********************************************************");
eslifLogger.info("Testing scan()/resume() on " + string);
eslifLogger.info("***********************************************************");
eslifLogger.info("");
if (doScan(eslifLogger, eslifRecognizer, true)) {
showLocation("After doScan", eslifLogger, eslifRecognizer);
if (! eslifRecognizer.isEof()) {
if (! eslifRecognizer.read()) {
break;
}
showRecognizerInput("after read", eslifLogger, eslifRecognizer);
}
if (i == 0) {
eslifRecognizer.progressLog(-1, -1, ESLIFLoggerLevel.get(ESLIFLoggerLevel.NOTICE.getCode()));
}
int j = 0;
while (eslifRecognizer.isCanContinue()) {
if (! doResume(eslifLogger, eslifRecognizer, 0)) {
break;
}
showLocation("After doResume", eslifLogger, eslifRecognizer);
ESLIFEvent[] events = eslifRecognizer.events();
for (int k = 0; k < events.length; k++) {
ESLIFEvent event = events[k];
if ("^NUMBER".equals(event.getEvent())) {
// Recognizer will wait forever if we do not feed the number
byte[] bytes = eslifRecognizer.lexemeLastPause("NUMBER");
if (bytes == null) {
throw new Exception("Pause before on NUMBER but no pause information!");
}
if (! doLexemeRead(eslifLogger, eslifRecognizer, "NUMBER", j+1, bytes)) {
throw new Exception("NUMBER expected but reading such lexeme fails!");
}
doDiscardTry(eslifLogger, eslifRecognizer);
doLexemeTry(eslifLogger, eslifRecognizer, "WHITESPACES");
doLexemeTry(eslifLogger, eslifRecognizer, "whitespaces");
}
}
if (j == 0) {
changeEventState("Loop No " + j, eslifLogger, eslifRecognizer, "Expression", ESLIFEventType.PREDICTED, false);
changeEventState("Loop No " + j, eslifLogger, eslifRecognizer, "whitespaces", ESLIFEventType.DISCARD, false);
changeEventState("Loop No " + j, eslifLogger, eslifRecognizer, "NUMBER", ESLIFEventType.AFTER, false);
}
showLastCompletion("Loop No " + j, eslifLogger, eslifRecognizer, "Expression", string);
showLastCompletion("Loop No " + j, eslifLogger, eslifRecognizer, "Number", string);
j++;
}
try {
AppValue eslifAppValue = new AppValue();
eslifLogger.info("Testing value() on " + string);
try {
ESLIFValue value = new ESLIFValue(eslifRecognizer, eslifAppValue);
while (value.value()) {
Object result = eslifAppValue.getResult();
eslifLogger.info("Result: " + result);
}
value.free();
} catch (Exception e) {
eslifLogger.error("Failed to parse " + string + ": " + e.getMessage());
}
} catch (Exception e){
eslifLogger.error("Cannot value the input: " + e);
}
}
eslifRecognizer.free();
}
eslifGrammar.free();
} catch (Exception e) {
Thread t = Thread.currentThread();
t.getUncaughtExceptionHandler().uncaughtException(t, e);
}
}
private static boolean doScan(ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer, boolean initialEvents) throws Exception {
String context;
eslifLogger.debug(" =============> scan(initialEvents=" + initialEvents + ")");
if (! eslifRecognizer.scan(initialEvents)) {
return false;
}
context = "after scan";
showRecognizerInput(context, eslifLogger, eslifRecognizer);
showEvents(context, eslifLogger, eslifRecognizer);
showLexemeExpected(context, eslifLogger, eslifRecognizer);
return true;
}
private static boolean doResume(ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer, int deltaLength) throws Exception {
String context;
eslifLogger.debug(" =============> resume(deltaLength=" + deltaLength + ")");
if (! eslifRecognizer.resume(deltaLength)) {
return false;
}
context = "after resume";
showRecognizerInput(context, eslifLogger, eslifRecognizer);
showEvents(context, eslifLogger, eslifRecognizer);
showLexemeExpected(context, eslifLogger, eslifRecognizer);
return true;
}
private static void doDiscardTry(ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer) throws UnsupportedEncodingException {
boolean test;
try {
test = eslifRecognizer.discardTry();
eslifLogger.debug("... Testing discard at current position returns " + test);
if (test) {
byte[] bytes = eslifRecognizer.discardLastTry();
String string = new String(bytes, "UTF-8");
eslifLogger.debug("... Testing discard at current position gave \"" + string + "\"");
}
} catch (ESLIFException e) {
// Because we test with a symbol that is not a lexeme, and that raises an exception
eslifLogger.debug(e.getMessage());
}
}
private static void doLexemeTry(ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer, String symbol) throws UnsupportedEncodingException {
boolean test;
try {
test = eslifRecognizer.lexemeTry(symbol);
eslifLogger.debug("... Testing " + symbol + " lexeme at current position returns " + test);
if (test) {
byte[] bytes = eslifRecognizer.lexemeLastTry(symbol);
String string = new String(bytes, "UTF-8");
eslifLogger.debug("... Testing " + symbol + " lexeme at current position gave \"" + string + "\"");
}
} catch (ESLIFException e) {
// Because we test with a symbol that is not a lexeme, and that raises an exception
eslifLogger.debug(e.getMessage());
}
}
// We replace current NUMBER by the Integer object representing value
private static boolean doLexemeRead(ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer, String symbol, int value, byte[] bytes) throws Exception {
String context;
String old = new String(bytes, "UTF-8");
eslifLogger.debug("... Forcing Integer object for \"" + value + "\" spanned on " + bytes.length + " bytes" + " instead of \"" + old + "\"");
if (! eslifRecognizer.lexemeRead(symbol, new Integer(value), bytes.length, 1 /* grammarLength */)) {
return false;
}
context = "after lexemeRead";
showRecognizerInput(context, eslifLogger, eslifRecognizer);
showEvents(context, eslifLogger, eslifRecognizer);
showLexemeExpected(context, eslifLogger, eslifRecognizer);
return true;
}
private static void showRecognizerInput(String context, ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer) throws UnsupportedEncodingException, ESLIFException {
byte[] bytes = eslifRecognizer.input();
if (bytes != null) {
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding
eslifLogger.debug("[" + context + "] Recognizer buffer:\n" + str);
} else {
eslifLogger.debug("[" + context + "] Recognizer buffer is null");
}
}
private static void showEvents(String context, ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer) throws Exception {
ESLIFEvent[] events = eslifRecognizer.events();
for (int j = 0; j < events.length; j++) {
ESLIFEvent event = events[j];
ESLIFEventType type = event.getType();
String symbol = event.getSymbol();
String name = event.getEvent();
eslifLogger.debug("[" + context + "]" + " Event: {Type, Symbol, Name}={" + type + ", " + symbol + ", " + name + "}");
if (ESLIFEventType.BEFORE.equals(type)) {
byte[] bytes = eslifRecognizer.lexemeLastPause(symbol);
if (bytes == null) {
throw new Exception("Pause before on " + symbol + " but no pause information!");
}
}
}
}
private static void showLexemeExpected(String context, ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer) throws ESLIFException {
String[] lexemeExpected = eslifRecognizer.lexemeExpected();
if (lexemeExpected != null) {
for (int j = 0; j < lexemeExpected.length; j++) {
eslifLogger.debug("[" + context + "] Expected lexeme: " + lexemeExpected[j]);
}
}
}
private static void changeEventState(String context, ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer, String symbol, ESLIFEventType type, boolean state) throws ESLIFException {
eslifLogger.debug("[" + context + "]" + " Changing event state " + type + " of symbol " + symbol + " to " + state);
eslifRecognizer.eventOnOff(symbol, new ESLIFEventType[] { ESLIFEventType.get(type.getCode()) }, state);
}
private static void showLastCompletion(String context, ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer, String symbol, String origin) {
try {
long lastExpressionOffset = eslifRecognizer.lastCompletedOffset(symbol);
long lastExpressionLength = eslifRecognizer.lastCompletedLength(symbol);
byte[] string2byte = origin.getBytes();
byte[] matchedbytes = Arrays.copyOfRange(string2byte, (int) lastExpressionOffset, (int) (lastExpressionOffset + lastExpressionLength));
String matchedString = new String(matchedbytes, "UTF-8");
eslifLogger.debug("[" + context + "] Last " + symbol + " completion is: " + matchedString);
} catch (Exception e) {
eslifLogger.warning("[" + context + "] Last " + symbol + " completion raised an exception");
}
}
private static void showLocation(String context, ESLIFLoggerInterface eslifLogger, ESLIFRecognizer eslifRecognizer) {
try {
long line = eslifRecognizer.line();
long column = eslifRecognizer.column();
eslifLogger.debug("[" + context + "] Location is [" + line + "," + column + "]");
} catch (Exception e) {
eslifLogger.warning("[" + context + "] line() or column() raised an exception");
}
}
} |
package app.hongs.db;
import app.hongs.Cnst;
import app.hongs.Core;
import app.hongs.CoreConfig;
import app.hongs.CoreLogger;
import app.hongs.HongsException;
import app.hongs.HongsExpedient;
import app.hongs.db.util.FetchCase;
import app.hongs.db.util.FetchPage;
import app.hongs.db.util.AssocCase;
import app.hongs.dh.IEntity;
import app.hongs.util.Synt;
import java.util.Iterator;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
*
* <p>
* create,add,update,put,delete,del .<br/>
: search,create,update,delete
: unique,exists
;
: get,add,put,del
;
filter, permit ,
permit filter , .<br/>
search :
<code>
* ?pn=1&rn=10&f1=123&f2.-gt=456&wd=a+b&ob=-f1+f2&rb=id+f1+f2
* </code>
* filter
* </p>
*
* <h3>:</h3>
* <pre>
* : 0x1090~0x109f
* 0x1091 id
* 0x1092 id
* 0x1093 id
* 0x1094 id
* 0x1096
* 0x1097
* 0x1098
* 0x109a nv()
* 0x109b ()
* 0x109c : $0
* </pre>
*
* @author Hongs
*/
public class Model
implements IEntity
{
public DB db;
public Table table;
public String[] listable = null;
public String[] sortable = null;
public String[] findable = null;
public String[] siftable = null;
/**
*
*
* .
* id,wd,pn,gn,rn,rb,ob ,
* ;
* .
*
* @param table
* @throws app.hongs.HongsException
*/
public Model(Table table)
throws HongsException
{
this.table = table;
this.db = table.db;
String cs;
cs = table.getField("listable");
if (cs != null) this.listable = cs.split(",");
cs = table.getField("sortable");
if (cs != null) this.sortable = cs.split(",");
cs = table.getField("findable");
if (cs != null) this.findable = cs.split(",");
cs = table.getField("siftable");
if (cs != null) this.siftable = cs.split(",");
}
/
/**
*
* @param rd
* @return
* @throws HongsException
*/
@Override
public Map search(Map rd)
throws HongsException
{
return this.search(rd, null);
}
/**
*
* @param rd
* @param caze
* @return
* @throws HongsException
*/
public Map search(Map rd, FetchCase caze)
throws HongsException
{
Object id = rd.get(this.table.primaryKey);
if (id == null || id instanceof Map || id instanceof Collection) {
return this.getList(rd, caze);
} else if (!"".equals (id)) {
return this.getInfo(rd, caze);
} else {
return new HashMap ( );
}
}
/**
*
*
* @param rd
* @return ID
* @throws HongsException
*/
@Override
public Map create(Map rd)
throws HongsException
{
String[] cf = listable;
String id = add(rd);
if (cf == null ) {
cf = (String[]) table.getFields().keySet().toArray(new String[]{});
}
if (cf.length == 0) {
rd.put(table.primaryKey, id);
return rd;
} else {
Map sd = new LinkedHashMap();
sd.put(table.primaryKey, id);
if (null != listable) {
for(String fn: listable) {
if ( ! fn.contains(".")) {
sd.put(fn, rd.get(fn));
}
}
}
return sd;
}
}
/**
*
*
* @param rd
* @return
* @throws app.hongs.HongsException
*/
@Override
public int update(Map rd)
throws HongsException
{
return this.update(rd, null);
}
/**
*
*
* @param rd
* @param caze
* @return
* @throws app.hongs.HongsException
*/
public int update(Map rd, FetchCase caze)
throws HongsException
{
Object idz = rd.get(Cnst.ID_KEY);
if (idz == null) {
idz = rd.get(table.primaryKey);
}
if (idz == null) {
return this.put(null, null);
}
Set<String> ids = new LinkedHashSet();
if (idz instanceof Collection ) {
ids.addAll((Collection)idz);
} else {
ids.add ( idz.toString());
}
Map dat = new HashMap(rd);
dat.remove(this.table.primaryKey);
FetchCase fc = caze != null ? caze.clone() : fetchCase ( );
Map wh = Synt.declare( rd.get(Cnst.WR_KEY), new HashMap());
fc.setOption("MODEL_METHOD", "update");
wh.put (this.table.primaryKey, ids);
this.filter(fc , wh );
if (this.table.fetchLess(fc).isEmpty()) {
throw new HongsException(0x1097, "Can not update for ids: "+ids);
}
for (String id : ids)
{
this.put( id , dat);
}
return ids.size();
}
/**
*
*
* @param rd
* @return
* @throws app.hongs.HongsException
*/
@Override
public int delete(Map rd)
throws HongsException
{
return this.delete(rd, null);
}
/**
*
*
* @param rd
* @param caze
* @return
* @throws app.hongs.HongsException
*/
public int delete(Map rd, FetchCase caze)
throws HongsException
{
Object idz = rd.get ( Cnst.ID_KEY );
if (idz == null) {
idz = rd.get(table.primaryKey);
}
if (idz == null) {
return this.del(null, null);
}
Set<String> ids = new LinkedHashSet();
if (idz instanceof Collection ) {
ids.addAll((Collection)idz);
} else {
ids.add ( idz.toString());
}
FetchCase fc = caze != null ? caze.clone() : fetchCase ( );
Map wh = Synt.declare( rd.get(Cnst.WR_KEY), new HashMap());
fc.setOption("MODEL_METHOD", "delete");
wh.put (this.table.primaryKey, ids);
this.filter(fc , wh );
if (this.table.fetchLess(fc).isEmpty()) {
throw new HongsException(0x1097, "Can not delete for ids: "+ids);
}
for (String id : ids)
{
this.del( id ,caze);
}
return ids.size();
}
/
public boolean unique(Map rd)
throws HongsException
{
return !exists(rd);
}
public boolean unique(Map rd, FetchCase caze)
throws HongsException
{
return !exists(rd, caze);
}
/**
*
*
* @param rd
* @return true, false
* @throws app.hongs.HongsException
*/
public boolean exists(Map rd)
throws HongsException
{
return exists(rd, null);
}
/**
*
*
* @param rd
* @param caze
* @return true, false
* @throws app.hongs.HongsException
*/
public boolean exists(Map rd, FetchCase caze)
throws HongsException
{
if (rd == null)
{
rd = new HashMap();
}
if (caze == null)
{
caze = fetchCase();
}
if (!caze.hasOption("ASSOCS")
&& !caze.hasOption("ASSOC_TYPES")
&& !caze.hasOption("ASSOC_JOINS"))
{
caze.setOption("ASSOCS", new HashSet());
}
if (!rd.containsKey("n") || !rd.containsKey("v"))
{
throw new HongsException(0x109a, "Param n or v can not be empty");
}
String n = (String) rd.get("n");
String v = (String) rd.get("v");
Map columns = this.table.getFields();
if (!columns.containsKey(n))
{
throw new HongsException(0x109b, "Column " + n + " is not exists");
}
caze.filter("`"+this.table.name+"`.`"+n+"` = ?", v);
Iterator it = rd.entrySet().iterator();
while (it.hasNext())
{
Map.Entry entry = (Map.Entry)it.next();
String field = (String) entry.getKey();
String value = (String) entry.getValue();
if (field.equals( this.table.primaryKey)
|| field.equals( Cnst.ID_KEY))
{
if (value != null && ! value.equals(""))
{
caze.filter("`"+this.table.name+"`.`"+this.table.primaryKey+"` != ?", value);
}
} else
if (columns.containsKey(field))
{
caze.filter("`"+this.table.name+"`.`"+field+"` = ?", value);
}
}
Map row = this.table.fetchLess(caze);
return !row.isEmpty();
}
/
/**
*
* id , id
* @param rd
* @return
* @throws HongsException
*/
public String set(Map rd)
throws HongsException
{
String id = Synt.asString(rd.get(this.table.primaryKey));
if (id == null || id.length() == 0)
{
id = this.add(rd);
}
else
{
this.put(id , rd);
}
return id;
}
/**
*
id
id
model
MySQL,SQLite add :
//
rd.remove(this.table.primaryKey );
int an = this.table.insert ( rd );
// ID, MySQL: last_insert_id() SQLite: last_insert_rowid()
Map rd = this.db.fetchOne ( "SELECT last_insert_id() AS id" );
Object id = rd.get("id");
//
rd.put(this.table.primaryKey, id);
this.table.insertSubValues ( rd );
DB,Table,Model , PreparedStatement.getGeneratedKeys
*
* @param rd
* @return ID
* @throws app.hongs.HongsException
*/
public String add(Map rd)
throws HongsException
{
String id = Core.newIdentity();
add(id,rd);
return id ;
}
/**
*
*
* @param id
* @param rd
* @return
* @throws HongsException
*/
public int add(String id, Map rd)
throws HongsException
{
if (id == null || id.length() == 0)
{
throw new HongsException (0x1091, "ID can not be empty for add");
}
rd.put(this.table.primaryKey, id);
int an = this.table.insert ( rd );
// rd.put(this.table.primaryKey, id);
this.table.insertSubValues ( rd );
return an;
}
/**
*
*
* @param rd
* @param id
* @return
* @throws app.hongs.HongsException
*/
public int put(String id, Map rd)
throws HongsException
{
if (id == null || id.length() == 0)
{
throw new HongsException (0x1092, "ID can not be empty for put");
}
rd.remove(this.table.primaryKey );
int an = this.table.update ( rd , "`"+this.table.primaryKey+"` = ?", id);
rd.put(this.table.primaryKey, id);
this.table.insertSubValues ( rd );
return an;
}
/**
*
*
* @param id
* @return
* @throws app.hongs.HongsException
*/
public int del(String id)
throws HongsException
{
return this.del(id, null);
}
/**
*
*
*
* ,
* .
*
* @param id
* @param caze
* @return
* @throws app.hongs.HongsException
*/
public int del(String id, FetchCase caze)
throws HongsException
{
if (id == null || id.length() == 0)
{
throw new HongsException (0x1093, "ID can not be empty for del");
}
int an;
if (caze == null || ! caze.getOption( "INCLUDE_REMOVED", false ) )
{
an = this.table.remove ("`"+ this.table.primaryKey +"` = ?", id);
}
else
{
an = this.table.delete ("`"+ this.table.primaryKey +"` = ?", id);
}
if (caze == null || ! caze.getOption( "EXCLUDE_HASMANY", false ) )
{
this.table.deleteSubValues ( id );
}
return an;
}
public Map get(String id)
throws HongsException
{
return this.get(id, null);
}
public Map get(String id, FetchCase caze)
throws HongsException
{
if (id == null || id.length() == 0)
{
throw new HongsException(0x1094, "ID can not be empty for get");
}
Map rd = new HashMap();
rd.put(this.table.primaryKey, id);
// filter
caze = caze != null ? caze.clone() : fetchCase();
caze.setOption("MODEL_METHOD", "get");
this.filter(caze , rd);
return this.table.fetchLess(caze);
}
public Map getOne(Map rd)
throws HongsException
{
return this.getOne(rd, null);
}
public Map getOne(Map rd, FetchCase caze)
throws HongsException
{
if (rd == null) {
rd = new HashMap();
}
// filter
caze = caze != null ? caze.clone() : fetchCase();
caze.setOption("MODEL_METHOD", "getOne");
this.filter(caze , rd);
return this.table.fetchLess(caze);
}
public List getAll(Map rd)
throws HongsException
{
return this.getAll(rd, null);
}
public List getAll(Map rd, FetchCase caze)
throws HongsException
{
if (rd == null) {
rd = new HashMap();
}
// filter
caze = caze != null ? caze.clone() : fetchCase();
caze.setOption("MODEL_METHOD", "getAll");
this.filter(caze , rd);
return this.table.fetchMore(caze);
}
/**
* ()
*
* @param rd
* @return
* @throws app.hongs.HongsException
*/
public Map getInfo(Map rd)
throws HongsException
{
return this.getInfo(rd, null);
}
/**
*
*
* @param rd
* @param caze
* @return
* @throws app.hongs.HongsException
*/
public Map getInfo(Map rd, FetchCase caze)
throws HongsException
{
if (rd == null)
{
rd = new HashMap();
}
if (caze == null)
{
caze = fetchCase();
}
if (rd.containsKey(Cnst.ID_KEY))
{
rd.put(table.primaryKey, rd.get(Cnst.ID_KEY));
}
caze.setOption("MODEL_METHOD", "getInfo");
this.filter(caze, rd);
Map info = table.fetchLess(caze);
Map data = new HashMap();
data.put( "info", info );
return data;
}
/**
* ()
*
* page.errno1, page.errno2
*
*
*
* @param rd
* @return
* @throws app.hongs.HongsException
*/
public Map getList(Map rd)
throws HongsException
{
return this.getList(rd, null);
}
/**
*
*
* page.errno1, page.errno2
* 0
* 0
* 0
* 0
*
* @param rd
* @param caze
* @return
* @throws app.hongs.HongsException
*/
public Map getList(Map rd, FetchCase caze)
throws HongsException
{
if (rd == null)
{
rd = new HashMap();
}
if (caze == null)
{
caze = fetchCase();
}
if (rd.containsKey(Cnst.ID_KEY))
{
rd.put(table.primaryKey, rd.get(Cnst.ID_KEY));
}
caze.setOption("MODEL_METHOD", "getList");
this.filter(caze, rd);
int page = 1;
if (rd.containsKey(Cnst.PN_KEY))
{
page = Synt.declare(rd.get(Cnst.PN_KEY), 1);
}
int pags = 0;
if (rd.containsKey(Cnst.GN_KEY))
{
pags = Synt.declare(rd.get(Cnst.GN_KEY), 0);
}
int rows;
if (rd.containsKey(Cnst.RN_KEY))
{
rows = Synt.declare(rd.get(Cnst.RN_KEY), 0);
}
else
{
rows = CoreConfig.getInstance().getProperty("fore.rows.per.page", Cnst.RN_DEF);
}
Map data = new HashMap();
if (rows != 0)
{
caze.from (table.tableName , table.name );
FetchPage fp = new FetchPage(caze, table);
fp.setPage(page != 0 ? page : 1);
fp.setPags(Math.abs(pags));
fp.setRows(Math.abs(rows));
if (page != 0)
{
List list = fp.getList();
data.put( "list", list );
}
if (rows > 0)
{
Map info = fp.getPage();
data.put( "page", info );
}
}
else
{
List list = table.fetchMore(caze);
data.put( "list", list );
}
return data;
}
/**
* FetchCase
* CLEVER_MODE false
*
*
* @return
* @throws app.hongs.HongsException
*/
public FetchCase fetchCase() throws HongsException
{
return table.fetchCase().setOption("CLEVER_MODE", false);
}
/
/**
* ""
*
* <pre>
* getPage,getList
*
* , ;
* : , reqcaze;
* joinLEFT,INNERlinkBLS_TO,HAS_ONE,
* FetchCaseoption: ASSOCS,
* FetchCaseoption: ASSOC_JOINS, ASSOC_TYEPS
*
* :
* 1) rb;
* : rb=a+b+crb=-a+x.b, -;
* 2) ob,
* : ob=a+b+cob=-a+b+c, -;
* 3) wd,
* : wd=x+y+z;
* : wd.a=xwd.a.b=y, ,
* a.b, : a,a.bfindCols;
* 4) ,
* .!gt,!lt,!ge,!le,!ne>,<,≥,≤,≠
* 5) .,
* ..!gt,!lt,!ge,!le,!ne>,<,≥,≤,≠
* : "+" URL; ; 1/2/3;
*
* [2016/9/4] AssocCase, listable field,allow
* </pre>
*
* @param caze
* @param rd
* @throws app.hongs.HongsException
*/
protected void filter(FetchCase caze, Map rd)
throws HongsException
{
/**
*
* BLS_TO , HAS_ONE ()
* LEFT,INNER,RIGHT ()
*/
if (null == caze.getOption("ASSOCS")
&& ("getAll" .equals(caze.getOption("MODEL_METHOD"))
|| "getList".equals(caze.getOption("MODEL_METHOD"))
)) {
if (null == caze.getOption("ASSOC_TYPES"))
{
Set types = new HashSet();
types.add("BLS_TO" );
types.add("HAS_ONE");
caze.setOption("ASSOC_TYPES", types);
}
if (null == caze.getOption("ASSOC_JOINS"))
{
Set types = new HashSet();
types.add( "INNER" );
types.add( "LEFT" );
types.add( "RIGHT" );
types.add( "FULL" );
caze.setOption("ASSOC_JOINS", types);
}
}
caze.setOption("ASSOC_FILLS", true);
if ( rd == null || rd.isEmpty() )
{
return;
}
/**
* table.fetchCase( )
*
*/
caze.from( table.tableName, table.name );
/**
* listable
* AssocCase
*
*
* JOIN
*/
Object rb = null ;
if (listable == null && !caze.hasField())
{
rb = rd.remove(Cnst.RB_KEY);
Set <String> sb = Synt.asTerms(rb);
if ( sb != null && !sb.isEmpty() )
{
field(caze,sb);
}
}
// AssocCase
try {
AssocCase uc = new AssocCase(caze);
uc.allow(this);
uc.parse( rd );
} finally {
if (rb !=null)
{
rd.put(Cnst.RB_KEY, rb);
}
}
}
/
/**
*
* @param caze
* @param rb
*/
protected final void field(FetchCase caze, Set<String> rb) {
if (rb == null) {
rb = new HashSet();
}
Map<String, Object[]> af = new LinkedHashMap();
Map<String, Set<String>> cf = new HashMap();
Set<String> tc = caze.getOption("ASSOCS", new HashSet());
Set<String> ic = new LinkedHashSet();
Set<String> ec = new LinkedHashSet();
Set<String> xc ;
allow(caze, af);
for(Map.Entry<String, Object[]> et : af.entrySet()) {
String fn = et.getKey( );
int p = fn.lastIndexOf(".");
String k ;
if (p > -1) {
k = fn.substring(0 , p)+".*";
} else {
k = "*";
}
Set<String> fs = cf.get( k);
if (fs == null ) {
fs = new LinkedHashSet( );
cf.put(k, fs);
// JOIN ,
Object[] fa = et.getValue();
String ln = (String ) fa[1];
FetchCase fc = (FetchCase) fa[2];
if (ln.contains( "." ) ) {
tc.add( fc.getName() );
}
}
fs.add(fn);
}
for(String fn : rb) {
if (fn.startsWith("-") ) {
fn = fn.substring(1);
xc = ec;
} else {
xc = ic;
}
if (cf.containsKey(fn) ) {
xc.addAll(cf.get(fn));
} else
if (af.containsKey(fn) ) {
xc.add(fn);
if (xc == ec) {
int p = fn.lastIndexOf(".");
if (p != -1) {
fn = fn.substring(0 , p)+".*";
} else {
fn = "*";
}
ic.addAll(cf.get(fn));
}
}
}
if (ic.isEmpty() == true ) {
ic.addAll(af.keySet());
}
if (ec.isEmpty() == false) {
ic.removeAll(ec);
}
for(String kn : ic) {
Object[] fa = af.get (kn);
String fn = (String ) fa[0];
String ln = (String ) fa[1];
FetchCase fc = (FetchCase) fa[2];
if (fn != null && ln != null) {
fc.select(fn + " AS `" + ln + "`");
}
tc.add( fc.getName( ) );
}
caze.setOption("ASSOCS",tc);
}
/**
*
* @param caze
* @param af , : { KEY: [FIELD, ALIAS, FetchCase]... }
*/
protected final void allow(FetchCase caze, Map af) {
String name = Synt.defoult( caze.getName(), table.name, table.tableName);
allow( table, table, table.getAssocs( ), table.getParams( )
, caze, name, null , null, af );
}
/**
*
* @param table
* @param assoc
* @param ac
* @param pc
* @param caze
* @param tn
* @param qn
* @param pn
* @param al , : {: [, , ]}
*/
private void allow(Table table, Table assoc, Map ac, Map pc,
FetchCase caze, String tn, String qn, String pn, Map al) {
String tx, ax, az;
tx = "`"+tn+"`." ;
if (null == qn ) {
qn = "";
ax = "";
} else
if ("".equals(qn)) {
qn = tn;
ax = qn + ".";
} else {
qn = qn + "."+ tn ;
ax = qn + ".";
}
if (null == pn ) {
pn = "";
az = "";
} else
if ("".equals(pn)) {
pn = tn;
az = pn + ".";
} else {
pn = pn + "."+ tn ;
az = pn + ".";
}
if (pc.containsKey( "fields" )) {
al.put(az+"*", new Object[] {null, null, caze});
} else try {
Map fs = assoc.getFields( );
for(Object n : fs.keySet()) {
String f = (String) n;
String k = f;
String l = f;
f = tx +"`"+ f +"`";
l = az + l ; //
k = ax + k ; //
al.put(k , new Object[] {f, l, caze});
}
} catch (HongsException e ) {
throw e.toExpedient( );
}
if (ac == null || ac.isEmpty()) {
return;
}
Iterator it = ac.entrySet().iterator( );
while (it.hasNext()) {
Map.Entry et = (Map.Entry) it.next();
Map tc = (Map) et.getValue( );
String jn = (String) tc.get ("join");
// JOIN pn,
if (!"INNER".equals(jn) && !"LEFT".equals(jn)
&& !"RIGHT".equals(jn) && !"FULL".equals(jn)) {
jn = null;
} else {
jn = pn ;
}
tn = (String) et.getKey( );
ac = (Map) tc.get("assocs");
pc = (Map) tc.get("params");
String rn;
rn = (String) tc.get("tableName");
if (rn == null || "".equals( rn )) {
rn = (String) tc.get ("name");
}
FetchCase caxe;
try {
assoc = table.db.getTable(rn);
caxe = caze . gotJoin (tn);
} catch (HongsException e ) {
throw e.toExpedient( );
}
if (null == assoc) {
throw new HongsExpedient.Common(
"Can not get table '"+ rn +"' in DB '"+ table.db.name +"'"
);
}
allow(table, assoc, ac, pc, caxe, tn, qn, jn, al);
}
}
} |
package ch.idsia.benchmark.mario.engine.sprites;
import ch.idsia.benchmark.mario.engine.Art;
import ch.idsia.benchmark.mario.engine.GlobalOptions;
import ch.idsia.benchmark.mario.engine.LevelScene;
import ch.idsia.benchmark.mario.engine.level.Level;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.benchmark.mario.environments.MarioEnvironment;
import ch.idsia.tools.MarioAIOptions;
public final class Mario extends Sprite
{
public static final String[] MODES = new String[]{"small", "Large", "FIRE"};
// fire = (mode == MODE.MODE_FIRE);
public static final int KEY_LEFT = 0;
public static final int KEY_RIGHT = 1;
public static final int KEY_DOWN = 2;
public static final int KEY_JUMP = 3;
public static final int KEY_SPEED = 4;
public static final int KEY_UP = 5;
public static final int STATUS_RUNNING = 2;
public static final int STATUS_WIN = 1;
public static final int STATUS_DEAD = 0;
private static float marioGravity;
public static boolean large = false;
public static boolean fire = false;
public static int coins = 0;
public static int hiddenBlocksFound = 0;
public static int collisionsWithCreatures = 0;
public static int mushroomsDevoured = 0;
public static int greenMushroomsDevoured = 0;
public static int flowersDevoured = 0;
private static boolean isTrace;
private static boolean isMarioInvulnerable;
private int status = STATUS_RUNNING;
// for racoon when carrying the shell
private int prevWPic;
private int prevxPicO;
private int prevyPicO;
private int prevHPic;
private boolean isRacoon;
private float yaa = 1;
private static float windCoeff = 0f;
private static float iceCoeff = 0f;
private static float jumpPower;
private boolean inLadderZone;
private boolean onLadder;
private boolean onTopOfLadder = false;
public static void resetStatic(MarioAIOptions marioAIOptions)
{
large = marioAIOptions.getMarioMode() > 0;
fire = marioAIOptions.getMarioMode() == 2;
coins = 0;
hiddenBlocksFound = 0;
mushroomsDevoured = 0;
flowersDevoured = 0;
isMarioInvulnerable = marioAIOptions.isMarioInvulnerable();
marioGravity = marioAIOptions.getMarioGravity();
jumpPower = marioAIOptions.getJumpPower();
isTrace = marioAIOptions.isTrace();
iceCoeff = marioAIOptions.getIce();
windCoeff = marioAIOptions.getWind();
}
public int getMode()
{
return ((large) ? 1 : 0) + ((fire) ? 1 : 0);
}
// private static float GROUND_INERTIA = 0.89f;
// private static float AIR_INERTIA = 0.89f;
public boolean[] keys = new boolean[Environment.numberOfKeys];
public boolean[] cheatKeys;
private float runTime;
boolean wasOnGround = false;
boolean onGround = false;
private boolean mayJump = false;
private boolean ducking = false;
private boolean sliding = false;
private int jumpTime = 0;
private float xJumpSpeed;
private float yJumpSpeed;
private boolean ableToShoot = false;
int width = 4;
int height = 24;
private static LevelScene levelScene;
public int facing;
public int xDeathPos, yDeathPos;
public int deathTime = 0;
public int winTime = 0;
private int invulnerableTime = 0;
public Sprite carried = null;
// private static Mario instance;
public Mario(LevelScene levelScene)
{
kind = KIND_MARIO;
// Mario.instance = this;
this.levelScene = levelScene;
x = levelScene.getMarioInitialPos().x;
y = levelScene.getMarioInitialPos().y;
mapX = (int) (x / 16);
mapY = (int) (y / 16);
facing = 1;
setMode(Mario.large, Mario.fire);
yaa = marioGravity * 3;
jT = jumpPower / (marioGravity);
}
private float jT;
private boolean lastLarge;
private boolean lastFire;
private boolean newLarge;
private boolean newFire;
private void blink(boolean on)
{
Mario.large = on ? newLarge : lastLarge;
Mario.fire = on ? newFire : lastFire;
// System.out.println("on = " + on);
if (large)
{
sheet = Art.mario;
if (fire)
sheet = Art.fireMario;
xPicO = 16;
yPicO = 31;
wPic = hPic = 32;
} else
{
sheet = Art.smallMario;
xPicO = 8;
yPicO = 15;
wPic = hPic = 16;
}
savePrevState();
calcPic();
}
void setMode(boolean large, boolean fire)
{
// System.out.println("large = " + large);
if (fire) large = true;
if (!large) fire = false;
lastLarge = Mario.large;
lastFire = Mario.fire;
Mario.large = large;
Mario.fire = fire;
newLarge = Mario.large;
newFire = Mario.fire;
blink(true);
}
public void setRacoon(boolean isRacoon)
{
// if (true)
// return;
this.isRacoon = isRacoon;
// this.setMode(isRacoon, false);
// System.out.println("isRacoon = " + isRacoon);
// System.out.println("Art.racoonmario.length = " + Art.racoonmario.length);
// System.out.println("Art.racoonmario[0].length = " + Art.racoonmario[0].length);
if (isRacoon)
{
savePrevState();
xPicO = 16;
yPicO = 31;
wPic = hPic = 32;
this.sheet = Art.racoonmario;
} else
{
this.sheet = prevSheet;
this.xPicO = this.prevxPicO;
this.yPicO = this.prevyPicO;
wPic = prevWPic;
hPic = prevHPic;
// blink(false);
}
}
private void savePrevState()
{
this.prevSheet = this.sheet;
prevWPic = wPic;
prevHPic = hPic;
this.prevxPicO = xPicO;
this.prevyPicO = yPicO;
}
public void move()
{
if (GlobalOptions.isFly)
{
xa = ya = 0;
ya = keys[KEY_DOWN] ? 10 : ya;
ya = keys[KEY_UP] ? -10 : ya;
xa = keys[KEY_RIGHT] ? 10 : xa;
xa = keys[KEY_LEFT] ? -10 : xa;
}
if (this.inLadderZone)
{
if (keys[KEY_UP] && !onLadder)
{
onLadder = true;
}
if (!keys[KEY_UP] && !keys[KEY_DOWN] && onLadder)
ya = 0;
if (onLadder)
{
if (!onTopOfLadder)
{
ya = keys[KEY_UP] ? -10 : ya;
} else
{
ya = 0;
ya = keys[KEY_DOWN] ? 10 : ya;
if (keys[KEY_DOWN])
onTopOfLadder = false;
}
onGround = true;
}
}
if (mapY > -1 && isTrace)
++levelScene.level.marioTrace[this.mapX][this.mapY];
if (winTime > 0)
{
winTime++;
xa = 0;
ya = 0;
return;
}
if (deathTime > 0)
{
deathTime++;
if (deathTime < 11)
{
xa = 0;
ya = 0;
} else if (deathTime == 11)
{
ya = -15;
} else
{
ya += 2;
}
x += xa;
y += ya;
return;
}
if (invulnerableTime > 0) invulnerableTime
visible = ((invulnerableTime / 2) & 1) == 0;
wasOnGround = onGround;
float sideWaysSpeed = keys[KEY_SPEED] ? 1.2f : 0.6f;
// float sideWaysSpeed = onGround ? 2.5f : 1.2f;
if (onGround)
{
ducking = keys[KEY_DOWN] && large;
}
if (xa > 2)
{
facing = 1;
}
if (xa < -2)
{
facing = -1;
}
// float Wind = 0.2f;
// float windAngle = 180;
// xa += Wind * Math.cos(windAngle * Math.PI / 180);
if (keys[KEY_JUMP] || (jumpTime < 0 && !onGround && !sliding))
{
if (jumpTime < 0)
{
xa = xJumpSpeed;
ya = -jumpTime * yJumpSpeed;
jumpTime++;
} else if (onGround && mayJump)
{
xJumpSpeed = 0;
yJumpSpeed = -1.9f;
jumpTime = (int) jT;
ya = jumpTime * yJumpSpeed;
onGround = false;
sliding = false;
} else if (sliding && mayJump)
{
xJumpSpeed = -facing * 6.0f;
yJumpSpeed = -2.0f;
jumpTime = -6;
xa = xJumpSpeed;
ya = -jumpTime * yJumpSpeed;
onGround = false;
sliding = false;
facing = -facing;
} else if (jumpTime > 0)
{
xa += xJumpSpeed;
ya = jumpTime * yJumpSpeed;
jumpTime
}
} else
{
jumpTime = 0;
}
if (keys[KEY_LEFT] && !ducking)
{
if (facing == 1) sliding = false;
xa -= sideWaysSpeed;
if (jumpTime >= 0) facing = -1;
}
if (keys[KEY_RIGHT] && !ducking)
{
if (facing == -1) sliding = false;
xa += sideWaysSpeed;
if (jumpTime >= 0) facing = 1;
}
if ((!keys[KEY_LEFT] && !keys[KEY_RIGHT]) || ducking || ya < 0 || onGround)
{
sliding = false;
}
if (keys[KEY_SPEED] && ableToShoot && Mario.fire && levelScene.fireballsOnScreen < 2)
{
levelScene.addSprite(new Fireball(levelScene, x + facing * 6, y - 20, facing));
}
// Cheats:
if (GlobalOptions.isPowerRestoration && keys[KEY_SPEED] && (!Mario.large || !Mario.fire))
setMode(true, true);
// if (cheatKeys[KEY_LIFE_UP])
// this.lives++;
// if (keys[KEY_DUMP_CURRENT_WORLD])
// try {
// System.out.println("DUMP:");
//// levelScene.getObservationStrings(System.out);
// //levelScene.level.save(System.out);
// System.out.println("DUMPED:");
// } catch (IOException e) {
// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
ableToShoot = !keys[KEY_SPEED];
mayJump = (onGround || sliding) && !keys[KEY_JUMP];
xFlipPic = facing == -1;
runTime += (Math.abs(xa)) + 5;
if (Math.abs(xa) < 0.5f)
{
runTime = 0;
xa = 0;
}
calcPic();
if (sliding)
{
for (int i = 0; i < 1; i++)
{
levelScene.addSprite(new Sparkle((int) (x + Math.random() * 4 - 2) + facing * 8, (int) (y + Math.random() * 4) - 24, (float) (Math.random() * 2 - 1), (float) Math.random() * 1, 0, 1, 5));
}
ya *= 0.5f;
}
onGround = false;
move(xa, 0);
move(0, ya);
if (y > levelScene.level.height * LevelScene.cellSize + LevelScene.cellSize)
die("Gap");
if (x < 0)
{
x = 0;
xa = 0;
}
/*if (x > levelScene.level.xExit * LevelScene.cellSize *//*- 8*//* &&
x < levelScene.level.xExit * LevelScene.cellSize + 2 * LevelScene.cellSize &&
y < levelScene.level.yExit * LevelScene.cellSize)*/
if (mapX == levelScene.level.xExit && mapY == levelScene.level.yExit)
{
x = (levelScene.level.xExit + 1) * LevelScene.cellSize;
win();
}
if (x > levelScene.level.length * LevelScene.cellSize)
{
x = levelScene.level.length * LevelScene.cellSize;
xa = 0;
}
ya *= 0.85f;
if (onGround)
{
xa *= (GROUND_INERTIA + windScale(windCoeff, facing) + iceScale(iceCoeff));
} else
{
xa *= (AIR_INERTIA + windScale(windCoeff, facing) + iceScale(iceCoeff));
}
if (!onGround)
{
// ya += 3;
ya += yaa;
}
if (carried != null)
{
carried.x = x + facing * 8; //TODO:|L| move to cellSize_2 = cellSize/2;
carried.y = y - 2;
if (!keys[KEY_SPEED])
{
carried.release(this);
carried = null;
setRacoon(false);
// System.out.println("carried = " + carried);
}
// System.out.println("sideWaysSpeed = " + sideWaysSpeed);
}
}
private void calcPic()
{
int runFrame;
if (large || isRacoon)
{
runFrame = ((int) (runTime / 20)) % 4;
if (runFrame == 3) runFrame = 1;
if (carried == null && Math.abs(xa) > 10) runFrame += 3;
if (carried != null) runFrame += 10;
if (!onGround)
{
if (carried != null) runFrame = 12;
else if (Math.abs(xa) > 10) runFrame = 7;
else runFrame = 6;
}
} else
{
runFrame = ((int) (runTime / 20)) % 2;
if (carried == null && Math.abs(xa) > 10) runFrame += 2;
if (carried != null) runFrame += 8;
if (!onGround)
{
if (carried != null) runFrame = 9;
else if (Math.abs(xa) > 10) runFrame = 5;
else runFrame = 4;
}
}
if (onGround && ((facing == -1 && xa > 0) || (facing == 1 && xa < 0)))
{
if (xa > 1 || xa < -1) runFrame = large ? 9 : 7;
if (xa > 3 || xa < -3)
{
for (int i = 0; i < 3; i++)
{
levelScene.addSprite(new Sparkle((int) (x + Math.random() * 8 - 4), (int) (y + Math.random() * 4), (float) (Math.random() * 2 - 1), (float) Math.random() * -1, 0, 1, 5));
}
}
}
if (large)
{
if (ducking) runFrame = 14;
height = ducking ? 12 : 24;
} else
{
height = 12;
}
xPic = runFrame;
}
private boolean move(float xa, float ya)
{
while (xa > 8)
{
if (!move(8, 0)) return false;
xa -= 8;
}
while (xa < -8)
{
if (!move(-8, 0)) return false;
xa += 8;
}
while (ya > 8)
{
if (!move(0, 8)) return false;
ya -= 8;
}
while (ya < -8)
{
if (!move(0, -8)) return false;
ya += 8;
}
boolean collide = false;
if (ya > 0)
{
if (isBlocking(x + xa - width, y + ya, xa, 0)) collide = true;
else if (isBlocking(x + xa + width, y + ya, xa, 0)) collide = true;
else if (isBlocking(x + xa - width, y + ya + 1, xa, ya)) collide = true;
else if (isBlocking(x + xa + width, y + ya + 1, xa, ya)) collide = true;
}
if (ya < 0)
{
if (isBlocking(x + xa, y + ya - height, xa, ya)) collide = true;
else if (collide || isBlocking(x + xa - width, y + ya - height, xa, ya)) collide = true;
else if (collide || isBlocking(x + xa + width, y + ya - height, xa, ya)) collide = true;
}
if (xa > 0)
{
sliding = true;
if (isBlocking(x + xa + width, y + ya - height, xa, ya)) collide = true;
else sliding = false;
if (isBlocking(x + xa + width, y + ya - height / 2, xa, ya)) collide = true;
else sliding = false;
if (isBlocking(x + xa + width, y + ya, xa, ya)) collide = true;
else sliding = false;
}
if (xa < 0)
{
sliding = true;
if (isBlocking(x + xa - width, y + ya - height, xa, ya)) collide = true;
else sliding = false;
if (isBlocking(x + xa - width, y + ya - height / 2, xa, ya)) collide = true;
else sliding = false;
if (isBlocking(x + xa - width, y + ya, xa, ya)) collide = true;
else sliding = false;
}
if (collide)
{
if (xa < 0)
{
x = (int) ((x - width) / 16) * 16 + width;
this.xa = 0;
}
if (xa > 0)
{
x = (int) ((x + width) / 16 + 1) * 16 - width - 1;
this.xa = 0;
}
if (ya < 0)
{
y = (int) ((y - height) / 16) * 16 + height;
jumpTime = 0;
this.ya = 0;
}
if (ya > 0)
{
y = (int) ((y - 1) / 16 + 1) * 16 - 1;
onGround = true;
}
return false;
} else
{
x += xa;
y += ya;
return true;
}
}
private boolean isBlocking(final float _x, final float _y, final float xa, final float ya)
{
int x = (int) (_x / 16);
int y = (int) (_y / 16);
if (x == (int) (this.x / 16) && y == (int) (this.y / 16)) return false;
boolean blocking = levelScene.level.isBlocking(x, y, xa, ya);
byte block = levelScene.level.getBlock(x, y);
if (((Level.TILE_BEHAVIORS[block & 0xff]) & Level.BIT_PICKUPABLE) > 0)
{
Mario.gainCoin();
levelScene.level.setBlock(x, y, (byte) 0);
for (int xx = 0; xx < 2; xx++)
for (int yy = 0; yy < 2; yy++)
levelScene.addSprite(new Sparkle(x * 16 + xx * 8 + (int) (Math.random() * 8), y * 16 + yy * 8 + (int) (Math.random() * 8), 0, 0, 0, 2, 5));
}
if (blocking && ya < 0)
{
levelScene.bump(x, y, large);
}
return blocking;
}
public void stomp(final Enemy enemy)
{
if (deathTime > 0) return;
float targetY = enemy.y - enemy.height / 2;
move(0, targetY - y);
mapY = (int) y / 16;
xJumpSpeed = 0;
yJumpSpeed = -1.9f;
jumpTime = (int) jT + 1;
ya = jumpTime * yJumpSpeed;
onGround = false;
sliding = false;
invulnerableTime = 1;
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.stomp);
}
public void stomp(final Shell shell)
{
if (deathTime > 0) return;
if (keys[KEY_SPEED] && shell.facing == 0)
{
carried = shell;
shell.carried = true;
setRacoon(true);
} else
{
float targetY = shell.y - shell.height / 2;
move(0, targetY - y);
mapY = (int) y / 16;
xJumpSpeed = 0;
yJumpSpeed = -1.9f;
jumpTime = (int) jT + 1;
ya = jumpTime * yJumpSpeed;
onGround = false;
sliding = false;
invulnerableTime = 1;
}
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.stomp);
}
public void getHurt(final int spriteKind)
{
if (deathTime > 0 || isMarioInvulnerable) return;
if (invulnerableTime > 0) return;
++collisionsWithCreatures;
levelScene.appendBonusPoints(-MarioEnvironment.IntermediateRewardsSystemOfValues.kills);
if (large)
{
// levelScene.paused = true;
// powerUpTime = -3 * FractionalPowerUpTime;
if (fire)
{
levelScene.mario.setMode(true, false);
} else
{
levelScene.mario.setMode(false, false);
}
invulnerableTime = 32;
} else
{
die("Collision with a creature [" + Sprite.getNameByKind(spriteKind) + "]");
}
}
public void win()
{
xDeathPos = (int) x;
yDeathPos = (int) y;
winTime = 1;
status = Mario.STATUS_WIN;
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.win);
}
public void die(final String reasonOfDeath)
{
xDeathPos = (int) x;
yDeathPos = (int) y;
deathTime = 25;
status = Mario.STATUS_DEAD;
levelScene.addMemoMessage("Reason of death: " + reasonOfDeath);
levelScene.appendBonusPoints(-MarioEnvironment.IntermediateRewardsSystemOfValues.win / 2);
}
public void devourFlower()
{
if (deathTime > 0) return;
if (!fire)
{
levelScene.mario.setMode(true, true);
} else
{
Mario.gainCoin();
}
++flowersDevoured;
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.flowerFire);
}
public void devourMushroom()
{
if (deathTime > 0) return;
if (!large)
{
levelScene.mario.setMode(true, false);
} else
{
Mario.gainCoin();
}
++mushroomsDevoured;
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.mushroom);
}
public void devourGreenMushroom(final int mushroomMode)
{
++greenMushroomsDevoured;
if (mushroomMode == 0)
getHurt(Sprite.KIND_GREEN_MUSHROOM);
else
die("Collision with a creature [" + Sprite.getNameByKind(Sprite.KIND_GREEN_MUSHROOM) + "]");
}
public void kick(final Shell shell)
{
// if (deathTime > 0 || levelScene.paused) return;
if (keys[KEY_SPEED])
{
carried = shell;
shell.carried = true;
setRacoon(true);
System.out.println("shell = " + shell);
} else
{
invulnerableTime = 1;
}
}
public void stomp(final BulletBill bill)
{
if (deathTime > 0)
return;
float targetY = bill.y - bill.height / 2;
move(0, targetY - y);
mapY = (int) y / 16;
xJumpSpeed = 0;
yJumpSpeed = -1.9f;
jumpTime = (int) jT + 1;
ya = jumpTime * yJumpSpeed;
onGround = false;
sliding = false;
invulnerableTime = 1;
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.stomp);
}
public static void gainCoin()
{
coins++;
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.coins);
// if (coins % 100 == 0)
// get1Up();
}
public static void gainHiddenBlock()
{
++hiddenBlocksFound;
levelScene.appendBonusPoints(MarioEnvironment.IntermediateRewardsSystemOfValues.hiddenBlock);
}
public int getStatus()
{
return status;
}
public boolean isOnGround()
{
return onGround;
}
public boolean mayJump()
{
return mayJump;
}
public boolean isAbleToShoot()
{
return ableToShoot;
}
public void setInLadderZone(final boolean inLadderZone)
{
this.inLadderZone = inLadderZone;
if (!inLadderZone)
{
onLadder = false;
onTopOfLadder = false;
}
}
public boolean isInLadderZone()
{
return this.inLadderZone;
}
public void setOnTopOfLadder(final boolean onTop)
{
this.onTopOfLadder = onTop;
}
public boolean isOnTopOfLadder()
{
return this.onTopOfLadder;
}
}
// public byte getKeyMask()
// int mask = 0;
// for (int i = 0; i < 7; i++)
// if (keys[i]) mask |= (1 << i);
// return (byte) mask;
// public void setKeys(byte mask)
// for (int i = 0; i < 7; i++)
// keys[i] = (mask & (1 << i)) > 0;
// public static void get1Up()
// lives++; |
package ch.unibas.cs.hpwc.patus.codegen;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import cetus.hir.AnnotationStatement;
import cetus.hir.ArrayAccess;
import cetus.hir.ArraySpecifier;
import cetus.hir.AssignmentExpression;
import cetus.hir.AssignmentOperator;
import cetus.hir.BinaryExpression;
import cetus.hir.BinaryOperator;
import cetus.hir.BreakStatement;
import cetus.hir.Case;
import cetus.hir.CommentAnnotation;
import cetus.hir.CompoundStatement;
import cetus.hir.Declaration;
import cetus.hir.DeclarationStatement;
import cetus.hir.Declarator;
import cetus.hir.Expression;
import cetus.hir.ExpressionStatement;
import cetus.hir.FunctionCall;
import cetus.hir.IDExpression;
import cetus.hir.Identifier;
import cetus.hir.Initializer;
import cetus.hir.IntegerLiteral;
import cetus.hir.NameID;
import cetus.hir.NestedDeclarator;
import cetus.hir.PointerSpecifier;
import cetus.hir.Procedure;
import cetus.hir.ProcedureDeclarator;
import cetus.hir.SizeofExpression;
import cetus.hir.Specifier;
import cetus.hir.Statement;
import cetus.hir.SwitchStatement;
import cetus.hir.TranslationUnit;
import cetus.hir.Traversable;
import cetus.hir.UnaryExpression;
import cetus.hir.UnaryOperator;
import cetus.hir.ValueInitializer;
import cetus.hir.VariableDeclaration;
import cetus.hir.VariableDeclarator;
import ch.unibas.cs.hpwc.patus.analysis.HIRAnalyzer;
import ch.unibas.cs.hpwc.patus.analysis.StrategyAnalyzer;
import ch.unibas.cs.hpwc.patus.arch.TypeDeclspec;
import ch.unibas.cs.hpwc.patus.ast.Parameter;
import ch.unibas.cs.hpwc.patus.ast.ParameterAssignment;
import ch.unibas.cs.hpwc.patus.ast.StatementList;
import ch.unibas.cs.hpwc.patus.ast.StatementListBundle;
import ch.unibas.cs.hpwc.patus.ast.StencilSpecifier;
import ch.unibas.cs.hpwc.patus.ast.SubdomainIdentifier;
import ch.unibas.cs.hpwc.patus.codegen.GlobalGeneratedIdentifiers.Variable;
import ch.unibas.cs.hpwc.patus.codegen.options.CodeGeneratorRuntimeOptions;
import ch.unibas.cs.hpwc.patus.geometry.Size;
import ch.unibas.cs.hpwc.patus.grammar.strategy.IAutotunerParam;
import ch.unibas.cs.hpwc.patus.representation.Stencil;
import ch.unibas.cs.hpwc.patus.representation.StencilCalculation;
import ch.unibas.cs.hpwc.patus.representation.StencilNode;
import ch.unibas.cs.hpwc.patus.util.ASTUtil;
import ch.unibas.cs.hpwc.patus.util.CodeGeneratorUtil;
import ch.unibas.cs.hpwc.patus.util.ExpressionUtil;
import ch.unibas.cs.hpwc.patus.util.StringUtil;
/**
*
* @author Matthias-M. Christen
*/
public class CodeGenerator
{
// Constants
private final static boolean SINGLE_ASSIGNMENT = false;
private final static Logger LOGGER = Logger.getLogger (CodeGenerator.class);
private final static DateFormat DATE_FORMAT = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
// Inner Types
private abstract class GeneratedProcedure
{
private String m_strBaseFunctionName;
private List<Declaration> m_listParams;
private StatementListBundle m_slbBody;
private TranslationUnit m_unit;
private boolean m_bMakeFortranCompatible;
public GeneratedProcedure (String strBaseFunctionName, List<Declaration> listParams, StatementListBundle slbBody,
TranslationUnit unit, boolean bMakeFortranCompatible)
{
m_strBaseFunctionName = strBaseFunctionName;
m_listParams = listParams;
m_slbBody = slbBody;
m_unit = unit;
m_bMakeFortranCompatible = bMakeFortranCompatible;
}
public final String getBaseFunctionName ()
{
return m_strBaseFunctionName;
}
public final String getFunctionName (boolean bIsParametrizedVersion)
{
String strFnxName = bIsParametrizedVersion ? StringUtil.concat (m_strBaseFunctionName, Globals.PARAMETRIZED_FUNCTION_SUFFIX) : m_strBaseFunctionName;
if (m_bMakeFortranCompatible)
strFnxName = Globals.createFortranName (strFnxName);
return strFnxName;
}
public final List<Declaration> getParams ()
{
return m_listParams;
}
public final StatementListBundle getBodyCodes ()
{
return m_slbBody;
}
public final TranslationUnit getTranslationUnit ()
{
return m_unit;
}
/**
*
* @param listAdditionalDeclSpecs List of additional declspecs for the function. Can be <code>null</code> if no
* additional specifiers are required.
* @param listParams
* @param cmpstmtBody
* @param unit
*/
public void addProcedureDeclaration (List<Specifier> listAdditionalDeclSpecs, CompoundStatement cmpstmtBody,
boolean bIsParametrizedVersion, boolean bIncludeStencilCommentAnnotation)
{
addProcedureDeclaration (listAdditionalDeclSpecs, m_listParams, cmpstmtBody, bIsParametrizedVersion, bIncludeStencilCommentAnnotation);
}
public void addProcedureDeclaration (List<Specifier> listAdditionalDeclSpecs, List<Declaration> listParams, CompoundStatement cmpstmtBody,
boolean bIsParametrizedVersion, boolean bIncludeStencilCommentAnnotation)
{
// set the name of the stencil/initialization function, which is called in the benchmarking harness
// i.e., always set the parametrized version
setGlobalGeneratedIdentifiersFunctionName (new NameID (getFunctionName (true)));
addProcedureDeclaration (listAdditionalDeclSpecs, getFunctionName (bIsParametrizedVersion), listParams, cmpstmtBody, bIncludeStencilCommentAnnotation);
}
public void addProcedureDeclaration (List<Specifier> listAdditionalDeclSpecs, String strFunctionName,
CompoundStatement cmpstmtBody, boolean bIncludeStencilCommentAnnotation)
{
addProcedureDeclaration (listAdditionalDeclSpecs, strFunctionName, m_listParams, cmpstmtBody, bIncludeStencilCommentAnnotation);
}
@SuppressWarnings("unchecked")
public void addProcedureDeclaration (List<Specifier> listAdditionalDeclSpecs, String strFunctionName,
List<Declaration> listParams, CompoundStatement cmpstmtBody, boolean bIncludeStencilCommentAnnotation)
{
List<Specifier> listSpecs = new ArrayList<> (listAdditionalDeclSpecs == null ? 1 : listAdditionalDeclSpecs.size () + 1);
if (listAdditionalDeclSpecs != null)
listSpecs.addAll (listAdditionalDeclSpecs);
listSpecs.add (Specifier.VOID);
Procedure procedure = new Procedure (
listSpecs,
new ProcedureDeclarator (new NameID (strFunctionName), (List<Declaration>) CodeGeneratorUtil.clone (listParams)),
cmpstmtBody
);
if (bIncludeStencilCommentAnnotation)
procedure.annotate (new CommentAnnotation (m_data.getStencilCalculation ().getStencilExpressions ()));
m_unit.addDeclaration (procedure);
}
protected abstract void setGlobalGeneratedIdentifiersFunctionName (NameID nidFnxName);
}
// Member Variables
/**
* The data shared by the code generators
*/
private CodeGeneratorSharedObjects m_data;
/**
* The code generator that generates the code one thread executes from the strategy code
*/
private ThreadCodeGenerator m_cgThreadCode;
/**
* Map of identifiers that are arguments to the stencil kernel.
* The identifiers are created when the function signature is created.
*/
private Map<String, Identifier> m_mapStencilOperationInputArgumentIdentifiers;
/**
* Map of identifiers that are arguments to the stencil kernel.
* The identifiers are created when the function signature is created.
*/
private Map<String, Identifier> m_mapStencilOperationOutputArgumentIdentifiers;
private int m_nCodeVariantsCount;
// Implementation
public CodeGenerator (CodeGeneratorSharedObjects data)
{
m_data = data;
m_cgThreadCode = new ThreadCodeGenerator (m_data);
m_mapStencilOperationInputArgumentIdentifiers = new HashMap<> ();
m_mapStencilOperationOutputArgumentIdentifiers = new HashMap<> ();
m_nCodeVariantsCount = 0;
}
/**
* Generates the code.
* @param unit The translation unit in which to place the kernels
* @param fileOutputDirectory The directory into which the generated code is written
* @param bIncludeAutotuneParameters Flag specifying whether to include the autotuning parameters
* in the function signatures
*/
public void generate (List<KernelSourceFile> listOutputs, File fileOutputDirectory, boolean bIncludeAutotuneParameters)
{
createFunctionParameterList (true, bIncludeAutotuneParameters);
// create the stencil calculation code (the code that one thread executes)
StatementListBundle slbThreadBody = createComputeCode ();
// create the initialization code
StatementListBundle slbInitializationBody = createInitializationCode (listOutputs);
// add global declarations
for (KernelSourceFile out : listOutputs)
addAdditionalGlobalDeclarations (out, slbThreadBody.getDefault ());
// add internal autotune parameters to the parameter list
createFunctionInternalAutotuneParameterList (slbThreadBody);
// do post-generation optimizations
optimizeCode (slbThreadBody);
// package the code into functions, add them to the translation unit, and write the code files
for (KernelSourceFile out : listOutputs)
{
packageKernelSourceFile (out, slbThreadBody, slbInitializationBody, bIncludeAutotuneParameters);
out.writeCode (this, m_data, fileOutputDirectory);
}
}
private StatementListBundle createComputeCode ()
{
m_data.getData ().setCreatingInitialization (false);
CodeGeneratorRuntimeOptions optionsStencil = new CodeGeneratorRuntimeOptions ();
optionsStencil.setOption (CodeGeneratorRuntimeOptions.OPTION_STENCILCALCULATION, CodeGeneratorRuntimeOptions.VALUE_STENCILCALCULATION_STENCIL);
optionsStencil.setOption (CodeGeneratorRuntimeOptions.OPTION_DOBOUNDARYCHECKS, m_data.getStencilCalculation ().getBoundaries () != null);
CompoundStatement cmpstmtStrategyKernelThreadBody = m_cgThreadCode.generate (m_data.getStrategy ().getBody (), optionsStencil);
m_data.getData ().capture ();
StatementListBundle slbThreadBody = new SingleThreadCodeGenerator (m_data).generate (cmpstmtStrategyKernelThreadBody, optionsStencil);
addAdditionalDeclarationsAndAssignments (slbThreadBody, optionsStencil);
return slbThreadBody;
}
private StatementListBundle createInitializationCode (List<KernelSourceFile> listOutputs)
{
StatementListBundle slbInitializationBody = null;
boolean bCreateInitialization = false;
for (KernelSourceFile out : listOutputs)
if (out.getCreateInitialization ())
{
bCreateInitialization = true;
break;
}
if (bCreateInitialization)
{
m_data.getData ().setCreatingInitialization (true);
m_data.getCodeGenerators ().reset ();
m_data.getData ().reset ();
CodeGeneratorRuntimeOptions optionsInitialize = new CodeGeneratorRuntimeOptions ();
optionsInitialize.setOption (CodeGeneratorRuntimeOptions.OPTION_STENCILCALCULATION, CodeGeneratorRuntimeOptions.VALUE_STENCILCALCULATION_INITIALIZE);
if (m_data.getArchitectureDescription ().useSIMD ())
optionsInitialize.setOption (CodeGeneratorRuntimeOptions.OPTION_NOVECTORIZE, !m_data.getOptions ().useNativeSIMDDatatypes ());
CompoundStatement cmpstmtStrategyInitThreadBody = m_cgThreadCode.generate (m_data.getStrategy ().getBody (), optionsInitialize);
slbInitializationBody = new SingleThreadCodeGenerator (m_data).generate (cmpstmtStrategyInitThreadBody, optionsInitialize);
addAdditionalDeclarationsAndAssignments (slbInitializationBody, optionsInitialize);
}
return slbInitializationBody;
}
private void packageKernelSourceFile (KernelSourceFile out, StatementListBundle slbThreadBody, StatementListBundle slbInitializationBody, boolean bIncludeAutotuneParameters)
{
// stencil function(s)
boolean bMakeFortranCompatible = out.getCompatibility () == CodeGenerationOptions.ECompatibility.FORTRAN;
packageCode (new GeneratedProcedure (
m_data.getStencilCalculation ().getName (),
m_data.getData ().getGlobalGeneratedIdentifiers ().getFunctionParameterList (true, bIncludeAutotuneParameters, false, false),
slbThreadBody,
out.getTranslationUnit (),
bMakeFortranCompatible)
{
@Override
protected void setGlobalGeneratedIdentifiersFunctionName (NameID nidFnxName)
{
m_data.getData ().getGlobalGeneratedIdentifiers ().setStencilFunctionName (nidFnxName);
}
}, true, true, bIncludeAutotuneParameters, bIncludeAutotuneParameters, out.getCompatibility ());
// initialization function
if (slbInitializationBody != null && out.getCreateInitialization ())
{
packageCode (new GeneratedProcedure (
Globals.getInitializeFunctionName (m_data.getStencilCalculation ().getName ()),
m_data.getData ().getGlobalGeneratedIdentifiers ().getFunctionParameterList (false, bIncludeAutotuneParameters, false, false),
slbInitializationBody,
out.getTranslationUnit (),
bMakeFortranCompatible)
{
@Override
protected void setGlobalGeneratedIdentifiersFunctionName (NameID nidFnxName)
{
m_data.getData ().getGlobalGeneratedIdentifiers ().setInitializeFunctionName (nidFnxName);
}
}, false, false, bIncludeAutotuneParameters, false, out.getCompatibility ());
}
}
/**
* Adds additional global declarations.
* @param unit The translation unit in which the declarations are placed
*/
private void addAdditionalGlobalDeclarations (KernelSourceFile out, Traversable trvContext)
{
TranslationUnit unit = out.getTranslationUnit ();
for (Declaration decl : m_data.getData ().getGlobalDeclarationsToAdd ())
{
VariableDeclarator declarator = (VariableDeclarator) decl.getChildren ().get (0);
if (HIRAnalyzer.isReferenced (new Identifier (declarator), trvContext))
unit.addDeclaration (decl);
}
}
/**
* Create initializers for the base memory objects if required.
* The base memory objects are initialized with the input arguments to the stencil kernel.
*/
private void setBaseMemoryObjectInitializers ()
{
MemoryObjectManager mom = m_data.getData ().getMemoryObjectManager ();
StrategyAnalyzer analyzer = m_data.getCodeGenerators ().getStrategyAnalyzer ();
// create the initializers only if we can't use pointer swapping
if (mom.canUsePointerSwapping (analyzer.getOuterMostSubdomainIterator ()))
return;
SubdomainIdentifier sdidBase = analyzer.getRootSubdomain ();
boolean bAreBaseMemoryObjectsReferenced = mom.areMemoryObjectsReferenced (sdidBase);
if (bAreBaseMemoryObjectsReferenced)
{
// create an initializer per memory object per vector index
StencilNodeSet setAll = m_data.getStencilCalculation ().getInputBaseNodeSet ().union (m_data.getStencilCalculation ().getOutputBaseNodeSet ());
for (int nVecIdx : setAll.getVectorIndices ())
{
// get only the memory objects (= classes of stencil nodes) that have the vector index nVecIdx
StencilNodeSet setVecIdx = setAll.restrict (null, nVecIdx);
List<Expression> listPointers = new ArrayList<> (setVecIdx.size ());
StencilNode nodeRepresentant = null;
// add the stencil nodes in the per-vector index set to the list of pointers
// (the stencil nodes (= memory objects) are ordered by time index implicitly
for (StencilNode node : setVecIdx)
{
listPointers.add (m_mapStencilOperationInputArgumentIdentifiers.get (MemoryObjectManager.createMemoryObjectName (null, node, null, true)).clone ());
nodeRepresentant = node;
}
// create and set the initializer
if (nodeRepresentant != null)
{
MemoryObject mo = m_data.getData ().getMemoryObjectManager ().getMemoryObject (sdidBase, nodeRepresentant, true);
((VariableDeclarator) mo.getIdentifier ().getSymbol ()).setInitializer (new Initializer (listPointers));
}
}
}
}
/**
* Adds additional declarations and assignments to the internal pointers from the kernel references to the
* function body.
* @param cmpstmt The kernel body
*/
private void addAdditionalDeclarationsAndAssignments (StatementListBundle slbCode, CodeGeneratorRuntimeOptions options)
{
// if necessary, add the pointer initializers
setBaseMemoryObjectInitializers ();
// add the additional declarations to the code
List<Statement> listDeclarationsAndAssignments = new ArrayList<> (m_data.getData ().getNumberOfDeclarationsToAdd ());
for (Declaration decl : m_data.getData ().getDeclarationsToAdd ())
listDeclarationsAndAssignments.add (new DeclarationStatement (decl));
/*
// if necessary, allocate space for local memory objects
for (Memoryobj m_data.getMemoryObjectManager ().g)
{
}*/
// add the initialization code
boolean bIsFirst = true;
for (Statement stmt : m_data.getData ().getInitializationStatements (
new ParameterAssignment (
CodeGeneratorData.PARAM_COMPUTATION_TYPE,
options.getIntValue (CodeGeneratorRuntimeOptions.OPTION_STENCILCALCULATION, CodeGeneratorRuntimeOptions.VALUE_STENCILCALCULATION_STENCIL)
)))
{
if (bIsFirst)
listDeclarationsAndAssignments.add (new AnnotationStatement (new CommentAnnotation ("Initializations")));
bIsFirst = false;
listDeclarationsAndAssignments.add (stmt);
}
listDeclarationsAndAssignments.add (new AnnotationStatement (new CommentAnnotation ("Implementation")));
// add the statements at the top
slbCode.addStatementsAtTop (listDeclarationsAndAssignments);
// add statements at bottom: assign the output grid to the kernel's output argument
/*
if (bAreBaseMemoryObjectsReferenced)
{
for (String strGrid : m_data.getStencilCalculation ().getOutputGrids ().keySet ())
{
StencilCalculation.GridType grid = m_data.getStencilCalculation ().getGrid (strGrid);
cmpstmt.addStatement (new ExpressionStatement (new AssignmentExpression (
new UnaryExpression (UnaryOperator.DEREFERENCE, null)
CodeGeneratorUtil.specifiers (grid.getSpecifier (), PointerSpecifier.UNQUALIFIED, PointerSpecifier.UNQUALIFIED),
new NameID (strGrid))));
}
cmpstmt.addStatement (new ExpressionStatement (new AssignmentExpression (null, null, null)));
}
*/
}
/**
*
* @param mapCodes
* @param unit
*/
private void packageCode (GeneratedProcedure proc,
boolean bIncludeStencilCommentAnnotation, boolean bIncludeOutputGrids, boolean bIncludeAutotuneParameters, boolean bIncludeInternalAutotuneParameters,
CodeGenerationOptions.ECompatibility compatibility)
{
int nCodesCount = proc.getBodyCodes ().size ();
boolean bIsFortranCompatible = compatibility == CodeGenerationOptions.ECompatibility.FORTRAN;
if (nCodesCount == 0)
{
// no codes: add an empty function
proc.addProcedureDeclaration (null, new CompoundStatement (), false, true);
}
else
{
// there is at least one code
List<String> listStencilFunctions = new ArrayList<> (nCodesCount);
for (ParameterAssignment pa : proc.getBodyCodes ())
{
// build a name for the function
StringBuilder sbFunctionName = new StringBuilder (proc.getBaseFunctionName ());
for (Parameter param : pa)
{
// skip the default parameter
if (param.equals (StatementListBundle.DEFAULT_PARAM))
continue;
sbFunctionName.append ("__");
sbFunctionName.append (param.getName ());
sbFunctionName.append ("_");
sbFunctionName.append (pa.getParameterValue (param));
}
String strDecoratedFunctionName = sbFunctionName.toString ();
// create the body compound statement
Statement stmtBody = proc.getBodyCodes ().getStatementList (pa).getCompoundStatement ();
CompoundStatement cmpstmtBody = null;
if (stmtBody instanceof CompoundStatement)
cmpstmtBody = (CompoundStatement) stmtBody;
else
{
cmpstmtBody = new CompoundStatement ();
cmpstmtBody.addStatement (stmtBody);
}
// add the code to the translation unit
if (nCodesCount == 1 && !bIsFortranCompatible)
proc.addProcedureDeclaration (m_data.getArchitectureDescription ().getDeclspecs (TypeDeclspec.KERNEL), cmpstmtBody, true, bIncludeStencilCommentAnnotation);
else
proc.addProcedureDeclaration (m_data.getArchitectureDescription ().getDeclspecs (TypeDeclspec.LOCALFUNCTION), strDecoratedFunctionName, cmpstmtBody, false);
listStencilFunctions.add (strDecoratedFunctionName);
}
// add a function call to the kernel (if there is more than one)
if (nCodesCount > 1 || bIsFortranCompatible)
createParametrizedProxyFunction (proc, listStencilFunctions, bIncludeStencilCommentAnnotation, bIncludeAutotuneParameters, bIsFortranCompatible);
// add a function calling the kernel function with the parameters from the tuned_params.h
if (m_data.getData ().getGlobalGeneratedIdentifiers ().getAutotuneVariables ().size () > 0)
{
createUnparametrizedProxyFunction (
proc, listStencilFunctions,
bIncludeStencilCommentAnnotation, bIncludeOutputGrids,
bIncludeAutotuneParameters, bIncludeInternalAutotuneParameters,
bIsFortranCompatible
);
}
}
}
@SuppressWarnings("unchecked")
protected void createParametrizedProxyFunction (GeneratedProcedure proc, List<String> listStencilFunctions,
boolean bIncludeStencilCommentAnnotation, boolean bIncludeAutotuneParameters, boolean bIsFortranCompatible)
{
// add a function that selects the right unrolling configuration based on a command line parameter
NameID nidCodeVariants = new NameID (StringUtil.concat ("g_rgCodeVariants", m_nCodeVariantsCount++));
if (m_data.getArchitectureDescription ().useFunctionPointers ())
proc.getTranslationUnit ().addDeclaration (CodeGenerator.createCodeVariantFnxPtrArray (nidCodeVariants, listStencilFunctions, proc.getParams ()));
// build the function parameter list: same as for the stencil functions, but with additional parameters for the code selection
List<Identifier> listSelectors = new ArrayList<> ();
List<Integer> listSelectorsCount = new ArrayList<> ();
for (Parameter param : proc.getBodyCodes ().getParameters ())
{
VariableDeclarator decl = new VariableDeclarator (new NameID (param.getName ()));
listSelectors.add (new Identifier (decl));
listSelectorsCount.add (param.getValues ().length);
}
int[] rgSelectorsCount = new int[listSelectorsCount.size ()];
int i = 0;
for (int nValue : listSelectorsCount)
rgSelectorsCount[i++] = nValue;
// add the function call
proc.addProcedureDeclaration (
m_data.getArchitectureDescription ().getDeclspecs (TypeDeclspec.KERNEL),
m_data.getData ().getGlobalGeneratedIdentifiers ().getFunctionParameterList (
true, bIncludeAutotuneParameters, bIncludeAutotuneParameters, bIsFortranCompatible),
getFunctionSelector (
nidCodeVariants,
listStencilFunctions,
(List<Declaration>) CodeGeneratorUtil.clone (proc.getParams ()),
listSelectors,
rgSelectorsCount,
bIsFortranCompatible),
true,
bIncludeStencilCommentAnnotation
);
}
protected void createUnparametrizedProxyFunction (GeneratedProcedure proc, List<String> listStencilFunctions,
boolean bIncludeStencilCommentAnnotation, boolean bIncludeOutputGrids,
boolean bIncludeAutotuneParameters, boolean bIncludeInternalAutotuneParameters,
boolean bIsFortranCompatible)
{
GlobalGeneratedIdentifiers glid = m_data.getData ().getGlobalGeneratedIdentifiers ();
// the function body containing the call to the parametrized kernel function
CompoundStatement cmpstmtFnxCall = new CompoundStatement ();
// create temporary variables for auto-tuning parameters so that we can pass pointers
if (bIsFortranCompatible)
{
for (Variable var : glid.getAutotuneVariables ())
{
VariableDeclarator decl = new VariableDeclarator (new NameID (var.getName ()));
decl.setInitializer (new ValueInitializer (new NameID (glid.getDefinedVariableName (var))));
cmpstmtFnxCall.addDeclaration (new VariableDeclaration (Globals.SPECIFIER_INDEX, decl));
}
}
List<Declaration> listArgs = m_data.getData ().getGlobalGeneratedIdentifiers ().getFunctionParameterList (
bIncludeOutputGrids, bIncludeAutotuneParameters, bIncludeInternalAutotuneParameters, bIsFortranCompatible);
List<Expression> listFnxCallArgs = new ArrayList<> ();
for (Declaration decl : listArgs)
{
IDExpression id = ((VariableDeclarator) ((VariableDeclaration) decl).getDeclarator (0)).getID ();
Variable var = glid.getVariableByName (id.getName ());
if (var != null)
{
if (!bIsFortranCompatible && var.isAutotuningParameter ())
listFnxCallArgs.add (new NameID (glid.getDefinedVariableName (var)));
else
listFnxCallArgs.add (id.clone ());
}
else
listFnxCallArgs.add (id.clone ());
}
// create the function call
cmpstmtFnxCall.addStatement (new ExpressionStatement (new FunctionCall (
new NameID (proc.getFunctionName (true)),
listFnxCallArgs
)));
// create the function
List<Specifier> listSpecs = new ArrayList<> ();
listSpecs.addAll (m_data.getArchitectureDescription ().getDeclspecs (TypeDeclspec.KERNEL));
//listSpecs.add (Specifier.INLINE);
proc.addProcedureDeclaration (
listSpecs,
m_data.getData ().getGlobalGeneratedIdentifiers ().getFunctionParameterList (bIncludeOutputGrids, false, false, bIsFortranCompatible),
cmpstmtFnxCall,
false,
bIncludeStencilCommentAnnotation
);
}
/**
* Creates a variable declaration for the argument named <code>strArgName</code>.
* @param strArgName
* @return
*/
protected VariableDeclaration createArgumentDeclaration (String strArgName, boolean bCreateOutputArgument)
{
StencilCalculation.ArgumentType type = m_data.getStencilCalculation ().getArgumentType (strArgName);
// create the variable name and the variable declarator
String strName = StringUtil.concat (strArgName, bCreateOutputArgument ? MemoryObjectManager.SUFFIX_OUTPUTGRID : null);
VariableDeclarator decl = new VariableDeclarator (new NameID (strName));
// add to the identifier map
(bCreateOutputArgument ? m_mapStencilOperationOutputArgumentIdentifiers : m_mapStencilOperationInputArgumentIdentifiers).
put (strArgName, new Identifier (decl));
// create and return the actual variable declaration
List<Specifier> listSpecifiers = type.getSpecifiers ();
int i = 0;
Specifier specType = null;
if (!type.getType ().equals (StencilCalculation.EArgumentType.PARAMETER))
{
for (Iterator<Specifier> it = listSpecifiers.iterator (); it.hasNext (); i++)
{
Specifier spec = it.next ();
if (Globals.isBaseDatatype (spec))
{
it.remove ();
specType = spec;
break;
}
}
}
if (specType != null)
{
if (m_data.getOptions ().useNativeSIMDDatatypes () && m_data.getArchitectureDescription ().useSIMD ())
listSpecifiers.addAll (i, m_data.getArchitectureDescription ().getType (specType));
else
listSpecifiers.add (i, specType);
}
if (bCreateOutputArgument)
listSpecifiers.add (PointerSpecifier.UNQUALIFIED);
return new VariableDeclaration (listSpecifiers, decl);
}
/**
* Creates a list of variable declarations containing the variables for
* <ul>
* <li>stencil grids</li>
* <li>stencil parameters</li>
* <li>strategy autotuner parameters</li>
* </ul>
* @return A list of variable declarations for the stencil kernel function
*/
protected void createFunctionParameterList (boolean bIncludeOutputGrids, boolean bIncludeAutotuneParameters)
{
for (Declaration declParam : m_data.getStrategy ().getParameters ())
{
if (declParam instanceof VariableDeclaration)
{
VariableDeclaration decl = (VariableDeclaration) declParam;
List<Specifier> listSpecifiers = decl.getSpecifiers ();
for (int i = 0; i < decl.getNumDeclarators (); i++)
{
VariableDeclarator declarator = (VariableDeclarator) decl.getDeclarator (i);
String strParamName = declarator.getSymbolName ();
if (listSpecifiers.size () == 1 && StencilSpecifier.STENCIL_GRID.equals (listSpecifiers.get (0)))
{
// the strategy argument is a grid identifier
// add output arguments
for (String strArgOutput : m_data.getStencilCalculation ().getArguments (StencilCalculation.EArgumentType.OUTPUT_GRID))
{
// create the variable declaration
VariableDeclaration declArg = createArgumentDeclaration (strArgOutput, true);
// set the variable as stencil function argument in the global generated identifiers
m_data.getData ().getGlobalGeneratedIdentifiers ().addStencilFunctionArguments (new GlobalGeneratedIdentifiers.Variable (
GlobalGeneratedIdentifiers.EVariableType.OUTPUT_GRID, declArg, strArgOutput, strArgOutput, null, m_data));
}
// add arguments (grids and parameters)
for (String strArgument : m_data.getStencilCalculation ().getArguments ())
{
VariableDeclaration declArg = createArgumentDeclaration (strArgument, false);
StencilCalculation.ArgumentType type = m_data.getStencilCalculation ().getArgumentType (strArgument);
StencilCalculation.EArgumentType typeArg = type.getType ();
GlobalGeneratedIdentifiers.EVariableType typeVar = StencilCalculation.EArgumentType.PARAMETER.equals (typeArg) ?
GlobalGeneratedIdentifiers.EVariableType.KERNEL_PARAMETER : GlobalGeneratedIdentifiers.EVariableType.INPUT_GRID;
StencilNode node = m_data.getStencilCalculation ().getReferenceStencilNode (strArgument);
String strOrigName = node == null ? strArgument : node.getName ();
m_data.getData ().getGlobalGeneratedIdentifiers ().addStencilFunctionArguments (
new GlobalGeneratedIdentifiers.Variable (
typeVar, declArg, strArgument, strOrigName,
type instanceof StencilCalculation.ParamType ? ((StencilCalculation.ParamType) type).getDefaultValue () : null,
m_data)
);
}
// add size parameters (all variables used to specify domain size and the grid size arguments to the operation)
for (NameID nidSizeParam : m_data.getStencilCalculation ().getSizeParameters ())
{
VariableDeclaration declSize = (VariableDeclaration) CodeGeneratorUtil.createVariableDeclaration (Globals.SPECIFIER_SIZE, nidSizeParam.clone (), null);
m_data.getData ().getGlobalGeneratedIdentifiers ().addStencilFunctionArguments (
new GlobalGeneratedIdentifiers.Variable (
GlobalGeneratedIdentifiers.EVariableType.SIZE_PARAMETER,
declSize,
nidSizeParam.getName (),
null,
new SizeofExpression (CodeGeneratorUtil.specifiers (Globals.SPECIFIER_SIZE)),
(Size) null
)
);
}
}
else if (listSpecifiers.size () == 1 && StencilSpecifier.STRATEGY_AUTO.equals (listSpecifiers.get (0)))
{
// the strategy argument is an autotuner parameter
// add autotuner parameters
VariableDeclaration declAutoParam = (VariableDeclaration) CodeGeneratorUtil.createVariableDeclaration (Globals.SPECIFIER_SIZE, strParamName, null);
m_data.getData ().getGlobalGeneratedIdentifiers ().addStencilFunctionArguments (
new GlobalGeneratedIdentifiers.Variable (
GlobalGeneratedIdentifiers.EVariableType.AUTOTUNE_PARAMETER,
declAutoParam,
strParamName,
null,
new SizeofExpression (CodeGeneratorUtil.specifiers (Specifier.INT)),
(Size) null
)
);
}
}
}
}
}
protected void createFunctionInternalAutotuneParameterList (StatementListBundle slbCode)
{
if (slbCode.size () <= 1)
return;
// build the function parameter list: same as for the stencil functions, but with additional parameters for the code selection
for (Parameter param : slbCode.getParameters ())
{
if (param.getValues ().length == 0)
continue;
VariableDeclarator decl = new VariableDeclarator (new NameID (param.getName ()));
m_data.getData ().getGlobalGeneratedIdentifiers ().addStencilFunctionArguments (
new GlobalGeneratedIdentifiers.Variable (
GlobalGeneratedIdentifiers.EVariableType.INTERNAL_AUTOTUNE_PARAMETER,
new VariableDeclaration (Specifier.INT, decl),
param.getName (),
new SizeofExpression (CodeGeneratorUtil.specifiers (Specifier.INT)),
new IAutotunerParam.AutotunerRangeParam (Globals.ZERO.clone (), new IntegerLiteral (param.getValues ().length - 1))
)
);
}
}
/**
* Creates a variable declaration for an array of function pointers with parameters defined in
* <code>listParams</code> an initializes it with the functions named as the entries of the list
* <code>listFunctionNames</code>.
* @param listFunctionNames The list of function names, one for each of the function variants
* @param listParams The list of parameters for the stencil function
* @return
*/
protected static VariableDeclaration createCodeVariantFnxPtrArray (NameID nidCodeVariants, List<String> listFunctionNames, List<Declaration> listParams)
{
// we want something like this:
// void (*rgFunctions[]) (float, char) = { a, b, c };
// where a, b, c are functions with the defined signatures
// create the list of types for the declaration of the function pointer array
List<VariableDeclaration> listTypeList = new ArrayList<> (listParams.size ());
for (Declaration declParam : listParams)
{
List<Specifier> listSpecifiers = ((VariableDeclaration) declParam).getSpecifiers ();
if (listSpecifiers.size () > 0)
listTypeList.add (new VariableDeclaration (listSpecifiers));
else
{
Declarator decl = ((VariableDeclaration) declParam).getDeclarator (0);
listTypeList.add (new VariableDeclaration (decl.getSpecifiers ()));
}
}
// declare the array of function pointers
NestedDeclarator declFunctionTable = new NestedDeclarator (
new VariableDeclarator (
CodeGeneratorUtil.specifiers (PointerSpecifier.UNQUALIFIED),
nidCodeVariants,
CodeGeneratorUtil.specifiers (new ArraySpecifier ())),
listTypeList);
// build a list of function identifiers
List<NameID> listFunctionIdentifiers = new ArrayList<> (listFunctionNames.size ());
for (String strFunctionName : listFunctionNames)
listFunctionIdentifiers.add (new NameID (strFunctionName));
// set the initializer
declFunctionTable.setInitializer (new Initializer (listFunctionIdentifiers));
// add the declaration to the function body
return new VariableDeclaration (CodeGeneratorUtil.specifiers (Specifier.STATIC, Specifier.VOID), declFunctionTable);
}
/**
* Returns the function body of a function selecting the function for a specific unrolling determined by
* a command line parameter.
* @param listFunctionNames The list of function names, one for each of the function variants
* @param listParams The list of parameters for the stencil function
* @return
*/
@SuppressWarnings("unchecked")
protected CompoundStatement getFunctionSelector (
NameID nidFunctionSelector,
List<String> listFunctionNames, List<Declaration> listParams, List<Identifier> listCodeSelectors,
int[] rgCodeSelectorsCount, boolean bMakeCompatibleWithFortran)
{
CompoundStatement cmpstmtBody = new CompoundStatement ();
// create a list with the function parameters as identifiers
List<Expression> listFnxParams = new ArrayList<> (listParams.size ());
for (Declaration declaration : listParams)
{
VariableDeclaration vardecl = (VariableDeclaration) declaration;
if (vardecl.getNumDeclarators () > 1)
throw new RuntimeException ("NotImpl: multiple variable declarators");
// check for double pointer; this is not compatible with fortran
if (bMakeCompatibleWithFortran && HIRAnalyzer.isDoublePointer (vardecl))
{
// one timestep is ok, just pass NULL as output pointer
// throw runtime exception if more than one timestep
if (!ExpressionUtil.isValue (m_data.getStencilCalculation ().getMaxIterations (), 1))
throw new RuntimeException ("Fortran is not supported with multiple timesteps.");
else
{
// create a new pointer variable
VariableDeclarator decl = new VariableDeclarator (vardecl.getDeclarator (0).getID ().clone ());
cmpstmtBody.addDeclaration (new VariableDeclaration (ASTUtil.dereference (vardecl.getSpecifiers ()), decl));
Identifier idPointer = new Identifier (decl);
listFnxParams.add (new UnaryExpression (UnaryOperator.ADDRESS_OF, idPointer));
}
}
else if (bMakeCompatibleWithFortran && HIRAnalyzer.isNoPointer (vardecl))
{
// the original parameter is no pointer; an indirection was added to the kernel function declaration
// add a dereference here where the C kernel is called
listFnxParams.add (new UnaryExpression (
UnaryOperator.DEREFERENCE,
(((VariableDeclarator) vardecl.getDeclarator (0)).getID ()).clone ()));
}
else
listFnxParams.add ((((VariableDeclarator) vardecl.getDeclarator (0)).getID ()).clone ());
}
// calculate the code selection expression
Expression exprCodeSelector = null;
for (int i = listCodeSelectors.size () - 1; i >= 0; i
{
if (rgCodeSelectorsCount[i] == 1)
{
// add a '0' if there is only one selector possibility
if (exprCodeSelector == null)
exprCodeSelector = Globals.ZERO.clone ();
}
else if (rgCodeSelectorsCount[i] != 0)
{
// add a dereference if necessary
Identifier idCodeSelector = listCodeSelectors.get (i);
Expression exprCodeSel = bMakeCompatibleWithFortran ?
new UnaryExpression (UnaryOperator.DEREFERENCE, idCodeSelector.clone ()) :
idCodeSelector.clone ();
// calculate the selector
if (exprCodeSelector == null)
exprCodeSelector = exprCodeSel;
else
{
exprCodeSelector = new BinaryExpression (
exprCodeSel,
BinaryOperator.ADD,
new BinaryExpression (new IntegerLiteral (rgCodeSelectorsCount[i]), BinaryOperator.MULTIPLY, exprCodeSelector)
);
}
}
}
if (m_data.getArchitectureDescription ().useFunctionPointers ())
{
// function pointers can be used: call the actual kernel function by calling the corresponding
// function pointer in the array
cmpstmtBody.addStatement (new ExpressionStatement (new FunctionCall (
new ArrayAccess (nidFunctionSelector.clone (), exprCodeSelector),
(List<Expression>) CodeGeneratorUtil.clone (listFnxParams))));
}
else
{
// no function pointers can be used: create a "switch" statement selecting the actual kernel
// build the switch statement
CompoundStatement cmpstmtSwitch = new CompoundStatement ();
int nIdx = 0;
for (String strFnxName : listFunctionNames)
{
cmpstmtSwitch.addStatement (new Case (new IntegerLiteral (nIdx)));
cmpstmtSwitch.addStatement (new ExpressionStatement (new FunctionCall (
new NameID (strFnxName),
(List<Expression>) CodeGeneratorUtil.clone (listFnxParams))));
cmpstmtSwitch.addStatement (new BreakStatement ());
nIdx++;
}
// add the "switch" to the function body and return it
cmpstmtBody.addStatement (new SwitchStatement (exprCodeSelector, cmpstmtSwitch));
}
return cmpstmtBody;
}
private static int m_nTempCount = 0;
private Expression substituteBinaryExpressionRecursive (List<Specifier> listSpecs, Expression expr, CompoundStatement cmpstmt)
{
if (expr instanceof BinaryExpression)
{
Expression exprLHS = substituteBinaryExpressionRecursive (listSpecs, ((BinaryExpression) expr).getLHS (), cmpstmt);
Expression exprRHS = substituteBinaryExpressionRecursive (listSpecs, ((BinaryExpression) expr).getRHS (), cmpstmt);
VariableDeclarator decl = new VariableDeclarator (new NameID (StringUtil.concat ("__tmp", CodeGenerator.m_nTempCount++)));
decl.setInitializer (new ValueInitializer (new BinaryExpression (exprLHS, ((BinaryExpression) expr).getOperator (), exprRHS)));
cmpstmt.addDeclaration (new VariableDeclaration (listSpecs, decl));
return new Identifier (decl);
}
return expr.clone ();
}
@SuppressWarnings("unchecked")
private CompoundStatement substituteBinaryExpression (Identifier idLHS, AssignmentOperator op, BinaryExpression expr)
{
CompoundStatement cmpstmt = new CompoundStatement ();
cmpstmt.addStatement (new ExpressionStatement (new AssignmentExpression (
idLHS.clone (),
op,
substituteBinaryExpressionRecursive (idLHS.getSymbol ().getTypeSpecifiers (), expr, cmpstmt))));
return cmpstmt;
}
private void substituteBinaryExpressions (Traversable trv)
{
if (trv instanceof ExpressionStatement)
{
Expression expr = ((ExpressionStatement) trv).getExpression ();
if (expr instanceof AssignmentExpression)
{
AssignmentExpression aexpr = (AssignmentExpression) expr;
if (aexpr.getLHS () instanceof Identifier && aexpr.getRHS () instanceof BinaryExpression)
((Statement) trv).swapWith (substituteBinaryExpression ((Identifier) aexpr.getLHS (), aexpr.getOperator (), (BinaryExpression) ((AssignmentExpression) expr).getRHS ()));
}
}
else
{
for (Traversable trvChild : trv.getChildren ())
substituteBinaryExpressions (trvChild);
}
}
/**
* Do post-code generation optimizations (loop unrolling, ...).
* @param cmpstmtBody
* @return
*/
protected void optimizeCode (StatementListBundle slbInput)
{
// create one assignment for each subexpression
if (CodeGenerator.SINGLE_ASSIGNMENT)
{
for (ParameterAssignment pa : slbInput)
{
StatementList sl = slbInput.getStatementList (pa);
for (Statement stmt : sl.getStatementsAsList ())
substituteBinaryExpressions (stmt);
}
}
// remove declarations of unused variables
for (ParameterAssignment pa : slbInput)
{
LOGGER.debug (StringUtil.concat ("Removing unused variables from ", pa.toString ()));
StatementList sl = slbInput.getStatementList (pa);
List<Statement> list = sl.getStatementsAsList ();
boolean bModified = false;
for (Iterator<Statement> it = list.iterator (); it.hasNext (); )
{
Statement stmt = it.next ();
if (stmt instanceof DeclarationStatement && ((DeclarationStatement) stmt).getDeclaration () instanceof VariableDeclaration)
{
VariableDeclaration vdecl = (VariableDeclaration) ((DeclarationStatement) stmt).getDeclaration ();
if (vdecl.getNumDeclarators () == 1)
{
if (!HIRAnalyzer.isReferenced (vdecl.getDeclarator (0).getID (), sl))
{
it.remove ();
bModified = true;
}
}
}
}
if (bModified)
slbInput.replaceStatementList (pa, new StatementList (list));
}
// remove
}
/**
*
* @param bIncludeAutotuneParameters
* @return
*/
public String getIncludesAndDefines (boolean bIncludeAutotuneParameters)
{
/*
return StringUtil.concat (
"#include <stdio.h>\n#include <stdlib.h>\n\n",
bIncludeAutotuneParameters ? "#include \"kerneltest.h\"\n\n" : null);
*/
//return "#define t_max 1\n#define THREAD_NUMBER 0\n#define NUMBER_OF_THREADS 1\n\n";
//return "#define t_max 1";
StringBuilder sb = new StringBuilder ();
// print header
sb.append ("/**\n * Kernel and initialization code for the stencil\n *");
for (Stencil stencil : m_data.getStencilCalculation ().getStencilBundle ())
{
sb.append ("\n * ");
sb.append (stencil.getStencilExpression ());
}
sb.append ("\n * \n * Strategy: ");
sb.append (m_data.getStrategy ().getFilename ());
sb.append ("\n * \n * This code was generated by Patus on ");
sb.append (DATE_FORMAT.format (new Date ()));
sb.append ("\n */\n\n");
if (m_data.getOptions ().isDebugPrintStencilIndices ())
sb.append ("#include <stdio.h>\n");
// include files
for (String strFile : m_data.getArchitectureDescription ().getIncludeFiles ())
{
sb.append ("#include \"");
sb.append (strFile);
sb.append ("\"\n");
}
sb.append ("#include <stdint.h>\n");
sb.append ("#include \"patusrt.h\"\n");
sb.append ("#include \"");
sb.append (CodeGenerationOptions.DEFAULT_TUNEDPARAMS_FILENAME);
sb.append ("\"\n");
//sb.append ("#define t_max 1");
return sb.toString ();
}
} |
package com.stripe.android;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
import android.support.annotation.VisibleForTesting;
import java.util.Map;
import java.util.concurrent.Executor;
import com.stripe.android.exception.APIConnectionException;
import com.stripe.android.exception.APIException;
import com.stripe.android.exception.AuthenticationException;
import com.stripe.android.exception.CardException;
import com.stripe.android.exception.InvalidRequestException;
import com.stripe.android.exception.StripeException;
import com.stripe.android.model.BankAccount;
import com.stripe.android.model.Card;
import com.stripe.android.model.Source;
import com.stripe.android.model.SourceParams;
import com.stripe.android.model.Token;
import com.stripe.android.net.PollingResponseHandler;
import com.stripe.android.net.RequestOptions;
import com.stripe.android.net.StripeApiHandler;
import static com.stripe.android.util.StripeNetworkUtils.hashMapFromBankAccount;
import static com.stripe.android.util.StripeNetworkUtils.hashMapFromCard;
/**
* Class that handles {@link Token} creation from charges and {@link Card} models.
*/
public class Stripe {
SourceCreator mSourceCreator = new SourceCreator() {
@Override
public void create(
@NonNull final SourceParams sourceParams,
@NonNull final String publishableKey,
@Nullable Executor executor,
@NonNull final SourceCallback sourceCallback) {
AsyncTask<Void, Void, ResponseWrapper> task =
new AsyncTask<Void, Void, ResponseWrapper>() {
@Override
protected ResponseWrapper doInBackground(Void... params) {
try {
Source source = StripeApiHandler.createSourceOnServer(
sourceParams,
publishableKey);
return new ResponseWrapper(source);
} catch (StripeException stripeException) {
return new ResponseWrapper(stripeException);
}
}
@Override
protected void onPostExecute(ResponseWrapper responseWrapper) {
if (responseWrapper.source != null) {
sourceCallback.onSuccess(responseWrapper.source);
} else if (responseWrapper.error != null) {
sourceCallback.onError(responseWrapper.error);
}
}
};
executeTask(executor, task);
}
};
@VisibleForTesting
TokenCreator mTokenCreator = new TokenCreator() {
@Override
public void create(
final Map<String, Object> tokenParams,
final String publishableKey,
final Executor executor,
final TokenCallback callback) {
AsyncTask<Void, Void, ResponseWrapper> task =
new AsyncTask<Void, Void, ResponseWrapper>() {
@Override
protected ResponseWrapper doInBackground(Void... params) {
try {
RequestOptions requestOptions =
RequestOptions.builder(publishableKey).build();
Token token = StripeApiHandler.createTokenOnServer(
tokenParams,
requestOptions,
mLoggingResponseListener);
return new ResponseWrapper(token);
} catch (StripeException e) {
return new ResponseWrapper(e);
}
}
@Override
protected void onPostExecute(ResponseWrapper result) {
tokenTaskPostExecution(result, callback);
}
};
executeTask(executor, task);
}
};
private Context mContext;
private StripeApiHandler.LoggingResponseListener mLoggingResponseListener;
private String mDefaultPublishableKey;
/**
* A constructor with only context, to set the key later.
*
* @param context {@link Context} for resolving resources
*/
public Stripe(@NonNull Context context) {
mContext = context;
}
/**
* Constructor with publishable key.
*
* @param context {@link Context} for resolving resources
* @param publishableKey the client's publishable key
* @throws AuthenticationException if the key is invalid
*/
public Stripe(@NonNull Context context, String publishableKey) throws AuthenticationException {
mContext = context;
setDefaultPublishableKey(publishableKey);
}
/**
* The simplest way to create a {@link BankAccount} token. This runs on the default
* {@link Executor} and with the currently set {@link #mDefaultPublishableKey}.
*
* @param bankAccount the {@link BankAccount} used to create this token
* @param callback a {@link TokenCallback} to receive either the token or an error
*/
public void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull final TokenCallback callback) {
createBankAccountToken(bankAccount, mDefaultPublishableKey, null, callback);
}
/**
* Call to create a {@link Token} for a {@link BankAccount} with the publishable key and
* {@link Executor} specified.
*
* @param bankAccount the {@link BankAccount} for which to create a {@link Token}
* @param publishableKey the publishable key to use
* @param executor an {@link Executor} to run this operation on. If null, this is run on a
* default non-ui executor
* @param callback a {@link TokenCallback} to receive the result or error message
*/
public void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
if (bankAccount == null) {
throw new RuntimeException(
"Required parameter: 'bankAccount' is requred to create a token");
}
createTokenFromParams(hashMapFromBankAccount(mContext, bankAccount), publishableKey, executor, callback);
}
/**
* Blocking method to create a {@link Token} for a {@link BankAccount}. Do not call this on
* the UI thread or your app will crash.
*
* This method uses the default publishable key for this {@link Stripe} instance.
*
* @param bankAccount the {@link Card} to use for this token
* @return a {@link Token} that can be used for this {@link BankAccount}
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws CardException should not be thrown with this type of token, but is theoretically
* possible given the underlying methods called
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
public Token createBankAccountTokenSynchronous(final BankAccount bankAccount)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
return createBankAccountTokenSynchronous(bankAccount, mDefaultPublishableKey);
}
/**
* Blocking method to create a {@link Token} using a {@link BankAccount}. Do not call this on
* the UI thread or your app will crash.
*
* @param bankAccount the {@link BankAccount} to use for this token
* @param publishableKey the publishable key to use with this request
* @return a {@link Token} that can be used for this {@link BankAccount}
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws CardException should not be thrown with this type of token, but is theoretically
* possible given the underlying methods called
* @throws APIException any other type of problem
*/
public Token createBankAccountTokenSynchronous(
final BankAccount bankAccount,
String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(publishableKey).build();
return StripeApiHandler.createTokenOnServer(
hashMapFromBankAccount(mContext, bankAccount), requestOptions, mLoggingResponseListener);
}
/**
* Create a {@link Source} using an {@link AsyncTask} on the default {@link Executor} with a
* publishable api key that has already been set on this {@link Stripe} instance.
*
* @param sourceParams the {@link SourceParams} to be used
* @param callback a {@link SourceCallback} to receive a result or an error message
*/
public void createSource(@NonNull SourceParams sourceParams, @NonNull SourceCallback callback) {
createSource(sourceParams, callback, null, null);
}
/**
* Create a {@link Source} using an {@link AsyncTask}.
*
* @param sourceParams the {@link SourceParams} to be used
* @param callback a {@link SourceCallback} to receive a result or an error message
* @param publishableKey the publishable api key to be used
* @param executor an {@link Executor} on which to execute the task, or {@link null} for default
*/
public void createSource(
@NonNull SourceParams sourceParams,
@NonNull SourceCallback callback,
@Nullable String publishableKey,
@Nullable Executor executor) {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return;
}
mSourceCreator.create(sourceParams, apiKey, executor, callback);
}
/**
* The simplest way to create a token, using a {@link Card} and {@link TokenCallback}. This
* runs on the default {@link Executor} and with the
* currently set {@link #mDefaultPublishableKey}.
*
* @param card the {@link Card} used to create this payment token
* @param callback a {@link TokenCallback} to receive either the token or an error
*/
public void createToken(@NonNull final Card card, @NonNull final TokenCallback callback) {
createToken(card, mDefaultPublishableKey, callback);
}
/**
* Call to create a {@link Token} with a specific public key.
*
* @param card the {@link Card} used for this transaction
* @param publishableKey the public key used for this transaction
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final String publishableKey,
@NonNull final TokenCallback callback) {
createToken(card, publishableKey, null, callback);
}
/**
* Call to create a {@link Token} on a specific {@link Executor}.
* @param card the {@link Card} to use for this token creation
* @param executor An {@link Executor} on which to run this operation. If you don't wish to
* specify an executor, use one of the other createTokenFromParams methods.
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final Executor executor,
@NonNull final TokenCallback callback) {
createToken(card, mDefaultPublishableKey, executor, callback);
}
/**
* Call to create a {@link Token} with the publishable key and {@link Executor} specified.
*
* @param card the {@link Card} used for this token
* @param publishableKey the publishable key to use
* @param executor an {@link Executor} to run this operation on. If null, this is run on a
* default non-ui executor
* @param callback a {@link TokenCallback} to receive the result or error message
*/
public void createToken(
@NonNull final Card card,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
if (card == null) {
throw new RuntimeException(
"Required Parameter: 'card' is required to create a token");
}
createTokenFromParams(hashMapFromCard(mContext, card), publishableKey, executor, callback);
}
/**
* Blocking method to create a {@link Source} object using this object's
* {@link Stripe#mDefaultPublishableKey key}.
*
* Do not call this on the UI thread or your app will crash.
*
* @param params a set of {@link SourceParams} with which to create the source
* @return a {@link Source}, or {@code null} if a problem occurred
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws CardException the card cannot be charged for some reason
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
@Nullable
public Source createSourceSynchronous(@NonNull SourceParams params)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
return createSourceSynchronous(params, null);
}
/**
* Blocking method to create a {@link Source} object.
* Do not call this on the UI thread or your app will crash.
*
* @param params a set of {@link SourceParams} with which to create the source
* @param publishableKey a publishable API key to use
* @return a {@link Source}, or {@code null} if a problem occurred
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
public Source createSourceSynchronous(
@NonNull SourceParams params,
@Nullable String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return null;
}
return StripeApiHandler.createSourceOnServer(params, apiKey);
}
/**
* Blocking method to create a {@link Token}. Do not call this on the UI thread or your app
* will crash. This method uses the default publishable key for this {@link Stripe} instance.
*
* @param card the {@link Card} to use for this token
* @return a {@link Token} that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws CardException the card cannot be charged for some reason
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
public Token createTokenSynchronous(final Card card)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
return createTokenSynchronous(card, mDefaultPublishableKey);
}
/**
* Blocking method to create a {@link Token}. Do not call this on the UI thread or your app
* will crash.
*
* @param card the {@link Card} to use for this token
* @param publishableKey the publishable key to use with this request
* @return a {@link Token} that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Token createTokenSynchronous(final Card card, String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(publishableKey).build();
return StripeApiHandler.createTokenOnServer(
hashMapFromCard(mContext, card),
requestOptions,
mLoggingResponseListener);
}
/**
* Poll for changes in a {@link Source} using a background thread with an exponential backoff.
*
* @param sourceId the {@link Source#mId} to check on
* @param clientSecret the {@link Source#mClientSecret} to check on
* @param publishableKey an API key
* @param callback a {@link PollingResponseHandler} to use as a callback
* @param timeoutMs the amount of time before the polling expires. If {@code null} is passed
* in, 10000ms will be used.
*/
public void pollSource(@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret,
@Nullable String publishableKey,
@NonNull PollingResponseHandler callback,
@Nullable Integer timeoutMs) {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return;
}
StripeApiHandler.pollSource(sourceId, clientSecret, apiKey, callback, timeoutMs);
}
/**
* Retrieve an existing {@link Source} from the Stripe API. Note that this is a
* synchronous method, and cannot be called on the main thread. Doing so will cause your app
* to crash. This method uses the default publishable key for this {@link Stripe} instance.
*
* @param sourceId the {@link Source#mId} field of the desired Source object
* @param clientSecret the {@link Source#mClientSecret} field of the desired Source object
* @return a {@link Source} if one could be found based on the input params, or {@code null} if
* no such Source could be found.
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
return retrieveSourceSynchronous(sourceId, clientSecret, null);
}
/**
* Retrieve an existing {@link Source} from the Stripe API. Note that this is a
* synchronous method, and cannot be called on the main thread. Doing so will cause your app
* to crash.
*
* @param sourceId the {@link Source#mId} field of the desired Source object
* @param clientSecret the {@link Source#mClientSecret} field of the desired Source object
* @param publishableKey a publishable API key to use
* @return a {@link Source} if one could be found based on the input params, or {@code null} if
* no such Source could be found.
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret,
@Nullable String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return null;
}
return StripeApiHandler.retrieveSource(sourceId, clientSecret, apiKey);
}
/**
* Set the default publishable key to use with this {@link Stripe} instance.
*
* @param publishableKey the key to be set
* @throws AuthenticationException if the key is null, empty, or a secret key
*/
public void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey)
throws AuthenticationException {
validateKey(publishableKey);
this.mDefaultPublishableKey = publishableKey;
}
@VisibleForTesting
void setLoggingResponseListener(StripeApiHandler.LoggingResponseListener listener) {
mLoggingResponseListener = listener;
}
private void createTokenFromParams(
@NonNull final Map<String, Object> tokenParams,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
try {
if (callback == null) {
throw new RuntimeException(
"Required Parameter: 'callback' is required to use the created " +
"token and handle errors");
}
validateKey(publishableKey);
mTokenCreator.create(tokenParams, publishableKey, executor, callback);
}
catch (AuthenticationException e) {
callback.onError(e);
}
}
private void validateKey(@NonNull @Size(min = 1) String publishableKey)
throws AuthenticationException {
if (publishableKey == null || publishableKey.length() == 0) {
throw new AuthenticationException("Invalid Publishable Key: " +
"You must use a valid publishable key to create a token. " +
"For more info, see https://stripe.com/docs/stripe.js.", null, 0);
}
if (publishableKey.startsWith("sk_")) {
throw new AuthenticationException("Invalid Publishable Key: " +
"You are using a secret key to create a token, " +
"instead of the publishable one. For more info, " +
"see https://stripe.com/docs/stripe.js", null, 0);
}
}
private void tokenTaskPostExecution(ResponseWrapper result, TokenCallback callback) {
if (result.token != null) {
callback.onSuccess(result.token);
}
else if (result.error != null) {
callback.onError(result.error);
}
else {
callback.onError(new RuntimeException(
"Somehow got neither a token response or an error response"));
}
}
private void executeTask(Executor executor, AsyncTask<Void, Void, ResponseWrapper> task) {
if (executor != null && Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(executor);
} else {
task.execute();
}
}
private class ResponseWrapper {
final Source source;
final Token token;
final Exception error;
private ResponseWrapper(Token token) {
this.token = token;
this.source = null;
this.error = null;
}
private ResponseWrapper(Source source) {
this.source = source;
this.error = null;
this.token = null;
}
private ResponseWrapper(Exception error) {
this.error = error;
this.source = null;
this.token = null;
}
}
interface SourceCreator {
void create(
@NonNull SourceParams params,
@NonNull String publishableKey,
@Nullable Executor executor,
@NonNull SourceCallback sourceCallback);
}
@VisibleForTesting
interface TokenCreator {
void create(Map<String, Object> params,
String publishableKey,
Executor executor,
TokenCallback callback);
}
} |
package cn.cerc.core;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TDateTime implements Serializable, Comparable<TDateTime>, Cloneable {
private static final long serialVersionUID = -7395748632907604015L;
private static Map<String, String> dateFormats = new HashMap<>();
private static Map<String, String> map;
static {
map = new HashMap<>();
map.put("YYYYMMDD", "yyyyMMdd");
map.put("YYMMDD", "yyMMdd");
map.put("YYYMMDD_HH_MM_DD", "yyyyMMdd_HH_mm_dd");
map.put("yymmddhhmmss", "yyMMddHHmmss");
map.put("yyyymmdd", "yyyyMMdd");
map.put("YYYYMMDDHHMMSSZZZ", "yyyyMMddHHmmssSSS");
map.put("YYYYMM", "yyyyMM");
map.put("YYYY-MM-DD", "yyyy-MM-dd");
map.put("yyyy-MM-dd", "yyyy-MM-dd");
map.put("yyyyMMdd", "yyyyMMdd");
map.put("YY", "yy");
map.put("yy", "yy");
map.put("YYYY", "yyyy");
map.put("YYYY/MM/DD", "yyyy/MM/dd");
dateFormats.put("yyyy-MM-dd HH:mm:ss", "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}");
dateFormats.put("yyyy-MM-dd HH:mm", "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}");
dateFormats.put("yyyy-MM-dd", "\\d{4}-\\d{2}-\\d{2}");
dateFormats.put("yyyy/MM/dd HH:mm:ss", "\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}");
dateFormats.put("yyyy/MM/dd", "\\d{4}/\\d{2}/\\d{2}");
dateFormats.put("yyyyMMdd", "\\d{8}");
}
private Date data;
public TDateTime() {
this.data = new Date(0);
}
public TDateTime(String value) {
String fmt = getFormat(value);
if (fmt == null) {
fmt = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
try {
data = sdf.parse(value);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
}
public TDateTime(String fmt, String value) {
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
try {
data = sdf.parse(value);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
}
public TDateTime(Date value) {
data = value;
}
public static TDateTime Now() {
TDateTime result = new TDateTime();
result.setData(new Date());
return result;
}
public static TDateTime fromDate(String val) {
String fmt = getFormat(val);
if (fmt == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
TDateTime tdtTo = new TDateTime();
try {
tdtTo.setData(sdf.parse(val));
return tdtTo;
} catch (ParseException e) {
return null;
}
}
public static TDateTime fromYearMonth(String val) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
TDateTime tdt = new TDateTime();
try {
tdt.setData(sdf.parse(val));
return tdt;
} catch (ParseException e) {
throw new RuntimeException(String.format(" %s yyyyMM", val));
}
}
public static String getFormat(String val) {
if (val == null) {
return null;
}
if ("".equals(val)) {
return null;
}
String fmt = null;
java.util.Iterator<String> it = dateFormats.keySet().iterator();
while (it.hasNext() && fmt == null) {
String key = it.next();
String str = dateFormats.get(key);
if (val.matches(str)) {
fmt = key;
}
}
return fmt;
}
/**
* ()
*
* @param startTime
* @param endTime
* @return
*/
public static boolean isTimeOut(TDateTime startTime, TDateTime endTime) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long diff;
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
try {
diff = dateFormat.parse(endTime.toString()).getTime() - dateFormat.parse(startTime.toString()).getTime();
day = diff / nd;
hour = diff % nd / nh + day * 24;
min = diff % nd % nh / nm + day * 24 * 60;
sec = diff % nd % nh % nm / ns;
} catch (ParseException e) {
e.printStackTrace();
}
if (day > 0) {
return true;
}
if (hour - day * 24 > 0) {
return true;
}
if (min - day * 24 * 60 > 0) {
return true;
}
return sec - day > 0;
}
public static String FormatDateTime(String fmt, TDateTime value) {
SimpleDateFormat sdf = null;
try {
sdf = new SimpleDateFormat(map.get(fmt));
} catch (IllegalArgumentException e) {
throw new RuntimeException("");
}
return sdf.format(value.getData());
}
public static TDateTime StrToDate(String val) {
String fmt = TDateTime.getFormat(val);
if (fmt == null) {
throw new RuntimeException(": value=" + val);
}
return new TDateTime(fmt, val);
}
public static String FormatDateTime(String fmt, Date value) {
SimpleDateFormat sdf = null;
try {
sdf = new SimpleDateFormat(fmt);
} catch (IllegalArgumentException e) {
sdf = new SimpleDateFormat(map.get(fmt));
}
return sdf.format(value);
}
/**
*
*
* @param start
* @param last
* @return
*/
public static boolean isInterval(String start, String last) {
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date now = null;
Date beginTime = null;
Date endTime = null;
try {
now = df.parse(df.format(new Date()));
beginTime = df.parse(start);
endTime = df.parse(last);
} catch (Exception e) {
e.printStackTrace();
}
Calendar date = Calendar.getInstance();
date.setTime(now);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
return date.after(begin) && date.before(end);
}
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
TDateTime date = TDateTime.fromDate("2016-02-28 08:00:01");
System.out.println(date.getTimestamp());
System.out.println(date.getUnixTimestamp());
System.out.println(date);
System.out.println(date.incMonth(1));
System.out.println(date.incMonth(2));
System.out.println(date.incMonth(3));
System.out.println(date.incMonth(4));
System.out.println(date.incMonth(12));
System.out.println(date.incMonth(13));
System.out.println(date);
TDateTime date2 = TDateTime.fromDate("2016-05-31 23:59:59");
System.out.println(date2);
System.out.println(date2.incMonth(1));
System.out.println(date2.incMonth(1).monthBof());
System.out.println(isInterval("05:30", "17:00"));
}
@Override
public String toString() {
if (data == null) {
return "";
}
return format("yyyy-MM-dd HH:mm:ss");
}
public String getDate() {
return format("yyyy-MM-dd");
}
public String getTime() {
return format("HH:mm:ss");
}
/**
* @return Java13
*/
public long getTimestamp() {
return this.getData().getTime();
}
/**
* @return Unix10
*/
public long getUnixTimestamp() {
return this.getData().getTime() / 1000;
}
public String getYearMonth() {
return format("yyyyMM");
}
public String getMonthDay() {
return format("MM-dd");
}
public String getYear() {
return format("yyyy");
}
public String getFull() {
return format("yyyy-MM-dd HH:mm:ss:SSS");
}
public String format(String fmt) {
if (data == null) {
return null;
}
if (data.compareTo(new Date(0)) == 0) {
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
return sdf.format(data);
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public long compareSecond(TDateTime startTime) {
if (startTime == null) {
return 0;
}
long second = 1000;
long start = startTime.getData().getTime();
long end = TDateTime.Now().getData().getTime();
return (end - start) / second;
}
public long compareMinute(TDateTime startTime) {
if (startTime == null) {
return 0;
}
long minute = 1000 * 60;
long start = startTime.getData().getTime();
long end = TDateTime.Now().getData().getTime();
return (end - start) / minute;
}
public long compareHour(TDateTime startTime) {
if (startTime == null) {
return 0;
}
long hour = 1000 * 60 * 60;
long start = startTime.getData().getTime();
long end = TDateTime.Now().getData().getTime();
return (end - start) / hour;
}
public int compareDay(TDateTime dateFrom) {
if (dateFrom == null) {
return 0;
}
// this - to ,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
String str1 = sdf.format(this.getData());
String str2 = sdf.format(dateFrom.getData());
int count = 0;
try {
cal1.setTime(sdf.parse(str2));
cal2.setTime(sdf.parse(str1));
int flag = 1;
if (cal1.after(cal2)) {
flag = -1;
}
while (cal1.compareTo(cal2) != 0) {
cal1.set(Calendar.DAY_OF_YEAR, cal1.get(Calendar.DAY_OF_YEAR) + flag);
count = count + flag;
}
} catch (ParseException e) {
throw new RuntimeException(" " + e.getMessage());
}
return count;
}
// MonthsBetweencompareMonth
public int compareMonth(TDateTime dateFrom) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(this.getData());
int month1 = cal1.get(Calendar.YEAR) * 12 + cal1.get(Calendar.MONTH);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(dateFrom.getData());
int month2 = cal2.get(Calendar.YEAR) * 12 + cal2.get(Calendar.MONTH);
return month1 - month2;
}
public int compareYear(TDateTime dateFrom) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(this.getData());
int year1 = cal1.get(Calendar.YEAR);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(dateFrom.getData());
int year2 = cal2.get(Calendar.YEAR);
return year1 - year2;
}
public TDate asDate() {
return new TDate(this.data);
}
public TDateTime incSecond(int value) {
TDateTime result = this.clone();
Calendar cal = Calendar.getInstance();
cal.setTime(result.getData());
cal.set(Calendar.SECOND, value + cal.get(Calendar.SECOND));
result.setData(cal.getTime());
return result;
}
public TDateTime incMinute(int value) {
TDateTime result = this.clone();
Calendar cal = Calendar.getInstance();
cal.setTime(result.getData());
cal.set(Calendar.MINUTE, value + cal.get(Calendar.MINUTE));
result.setData(cal.getTime());
return result;
}
public TDateTime incHour(int value) {
TDateTime result = this.clone();
Calendar cal = Calendar.getInstance();
cal.setTime(result.getData());
cal.set(Calendar.HOUR_OF_DAY, value + cal.get(Calendar.HOUR_OF_DAY));
result.setData(cal.getTime());
return result;
}
public TDateTime incDay(int value) {
TDateTime result = this.clone();
Calendar cal = Calendar.getInstance();
cal.setTime(result.getData());
cal.set(Calendar.DAY_OF_MONTH, value + cal.get(Calendar.DAY_OF_MONTH));
result.setData(cal.getTime());
return result;
}
public TDateTime incMonth(int offset) {
TDateTime result = this.clone();
if (offset == 0) {
return result;
}
Calendar cal = Calendar.getInstance();
cal.setTime(result.getData());
int day = cal.get(Calendar.DATE);
cal.set(Calendar.DATE, 1);
boolean isMaxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH) == day;
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + offset);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (isMaxDay || day > maxDay) {
cal.set(Calendar.DATE, maxDay);
} else {
cal.set(Calendar.DATE, day);
}
result.setData(cal.getTime());
return result;
}
@Deprecated
public TDateTime addDay(int value) {
return this.incDay(value);
}
// value1
public TDateTime monthBof() {
Calendar cal = Calendar.getInstance();
cal.setTime(this.getData());
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
TDateTime tdt = new TDateTime();
tdt.setData(cal.getTime());
return tdt;
}
public TDateTime monthEof() {
// value1
Calendar cal = Calendar.getInstance();
cal.setTime(this.getData());
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
TDateTime tdt = new TDateTime();
tdt.setData(cal.getTime());
return tdt;
}
public int getMonth() {
// value 1-12
Calendar cal = Calendar.getInstance();
cal.setTime(this.data);
return cal.get(Calendar.MONTH) + 1;
}
public int getDay() {
// value
Calendar cal = Calendar.getInstance();
cal.setTime(this.data);
return cal.get(Calendar.DAY_OF_MONTH);
}
public int getHours() {
// value
Calendar cal = Calendar.getInstance();
cal.setTime(this.data);
return cal.get(Calendar.HOUR_OF_DAY);
}
public int getMinutes() {
// value
Calendar cal = Calendar.getInstance();
cal.setTime(this.data);
return cal.get(Calendar.MINUTE);
}
public String getGregDate() {
Calendar cal = Calendar.getInstance();
cal.setTime(this.getData());
Lunar lunar = new Lunar(cal);
return lunar.toString().substring(5, lunar.toString().length()).replaceAll("-", "/");
}
@Override
public int compareTo(TDateTime tdt) {
if (tdt == null) {
return 1;
}
if (tdt.getData().getTime() == this.getData().getTime()) {
return 0;
} else {
return this.getData().getTime() > tdt.getData().getTime() ? 1 : -1;
}
}
@Override
public TDateTime clone() {
return new TDateTime(this.getData());
}
public boolean isNull() {
return this.data == null;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.venky.swf.views;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.venky.core.collections.LowerCaseStringCache;
import com.venky.core.collections.SequenceSet;
import com.venky.core.collections.UpperCaseStringCache;
import com.venky.core.log.SWFLogger;
import com.venky.core.log.TimerStatistics.Timer;
import com.venky.core.util.ObjectUtil;
import com.venky.core.util.pkg.JarIntrospector;
import com.venky.extension.Registry;
import com.venky.swf.path._IPath;
import com.venky.swf.routing.Config;
import com.venky.swf.views.controls._IControl;
import com.venky.swf.views.controls.page.*;
import com.venky.swf.views.controls.page.layout.Div;
import com.venky.swf.views.controls.page.layout.FluidContainer;
import com.venky.swf.views.controls.page.layout.FluidContainer.Column;
import com.venky.swf.views.controls.page.layout.Glyphicon;
import com.venky.swf.views.controls.page.layout.LineBreak;
import com.venky.swf.views.controls.page.layout.Paragraph;
/**
*
* @author venky
*/
public abstract class HtmlView extends View{
public HtmlView(_IPath path){
super(path);
}
private SequenceSet<HotLink> links = null;
public SequenceSet<HotLink> getHotLinks(){
if (links == null){
links = new SequenceSet<HotLink>();
HotLink home = new HotLink("/dashboard");
home.addClass("home");
home.addControl(new Glyphicon("glyphicon-home","Home"));
links.add(home);
HotLink back = new HotLink(getPath().controllerPath() + "/back");
back.addClass("back");
back.addControl(new Glyphicon("glyphicon-arrow-left","Back"));
links.add(back);
}
return links;
}
@Override
public void write(int httpStatusCode) throws IOException{
HttpServletResponse response = getPath().getResponse();
response.setContentType("text/html;charset=utf-8");
response.setStatus(httpStatusCode);
response.getWriter().println("<!DOCTYPE html>");
response.getWriter().println(this);
}
@Override
public String toString(){
Html html = new Html();
SWFLogger cat = Config.instance().getLogger(getClass().getName());
Timer htmlCreation = cat.startTimer("html creation.");
try {
createHtml(html);
}finally {
htmlCreation.stop();
}
Timer htmlToString = cat.startTimer("html rendering.");
try {
return html.toString();
}finally {
htmlToString.stop();
}
}
protected void createHtml(Html html){
Head head = new Head();
html.addControl(head);
_createHead(head);
Body body = new Body();
html.addControl(body);
_createBody(body,true);
Registry.instance().callExtensions("finalize.view" + getPath().getTarget() , this , html);
}
private Paragraph status = new Paragraph();
public static enum StatusType {
ERROR(){
public String toString(){
return "error alert alert-warning";
}
},
INFO() {
public String toString(){
return "info alert alert-success";
}
};
public String getSessionKey(){
return "ui."+ toString() + ".msg";
}
}
public void setStatus(StatusType type, String text){
if (ObjectUtil.isVoid(text)){
return;
}
this.status.addClass(type.toString());
String statusText = this.status.getText();
if (!ObjectUtil.isVoid(statusText)){
statusText += "<br/>" ;
}
statusText += text;
this.status.setText(statusText);
}
protected void createHead(Head head){
}
protected void _createHead(Head head){
head.addControl(new Css("/resources/scripts/node_modules/bootstrap/dist/css/bootstrap.min.css"));
head.addControl(new Css("/resources/images/fontawesome/css/all.min.css"));
head.addControl(new Css("/resources/scripts/node_modules/tablesorter/dist/css/theme.bootstrap.min.css"));
head.addControl(new Css("/resources/scripts/node_modules/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css"));
head.addControl(new Script("/resources/scripts/node_modules/jquery/dist/jquery.min.js"));
head.addControl(new Script("/resources/scripts/node_modules/popper.js/dist/popper.min.js"));
head.addControl(new Script("/resources/scripts/node_modules/bootstrap/dist/js/bootstrap.min.js"));
head.addControl(new Script("/resources/scripts/node_modules/tablesorter/dist/js/jquery.tablesorter.min.js"));
head.addControl(new Script("/resources/scripts/node_modules/tablesorter/dist/js/jquery.tablesorter.widgets.min.js"));
head.addControl(new Script("/resources/scripts/node_modules/bootstrap-ajax-typeahead/bootstrap-typeahead.js"));
head.addControl(new Script("/resources/scripts/node_modules/moment/min/moment-with-locales.min.js"));
head.addControl(new Script("/resources/scripts/node_modules/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"));
head.addControl(new Css("/resources/scripts/swf/css/swf.css"));
head.addControl(new Script("/resources/scripts/swf/js/swf.js"));
String applicationInitScript = Config.instance().getProperty("swf.application.init.script", "/resources/scripts/application.js");
if ( !applicationInitScript.startsWith("/") ) {
applicationInitScript = "/" + applicationInitScript;
}
if ( applicationInitScript.startsWith("/resources")) {
applicationInitScript = applicationInitScript.substring("/resources".length());
}
URL r = getClass().getResource(applicationInitScript);
if (r != null){
head.addControl(new Script("/resources" + applicationInitScript));
}
addProgressiveWebAppLinks(head);
createHead(head);
Registry.instance().callExtensions("after.create.head."+getPath().controllerPathElement()+"/"+getPath().action(), getPath(), head);
Registry.instance().callExtensions("after.create.head",getPath(),head); // Global.
}
public void addProgressiveWebAppLinks(Head head){
URL r = getClass().getResource("/web_manifest/manifest.json");
if (r == null){
return;
}
Link link = new HLink("/resources/web_manifest/manifest.json");
link.setProperty("rel","manifest");
head.addControl(link);
link = new HLink("/resources/web_manifest/manifest.png"); //192x192
link.setProperty("rel","icon");
head.addControl(link);
link = new HLink("/resources/web_manifest/manifest.png");
link.setProperty("rel","apple-touch-icon");
head.addControl(link);
head.addControl(new Meta("mobile-web-app-capable" , "yes"));
head.addControl(new Meta("apple-mobile-web-app-capable" , "yes"));
String applicationName = Config.instance().getProperty("swf.application.name", "Application");
head.addControl(new Meta("application-name" , applicationName));
head.addControl(new Meta("apple-mobile-web-app-title" , applicationName));
head.addControl(new Meta("msapplication-starturl","/"));
head.addControl(new Meta("viewport","width=device-width, initial-scale=1, shrink-to-fit=no"));
//head.addControl(new Meta( "Service-Worker-Allowed" , "yes"));
}
/*
* When views are composed, includeStatusMessage is passed as false so that it may be included in parent/including view
*/
protected void _createBody(_IControl body,boolean includeStatusMessage){
int statusMessageIndex = body.getContainedControls().size();
showErrorsIfAny(body,statusMessageIndex, includeStatusMessage);
createBody(body);
}
protected Div getStatus(){
FluidContainer container = new FluidContainer();
Column column = container.createRow().createColumn(0, 12);
column.addControl(status);
return container;
}
@SuppressWarnings("unchecked")
protected void showErrorsIfAny(_IControl body,int index, boolean includeStatusMessage){
HttpSession session = getPath().getSession();
if (session != null && includeStatusMessage){
body.addControl(index,getStatus());
List<String> errorMessages = getPath().getErrorMessages();
List<String> infoMessages = getPath().getInfoMessages();
boolean hasError = !errorMessages.isEmpty();
boolean addNewLine = false;
StringBuilder message = new StringBuilder();
for (List<String> messageList : Arrays.asList(errorMessages,infoMessages)){
for (String errorMsg : messageList){
if (addNewLine){
message.append(new LineBreak());
}
message.append(errorMsg);
addNewLine = true;
}
}
setStatus(hasError ? StatusType.ERROR : StatusType.INFO , message.toString());
}
}
public void addHotLinks(_IControl b, SequenceSet<HotLink> links, SequenceSet<HotLink> excludeLinks){
addHotLinks(b, b.getContainedControls().size(), links, excludeLinks);
}
public void addHotLinks(_IControl b, int index, SequenceSet<HotLink> links, SequenceSet<HotLink> excludeLinks){
FluidContainer hotlinks = new FluidContainer();
hotlinks.addClass("hotlinks");
b.addControl(index,hotlinks);
Column hotlinksCell = hotlinks.createRow().createColumn(0,12);
for (_IControl link : links){
if (!excludeLinks.contains(link)){
hotlinksCell.addControl(link);
}
}
}
protected abstract void createBody(_IControl b);
} |
package com.bkahlert.nebula.widgets.composer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.BrowserFunction;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.bkahlert.nebula.utils.ExecUtils;
import com.bkahlert.nebula.utils.IConverter;
import com.bkahlert.nebula.utils.JSONUtils;
import com.bkahlert.nebula.utils.colors.RGB;
import com.bkahlert.nebula.widgets.browser.Browser;
import com.bkahlert.nebula.widgets.browser.BrowserUtils;
import com.bkahlert.nebula.widgets.browser.extended.html.Anker;
import com.bkahlert.nebula.widgets.browser.extended.html.IAnker;
/**
* This is a wrapped CKEditor (ckeditor.com).
* <p>
* <b>Important developer warning</b>: Do not try to wrap a WYSIWYG editor based
* on iframes like TinyMCE. Some internal browsers (verified with Webkit) do not
* handle cut, copy and paste actions when the iframe is in focus. CKEditor can
* operate in both modes - iframes and divs (and p tags).
*
* @author bkahlert
*
*/
public class Composer extends Browser {
private static final Logger LOGGER = Logger.getLogger(Composer.class);
private static final Pattern URL_PATTERN = Pattern
.compile("(.*?)(\\w+://[!#$&-;=?-\\[\\]_a-zA-Z~%]+)(.*?)");
public static enum ToolbarSet {
DEFAULT, TERMINAL, NONE;
}
private final ToolbarSet toolbarSet;
private final List<IAnkerLabelProvider> ankerLabelProviders = new ArrayList<IAnkerLabelProvider>();
private final List<ModifyListener> modifyListeners = new ArrayList<ModifyListener>();
private String oldHtml = "";
private final Timer delayChangeTimer = new Timer(this.getClass()
.getSimpleName() + " :: Delay Change Timer", false);
private TimerTask delayChangeTimerTask = null;
public Composer(Composite parent, int style) {
this(parent, style, 0, ToolbarSet.DEFAULT);
}
/**
*
* @param parent
* @param style
* @param delayChangeEventUpTo
* is the delay that must have been passed in order to fire a
* change event. If 0 no delay will be applied. The minimal delay
* is defined by the CKEditor's config.js.
* @throws IOException
*/
public Composer(Composite parent, int style,
final long delayChangeEventUpTo, ToolbarSet toolbarSet) {
super(parent, style);
this.deactivateNativeMenu();
this.toolbarSet = toolbarSet;
this.fixShortcuts(delayChangeEventUpTo);
this.listenForModifications(delayChangeEventUpTo);
this.open(BrowserUtils.getFileUrl(Composer.class, "html/index.html",
"?internal=true&toolbarSet="
+ toolbarSet.toString().toLowerCase()), 30000,
"typeof jQuery != \"undefined\" && jQuery(\"html\").hasClass(\"ready\")");
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
if (Composer.this.delayChangeTimer != null) {
Composer.this.delayChangeTimer.cancel();
}
}
});
}
public void fixShortcuts(final long delayChangeEventUpTo) {
this.getBrowser().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if ((e.stateMask & SWT.CTRL) != 0
|| (e.stateMask & SWT.COMMAND) != 0) {
if (e.keyCode == 97) {
// a - select all
Composer.this.selectAll();
}
/*
* The CKEditor plugin "onchange" does not notify on cut and
* paste operations. Therefore we need to handle them here.
*/
if (e.keyCode == 120) {
// x - cut
// wait for the ui thread to apply the operation
ExecUtils.asyncExec(new Runnable() {
@Override
public void run() {
Composer.this.modifiedCallback(
Composer.this.getSource(),
delayChangeEventUpTo);
}
});
}
if (e.keyCode == 99) {
// c - copy
// do nothing
}
if (e.keyCode == 118) {
// v - paste
// wait for the ui thread to apply the operation
ExecUtils.asyncExec(new Runnable() {
@Override
public void run() {
Composer.this.modifiedCallback(
Composer.this.getSource(),
delayChangeEventUpTo);
}
});
}
}
}
});
}
public void listenForModifications(final long delayChangeEventUpTo) {
new BrowserFunction(this.getBrowser(), "modified") {
@Override
public Object function(Object[] arguments) {
if (arguments.length >= 1) {
if (arguments[0] instanceof String) {
String newHtml = (String) arguments[0];
Composer.this.modifiedCallback(newHtml,
delayChangeEventUpTo);
}
}
return null;
}
};
this.getBrowser().addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
Composer.this.modifiedCallback(Composer.this.getSource(), 0);
}
});
}
protected void modifiedCallback(String html, final long delayChangeEventTo) {
String newHtml = (html == null || html.replace(" ", " ").trim()
.isEmpty()) ? "" : html.trim();
if (StringUtils.equals(this.oldHtml, newHtml)) {
return;
}
this.oldHtml = newHtml;
// When space entered but widget is not disposing, create links
if (delayChangeEventTo > 0) {
String prevCaretCharacter = this.getPrevCaretCharacter();
if (prevCaretCharacter != null
&& this.getPrevCaretCharacter().matches("[\\s| ]")) { // space
// non
// breaking
// space
String autoLinkedHtml = this.createLinks(newHtml);
if (!autoLinkedHtml.equals(newHtml)) {
this.setSource(autoLinkedHtml, true);
newHtml = autoLinkedHtml;
}
}
}
final String saveHtml = newHtml;
ExecUtils.nonUISyncExec(new Runnable() {
@Override
public void run() {
try {
final Runnable fireRunnable = new Runnable() {
@Override
public void run() {
Event event = new Event();
event.display = Display.getCurrent();
event.widget = Composer.this;
event.text = saveHtml;
event.data = saveHtml;
ModifyEvent modifyEvent = new ModifyEvent(event);
for (ModifyListener modifyListener : Composer.this.modifyListeners) {
modifyListener.modifyText(modifyEvent);
}
}
};
synchronized (this) {
if (Composer.this.delayChangeTimerTask != null) {
Composer.this.delayChangeTimerTask.cancel();
}
if (delayChangeEventTo > 0) {
Composer.this.delayChangeTimerTask = new TimerTask() {
@Override
public void run() {
fireRunnable.run();
}
};
Composer.this.delayChangeTimer.schedule(
Composer.this.delayChangeTimerTask,
delayChangeEventTo);
} else {
Composer.this.delayChangeTimerTask = null;
fireRunnable.run();
}
}
} catch (Exception e) {
LOGGER.error("Error saving memo", e);
}
}
});
}
private String createLinks(String html) {
boolean htmlChanged = false;
Document doc = Jsoup.parseBodyFragment(html);
for (Element e : doc.getAllElements()) {
if (e.tagName().equals("a")) {
IAnker anker = new Anker(e);
IAnker newAnker = this.createAnkerFromLabelProviders(anker);
if (newAnker == null
&& !anker.getHref().equals(anker.getContent())) {
newAnker = new Anker(anker.getContent(),
anker.getClasses(), anker.getContent());
}
if (newAnker != null) {
e.html(newAnker.toHtml());
htmlChanged = true;
}
} else {
String ownText = e.ownText();
Matcher matcher = URL_PATTERN.matcher(ownText);
if (matcher.matches()) {
String uri = matcher.group(2);
IAnker anker = new Anker(uri, new String[0], uri);
IAnker newAnker = this.createAnkerFromLabelProviders(anker);
if (newAnker == null) {
newAnker = anker;
}
String newHtml = e.html().replace(uri, newAnker.toHtml());
e.html(newHtml);
htmlChanged = true;
}
}
}
String newHtml = htmlChanged ? doc.body().children().toString() : html;
return newHtml;
}
public IAnker createAnkerFromLabelProviders(IAnker oldAnker) {
IAnker newAnker = null;
for (IAnkerLabelProvider ankerLabelProvider : this.ankerLabelProviders) {
if (ankerLabelProvider.isResponsible(oldAnker)) {
newAnker = new Anker(ankerLabelProvider.getHref(oldAnker),
ankerLabelProvider.getClasses(oldAnker),
ankerLabelProvider.getContent(oldAnker));
break;
}
}
return newAnker;
}
public ToolbarSet getToolbarSet() {
return this.toolbarSet;
}
/**
* Checks whether the current editor contents present changes when compared
* to the contents loaded into the editor at startup.
*
* @return
*/
public Boolean isDirty() {
Boolean isDirty = (Boolean) this.getBrowser().evaluate(
"return com.bkahlert.nebula.editor.isDirty();");
if (isDirty != null) {
return isDirty;
} else {
return null;
}
}
public void selectAll() {
this.run("com.bkahlert.nebula.editor.selectAll();");
}
public Future<Boolean> setSource(String html) {
return this.setSource(html, false);
}
public Future<Boolean> setSource(String html, boolean restoreSelection) {
/*
* do not wait for the delay to pass but invoke the task immediately
*/
synchronized (this) {
if (this.delayChangeTimerTask != null) {
this.delayChangeTimerTask.cancel();
this.delayChangeTimerTask.run();
this.delayChangeTimerTask = null;
}
}
this.oldHtml = html;
return this.run("return com.bkahlert.nebula.editor.setSource("
+ JSONUtils.enquote(html) + ", "
+ (restoreSelection ? "true" : "false") + ");",
IConverter.CONVERTER_BOOLEAN);
}
/**
* TODO use this.run
*
* @return
*/
public String getSource() {
if (!this.isLoadingCompleted()) {
return null;
}
String html = (String) this.getBrowser().evaluate(
"return com.bkahlert.nebula.editor.getSource();");
return html;
}
public void setMode(String mode) {
this.run("com.bkahlert.nebula.editor.setMode(\"" + mode + "\");");
}
public void showSource() {
this.setMode("source");
}
public void hideSource() {
this.setMode("wysiwyg");
}
public String getPrevCaretCharacter() {
if (!this.isLoadingCompleted()) {
return null;
}
String html = (String) this.getBrowser().evaluate(
"return com.bkahlert.nebula.editor.getPrevCaretCharacter();");
return html;
}
public void saveSelection() {
this.run("com.bkahlert.nebula.editor.saveSelection();");
}
public void restoreSelection() {
this.run("com.bkahlert.nebula.editor.restoreSelection();");
}
@Override
public void setEnabled(boolean isEnabled) {
this.run("return com.bkahlert.nebula.editor.setEnabled("
+ (isEnabled ? "true" : "false") + ");",
IConverter.CONVERTER_BOOLEAN);
}
@Override
public void setBackground(Color color) {
this.setBackground(color != null ? new RGB(color.getRGB()) : null);
}
public void setBackground(RGB rgb) {
String hex = rgb != null ? rgb.toHexString() : "transparent";
this.injectCss("html .cke_reset { background-color: " + hex + "; }");
}
public void addAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) {
this.ankerLabelProviders.add(ankerLabelProvider);
}
public void removeAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) {
this.ankerLabelProviders.remove(ankerLabelProvider);
}
/**
* Adds a {@link ModifyListener} to this {@link Image}.
* <p>
* Please note that {@link ModifyListener#modifyText(ModifyEvent)} is also
* fired when the {@link Image} is being disposed. This is the last
* opportunity to read the {@link Image}'s current demoAreaContent.
*
* @param modifyListener
*/
public void addModifyListener(ModifyListener modifyListener) {
this.modifyListeners.add(modifyListener);
}
/**
* Removes a {@link ModifyListener} from this {@link Image}.
*
* @param modifyListener
*/
public void removeModifyListener(ModifyListener modifyListener) {
this.modifyListeners.remove(modifyListener);
}
} |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Create By Qiujuer
* 2014-08-05
* <p/>
*
*/
public class ProcessModel {
private static final String TAG = "ProcessModel";
private static final int MAX_READ_ERROR = 10;
private static final String BREAK_LINE;
private static final byte[] BUFFER;
private static final int BUFFER_LENGTH;
private static final Lock LOCK = new ReentrantLock();
//ProcessBuilder
private static final ProcessBuilder PRC;
final private Process process;
final private InputStream in;
final private InputStream err;
final private OutputStream out;
final private StringBuilder sbReader;
private BufferedReader bInReader = null;
private InputStreamReader isInReader = null;
private boolean isDone;
private boolean isDestroy;
private int errorCount;
static {
BREAK_LINE = "\n";
BUFFER_LENGTH = 128;
BUFFER = new byte[BUFFER_LENGTH];
LOCK.lock();
PRC = new ProcessBuilder();
LOCK.unlock();
}
/**
* ProcessModel
*
* @param process Process
*/
private ProcessModel(Process process) {
//init
this.process = process;
//get
out = process.getOutputStream();
in = process.getInputStream();
err = process.getErrorStream();
if (in != null) {
isInReader = new InputStreamReader(in);
bInReader = new BufferedReader(isInReader, BUFFER_LENGTH);
}
sbReader = new StringBuilder();
//start read thread
readThread();
}
public static ProcessModel create(String... params) {
Process process = null;
try {
LOCK.lock();
process = PRC.command(params)
.redirectErrorStream(true)
.start();
} catch (IOException e) {
e.printStackTrace();
} finally {
//sleep 100
StaticFunction.sleepIgnoreInterrupt(100);
LOCK.unlock();
}
if (process == null)
return null;
return new ProcessModel(process);
}
/**
* Android
*
* @param process
*/
public static void kill(Process process) {
int pid = getProcessId(process);
if (pid != 0) {
try {
android.os.Process.killProcess(pid);
} catch (Exception e) {
try {
process.destroy();
} catch (Exception ex) {
//ex.printStackTrace();
}
}
}
}
/**
* ID
*
* @param process
* @return id
*/
public static int getProcessId(Process process) {
String str = process.toString();
try {
int i = str.indexOf("=") + 1;
int j = str.indexOf("]");
str = str.substring(i, j);
return Integer.parseInt(str);
} catch (Exception e) {
return 0;
}
}
private void read() {
String str;
//read In
try {
while ((str = bInReader.readLine()) != null) {
sbReader.append(str);
sbReader.append(BREAK_LINE);
}
} catch (Exception e) {
String err = e.getMessage();
if (err != null && err.length() > 0)
Logs.e(TAG, "Read Exception:" + err);
errorCount++;
}
}
private void readThread() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//while to end
while (true) {
try {
process.exitValue();
//read last
read();
break;
} catch (IllegalThreadStateException e) {
read();
if (isDestroy && errorCount > MAX_READ_ERROR){
break;
}
}
StaticFunction.sleepIgnoreInterrupt(300);
}
//read end
int len;
if (in != null) {
try {
while ((len = in.read(BUFFER)) > 0) {
Logs.d(TAG, "Read End:" + len);
}
} catch (IOException e) {
String err = e.getMessage();
if (err != null && err.length() > 0)
Logs.e(TAG, "Read Thread IOException:" + err);
}
}
//close
close();
//done
isDone = true;
}
});
thread.setName("DroidTestAgent.Test.TestModel.ProcessModel:ReadThread");
thread.setDaemon(true);
thread.start();
}
/**
*
*
* @return
*/
public String getResult() {
//waite process setValue
try {
process.waitFor();
} catch (InterruptedException e) {
String err = e.getMessage();
if (err != null && err.length() > 0)
Logs.e(TAG, "GetResult WaitFor InterruptedException:" + err);
}
//until startRead en
while (true) {
if (isDone)
break;
StaticFunction.sleepIgnoreInterrupt(100);
}
//return
if (sbReader.length() == 0)
return null;
else
return sbReader.toString();
}
private void close() {
//close out
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//err
if (err != null) {
try {
err.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (isInReader != null) {
try {
isInReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bInReader != null) {
try {
bInReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void destroy() {
//process
try {
process.destroy();
} catch (Exception e) {
kill(process);
}
isDestroy = true;
}
} |
package com.ecyrd.jspwiki.providers;
import com.ecyrd.jspwiki.WikiException;
/**
* This exception represents the superclass of all exceptions that providers
* may throw. It is okay to throw it in case you cannot use any of
* the specific subclasses, in which case the page loading is
* considered to be broken, and the user is notified.
*/
public class ProviderException
extends WikiException
{
public ProviderException( String msg )
{
super( msg );
}
} |
package com.esotericsoftware.kryo.io;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.util.UnsafeUtil;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
/** An OutputStream that buffers data in a byte array and optionally flushes to another OutputStream. Utility methods are provided
* for efficiently writing primitive types and strings.
*
* @author Roman Levenstein <romixlev@gmail.com> */
public class ByteBufferOutput extends Output {
protected ByteBuffer niobuffer;
protected boolean varIntsEnabled = true;
// Default byte order is BIG_ENDIAN to be compatible to the base class
ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
protected final static ByteOrder nativeOrder = ByteOrder.nativeOrder();
/** Creates an uninitialized Output. A buffer must be set before the Output is used.
* @see #setBuffer(ByteBuffer, int) */
public ByteBufferOutput () {
}
/** Creates a new Output for writing to a direct ByteBuffer.
* @param bufferSize The initial and maximum size of the buffer. An exception is thrown if this size is exceeded. */
public ByteBufferOutput (int bufferSize) {
this(bufferSize, bufferSize);
}
/** Creates a new Output for writing to a direct ByteBuffer.
* @param bufferSize The initial size of the buffer.
* @param maxBufferSize The buffer is doubled as needed until it exceeds maxBufferSize and an exception is thrown. */
public ByteBufferOutput (int bufferSize, int maxBufferSize) {
if (maxBufferSize < -1) throw new IllegalArgumentException("maxBufferSize cannot be < -1: " + maxBufferSize);
this.capacity = bufferSize;
this.maxCapacity = maxBufferSize == -1 ? Integer.MAX_VALUE : maxBufferSize;
niobuffer = ByteBuffer.allocateDirect(bufferSize);
niobuffer.order(byteOrder);
}
/** Creates a new Output for writing to an OutputStream. A buffer size of 4096 is used. */
public ByteBufferOutput (OutputStream outputStream) {
this(4096, 4096);
if (outputStream == null) throw new IllegalArgumentException("outputStream cannot be null.");
this.outputStream = outputStream;
}
/** Creates a new Output for writing to an OutputStream. */
public ByteBufferOutput (OutputStream outputStream, int bufferSize) {
this(bufferSize, bufferSize);
if (outputStream == null) throw new IllegalArgumentException("outputStream cannot be null.");
this.outputStream = outputStream;
}
/** Creates a new Output for writing to a ByteBuffer. */
public ByteBufferOutput (ByteBuffer buffer) {
setBuffer(buffer);
}
/** Creates a new Output for writing to a ByteBuffer.
* @param maxBufferSize The buffer is doubled as needed until it exceeds maxCapacity and an exception is thrown. */
public ByteBufferOutput (ByteBuffer buffer, int maxBufferSize) {
setBuffer(buffer, maxBufferSize);
}
/** Creates a direct ByteBuffer of a given size at a given address.
* <p>
* Typical usage could look like this snippet:
*
* <pre>
* // Explicitly allocate memory
* long bufAddress = UnsafeUtil.unsafe().allocateMemory(4096);
* // Create a ByteBufferOutput using the allocated memory region
* ByteBufferOutput buffer = new ByteBufferOutput(bufAddress, 4096);
*
* // Do some operations on this buffer here
*
* // Say that ByteBuffer won't be used anymore
* buffer.release();
* // Release the allocated region
* UnsafeUtil.unsafe().freeMemory(bufAddress);
* </pre>
* @param address starting address of a memory region pre-allocated using Unsafe.allocateMemory()
* @param maxBufferSize */
public ByteBufferOutput (long address, int maxBufferSize) {
niobuffer = UnsafeUtil.getDirectBufferAt(address, maxBufferSize);
setBuffer(niobuffer, maxBufferSize);
}
/** Release a direct buffer. {@link #setBuffer(ByteBuffer, int)} should be called before next write operations can be called.
*
* NOTE: If Cleaner is not accessible due to SecurityManager restrictions, reflection could be used to obtain the "clean"
* method and then invoke it. */
public void release () {
clear();
UnsafeUtil.releaseBuffer(niobuffer);
niobuffer = null;
}
public ByteOrder order () {
return byteOrder;
}
public void order (ByteOrder byteOrder) {
this.byteOrder = byteOrder;
}
public OutputStream getOutputStream () {
return outputStream;
}
/** Sets a new OutputStream. The position and total are reset, discarding any buffered bytes.
* @param outputStream May be null. */
public void setOutputStream (OutputStream outputStream) {
this.outputStream = outputStream;
position = 0;
total = 0;
}
/** Sets the buffer that will be written to. maxCapacity is set to the specified buffer's capacity.
* @see #setBuffer(ByteBuffer, int) */
public void setBuffer (ByteBuffer buffer) {
setBuffer(buffer, buffer.capacity());
}
/** Sets the buffer that will be written to. The byte order, position and capacity are set to match the specified buffer. The
* total is set to 0. The {@link #setOutputStream(OutputStream) OutputStream} is set to null.
* @param maxBufferSize The buffer is doubled as needed until it exceeds maxCapacity and an exception is thrown. */
public void setBuffer (ByteBuffer buffer, int maxBufferSize) {
if (buffer == null) throw new IllegalArgumentException("buffer cannot be null.");
if (maxBufferSize < -1) throw new IllegalArgumentException("maxBufferSize cannot be < -1: " + maxBufferSize);
this.niobuffer = buffer;
this.maxCapacity = maxBufferSize == -1 ? Integer.MAX_VALUE : maxBufferSize;
byteOrder = buffer.order();
capacity = buffer.capacity();
position = buffer.position();
total = 0;
outputStream = null;
}
/** Returns the buffer. The bytes between zero and {@link #position()} are the data that has been written. */
public ByteBuffer getByteBuffer () {
niobuffer.position(position);
return niobuffer;
}
/** Returns a new byte array containing the bytes currently in the buffer between zero and {@link #position()}. */
public byte[] toBytes () {
byte[] newBuffer = new byte[position];
niobuffer.position(0);
niobuffer.get(newBuffer, 0, position);
return newBuffer;
}
/** Sets the current position in the buffer. */
public void setPosition (int position) {
this.position = position;
}
/** Sets the position and total to zero. */
public void clear () {
niobuffer.clear();
position = 0;
total = 0;
}
/** @return true if the buffer has been resized. */
protected boolean require (int required) throws KryoException {
if (capacity - position >= required) return false;
if (required > maxCapacity)
throw new KryoException("Buffer overflow. Max capacity: " + maxCapacity + ", required: " + required);
flush();
while (capacity - position < required) {
if (capacity == maxCapacity)
throw new KryoException("Buffer overflow. Available: " + (capacity - position) + ", required: " + required);
// Grow buffer.
if (capacity == 0) capacity = 1;
capacity = Math.min(capacity * 2, maxCapacity);
if (capacity < 0) capacity = maxCapacity;
ByteBuffer newBuffer = (niobuffer != null && !niobuffer.isDirect()) ? ByteBuffer.allocate(capacity) : ByteBuffer
.allocateDirect(capacity);
// Copy the whole buffer
niobuffer.position(0);
niobuffer.limit(position);
newBuffer.put(niobuffer);
newBuffer.order(niobuffer.order());
setBuffer(newBuffer, maxCapacity);
}
return true;
}
// OutputStream
/** Writes the buffered bytes to the underlying OutputStream, if any. */
public void flush () throws KryoException {
if (outputStream == null) return;
try {
byte[] tmp = new byte[position];
niobuffer.position(0);
niobuffer.get(tmp);
niobuffer.position(0);
outputStream.write(tmp, 0, position);
} catch (IOException ex) {
throw new KryoException(ex);
}
total += position;
position = 0;
}
/** Flushes any buffered bytes and closes the underlying OutputStream, if any. */
public void close () throws KryoException {
flush();
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ignored) {
}
}
}
/** Writes a byte. */
public void write (int value) throws KryoException {
if (position == capacity) require(1);
niobuffer.put((byte)value);
position++;
}
/** Writes the bytes. Note the byte[] length is not written. */
public void write (byte[] bytes) throws KryoException {
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
writeBytes(bytes, 0, bytes.length);
}
/** Writes the bytes. Note the byte[] length is not written. */
public void write (byte[] bytes, int offset, int length) throws KryoException {
writeBytes(bytes, offset, length);
}
// byte
public void writeByte (byte value) throws KryoException {
if (position == capacity) require(1);
niobuffer.put(value);
position++;
}
public void writeByte (int value) throws KryoException {
if (position == capacity) require(1);
niobuffer.put((byte)value);
position++;
}
/** Writes the bytes. Note the byte[] length is not written. */
public void writeBytes (byte[] bytes) throws KryoException {
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
writeBytes(bytes, 0, bytes.length);
}
/** Writes the bytes. Note the byte[] length is not written. */
public void writeBytes (byte[] bytes, int offset, int count) throws KryoException {
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
int copyCount = Math.min(capacity - position, count);
while (true) {
niobuffer.put(bytes, offset, copyCount);
position += copyCount;
count -= copyCount;
if (count == 0) return;
offset += copyCount;
copyCount = Math.min(capacity, count);
require(copyCount);
}
}
// int
/** Writes a 4 byte int. */
public void writeInt (int value) throws KryoException {
require(4);
niobuffer.putInt(value);
position += 4;
}
public int writeInt (int value, boolean optimizePositive) throws KryoException {
if (!varIntsEnabled) {
writeInt(value);
return 4;
} else
return writeVarInt(value, optimizePositive);
}
public int writeVarInt (int val, boolean optimizePositive) throws KryoException {
niobuffer.position(position);
int value = val;
if (!optimizePositive) value = (value << 1) ^ (value >> 31);
int varInt = 0;
varInt = (value & 0x7F);
value >>>= 7;
if (value == 0) {
writeByte(varInt);
return 1;
}
varInt |= 0x80;
varInt |= ((value & 0x7F) << 8);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 2;
niobuffer.position(position);
return 2;
}
varInt |= (0x80 << 8);
varInt |= ((value & 0x7F) << 16);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 1;
niobuffer.position(position);
return 3;
}
varInt |= (0x80 << 16);
varInt |= ((value & 0x7F) << 24);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 0;
return 4;
}
varInt |= (0x80 << 24);
long varLong = (varInt & 0xFFFFFFFFL) | (((long)value) << 32);
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
position -= 3;
niobuffer.position(position);
return 5;
}
// string
/** Writes the length and string, or null. Short strings are checked and if ASCII they are written more efficiently, else they
* are written as UTF8. If a string is known to be ASCII, {@link #writeAscii(String)} may be used. The string can be read using
* {@link Input#readString()} or {@link Input#readStringBuilder()}.
* @param value May be null. */
public void writeString (String value) throws KryoException {
niobuffer.position(position);
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
// Detect ASCII.
boolean ascii = false;
if (charCount > 1 && charCount < 64) {
ascii = true;
for (int i = 0; i < charCount; i++) {
int c = value.charAt(i);
if (c > 127) {
ascii = false;
break;
}
}
}
if (ascii) {
if (capacity - position < charCount)
writeAscii_slow(value, charCount);
else {
byte[] tmp = value.getBytes();
niobuffer.put(tmp, 0, tmp.length);
position += charCount;
}
niobuffer.put(position - 1, (byte)(niobuffer.get(position - 1) | 0x80));
} else {
writeUtf8Length(charCount + 1);
int charIndex = 0;
if (capacity - position >= charCount) {
// Try to write 8 bit chars.
int position = this.position;
for (; charIndex < charCount; charIndex++) {
int c = value.charAt(charIndex);
if (c > 127) break;
niobuffer.put(position++, (byte)c);
}
this.position = position;
niobuffer.position(position);
}
if (charIndex < charCount) writeString_slow(value, charCount, charIndex);
niobuffer.position(position);
}
}
/** Writes the length and CharSequence as UTF8, or null. The string can be read using {@link Input#readString()} or
* {@link Input#readStringBuilder()}.
* @param value May be null. */
public void writeString (CharSequence value) throws KryoException {
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
writeUtf8Length(charCount + 1);
int charIndex = 0;
if (capacity - position >= charCount) {
// Try to write 8 bit chars.
int position = this.position;
for (; charIndex < charCount; charIndex++) {
int c = value.charAt(charIndex);
if (c > 127) break;
niobuffer.put(position++, (byte)c);
}
this.position = position;
niobuffer.position(position);
}
if (charIndex < charCount) writeString_slow(value, charCount, charIndex);
niobuffer.position(position);
}
/** Writes a string that is known to contain only ASCII characters. Non-ASCII strings passed to this method will be corrupted.
* Each byte is a 7 bit character with the remaining byte denoting if another character is available. This is slightly more
* efficient than {@link #writeString(String)}. The string can be read using {@link Input#readString()} or
* {@link Input#readStringBuilder()}.
* @param value May be null. */
public void writeAscii (String value) throws KryoException {
if (value == null) {
writeByte(0x80); // 0 means null, bit 8 means UTF8.
return;
}
int charCount = value.length();
if (charCount == 0) {
writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
return;
}
if (capacity - position < charCount)
writeAscii_slow(value, charCount);
else {
byte[] tmp = value.getBytes();
niobuffer.put(tmp, 0, tmp.length);
position += charCount;
}
niobuffer.put(position - 1, (byte)(niobuffer.get(position - 1) | 0x80)); // Bit 8 means end of ASCII.
}
/** Writes the length of a string, which is a variable length encoded int except the first byte uses bit 8 to denote UTF8 and
* bit 7 to denote if another byte is present. */
private void writeUtf8Length (int value) {
if (value >>> 6 == 0) {
require(1);
niobuffer.put((byte)(value | 0x80)); // Set bit 8.
position += 1;
} else if (value >>> 13 == 0) {
require(2);
niobuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
niobuffer.put((byte)(value >>> 6));
position += 2;
} else if (value >>> 20 == 0) {
require(3);
niobuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
niobuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
niobuffer.put((byte)(value >>> 13));
position += 3;
} else if (value >>> 27 == 0) {
require(4);
niobuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
niobuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
niobuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
niobuffer.put((byte)(value >>> 20));
position += 4;
} else {
require(5);
niobuffer.put((byte)(value | 0x40 | 0x80)); // Set bit 7 and 8.
niobuffer.put((byte)((value >>> 6) | 0x80)); // Set bit 8.
niobuffer.put((byte)((value >>> 13) | 0x80)); // Set bit 8.
niobuffer.put((byte)((value >>> 20) | 0x80)); // Set bit 8.
niobuffer.put((byte)(value >>> 27));
position += 5;
}
}
private void writeString_slow (CharSequence value, int charCount, int charIndex) {
for (; charIndex < charCount; charIndex++) {
if (position == capacity) require(Math.min(capacity, charCount - charIndex));
int c = value.charAt(charIndex);
if (c <= 0x007F) {
niobuffer.put(position++, (byte)c);
} else if (c > 0x07FF) {
niobuffer.put(position++, (byte)(0xE0 | c >> 12 & 0x0F));
require(2);
niobuffer.put(position++, (byte)(0x80 | c >> 6 & 0x3F));
niobuffer.put(position++, (byte)(0x80 | c & 0x3F));
} else {
niobuffer.put(position++, (byte)(0xC0 | c >> 6 & 0x1F));
require(1);
niobuffer.put(position++, (byte)(0x80 | c & 0x3F));
}
}
}
private void writeAscii_slow (String value, int charCount) throws KryoException {
ByteBuffer buffer = this.niobuffer;
int charIndex = 0;
int charsToWrite = Math.min(charCount, capacity - position);
while (charIndex < charCount) {
byte[] tmp = new byte[charCount];
value.getBytes(charIndex, charIndex + charsToWrite, tmp, 0);
buffer.put(tmp, 0, charsToWrite);
// value.getBytes(charIndex, charIndex + charsToWrite, buffer, position);
charIndex += charsToWrite;
position += charsToWrite;
charsToWrite = Math.min(charCount - charIndex, capacity);
if (require(charsToWrite)) buffer = this.niobuffer;
}
}
// float
/** Writes a 4 byte float. */
public void writeFloat (float value) throws KryoException {
require(4);
niobuffer.putFloat(value);
position += 4;
}
/** Writes a 1-5 byte float with reduced precision.
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (5 bytes). */
public int writeFloat (float value, float precision, boolean optimizePositive) throws KryoException {
return writeInt((int)(value * precision), optimizePositive);
}
// short
/** Writes a 2 byte short. */
public void writeShort (int value) throws KryoException {
require(2);
niobuffer.putShort((short)value);
position += 2;
}
// long
/** Writes an 8 byte long. */
public void writeLong (long value) throws KryoException {
require(8);
niobuffer.putLong(value);
position += 8;
}
public int writeLong (long value, boolean optimizePositive) throws KryoException {
if (!varIntsEnabled) {
writeLong(value);
return 8;
} else
return writeVarLong(value, optimizePositive);
}
public int writeVarLong (long value, boolean optimizePositive) throws KryoException {
if (!optimizePositive) value = (value << 1) ^ (value >> 63);
int varInt = 0;
varInt = (int)(value & 0x7F);
value >>>= 7;
if (value == 0) {
writeByte(varInt);
return 1;
}
varInt |= 0x80;
varInt |= ((value & 0x7F) << 8);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 2;
niobuffer.position(position);
return 2;
}
varInt |= (0x80 << 8);
varInt |= ((value & 0x7F) << 16);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 1;
niobuffer.position(position);
return 3;
}
varInt |= (0x80 << 16);
varInt |= ((value & 0x7F) << 24);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 0;
return 4;
}
varInt |= (0x80 << 24);
long varLong = (varInt & 0xFFFFFFFFL);
varLong |= (((long)(value & 0x7F)) << 32);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
position -= 3;
niobuffer.position(position);
return 5;
}
varLong |= (0x80L << 32);
varLong |= (((long)(value & 0x7F)) << 40);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
position -= 2;
niobuffer.position(position);
return 6;
}
varLong |= (0x80L << 40);
varLong |= (((long)(value & 0x7F)) << 48);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
position -= 1;
niobuffer.position(position);
return 7;
}
varLong |= (0x80L << 48);
varLong |= (((long)(value & 0x7F)) << 56);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
return 8;
}
varLong |= (0x80L << 56);
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
write((byte)(value));
return 9;
}
/** Writes a 1-9 byte long.
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (9 bytes). */
public int writeLongS (long value, boolean optimizePositive) throws KryoException {
if (!optimizePositive) value = (value << 1) ^ (value >> 63);
if (value >>> 7 == 0) {
require(1);
niobuffer.put((byte)value);
position += 1;
return 1;
}
if (value >>> 14 == 0) {
require(2);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7));
position += 2;
return 2;
}
if (value >>> 21 == 0) {
require(3);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7 | 0x80));
niobuffer.put((byte)(value >>> 14));
position += 3;
return 3;
}
if (value >>> 28 == 0) {
require(4);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7 | 0x80));
niobuffer.put((byte)(value >>> 14 | 0x80));
niobuffer.put((byte)(value >>> 21));
position += 4;
return 4;
}
if (value >>> 35 == 0) {
require(5);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7 | 0x80));
niobuffer.put((byte)(value >>> 14 | 0x80));
niobuffer.put((byte)(value >>> 21 | 0x80));
niobuffer.put((byte)(value >>> 28));
position += 5;
return 5;
}
if (value >>> 42 == 0) {
require(6);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7 | 0x80));
niobuffer.put((byte)(value >>> 14 | 0x80));
niobuffer.put((byte)(value >>> 21 | 0x80));
niobuffer.put((byte)(value >>> 28 | 0x80));
niobuffer.put((byte)(value >>> 35));
position += 6;
return 6;
}
if (value >>> 49 == 0) {
require(7);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7 | 0x80));
niobuffer.put((byte)(value >>> 14 | 0x80));
niobuffer.put((byte)(value >>> 21 | 0x80));
niobuffer.put((byte)(value >>> 28 | 0x80));
niobuffer.put((byte)(value >>> 35 | 0x80));
niobuffer.put((byte)(value >>> 42));
position += 7;
return 7;
}
if (value >>> 56 == 0) {
require(8);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7 | 0x80));
niobuffer.put((byte)(value >>> 14 | 0x80));
niobuffer.put((byte)(value >>> 21 | 0x80));
niobuffer.put((byte)(value >>> 28 | 0x80));
niobuffer.put((byte)(value >>> 35 | 0x80));
niobuffer.put((byte)(value >>> 42 | 0x80));
niobuffer.put((byte)(value >>> 49));
position += 8;
return 8;
}
require(9);
niobuffer.put((byte)((value & 0x7F) | 0x80));
niobuffer.put((byte)(value >>> 7 | 0x80));
niobuffer.put((byte)(value >>> 14 | 0x80));
niobuffer.put((byte)(value >>> 21 | 0x80));
niobuffer.put((byte)(value >>> 28 | 0x80));
niobuffer.put((byte)(value >>> 35 | 0x80));
niobuffer.put((byte)(value >>> 42 | 0x80));
niobuffer.put((byte)(value >>> 49 | 0x80));
niobuffer.put((byte)(value >>> 56));
position += 9;
return 9;
}
// boolean
/** Writes a 1 byte boolean. */
public void writeBoolean (boolean value) throws KryoException {
require(1);
niobuffer.put((byte)(value ? 1 : 0));
position++;
}
// char
/** Writes a 2 byte char. */
public void writeChar (char value) throws KryoException {
require(2);
niobuffer.putChar(value);
position += 2;
}
// double
/** Writes an 8 byte double. */
public void writeDouble (double value) throws KryoException {
require(8);
niobuffer.putDouble(value);
position += 8;
}
/** Writes a 1-9 byte double with reduced precision.
* @param optimizePositive If true, small positive numbers will be more efficient (1 byte) and small negative numbers will be
* inefficient (9 bytes). */
public int writeDouble (double value, double precision, boolean optimizePositive) throws KryoException {
return writeLong((long)(value * precision), optimizePositive);
}
// Methods implementing bulk operations on arrays of primitive types
/** Bulk output of an int array. */
public void writeInts (int[] object) throws KryoException {
if (capacity - position >= object.length * 4 && isNativeOrder()) {
IntBuffer buf = niobuffer.asIntBuffer();
buf.put(object);
position += object.length * 4;
} else
super.writeInts(object);
}
/** Bulk output of an long array. */
public void writeLongs (long[] object) throws KryoException {
if (capacity - position >= object.length * 8 && isNativeOrder()) {
LongBuffer buf = niobuffer.asLongBuffer();
buf.put(object);
position += object.length * 8;
} else
super.writeLongs(object);
}
/** Bulk output of a float array. */
public void writeFloats (float[] object) throws KryoException {
if (capacity - position >= object.length * 4 && isNativeOrder()) {
FloatBuffer buf = niobuffer.asFloatBuffer();
buf.put(object);
position += object.length * 4;
} else
super.writeFloats(object);
}
/** Bulk output of a short array. */
public void writeShorts (short[] object) throws KryoException {
if (capacity - position >= object.length * 2 && isNativeOrder()) {
ShortBuffer buf = niobuffer.asShortBuffer();
buf.put(object);
position += object.length * 2;
} else
super.writeShorts(object);
}
/** Bulk output of a char array. */
public void writeChars (char[] object) throws KryoException {
if (capacity - position >= object.length * 2 && isNativeOrder()) {
CharBuffer buf = niobuffer.asCharBuffer();
buf.put(object);
position += object.length * 2;
} else
super.writeChars(object);
}
/** Bulk output of a double array. */
public void writeDoubles (double[] object) throws KryoException {
if (capacity - position >= object.length * 8 && isNativeOrder()) {
DoubleBuffer buf = niobuffer.asDoubleBuffer();
buf.put(object);
position += object.length * 8;
} else
super.writeDoubles(object);
}
private boolean isNativeOrder () {
return byteOrder == nativeOrder;
}
/** Return current setting for variable length encoding of integers
* @return current setting for variable length encoding of integers */
public boolean getVarIntsEnabled () {
return varIntsEnabled;
}
/** Controls if a variable length encoding for integer types should be used when serializers suggest it.
*
* @param varIntsEnabled */
public void setVarIntsEnabled (boolean varIntsEnabled) {
this.varIntsEnabled = varIntsEnabled;
}
} |
package com.gmail.liamgomez75.parkourroll;
import com.gmail.liamgomez75.parkourroll.listeners.DamageListener;
import com.gmail.liamgomez75.parkourroll.localisation.Localisable;
import com.gmail.liamgomez75.parkourroll.localisation.Localisation;
import com.gmail.liamgomez75.parkourroll.localisation.LocalisationEntry;
import com.gmail.liamgomez75.parkourroll.utils.EXPConfigUtils;
import com.gmail.liamgomez75.parkourroll.utils.LevelConfigUtils;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Parkour Roll plugin for Bukkit.
*
* @author Liam Gomez <liamgomez75.gmail.com>
* @author JamesHealey94 <jameshealey1994.gmail.com>
*/
public class ParkourRoll extends JavaPlugin implements Localisable {
/**
* The current localisation for the plugin.
*/
private Localisation localisation = new Localisation(this);
@Override
public void onEnable() {
final DamageListener fallDamage = new DamageListener(this);
getServer().getPluginManager().registerEvents(fallDamage, this);
saveDefaultConfig();
}
/**
* Executes the command.
*
* @param sender sender of the command
* @param cmd command sent
* @param commandLabel exact command string sent
* @param args arguments given with the command
* @return if the command was executed correctly
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("Parkourroll")) {
if (args.length > 0) {
if ((args[0].equalsIgnoreCase("reload"))) {
return reload(sender);
} else if ((args[0].equalsIgnoreCase("level"))) {
if(sender instanceof Player) {
Player p = (Player) sender;
World world = p.getWorld();
int lvlNum = LevelConfigUtils.getPlayerLevel(p,world,this);
int expNum = EXPConfigUtils.getPlayerExp(p,world,this);
int reqExp = this.getConfig().getInt("Level." + lvlNum + ".Exp Required");
sender.sendMessage("You are level " + lvlNum + ".");
sender.sendMessage("Exp: " + expNum + "/" + reqExp);
return true;
} else {
sender.sendMessage("You can't run that command from the console!");
}
}
}
}
return false;
}
public boolean reload(CommandSender sender) {
if (sender.hasPermission("pkr.admin")) {
reloadConfig();
sender.sendMessage(localisation.get(LocalisationEntry.MSG_CONFIG_RELOADED));
return true;
} else {
sender.sendMessage(localisation.get(LocalisationEntry.ERR_PERMISSION_DENIED));
}
return false;
}
@Override
public Localisation getLocalisation() {
return localisation;
}
@Override
public void setLocalisation(Localisation localisation) {
this.localisation = localisation;
}
} |
package com.haxademic.sketch.particle;
import java.util.ArrayList;
import processing.core.PVector;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.util.DrawUtil;
import com.haxademic.core.draw.util.OpenGLUtil;
import com.haxademic.core.image.filters.FXAAFilter;
import com.haxademic.core.math.easing.EasingFloat;
@SuppressWarnings("serial")
public class VectorFieldTest
extends PAppletHax
{
protected ArrayList<PVector> _vectorField;
protected ArrayList<FieldParticle> _particles;
public static void main(String args[]) {
_hasChrome = false;
PAppletHax.main(P.concat(args, new String[] { "--hide-stop", "--bgcolor=000000", Thread.currentThread().getStackTrace()[1].getClassName() }));
}
protected void overridePropsFile() {
_appConfig.setProperty( "width", "1280" );
_appConfig.setProperty( "height", "720" );
_appConfig.setProperty( "fills_screen", "true" );
_appConfig.setProperty( "force_foreground", "true" );
// _appConfig.setProperty( "fps", "30" );
// _appConfig.setProperty( "rendering", "true" );
}
public void setup() {
super.setup();
p.smooth(OpenGLUtil.SMOOTH_LOW);
// p.smooth();
_vectorField = new ArrayList<PVector>();
float spacing = 100f;
for( int x = 0; x <= p.width; x += spacing ) {
for( int y = 0; y <= p.height; y += spacing ) {
_vectorField.add( new PVector(x, y, 0) );
}
}
_particles = new ArrayList<FieldParticle>();
for( int i = 0; i < 6000; i++ ) {
_particles.add( new FieldParticle() );
}
}
public void drawApp() {
if( p.frameCount == 1 ) p.background(0);
// OpenGLUtil.setBlending(p.g, true);
// OpenGLUtil.setBlendMode(p.g, OpenGLUtil.Blend.ADDITIVE);
// fade out background
DrawUtil.setDrawCorner(p);
p.noStroke();
p.fill(0, 20);
p.rect(0,0,p.width, p.height);
// draw field
DrawUtil.setDrawCenter(p);
p.fill(255);
for (PVector vector : _vectorField) {
float noise = p.noise(
vector.x/11f + p.noise(p.frameCount/100f),
vector.y/20f + p.noise(p.frameCount/50f)
);
vector.set(vector.x, vector.y, noise * 2f * P.TWO_PI);
// draw attractors
p.pushMatrix();
p.translate(vector.x, vector.y);
p.rotate( vector.z ); // use z for rotation!
p.rect(0, 0, 1, 10);
p.popMatrix();
}
// draw particles
DrawUtil.setDrawCenter(p);
for( int i = 0; i < _particles.size(); i++ ) {
p.fill((i % 150 + 55 / 10), i % 155 + 100, i % 100 + 100);
_particles.get(i).update( _vectorField );
}
FXAAFilter.applyTo(p, p.g);
}
public class FieldParticle {
public PVector position;
public EasingFloat radians;
public float speed;
public FieldParticle() {
speed = p.random(10,20);
radians = new EasingFloat(0, p.random(6,20) );
position = new PVector( p.random(0, p.width), p.random(0, p.height) );
}
public void update( ArrayList<PVector> vectorField ) {
// adjust to surrounding vectors
int closeVectors = 0;
float averageDirection = 0;
for (PVector vector : _vectorField) {
if( vector.dist( position ) < 100 ) {
averageDirection += vector.z;
closeVectors++;
}
}
if( closeVectors > 0 ) {
if( p.frameCount == 1 ) {
radians.setCurrent( -averageDirection / closeVectors );
} else {
radians.setTarget( -averageDirection / closeVectors );
}
}
radians.update();
// update position
position.set( position.x + P.sin(radians.value()) * speed, position.y + P.cos(radians.value()) * speed );
if( position.x < 0 ) position.set( p.width, position.y );
if( position.x > p.width ) position.set( 0, position.y );
if( position.y < 0 ) position.set( position.x, p.height );
if( position.y > p.height ) position.set( position.x, 0 );
// draw
p.pushMatrix();
p.translate(position.x, position.y);
p.rotate( -radians.value() );
p.rect(0, 0, speed * 0.2f, speed * 1.8f);
p.popMatrix();
}
}
} |
package com.iskrembilen.quasseldroid.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import com.iskrembilen.quasseldroid.Buffer;
import com.iskrembilen.quasseldroid.IrcMessage;
import com.iskrembilen.quasseldroid.NetworkCollection;
import com.iskrembilen.quasseldroid.R;
public class MessageUtil {
private static final String TAG = MessageUtil.class.getSimpleName();
/**
* Checks if there is a highlight in the message and then sets the flag of
* that message to highlight
*
* @param buffer
* the buffer the message belongs to
* @param message
* the message to check
*/
public static void checkMessageForHighlight(String nick, Buffer buffer, IrcMessage message) {
if (message.type == IrcMessage.Type.Plain || message.type == IrcMessage.Type.Action) {
if(nick == null) {
Log.e(TAG, "Nick is null in check message for highlight");
return;
} else if(nick.equals("")) return;
Pattern regexHighlight = Pattern.compile(".*(?<!(\\w|\\d))" + Pattern.quote(nick) + "(?!(\\w|\\d)).*", Pattern.CASE_INSENSITIVE);
Matcher matcher = regexHighlight.matcher(message.content);
if (matcher.find()) {
message.setFlag(IrcMessage.Flag.Highlight);
// FIXME: move to somewhere proper
}
}
}
/**
* Parse mIRC style codes in IrcMessage
*/
public static void parseStyleCodes(Context context, IrcMessage message) {
final char boldIndicator = 2;
final char normalIndicator = 15;
final char italicIndicator = 29;
final char underlineIndicator = 31;
final char colorIndicator = 3;
String content = message.content.toString();
if (content.indexOf(boldIndicator) == -1
&& content.indexOf(italicIndicator) == -1
&& content.indexOf(underlineIndicator) == -1
&& content.indexOf(colorIndicator) == -1)
return;
SpannableStringBuilder newString = new SpannableStringBuilder(message.content);
int start, end, endSearchOffset, startIndicatorLength, style, fg, bg;
while (true) {
content = newString.toString();
end = -1;
startIndicatorLength = 1;
style = 0;
fg = -1;
bg = -1;
start = content.indexOf(boldIndicator);
if (start != -1) {
end = content.indexOf(boldIndicator, start+1);
style = Typeface.BOLD;
}
if (start == -1) {
start = content.indexOf(italicIndicator);
if (start != -1) {
end = content.indexOf(italicIndicator, start+1);
style = Typeface.ITALIC;
}
}
if (start == -1) {
start = content.indexOf(underlineIndicator);
if (start != -1) {
end = content.indexOf(underlineIndicator, start+1);
style = -1;
}
}
endSearchOffset = start + 1;
// Colors?
if (start == -1) {
start = content.indexOf(colorIndicator);
if (start != -1) {
// Note that specifying colour codes here is optional, as the same indicator will cancel existing colours
endSearchOffset = start + 1;
if (endSearchOffset < content.length()) {
if (Character.isDigit(content.charAt(endSearchOffset))) {
if (endSearchOffset+1 < content.length() && Character.isDigit(content.charAt(endSearchOffset + 1))) {
fg = Integer.parseInt(content.substring(endSearchOffset, endSearchOffset + 2));
endSearchOffset += 2;
} else {
fg = Integer.parseInt(content.substring(endSearchOffset, endSearchOffset+1));
endSearchOffset += 1;
}
if (endSearchOffset < content.length() && content.charAt(endSearchOffset) == ',') {
if (endSearchOffset+1 < content.length() && Character.isDigit(content.charAt(endSearchOffset+1))) {
endSearchOffset++;
if (endSearchOffset+1 < content.length() && Character.isDigit(content.charAt(endSearchOffset + 1))) {
bg = Integer.parseInt(content.substring(endSearchOffset, endSearchOffset + 2));
endSearchOffset += 2;
} else {
bg = Integer.parseInt(content.substring(endSearchOffset, endSearchOffset + 1));
endSearchOffset += 1;
}
}
}
}
}
startIndicatorLength = endSearchOffset - start;
end = content.indexOf(colorIndicator, endSearchOffset);
}
}
if (start == -1)
break;
int norm = content.indexOf(normalIndicator, start+1);
if (norm != -1 && (end == -1 || norm < end))
end = norm;
if (end == -1)
end = content.length();
if (end - (start + startIndicatorLength) > 0) {
// Only set spans if there's any text between start & end
if (style == -1) {
newString.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
} else {
newString.setSpan(new StyleSpan(style), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (fg != -1) {
newString.setSpan(new ForegroundColorSpan(context.getResources()
.getColor(mircCodeToColor(fg))), start, end,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (bg != -1) {
newString.setSpan(new BackgroundColorSpan(context.getResources()
.getColor(mircCodeToColor(bg))), start, end,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
// Intentionally don't remove "normal" indicators or color here, as they are multi-purpose
if (end < content.length() && (content.charAt(end) == boldIndicator
|| content.charAt(end) == italicIndicator
|| content.charAt(end) == underlineIndicator))
newString.delete(end, end+1);
newString.delete(start, start + startIndicatorLength);
}
// NOW we remove the "normal" and color indicator
while (true) {
content = newString.toString();
int normPos = content.indexOf(normalIndicator);
if (normPos != -1)
newString.delete(normPos, normPos+1);
int colorPos = content.indexOf(colorIndicator);
if (colorPos != -1)
newString.delete(colorPos, colorPos+1);
if (normPos == -1 && colorPos == -1)
break;
}
message.content = newString;
}
public static int mircCodeToColor(int code) {
int color;
switch (code) {
case 0: // white
color = R.color.ircmessage_white;
break;
case 1: // black
color = R.color.ircmessage_black;
break;
case 2: // blue (navy)
color = R.color.ircmessage_blue;
break;
case 3: // green
color = R.color.ircmessage_green;
break;
case 4: // red
color = R.color.ircmessage_red;
break;
case 5: // brown (maroon)
color = R.color.ircmessage_brown;
break;
case 6: // purple
color = R.color.ircmessage_purple;
break;
case 7: // orange (olive)
color = R.color.ircmessage_orange;
break;
case 8: // yellow
color = R.color.ircmessage_yellow;
break;
case 9: // light green (lime)
color = R.color.ircmessage_light_green;
break;
case 10: // teal (a green/blue cyan)
color = R.color.ircmessage_teal;
break;
case 11: // light cyan (cyan) (aqua)
color = R.color.ircmessage_light_cyan;
break;
case 12: // light blue (royal)
color = R.color.ircmessage_light_blue;
break;
case 13: // pink (light purple) (fuchsia)
color = R.color.ircmessage_pink;
break;
case 14: // grey
color = R.color.ircmessage_gray;
break;
default:
color = ThemeUtil.chatPlainResource;
}
return color;
}
} |
package com.jme.scene.model.XMLparser;
import com.jme.scene.*;
import com.jme.scene.model.JointMesh2;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.LightState;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.math.Vector2f;
import com.jme.renderer.ColorRGBA;
import com.jme.animation.VertexKeyframeController;
import com.jme.animation.JointController;
import com.jme.animation.KeyframeController;
import com.jme.animation.SpatialTransformer;
import com.jme.light.Light;
import com.jme.light.SpotLight;
import com.jme.light.PointLight;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.*;
import java.net.URL;
public class JmeBinaryWriter {
private DataOutputStream myOut;
private static final boolean DEBUG=false;
/**
* These are the Spatial,RenderState,Controller that occur twice in the file. They
* are saved as shares to better reflect how the file currently is
*/
private IdentityHashMap sharedObjects=new IdentityHashMap(20);
/** Contains the address of every Spatial, RenderState, Controller in the scene. Whenever
* an address is entered twice, it is sent to sharedObjects
*/
private IdentityHashMap entireScene=new IdentityHashMap(256);
private static final Quaternion DEFAULT_ROTATION=new Quaternion();
private static final Vector3f DEFAULT_TRANSLATION = new Vector3f();
private static final Vector3f DEFAULT_SCALE = new Vector3f(1,1,1);
/**
* Holds properties that modify how JmeBinaryWriter writes a file.
*/
private HashMap properties=new HashMap();
/**
* Creates a new Binary Writer.
*/
public JmeBinaryWriter(){
}
/**
* Converts a given node to jME's binary format.
* @param scene The node to save
* @param bin The OutputStream that will store the binary format
* @throws IOException If anything wierd happens.
*/
public void writeScene(Node scene,OutputStream bin) throws IOException {
myOut=new DataOutputStream(bin);
sharedObjects.clear();
entireScene.clear();
writeHeader();
findDuplicates(scene);
writeDuplicates();
writeNode(scene);
writeClosing();
myOut.close();
}
/**
* All objects that are twice in the file are written as shared types.
* @throws IOException
*/
private void writeDuplicates() throws IOException {
if (sharedObjects.size()==0)
return;
// IdentityHashMap temp=sharedObjects;
// sharedObjects=new IdentityHashMap();
writeTag("sharedtypes",null);
List l=new ArrayList(sharedObjects.keySet());
HashMap atts=new HashMap();
for (int i=0;i<l.size();i++){ // write renderstates first
atts.clear();
Object thisType=l.get(i);
String name=(String) sharedObjects.get(thisType);
atts.put("ident",name);
if (thisType instanceof RenderState){
writeTag("sharedrenderstate",atts);
sharedObjects.remove(thisType);
writeRenderState((RenderState) thisType);
sharedObjects.put(thisType,name);
writeEndTag("sharedrenderstate");
}
}
for (int i=0;i<l.size();i++){ // write Meshes second
atts.clear();
Object thisType=l.get(i);
String name=(String) sharedObjects.get(thisType);
atts.put("ident",name);
if (thisType instanceof TriMesh){
writeTag("sharedtrimesh",atts);
sharedObjects.remove(thisType);
writeMesh((TriMesh) thisType);
sharedObjects.put(thisType,name);
writeEndTag("sharedtrimesh");
}
}
for (int i=0;i<l.size();i++){ // write Nodes third
atts.clear();
Object thisType=l.get(i);
String name=(String) sharedObjects.get(thisType);
atts.put("ident",name);
if (thisType instanceof Node){
writeTag("sharednode",atts);
sharedObjects.remove(thisType);
writeNode((Node) thisType);
sharedObjects.put(thisType,name);
writeEndTag("sharednode");
}
}
writeEndTag("sharedtypes");
// sharedObjects=temp;
}
/**
* Looks to see if the given Spatial is already contained in the entireScene.
* If it is, then place it in sharedObjects. If not, then look thru its Controllers/RenderStates
* and also look thru its children if it is a Node
* @param n Spatial to look at
*/
private void findDuplicates(Spatial n) {
if (n==null) return;
if (entireScene.containsKey(n)){
sharedObjects.put(n,entireScene.get(n));
return;
} else{
entireScene.put(n,n.getName());
}
evaluateSpatialChildrenDuplicates(n);
if (n instanceof Node){
Node newN=(Node)n;
for (int i=0;i<newN.getQuantity();i++)
findDuplicates(newN.getChild(i));
}
}
/**
* Looks for duplicate RenderStates and Controllers in a Spatial. If they are there,
* place them in then sharedObjects
* @param s The spatial to examine.
*/
private void evaluateSpatialChildrenDuplicates(Spatial s) {
if (s==null) return;
for (int i=0;i<s.getControllers().size();i++){
Controller evaluCont=s.getController(i);
if (evaluCont==null) continue;
if (evaluCont instanceof SpatialTransformer){
for (int j=0;j<((SpatialTransformer)evaluCont).toChange.length;j++){
findDuplicateObjects(((SpatialTransformer)evaluCont).toChange[j]);
}
}
if (entireScene.containsKey(evaluCont))
sharedObjects.put(evaluCont,entireScene.get(evaluCont));
else
entireScene.put(evaluCont,"controller"+(s.hashCode()*evaluCont.hashCode()));
}
for (int i=0;i<s.getRenderStateList().length;i++){
RenderState evaluRend=s.getRenderStateList()[i];
if (evaluRend==null) continue;
if (entireScene.containsKey(evaluRend))
sharedObjects.put(evaluRend,entireScene.get(evaluRend));
else
entireScene.put(evaluRend,"RenderState"+(s.hashCode()*evaluRend.hashCode()));
}
}
private void findDuplicateObjects(Object n) {
if (n instanceof Spatial)
findDuplicates((Spatial)n);
}
/**
* Converts a given Geometry to jME's binary format.
* @param geo The Geometry to save
* @param bin The OutputStream that will store the binary format
* @throws IOException If anything wierd happens.
*/
public void writeScene(Geometry geo,OutputStream bin) throws IOException {
myOut=new DataOutputStream(bin);
sharedObjects.clear();
entireScene.clear();
writeHeader();
findDuplicates(geo);
writeSpatial(geo);
writeClosing();
myOut.close();
}
/**
* Writes a node to binary format.
* @param node The node to write
* @throws IOException If anything bad happens.
*/
private void writeNode(Node node) throws IOException {
HashMap atts=new HashMap();
atts.clear();
putSpatialAtts(node,atts);
writeTag("node",atts);
writeChildren(node);
writeSpatialChildren(node);
writeEndTag("node");
}
/**
* Writes a Node's children. writeSpatial is called on each child
* @param node The node who's children you want to write
* @throws IOException
*/
private void writeChildren(Node node) throws IOException {
for (int i=0;i<node.getQuantity();i++)
writeSpatial(node.getChild(i));
}
/**
* Writes a Spatial to binary format.
* @param s The spatial to write
* @throws IOException
*/
private void writeSpatial(Spatial s) throws IOException {
if (sharedObjects.containsKey(s)){
writePublicObject(s);
return;
}
if (s instanceof XMLloadable)
writeXMLloadable((XMLloadable)s);
else if (s instanceof LoaderNode)
writeLoaderNode((LoaderNode)s);
else if (s instanceof JointMesh2)
writeJointMesh((JointMesh2)s);
else if (s instanceof Node)
writeNode((Node) s);
else if (s instanceof TriMesh)
writeMesh((TriMesh)s);
}
private void writeLoaderNode(LoaderNode loaderNode) throws IOException {
HashMap atts=new HashMap();
atts.clear();
atts.put("type",loaderNode.type);
if (loaderNode.filePath!=null)
atts.put("file",loaderNode.filePath);
else if (loaderNode.urlPath!=null)
atts.put("url",loaderNode.urlPath);
else if (loaderNode.classLoaderPath!=null)
atts.put("classloader",loaderNode.classLoaderPath);
writeTag("jmefile",atts);
writeEndTag("jmefile");
}
/**
* Writes a mesh to binary format.
* @param triMesh The mesh to write
* @throws IOException
*/
private void writeMesh(TriMesh triMesh) throws IOException {
if (triMesh==null) return;
if (sharedObjects.containsKey(triMesh)){
writePublicObject(triMesh);
return;
}
HashMap atts=new HashMap();
atts.clear();
putSpatialAtts(triMesh,atts);
writeTag("mesh",atts);
writeTriMeshTags(triMesh);
writeSpatialChildren(triMesh);
writeEndTag("mesh");
}
/**
* Writes a JointMesh2 to binary format.
* @param jointMesh The JointMesh to write
* @throws IOException
*/
private void writeJointMesh(JointMesh2 jointMesh) throws IOException {
if ("astrimesh".equals(properties.get("jointmesh"))){
writeMesh(jointMesh);
return;
}
int i;
for (i=0;i<jointMesh.jointIndex.length;i++)
if (jointMesh.jointIndex[i]!=-1) break;
if (i==jointMesh.jointIndex.length){ // if the mesh has no joint parents, I just write it as a TriMesh
writeMesh(jointMesh);
return;
}
HashMap atts=new HashMap();
atts.clear();
putSpatialAtts(jointMesh,atts);
writeTag("jointmesh",atts);
writeJointMeshTags(jointMesh);
writeSpatialChildren(jointMesh);
writeEndTag("jointmesh");
}
/**
* Writes the inner tags of a JointMesh2 to binary format.
* @param jointMesh Mesh who's tags are to be written
* @throws IOException
*/
private void writeJointMeshTags(JointMesh2 jointMesh) throws IOException {
HashMap atts=new HashMap();
atts.clear();
atts.put("data",jointMesh.jointIndex);
writeTag("jointindex",atts);
writeEndTag("jointindex");
atts.clear();
atts.put("data",jointMesh.originalVertex);
writeTag("origvertex",atts);
writeEndTag("origvertex");
atts.clear();
atts.put("data",jointMesh.originalNormal);
writeTag("orignormal",atts);
writeEndTag("orignormal");
writeTriMeshTags(jointMesh);
}
/**
* Writes an XMLloadable class to binary format.
* @param xmlloadable The class to write
* @throws IOException
*/
private void writeXMLloadable(XMLloadable xmlloadable) throws IOException {
HashMap atts=new HashMap();
atts.put("class",xmlloadable.getClass().getName());
if (xmlloadable instanceof Spatial)
putSpatialAtts((Spatial) xmlloadable,atts);
atts.put("args",xmlloadable.writeToXML());
writeTag("xmlloadable",atts);
if (xmlloadable instanceof Spatial)
writeSpatialChildren((Spatial) xmlloadable);
if (xmlloadable instanceof Node)
writeChildren((Node) xmlloadable);
writeEndTag("xmlloadable");
}
/**
* Writes a spatial's children (RenderStates and Controllers) to binary format.
* @param spatial Spatial to write
* @throws IOException
*/
private void writeSpatialChildren(Spatial spatial) throws IOException {
writeRenderStates(spatial);
writeControllers(spatial);
}
/**
* Writes a Controller acording to which type of controller it is. Only writes
* known controllers
* @param spatial The spatial who's controllers need to be written
* @throws IOException
*/
private void writeControllers(Spatial spatial) throws IOException {
ArrayList conts=spatial.getControllers();
if (conts==null) return;
for (int i=0;i<conts.size();i++){
Controller r=(Controller) conts.get(i);
if (r instanceof JointController){
writeJointController((JointController)r);
} else if (r instanceof SpatialTransformer){
writeSpatialTransformer((SpatialTransformer)r);
} else if (r instanceof KeyframeController){
writeKeyframeController((KeyframeController)r);
}
}
}
private void writeSpatialTransformer(SpatialTransformer st) throws IOException {
HashMap atts=new HashMap();
atts.clear();
atts.put("numobjects",new Integer(st.getNumObjects()));
writeTag("spatialtransformer",atts);
for (int i=0;i<st.toChange.length;i++){
atts.clear();
atts.put("obnum",new Integer(i));
atts.put("parnum",new Integer(st.parentIndexes[i]));
writeTag("stobj",atts);
writeObject(st.toChange[i]);
writeEndTag("stobj");
}
ArrayList keyframes=st.keyframes;
for (int i=0;i<keyframes.size();i++){
writeSpatialTransformerPointInTime((SpatialTransformer.PointInTime)keyframes.get(i));
}
writeEndTag("spatialtransformer");
}
private void writeObject(Object o) throws IOException {
if (o instanceof TriMesh){
writeMesh((TriMesh) o);
} else if (o instanceof Node){
writeNode((Node) o);
}
}
private void writeSpatialTransformerPointInTime(SpatialTransformer.PointInTime pointInTime) throws IOException {
HashMap atts=new HashMap();
atts.clear();
atts.put("time",new Float(pointInTime.time));
writeTag("spatialpointtime",atts);
BitSet thisSet;
thisSet=pointInTime.usedScale;
int [] setScales=new int[thisSet.cardinality()];
Vector3f[] scaleValues=new Vector3f[thisSet.cardinality()];
for (int i=thisSet.nextSetBit(0),j=0;i>=0;i=thisSet.nextSetBit(i+1),j++){
setScales[j]=i;
scaleValues[j]=new Vector3f();
pointInTime.look[i].getScale(scaleValues[j]);
}
atts.clear();
atts.put("index",setScales);
atts.put("scalevalues",scaleValues);
writeTag("sptscale",atts);
writeEndTag("sptscale");
thisSet=pointInTime.usedRot;
int [] setRots=new int[thisSet.cardinality()];
Quaternion[] rotValues=new Quaternion[thisSet.cardinality()];
for (int i=thisSet.nextSetBit(0),j=0;i>=0;i=thisSet.nextSetBit(i+1),j++){
setRots[j]=i;
rotValues[j]=new Quaternion();
pointInTime.look[i].getRotation(rotValues[j]);
}
atts.clear();
atts.put("index",setRots);
atts.put("rotvalues",rotValues);
writeTag("sptrot",atts);
writeEndTag("sptrot");
thisSet=pointInTime.usedTrans;
int [] setTrans=new int[thisSet.cardinality()];
Vector3f[] transValues=new Vector3f[thisSet.cardinality()];
for (int i=thisSet.nextSetBit(0),j=0;i>=0;i=thisSet.nextSetBit(i+1),j++){
setTrans[j]=i;
transValues[j]=new Vector3f();
pointInTime.look[i].getTranslation(transValues[j]);
}
atts.clear();
atts.put("index",setTrans);
atts.put("transvalues",transValues);
writeTag("spttrans",atts);
writeEndTag("spttrans");
writeEndTag("spatialpointtime");
}
/**
* Writes a KeyframeController to binary format.
* @param kc KeyframeControlelr to write
* @throws IOException
*/
private void writeKeyframeController(KeyframeController kc) throws IOException {
// Assume that morphMesh is keyframeController's parent
writeTag("keyframecontroller",null);
ArrayList keyframes=kc.keyframes;
for (int i=0;i<keyframes.size();i++)
writeKeyFramePointInTime((KeyframeController.PointInTime)keyframes.get(i));
writeEndTag("keyframecontroller");
}
/**
* Writes a PointInTime for a KeyframeController.
* @param pointInTime Which point in time to write
* @throws IOException
*/
private void writeKeyFramePointInTime(KeyframeController.PointInTime pointInTime) throws IOException {
HashMap atts=new HashMap();
atts.clear();
atts.put("time",new Float(pointInTime.time));
writeTag("keyframepointintime",atts);
writeTriMeshTags(pointInTime.newShape);
writeEndTag("keyframepointintime");
}
/**
* Writes the inner tags of a TriMesh (Verticies, Normals, ect) to binary format.
* @param triMesh The TriMesh whos tags are to be written
* @throws IOException
*/
private void writeTriMeshTags(TriMesh triMesh) throws IOException {
if (triMesh==null) return;
HashMap atts=new HashMap();
atts.clear();
if (triMesh.getVertices()!=null)
atts.put("data",triMesh.getVertices());
writeTag("vertex",atts);
writeEndTag("vertex");
atts.clear();
if (triMesh.getNormals()!=null)
atts.put("data",triMesh.getNormals());
writeTag("normal",atts);
writeEndTag("normal");
atts.clear();
if (triMesh.getColors()!=null)
atts.put("data",triMesh.getColors());
writeTag("color",atts);
writeEndTag("color");
atts.clear();
if (triMesh.getTextures()!=null)
atts.put("data",triMesh.getTextures());
writeTag("texturecoords",atts);
writeEndTag("texturecoords");
atts.clear();
if (triMesh.getIndices()!=null)
atts.put("data",triMesh.getIndices());
writeTag("index",atts);
writeEndTag("index");
}
private void writeJointController(JointController jc) throws IOException{
HashMap atts=new HashMap();
atts.clear();
atts.put("numJoints",new Integer(jc.numJoints));
writeTag("jointcontroller",atts);
Object[] o=jc.movementInfo.toArray();
Vector3f tempV=new Vector3f();
Quaternion tempQ=new Quaternion();
for (int j=0;j<jc.numJoints;j++){
atts.clear();
atts.put("index",new Integer(j));
atts.put("parentindex",new Integer(jc.parentIndex[j]));
jc.localRefMatrix[j].getRotation(tempQ);
jc.localRefMatrix[j].getTranslation(tempV);
atts.put("localrot",tempQ);
atts.put("localvec",tempV);
writeTag("joint",atts);
for (int i=0;i<o.length;i++){
JointController.PointInTime jp=(JointController.PointInTime) o[i];
if (jp.usedTrans.get(j) || jp.usedRot.get(j)){
atts.clear();
atts.put("time",new Float(jp.time));
if (jp.usedTrans.get(j))
atts.put("trans",jp.jointTranslation[j]);
if (jp.usedRot.get(j))
atts.put("rot",jp.jointRotation[j]);
writeTag("keyframe",atts);
writeEndTag("keyframe");
}
}
writeEndTag("joint");
}
writeEndTag("jointcontroller");
}
/**
* Writes a spatial's RenderStates to binary format.
* @param spatial The spatial to look at.
* @throws IOException
*/
private void writeRenderStates(Spatial spatial) throws IOException {
RenderState[] states=spatial.getRenderStateList();
if (states==null) return;
for (int i=0;i<states.length;i++)
writeRenderState(states[i]);
}
/**
* Writes a single render state to binary format. Only writes known RenderStates
* @param renderState The state to write
* @throws IOException
*/
private void writeRenderState(RenderState renderState) throws IOException {
if (renderState==null) return;
if (sharedObjects.containsKey(renderState))
writePublicObject(renderState);
else if (renderState instanceof MaterialState)
writeMaterialState((MaterialState) renderState);
else if (renderState instanceof TextureState)
writeTextureState((TextureState)renderState);
else if (renderState instanceof LightState)
writeLightState((LightState)renderState);
}
private void writeLightState(LightState lightState) throws IOException {
if (lightState==null) return;
HashMap atts=new HashMap();
writeTag("lightstate",null);
for (int i=0;i<lightState.getQuantity();i++){
atts.clear();
Light thisChild=lightState.get(i);
putLightProperties(thisChild,atts);
if (thisChild.getType()==Light.LT_SPOT)
writeSpotLight((SpotLight)thisChild,atts);
else if (thisChild.getType()==Light.LT_POINT)
writePointLight((PointLight)thisChild,atts);
}
writeEndTag("lightstate");
}
private void writePointLight(PointLight pointLight, HashMap atts) throws IOException {
atts.put("loc",pointLight.getLocation());
writeTag("pointlight",atts);
writeEndTag("pointlight");
}
private void putLightProperties(Light child, HashMap atts) {
atts.put("ambient",child.getAmbient());
atts.put("fconstant",new Float(child.getConstant()));
atts.put("diffuse",child.getDiffuse());
atts.put("flinear",new Float(child.getLinear()));
atts.put("fquadratic",new Float(child.getQuadratic()));
atts.put("specular",child.getSpecular());
atts.put("isattenuate",new Boolean(child.isAttenuate()));
}
private void writeSpotLight(SpotLight spotLight,HashMap atts) throws IOException {
atts.put("loc",spotLight.getLocation());
atts.put("fangle",new Float(spotLight.getAngle()));
atts.put("dir",spotLight.getDirection());
atts.put("fexponent",new Float(spotLight.getExponent()));
writeTag("spotlight",atts);
writeEndTag("spotlight");
}
private void writePublicObject(Object o) throws IOException {
String ident=(String) sharedObjects.get(o);
HashMap atts=new HashMap();
atts.clear();
atts.put("ident",ident);
writeTag("publicobject",atts);
writeEndTag("publicobject");
}
/**
* Writes a TextureState to binary format. An attempt is made to look at the
* TextureState's ImageLocation to determine how to point the TextureState's information
* @param state The state to write
* @throws IOException
*/
private void writeTextureState(TextureState state) throws IOException{
if (state.getTexture()==null || state.getTexture().getImageLocation()==null) return;
String s=state.getTexture().getImageLocation();
HashMap atts=new HashMap();
atts.clear();
if ("file:/".equals(s.substring(0,6)))
atts.put("file",replaceSpecialsForFile(new StringBuffer(s.substring(6))).toString());
else
atts.put("URL",new URL(s));
writeTag("texturestate",atts);
writeEndTag("texturestate");
}
/**
* Replaces "%20" with " " to convert from a URL to a file.
* @param s String to look at
* @return A replaced string.
*/
private static StringBuffer replaceSpecialsForFile(StringBuffer s) {
int i=s.indexOf("%20");
if (i==-1) return s; else return replaceSpecialsForFile(s.replace(i,i+3," "));
}
/**
* Writes a MaterialState to binary format.
* @param state The state to write
* @throws IOException
*/
private void writeMaterialState(MaterialState state) throws IOException {
if (state==null) return;
HashMap atts=new HashMap();
atts.clear();
atts.put("emissive",state.getEmissive());
atts.put("ambient",state.getAmbient());
atts.put("diffuse",state.getDiffuse());
atts.put("specular",state.getSpecular());
atts.put("alpha",new Float(state.getAlpha()));
atts.put("shiny",new Float(state.getShininess()));
writeTag("materialstate",atts);
writeEndTag("materialstate");
}
/**
* Writes an END_TAG flag for the given tag.
* @param name The name of the tag whos end has come
* @throws IOException
*/
private void writeEndTag(String name) throws IOException{
if (DEBUG) System.out.println("Writting end tag for *" + name + "*");
myOut.writeByte(BinaryFormatConstants.END_TAG);
myOut.writeUTF(name);
}
/**
* Given the tag's name and it's attributes, the tag is written to the file.
* @param name The name of the tag
* @param atts The tag's attributes
* @throws IOException
*/
private void writeTag(String name, HashMap atts) throws IOException {
if (DEBUG) System.out.println("Writting begining tag for *" + name + "*");
myOut.writeByte(BinaryFormatConstants.BEGIN_TAG);
myOut.writeUTF(name);
if (atts==null){ // no attributes
myOut.writeByte(0);
return;
}
myOut.writeByte(atts.size());
Iterator i=atts.keySet().iterator();
while (i.hasNext()){
String attName=(String) i.next();
Object attrib=atts.get(attName);
myOut.writeUTF(attName);
if (attrib instanceof Vector3f[])
writeVec3fArray((Vector3f[]) attrib);
else if (attrib instanceof Vector2f[])
writeVec2fArray((Vector2f[]) attrib);
else if (attrib instanceof ColorRGBA[])
writeColorArray((ColorRGBA[]) attrib);
else if (attrib instanceof String)
writeString((String) attrib);
else if (attrib instanceof int[])
writeIntArray((int[]) attrib);
else if (attrib instanceof Vector3f)
writeVec3f((Vector3f) attrib);
else if (attrib instanceof Quaternion)
writeQuat((Quaternion) attrib);
else if (attrib instanceof Float)
writeFloat((Float) attrib);
else if (attrib instanceof ColorRGBA)
writeColor((ColorRGBA) attrib);
else if (attrib instanceof URL)
writeURL((URL) attrib);
else if (attrib instanceof Integer)
writeInt((Integer) attrib);
else if (attrib instanceof Boolean)
writeBoolean((Boolean)attrib);
else if (attrib instanceof Quaternion[])
writeQuatArray((Quaternion[])attrib);
else
throw new IOException("unknown class type for " + attrib + " of " + attrib.getClass());
i.remove();
}
}
private void writeQuatArray(Quaternion[] array) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_QUATARRAY);
myOut.writeInt(array.length);
for (int i=0;i<array.length;i++){
myOut.writeFloat(array[i].x);
myOut.writeFloat(array[i].y);
myOut.writeFloat(array[i].z);
myOut.writeFloat(array[i].w);
}
}
private void writeBoolean(Boolean aBoolean) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_BOOLEAN);
myOut.writeBoolean(aBoolean.booleanValue());
}
private void writeInt(Integer i) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_INT);
myOut.writeInt(i.intValue());
}
private void writeURL(URL url) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_URL);
myOut.writeUTF(url.toString());
}
private void writeColor(ColorRGBA c) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_COLOR);
myOut.writeFloat(c.r);
myOut.writeFloat(c.g);
myOut.writeFloat(c.b);
myOut.writeFloat(c.a);
}
private void writeFloat(Float f) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_FLOAT);
myOut.writeFloat(f.floatValue());
}
private void writeQuat(Quaternion q) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_QUAT);
myOut.writeFloat(q.x);
myOut.writeFloat(q.y);
myOut.writeFloat(q.z);
myOut.writeFloat(q.w);
}
private void writeVec3f(Vector3f v) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_V3F);
myOut.writeFloat(v.x);
myOut.writeFloat(v.y);
myOut.writeFloat(v.z);
}
private void writeIntArray(int[] array) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_INTARRAY);
myOut.writeInt(array.length);
for (int i=0;i<array.length;i++)
myOut.writeInt(array[i]);
}
private void writeString(String s) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_STRING);
myOut.writeUTF(s);
}
private void writeColorArray(ColorRGBA[] array) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_COLORARRAY);
myOut.writeInt(array.length);
for (int i=0;i<array.length;i++){
myOut.writeFloat(array[i].r);
myOut.writeFloat(array[i].g);
myOut.writeFloat(array[i].b);
myOut.writeFloat(array[i].a);
}
}
private void writeVec2fArray(Vector2f[] array) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_V2FARRAY);
myOut.writeInt(array.length);
for (int i=0;i<array.length;i++){
myOut.writeFloat(array[i].x);
myOut.writeFloat(array[i].y);
}
}
private void writeVec3fArray(Vector3f[] array) throws IOException {
myOut.writeByte(BinaryFormatConstants.DATA_V3FARRAY);
myOut.writeInt(array.length);
for (int i=0;i<array.length;i++){
if (array[i]==null){
myOut.writeFloat(Float.NaN);
myOut.writeFloat(Float.NaN);
myOut.writeFloat(Float.NaN);
} else{
myOut.writeFloat(array[i].x);
myOut.writeFloat(array[i].y);
myOut.writeFloat(array[i].z);
}
}
}
/**
* Looks at a spatial and puts its attributes into the HashMap.
* @param spatial The spatial to look at
* @param atts The HashMap to put the attributes into
*/
private void putSpatialAtts(Spatial spatial, HashMap atts) {
atts.put("name",spatial.getName());
if (!spatial.getLocalScale().equals(DEFAULT_SCALE))
atts.put("scale",spatial.getLocalScale());
if (!spatial.getLocalRotation().equals(DEFAULT_ROTATION))
atts.put("rotation",spatial.getLocalRotation());
if (!spatial.getLocalTranslation().equals(DEFAULT_TRANSLATION))
atts.put("translation",spatial.getLocalTranslation());
}
/**
* Writes the end of the file by writting the end of scene, then the END_FILE flag.
* @throws IOException
*/
private void writeClosing() throws IOException {
writeEndTag("scene");
if (DEBUG) System.out.println("Writting file close");
myOut.writeByte(BinaryFormatConstants.END_FILE);
}
/**
* Writes the be BEGIN_FILE tag to a file, then the scene tag.
* @throws IOException
*/
private void writeHeader() throws IOException {
if (DEBUG) System.out.println("Writting file begin");
myOut.writeLong(BinaryFormatConstants.BEGIN_FILE);
writeTag("scene",null);
}
/**
* Adds a property . Properties can tell this how to save the binary file.<br><br>
* The only keys currently used are:<br>
* key -> PropertyDataType<br>
*
* @param key Key to add (For example "texdir")
* @param property Property for that key to have (For example "c:\\blarg\\")
*/
public void setProperty(String key, Object property) {
properties.put(key,property);
}
/**
* Removes a property. This is equivalent to setProperty(key,null)
* @param key The property to remove.
*/
public void clearProperty(String key){
properties.remove(key);
}
} |
package com.lonelybytes.swiftlint;
import com.intellij.codeInspection.*;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.ASTNode;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.jetbrains.swift.psi.SwiftIdentifierPattern;
import com.jetbrains.swift.psi.SwiftParameter;
import com.jetbrains.swift.psi.SwiftVariableDeclaration;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR;
import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
//@com.intellij.openapi.components.State(
// name = "com.appcodeplugins.swiftlint.v1_7",
// storages = { @Storage(StoragePathMacros.WORKSPACE_FILE) }
public class SwiftLintInspection extends LocalInspectionTool {
// implements PersistentStateComponent<SwiftLintInspection.State>
// State
@SuppressWarnings("WeakerAccess")
static class State {
public String getAppPath() {
return PropertiesComponent.getInstance().getValue("com.appcodeplugins.swiftlint.v1_7.appName");
}
public void setAppPath(String aAppPath) {
PropertiesComponent.getInstance().setValue("com.appcodeplugins.swiftlint.v1_7.appName", aAppPath);
}
public boolean isQuickFixEnabled() {
return PropertiesComponent.getInstance().getBoolean("com.appcodeplugins.swiftlint.v1_7.quickFixEnabled");
}
public void setQuickFixEnabled(boolean aQuickFixEnabled) {
PropertiesComponent.getInstance().setValue("com.appcodeplugins.swiftlint.v1_7.quickFixEnabled", aQuickFixEnabled);
}
public boolean isDisableWhenNoConfigPresent() {
return PropertiesComponent.getInstance().getBoolean("com.appcodeplugins.swiftlint.v1_7.isDisableWhenNoConfigPresent");
}
public void setDisableWhenNoConfigPresent(boolean aDisableWhenNoConfigPresent) {
PropertiesComponent.getInstance().setValue("com.appcodeplugins.swiftlint.v1_7.isDisableWhenNoConfigPresent", aDisableWhenNoConfigPresent);
}
}
@SuppressWarnings("WeakerAccess")
static State STATE = new State();
// @Nullable
// @Override
// public State getState() {
// return STATE;
// @Override
// public void loadState(State aState) {
// STATE = aState;
// Main Class
private static final String QUICK_FIX_NAME = "Autocorrect";
private Map<String, Integer> _fileHashes = new HashMap<>();
@Override
public void inspectionStarted(@NotNull LocalInspectionToolSession session, boolean isOnTheFly) {
super.inspectionStarted(session, isOnTheFly);
saveAll();
}
@Override
public boolean runForWholeFile() {
return true;
}
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
Document document = FileDocumentManager.getInstance().getDocument(file.getVirtualFile());
if (document == null || document.getLineCount() == 0 || !shouldCheck(file, document)) {
return null;
}
if (STATE == null || STATE.getAppPath() == null) {
return null;
}
if (STATE.isDisableWhenNoConfigPresent() && !weHaveSwiftLintConfigInProject(file.getProject(), 5)) {
return null;
}
String toolPath = STATE.getAppPath();
String toolOptions = "lint --path";
Pattern errorsPattern = Pattern.compile("^(\\S.*?):(?:(\\d+):)(?:(\\d+):)? (\\S+):([^\\(]*)\\((.*)\\)$");
int lineMatchIndex = 2;
int columnMatchIndex = 3;
int severityMatchIndex = 4;
int messageMatchIndex = 5;
int errorTypeMatchIndex = 6;
List<ProblemDescriptor> descriptors = new ArrayList<>();
try {
String fileText = Utils.executeCommandOnFile(toolPath, toolOptions, file);
// System.out.println("\n" + fileText + "\n");
if (fileText.isEmpty()) {
return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
}
Scanner scanner = new Scanner(fileText);
String line;
while (scanner.hasNext()) {
line = scanner.nextLine();
if (!line.contains(":")) {
continue;
}
Matcher matcher = errorsPattern.matcher(line);
if (!matcher.matches()) {
continue;
}
final String errorType = matcher.group(errorTypeMatchIndex);
int linePointerFix = errorType.equals("mark") ? -1 : -1;
int lineNumber = Math.min(document.getLineCount() + linePointerFix, Integer.parseInt(matcher.group(lineMatchIndex)) + linePointerFix);
lineNumber = Math.max(0, lineNumber);
int columnNumber = matcher.group(columnMatchIndex) == null ? -1 : Math.max(0, Integer.parseInt(matcher.group(columnMatchIndex)));
if (errorType.equals("empty_first_line")) {
// SwiftLint shows some strange identifier on the previous line
lineNumber += 1;
columnNumber = -1;
}
final String severity = matcher.group(severityMatchIndex);
final String errorMessage = matcher.group(messageMatchIndex);
int highlightStartOffset = document.getLineStartOffset(lineNumber);
int highlightEndOffset = lineNumber < document.getLineCount() - 1
? document.getLineStartOffset(lineNumber + 1)
: document.getLineEndOffset(lineNumber);
TextRange range = TextRange.create(highlightStartOffset, highlightEndOffset);
boolean weHaveAColumn = columnNumber > 0;
if (weHaveAColumn) {
highlightStartOffset = Math.min(document.getTextLength() - 1, highlightStartOffset + columnNumber - 1);
}
CharSequence chars = document.getImmutableCharSequence();
if (chars.length() <= highlightStartOffset) {
// This can happen when we browsing a file after it has been edited (some lines removed for example)
continue;
}
char startChar = chars.charAt(highlightStartOffset);
PsiElement startPsiElement = file.findElementAt(highlightStartOffset);
ASTNode startNode = startPsiElement == null ? null : startPsiElement.getNode();
boolean isErrorInLineComment = startNode != null && startNode.getElementType().toString().equals("EOL_COMMENT");
ProblemHighlightType highlightType = severityToHighlightType(severity);
if (isErrorInLineComment) {
range = TextRange.create(document.getLineStartOffset(lineNumber), document.getLineEndOffset(lineNumber));
} else {
boolean isErrorNewLinesOnly = (startChar == '\n');
boolean isErrorInSymbol = !Character.isLetterOrDigit(startChar) && !Character.isWhitespace(startChar);
isErrorInSymbol |= errorType.equals("opening_brace") || errorType.equals("colon");
if (!isErrorInSymbol) {
if (!isErrorNewLinesOnly && weHaveAColumn) {
// SwiftLint returns column for the previous non-space token, not the erroneous one. Let's try to correct it.
switch (errorType) {
case "unused_closure_parameter": {
PsiElement psiElement = file.findElementAt(highlightStartOffset);
range = psiElement != null ? psiElement.getTextRange() : range;
break;
}
case "syntactic_sugar": {
PsiElement psiElement = file.findElementAt(highlightStartOffset);
if (psiElement != null) {
psiElement = psiElement.getParent();
}
range = psiElement != null ? psiElement.getTextRange() : range;
break;
}
case "variable_name":
range = findVarInDefinition(file, highlightStartOffset, errorType);
break;
case "type_name": {
PsiElement psiElement = file.findElementAt(highlightStartOffset);
range = psiElement != null ? psiElement.getTextRange() : range;
break;
}
default:
range = getNextTokenAtIndex(file, highlightStartOffset, errorType);
break;
}
} else if (isErrorNewLinesOnly) {
// Let's select all empty lines here, we need to show that something is wrong with them
range = getEmptyLinesAroundIndex(document, highlightStartOffset);
}
} else {
PsiElement psiElement = file.findElementAt(highlightStartOffset);
if (psiElement != null) {
range = psiElement.getTextRange();
if (errorType.equals("colon")) {
range = getNextTokenAtIndex(file, highlightStartOffset, errorType);
}
}
}
if (errorType.equals("opening_brace") && Character.isWhitespace(startChar)) {
range = getNextTokenAtIndex(file, highlightStartOffset, errorType);
}
if (errorType.equals("valid_docs")) {
range = prevElement(file, highlightStartOffset).getTextRange();
}
if (errorType.equals("trailing_newline") && !weHaveAColumn && chars.charAt(chars.length() - 1) != '\n') {
highlightType = GENERIC_ERROR;
range = TextRange.create(highlightEndOffset - 1, highlightEndOffset);
}
if (isErrorNewLinesOnly) {
// Sometimes we need to highlight several returns. Usual error highlighting will not work in this case
highlightType = GENERIC_ERROR_OR_WARNING;
}
}
if (STATE.isQuickFixEnabled()) {
descriptors.add(manager.createProblemDescriptor(file, range, errorMessage.trim(), highlightType, false, new LocalQuickFix() {
@Nls
@NotNull
@Override
public String getName() {
return QUICK_FIX_NAME;
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return QUICK_FIX_NAME;
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemDescriptor) {
WriteCommandAction writeCommandAction = new WriteCommandAction(project, file) {
@Override
protected void run(@NotNull Result aResult) throws Throwable {
executeSwiftLintQuickFix(toolPath, file);
}
};
writeCommandAction.execute();
}
}));
} else {
descriptors.add(manager.createProblemDescriptor(file, range, errorMessage.trim(), highlightType, false, LocalQuickFix.EMPTY_ARRAY));
}
}
} catch (ProcessCanceledException ex) {
// Do nothing here
} catch (IOException ex) {
if (ex.getMessage().contains("No such file or directory") || ex.getMessage().contains("error=2")) {
Notifications.Bus.notify(new Notification(Configuration.KEY_SWIFTLINT, "Error", "Can't find swiftlint utility here:\n" + toolPath + "\nPlease check the path in settings.", NotificationType.ERROR));
} else {
Notifications.Bus.notify(new Notification(Configuration.KEY_SWIFTLINT, "Error", "IOException: " + ex.getMessage(), NotificationType.ERROR));
}
} catch (Exception ex) {
Notifications.Bus.notify(new Notification(Configuration.KEY_SWIFTLINT, "Error", "Exception: " + ex.getMessage(), NotificationType.INFORMATION));
ex.printStackTrace();
}
int newHash = document.getText().hashCode();
_fileHashes.put(file.getVirtualFile().getCanonicalPath(), newHash);
return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
}
private void executeSwiftLintQuickFix(String aToolPath, @NotNull PsiFile file) {
saveAll();
ApplicationManager.getApplication().invokeLater(() -> {
try {
Utils.executeCommandOnFile(aToolPath, "autocorrect --path", file);
LocalFileSystem.getInstance().refreshFiles(Collections.singletonList(file.getVirtualFile()));
} catch (IOException aE) {
Notifications.Bus.notify(new Notification(Configuration.KEY_SWIFTLINT, "Error", "Can't quick-fix.\nIOException: " + aE.getMessage(), NotificationType.ERROR));
}
});
}
private static class DepthedFile {
int _depth;
VirtualFile _file;
DepthedFile(int aDepth, VirtualFile aFile) {
_depth = aDepth;
_file = aFile;
}
}
private boolean weHaveSwiftLintConfigInProject(Project aProject, int aDepthToLookAt) {
if (aProject.getBaseDir().findChild(".swiftlint.yml") != null) {
return true;
}
List<DepthedFile> filesToLookAt = new LinkedList<>();
filesToLookAt.addAll(
Arrays.stream(aProject.getBaseDir().getChildren())
.filter(VirtualFile::isDirectory)
.map(aVirtualFile -> new DepthedFile(0, aVirtualFile))
.collect(Collectors.toList())
);
while (!filesToLookAt.isEmpty()) {
DepthedFile file = filesToLookAt.get(0);
filesToLookAt.remove(0);
if (file._depth > aDepthToLookAt) {
break;
}
if (file._file.findChild(".swiftlint.yml") != null) {
return true;
} else {
filesToLookAt.addAll(
Arrays.stream(file._file.getChildren())
.filter(VirtualFile::isDirectory)
.map(aVirtualFile -> new DepthedFile(file._depth + 1, aVirtualFile))
.collect(Collectors.toList())
);
}
}
return false;
}
private void saveAll() {
final FileDocumentManager documentManager = FileDocumentManager.getInstance();
if (documentManager.getUnsavedDocuments().length != 0) {
ApplicationManager.getApplication().invokeLater(documentManager::saveAllDocuments);
}
}
private TextRange getEmptyLinesAroundIndex(Document aDocument, int aInitialIndex) {
CharSequence chars = aDocument.getImmutableCharSequence();
int from = aInitialIndex;
while (from >= 0) {
if (!Character.isWhitespace(chars.charAt(from))) {
from += 1;
break;
}
from -= 1;
}
int to = aInitialIndex;
while (to < chars.length()) {
if (!Character.isWhitespace(chars.charAt(to))) {
to -= 1;
break;
}
to += 1;
}
from = Math.max(0, from);
if (from > 0 && chars.charAt(from) == '\n') {
from += 1;
}
if (to > 0) {
while (chars.charAt(to - 1) != '\n') {
to -= 1;
}
}
to = Math.max(from, to);
return new TextRange(from, to);
}
private TextRange getNextTokenAtIndex(@NotNull PsiFile file, int aCharacterIndex, String aErrorType) {
TextRange result = null;
PsiElement psiElement;
try {
psiElement = file.findElementAt(aCharacterIndex);
if (psiElement != null) {
if (";".equals(psiElement.getText()) || (aErrorType.equals("variable_name") && psiElement.getNode().getElementType().toString().equals("IDENTIFIER"))) {
result = psiElement.getTextRange();
} else {
result = psiElement.getNode().getTextRange();
psiElement = nextElement(file, aCharacterIndex);
if (psiElement != null) {
if (psiElement.getContext() != null && psiElement.getContext().getNode().getElementType().toString().equals("OPERATOR_SIGN")) {
result = psiElement.getContext().getNode().getTextRange();
} else {
result = psiElement.getNode().getTextRange();
}
}
}
}
} catch (ProcessCanceledException aE) {
// Do nothing
} catch (Exception aE) {
aE.printStackTrace();
}
return result;
}
private TextRange findVarInDefinition(@NotNull PsiFile file, int aCharacterIndex, String aErrorType) {
TextRange result = null;
PsiElement psiElement;
try {
psiElement = file.findElementAt(aCharacterIndex);
while (psiElement != null &&
!(psiElement instanceof SwiftVariableDeclaration) &&
!(psiElement instanceof SwiftParameter)) {
psiElement = psiElement.getParent();
}
if (psiElement != null) {
if (psiElement instanceof SwiftVariableDeclaration) {
SwiftVariableDeclaration variableDeclaration = (SwiftVariableDeclaration) psiElement;
SwiftIdentifierPattern identifierPattern = variableDeclaration.getVariables().get(0);
result = identifierPattern.getNode().getTextRange();
} else /*if (psiElement instanceof SwiftParameter)*/ {
SwiftParameter variableDeclaration = (SwiftParameter) psiElement;
result = variableDeclaration.getNode().getTextRange();
}
}
} catch (ProcessCanceledException aE) {
// Do nothing
} catch (Exception aE) {
aE.printStackTrace();
}
return result;
}
private PsiElement nextElement(PsiFile aFile, int aElementIndex) {
PsiElement nextElement = null;
PsiElement initialElement = aFile.findElementAt(aElementIndex);
if (initialElement != null) {
int index = aElementIndex + initialElement.getTextLength();
nextElement = aFile.findElementAt(index);
while (nextElement != null && (nextElement == initialElement || nextElement instanceof PsiWhiteSpace)) {
index += nextElement.getTextLength();
nextElement = aFile.findElementAt(index);
}
}
return nextElement;
}
private PsiElement prevElement(PsiFile aFile, int aElementIndex) {
PsiElement nextElement = null;
PsiElement initialElement = aFile.findElementAt(aElementIndex);
if (initialElement != null) {
int index = initialElement.getTextRange().getStartOffset() - 1;
nextElement = aFile.findElementAt(index);
while (nextElement != null && (nextElement == initialElement || nextElement instanceof PsiWhiteSpace)) {
index = nextElement.getTextRange().getStartOffset() - 1;
if (index >= 0) {
nextElement = aFile.findElementAt(index);
} else {
break;
}
}
}
return nextElement;
}
private boolean shouldCheck(@NotNull final PsiFile aFile, @NotNull final Document aDocument) {
boolean isExtensionSwifty = "swift".equalsIgnoreCase(aFile.getVirtualFile().getExtension());
Integer previousHash = _fileHashes.get(aFile.getVirtualFile().getCanonicalPath());
int newHash = aDocument.getText().hashCode();
boolean fileChanged = previousHash == null || previousHash != newHash;
return isExtensionSwifty;
}
private static ProblemHighlightType severityToHighlightType(@NotNull final String severity) {
switch (severity.trim().toLowerCase()) {
case "error":
return GENERIC_ERROR;
case "warning":
return GENERIC_ERROR_OR_WARNING;
case "style":
case "performance":
case "portability":
return ProblemHighlightType.LIKE_UNKNOWN_SYMBOL;
case "information":
return ProblemHighlightType.LIKE_UNKNOWN_SYMBOL;
default:
return ProblemHighlightType.LIKE_UNKNOWN_SYMBOL;
}
}
} |
package com.madphysicist.tools.util;
import java.awt.Image;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
/**
* A utility class for manipulating resources found inside and outside of JAR
* files. This class can not be instantiated.
*
* @author Joseph Fox-Rabinovitz
* @version 1.0.0, 13 Feb 2013 - J. Fox-Rabinovitz - Created
* @version 1.0.1, 04 Jun 2013 - J. Fox-Rabinovitz - Added copyResourceToFile()
* @version 1.0.2, 16 Nov 2013 - J. Fox-Rabinovitz - Added loadLibrary() and loadIcon()
* @since 1.0.0.
*/
public class ResourceUtilities
{
/**
* The approximate size of a disk block in bytes. This number is intended to
* be nearly optimal for copying files across multiple platforms. It may be
* advisable to compute this constant for each device being copied to if
* such a method should become readily available.
*
* @since 1.0.0
*/
private static final int DISK_BLOCK = 8192;
/**
* A private constructor to prevent instantiation.
*
* @since 1.0.0
*/
private ResourceUtilities() {}
/**
* Copies a named resource into a temporary file on the file system. An
* object referencing the newly created file is returned. This method is
* useful when random access or marking within the resource stream are
* required. In such a case (as with audio files), obtaining the resource as
* a stream from the default class loader is not sufficient.
*
* @param resourceName the name of the resource to copy.
* @param deleteOnExit specifies whether or not the file should be deleted
* when the application terminates.
* @return a {@code File} referfencing the newly created copy of the
* resource.
* @throws IOException if the temporary file can not be created or the
* resource can not be copied into it.
* @since 1.0.0
*/
public static File getResourceAsFile(String resourceName, boolean deleteOnExit) throws IOException
{
int extensionIndex = resourceName.lastIndexOf('.');
String name = resourceName.replace('/', '.').replace('\\', '.');
File file = (extensionIndex == -1) ?
File.createTempFile(name, null) :
File.createTempFile(name.substring(0, extensionIndex),
name.substring(extensionIndex));
if(deleteOnExit)
file.deleteOnExit();
copyResourceToFile(resourceName, file);
return file;
}
/**
* Extracts a native dynamically linked library from a resource and loads it
* into memory. This method is particularly useful for loading .so and .dll
* modules stored within a JAR file.
*
* @param parent the root path of the resource, minus the file name.
* @param baseName the base name of the library. Any extensions will be
* interpreted by the loacl platform as necessary.
* @throws IOException if the library can not be extracted for any reason.
* @throws UnsatisfiedLinkError if the library can not be linked after it is
* extracted.
* @see System#mapLibraryName(java.lang.String)
* @since 1.0.2
*/
public static void loadLibrary(String parent, String baseName) throws IOException, UnsatisfiedLinkError
{
File lib = getResourceAsFile(baseName + File.separator + System.mapLibraryName(baseName), true);
System.load(lib.getCanonicalPath());
}
/**
* Copies a resource to the specified file on the file system. This method
* can be useful for the initial setup of a program, when defaults must be
* copied to the home directory.
*
* @param resourceName the name of the resource to copy.
* @param file the file to copy the resource to. If this represents an
* existing file, it will be overwritten.
* @throws IOException if the file can not be created or the resource can
* not be copied into it.
* @since 1.0.1
*/
@SuppressWarnings("NestedAssignment")
public static void copyResourceToFile(String resourceName, File file) throws IOException
{
byte[] buffer = new byte[DISK_BLOCK];
try (InputStream input = ClassLoader.getSystemResourceAsStream(resourceName);
OutputStream output = new FileOutputStream(file)) {
int nRead;
while((nRead = input.read(buffer)) != -1)
output.write(buffer, 0, nRead);
}
}
/**
* Loads an image from a resource. To load the image as an {@code Icon}, use
* the {@link #loadIcon(java.lang.String) loadIcon()} method.
*
* @param resourceName the name of the resource to load.
* @return the image named by the specified resource, or {@code null} if the
* resource could not be found.
* @throws IOException if an error occurs while opening or reading the
* resource stream.
* @since 1.0.0
*/
public static Image loadImage(String resourceName) throws IOException
{
try(InputStream input = ClassLoader.getSystemResourceAsStream(resourceName)) {
return (input == null) ? null : ImageIO.read(input);
}
}
/**
* Loads an icon from a resource. This method wraps an image returned by
* {@link #loadImage(java.lang.String) loadImage()} into an {@code Icon}.
*
* @param resourceName the name of the resource to load.
* @return the icon named by the specified resource, or {@code null} if the
* resource could not be found.
* @throws IOException if an error occurs while opening or reading the
* resource stream.
* @since 1.0.2
*/
public static Icon loadIcon(String resourceName) throws IOException
{
Image image = loadImage(resourceName);
if(image == null)
return null;
return new ImageIcon(image);
}
} |
package com.mead.android.crazymonkey;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executors;
import com.mead.android.crazymonkey.process.Callable;
import com.mead.android.crazymonkey.process.LocalChannel;
import com.mead.android.crazymonkey.util.Utils;
public class CrazyMonkeyBuild {
private String crazyMonkeyHome;
private String androidSdkHome;
private String androidRootHome;
private int numberOfEmulators = 15;
private int startPort;
private int endPort;
private LocalChannel channel;
private String logPath;
private String apkFilePath;
private String testScriptPath;
private String userDataPath;
private String nodeHttpServer;
private StreamTaskListener listener;
private int startUpDelay = 2;
private int configPhoneDelay = 10;
private int installApkDelay = 5;
private int runScriptDelay = 5;
private int emulatorTimeout = 30;
private int runScriptTimeout = 1000;
private Set<Integer> occupiedPorts = new HashSet<Integer>();
private int[] emulators;
private String emulatorType = "ANDROID";
private boolean isConnectToVPN = false;
public static final int ADB_CONNECT_TIMEOUT_MS = 5 * 60 * 1000;
/** Duration by which emulator booting should normally complete. */
public static final int BOOT_COMPLETE_TIMEOUT_MS = 5 * 60 * 1000;
/** Interval during which killing a process should complete. */
public static final int KILL_PROCESS_TIMEOUT_MS = 5 * 10 * 1000;
public static final String EMULATOR_NAME_PREFIX = "Android_Monkey_";
public CrazyMonkeyBuild(String emulatorType) throws IOException {
this.emulatorType = emulatorType;
File crazyMonkeyFile = Utils.getCrazyMonkeyHomeDirectory(".");
this.setCrazyMonkeyHome(crazyMonkeyFile.getAbsolutePath());
// get the properties from properties file
File configFile = new File(this.getCrazyMonkeyHome(), "config-dev.ini");
if (!configFile.exists()) {
configFile = new File(this.getCrazyMonkeyHome(), "config.ini");
}
Map<String, String> config = Utils.parseConfigFile(configFile);
this.setAndroidSdkHome(config.get("android.sdk.home"));
this.setAndroidRootHome(config.get("android.sdk.root"));
this.setNodeHttpServer(config.get("node.httpserver"));
try {
this.setStartPort(Integer.parseInt(config.get("emulator.start_port")));
} catch (NumberFormatException e) {
}
try {
this.setEndPort(Integer.parseInt(config.get("emulator.end_port")));
} catch (NumberFormatException e) {
}
try {
this.setStartUpDelay(Integer.parseInt(config.get("emulator.start_up_delay")));
} catch (NumberFormatException e) {
}
try {
this.setConfigPhoneDelay(Integer.parseInt(config.get("emulator.config_phone_delay")));
} catch (NumberFormatException e) {
}
try {
this.setInstallApkDelay(Integer.parseInt(config.get("emulator.install_apk_delay")));
} catch (NumberFormatException e) {
}
try {
this.setRunScriptDelay(Integer.parseInt(config.get("emulator.run_script_delay")));
} catch (NumberFormatException e) {
}
try {
this.setEmulatorTimeout(Integer.parseInt(config.get("emulator.timeout.minute")));
} catch (NumberFormatException e) {
}
try {
this.setNumberOfEmulators(Integer.parseInt(config.get("emulator.max_number")));
} catch (NumberFormatException e) {
}
try {
this.setRunScriptTimeout(Integer.parseInt(config.get("emulator.run_script_timeout")));
} catch (NumberFormatException e) {
}
try {
this.setConnectToVPN(Boolean.valueOf(config.get("emulator.connect_to_vpn")));
} catch (NumberFormatException e) {
}
this.setLogPath(this.crazyMonkeyHome + "//logs");
this.setApkFilePath(this.crazyMonkeyHome + "//apk");
this.setTestScriptPath(this.crazyMonkeyHome + "//scripts");
this.setUserDataPath(this.crazyMonkeyHome + "//userdata");
this.listener = StreamTaskListener.fromStdout();
this.channel = new LocalChannel(Executors.newCachedThreadPool());
this.emulators = new int[this.numberOfEmulators];
for (int i = 0; i < emulators.length; i++) {
this.emulators[i] = 0;
}
}
private static final int MAX_TRIES = 100;
public synchronized int[] getNextPorts() {
int count = 2;
int start = this.getStartPort();
int end = this.getEndPort();
boolean isConsecutive = true;
int[] allocated = new int[count];
boolean allocationFailed = true;
Random rnd = new Random();
// Attempt the whole allocation a few times using a brute force approach.
for (int trynum = 0; (allocationFailed && (trynum < MAX_TRIES)); trynum++) {
allocationFailed = false;
// Allocate all of the ports in the range
for (int offset = 0; offset < count; offset++) {
final int requestedPort;
if (!isConsecutive || (offset == 0)) {
requestedPort = rnd.nextInt((end - start) - count) + start;
} else {
requestedPort = allocated[0] + offset;
}
try {
final int i;
synchronized (this) {
i = allocatePort(requestedPort);
if (!this.occupiedPorts.contains(i)) {
this.occupiedPorts.add(i);
} else {
throw new IOException("The port has been occupied.");
}
}
allocated[offset] = i;
} catch (IOException ex) {
allocationFailed = true;
break;
} catch (InterruptedException e) {
allocationFailed = true;
e.printStackTrace();
}
}
}
return allocated;
}
public String getCrazyMonkeyHome() {
return crazyMonkeyHome;
}
public void setCrazyMonkeyHome(String crazyMonkeyHome) {
this.crazyMonkeyHome = crazyMonkeyHome;
}
public String getAndroidSdkHome() {
return androidSdkHome;
}
public void setAndroidSdkHome(String androidSdkHome) {
this.androidSdkHome = androidSdkHome;
}
public String getAndroidRootHome() {
return androidRootHome;
}
public void setAndroidRootHome(String androidRootHome) {
this.androidRootHome = androidRootHome;
}
public int getNumberOfEmulators() {
return numberOfEmulators;
}
public void setNumberOfEmulators(int numberOfEmulators) {
this.numberOfEmulators = numberOfEmulators;
}
public StreamTaskListener getListener() {
return listener;
}
public void setListener(StreamTaskListener listener) {
this.listener = listener;
}
public int getStartUpDelay() {
return startUpDelay;
}
public void setStartUpDelay(int startUpDelay) {
this.startUpDelay = startUpDelay;
}
public int getStartPort() {
return startPort;
}
public void setStartPort(int startPort) {
this.startPort = startPort;
}
public int getEndPort() {
return endPort;
}
public void setEndPort(int endPort) {
this.endPort = endPort;
}
public LocalChannel getChannel() {
return channel;
}
public void setChannel(LocalChannel channel) {
this.channel = channel;
}
private int allocatePort(final int port) throws InterruptedException, IOException {
return this.getChannel().call(new AllocateTask(port));
}
private static final class AllocateTask implements Callable<Integer,IOException> {
private final int port;
public AllocateTask(int port) {
this.port = port;
}
public Integer call() throws IOException {
ServerSocket server;
try {
server = new ServerSocket(port);
} catch (IOException e) {
throw e;
}
int localPort = server.getLocalPort();
server.close();
return localPort;
}
private static final long serialVersionUID = 1L;
}
public String getLogPath() {
return logPath;
}
public void setLogPath(String logPath) {
this.logPath = logPath;
}
public String getApkFilePath() {
return apkFilePath;
}
public void setApkFilePath(String apkFilePath) {
this.apkFilePath = apkFilePath;
}
public String getTestScriptPath() {
return testScriptPath;
}
public void setTestScriptPath(String testScriptPath) {
this.testScriptPath = testScriptPath;
}
public Set<Integer> getOccupiedPorts() {
return occupiedPorts;
}
public void setOccupiedPorts(Set<Integer> occupiedPorts) {
this.occupiedPorts = occupiedPorts;
}
public synchronized void freePorts (int[] ports) {
if (ports != null) {
for (int i = 0; i < ports.length; i++) {
if (this.occupiedPorts.contains(ports[i])) {
this.occupiedPorts.remove(ports[i]);
}
}
}
}
public String getNodeHttpServer() {
return nodeHttpServer;
}
public void setNodeHttpServer(String nodeHttpServer) {
this.nodeHttpServer = nodeHttpServer;
}
public int getConfigPhoneDelay() {
return configPhoneDelay;
}
public void setConfigPhoneDelay(int configPhoneDelay) {
this.configPhoneDelay = configPhoneDelay;
}
public String getUserDataPath() {
return userDataPath;
}
public void setUserDataPath(String userDataPath) {
this.userDataPath = userDataPath;
}
public int getInstallApkDelay() {
return installApkDelay;
}
public void setInstallApkDelay(int installApkDelay) {
this.installApkDelay = installApkDelay;
}
public int getRunScriptDelay() {
return runScriptDelay;
}
public void setRunScriptDelay(int runScriptDelay) {
this.runScriptDelay = runScriptDelay;
}
public int getEmulatorTimeout() {
return emulatorTimeout;
}
public void setEmulatorTimeout(int emulatorTimeout) {
this.emulatorTimeout = emulatorTimeout;
}
public int[] getEmulators() {
return emulators;
}
public int getRunScriptTimeout() {
return runScriptTimeout;
}
public void setRunScriptTimeout(int runScriptTimeout) {
this.runScriptTimeout = runScriptTimeout;
}
public synchronized int getAvailableEmualtorIndex() {
for (int i = 0; i < emulators.length; i++) {
if (emulators[i] == 0) {
emulators[i] = 1;
return i;
}
}
return -1;
}
public synchronized void freeEmulatorIndex (int i) {
if (i >= 0 && i < emulators.length) {
emulators[i] = 0;
}
}
public synchronized int getActiveEmulatorCount () {
int count = 0;
for (int i = 0; i < emulators.length; i++) {
if (emulators[i] == 1) {
count++;
}
}
return count;
}
public synchronized void freeEmulator (String emulatorName) {
int index = Integer.parseInt(emulatorName.substring(CrazyMonkeyBuild.EMULATOR_NAME_PREFIX.length()));
this.freeEmulatorIndex(index);
}
public String getEmulatorType() {
return emulatorType;
}
public void setEmulatorType(String emulatorType) {
this.emulatorType = emulatorType;
}
public boolean isConnectToVPN() {
return isConnectToVPN;
}
public void setConnectToVPN(boolean isConnectToVPN) {
this.isConnectToVPN = isConnectToVPN;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.