answer stringlengths 17 10.2M |
|---|
package pixlepix.minechem.api.core;
public enum EnumOre {
iron("Copper", new Element(EnumElement.Fe, 16)),
gold("Tin", new Element(EnumElement.Au, 16)),
copper("Copper", new Element(EnumElement.Cu, 16)),
tin("Tin", new Element(EnumElement.Sn, 16)),
silver("Silver", new Element(EnumElement.Ag, 16)),
aluminum("Aluminum", new Element(EnumElement.Al, 16)),
titanium("Titanium", new Element(EnumElement.Ti, 16)),
chrome("Chrome", new Element(EnumElement.Al, 16)),
tungsten("Tungsten", new Element(EnumElement.W, 16)),
lead("Lead", new Element(EnumElement.Pb, 16)),
zinc("Zinc", new Element(EnumElement.Zn, 16)),
platinum("Platinum", new Element(EnumElement.Pt, 16)),
thorium("Thorium", new Element(EnumElement.Th, 16)),
nickel("Nickel", new Element(EnumElement.Ni, 16)),
osmium("Osmium", new Element(EnumElement.Os, 16)),
antimony("Antimony", new Element(EnumElement.Sb, 16)),
iridium("Iridium", new Element(EnumElement.Ir, 16)),
uranium("Uranium", new Element(EnumElement.U, 16)),
plutonium("Plutonium", new Element(EnumElement.Pu, 16)),
manganese("Manganese", new Element(EnumElement.Mn, 16)),
phosphorus("Phosphorus", new Element(EnumElement.P, 16)),
bitumen("Bitumen", new Molecule(EnumMolecule.propane, 16)),
prometheum("Prometheum", new Element(EnumElement.Pm, 16)),
amethyst("Amethyst", new Molecule(EnumMolecule.siliconDioxide, 16)),
peridot("Peridot", new Molecule(EnumMolecule.peridot, 16)),
topaz("Topaz", new Molecule(EnumMolecule.topaz, 16)),
tanzanite("Tanzanite", new Molecule(EnumMolecule.zoisite, 16)),
potash("Potash", new Molecule(EnumMolecule.potassiumNitrate, 16)),
sulfur("Sulfur", new Element(EnumElement.S, 16)),
saphire("Sapphire", new Molecule(EnumMolecule.aluminiumOxide, 1)),
ruby("Ruby", new Molecule(EnumMolecule.aluminiumOxide, 1), new Element(EnumElement.Cr, 1)),
cobalt("Cobalt", new Element(EnumElement.Co, 16)),
ardite("Ardite", new Element(EnumElement.Ar, 16));
private String name;
private Chemical[] composition;
public String getName() {
return this.name;
}
public Chemical[] getComposition() {
return this.composition;
}
EnumOre(String name, Chemical... composition) {
this.name = name;
this.composition = composition;
}
} |
package ru.ifmo.ctddev.gmwcs.graph;
import ru.ifmo.ctddev.gmwcs.Signals;
import java.io.*;
import java.text.ParseException;
import java.util.*;
public class GraphIO {
private File nodeIn;
private File edgeIn;
private File signalIn;
private Map<String, Node> nodeNames;
private Map<Unit, String> unitMap;
private Signals signals;
private Map<String, Integer> signalNames;
public GraphIO(File nodeIn, File edgeIn, File signalIn) {
this.nodeIn = nodeIn;
this.edgeIn = edgeIn;
this.signalIn = signalIn;
signals = new Signals();
nodeNames = new LinkedHashMap<>();
unitMap = new HashMap<>();
signalNames = new HashMap<>();
}
public Graph read() throws IOException, ParseException {
try (LineNumberReader nodes = new LineNumberReader(new FileReader(nodeIn));
LineNumberReader edges = new LineNumberReader(new FileReader(edgeIn));
LineNumberReader signalsReader = new LineNumberReader(new FileReader(signalIn))) {
Graph graph = new Graph();
parseNodes(nodes, graph);
parseEdges(edges, graph);
parseSignals(signalsReader);
return graph;
}
}
private void parseNodes(LineNumberReader reader, Graph graph) throws ParseException, IOException {
String line;
int cnt = 0;
while ((line = reader.readLine()) != null) {
if (line.startsWith("
continue;
}
StringTokenizer tokenizer = new StringTokenizer(line);
if (!tokenizer.hasMoreTokens()) {
continue;
}
String node = tokenizer.nextToken();
try {
Node vertex = new Node(cnt++, 0);
if (nodeNames.containsKey(node)) {
throw new ParseException("Duplicate node " + node, 0);
}
nodeNames.put(node, vertex);
graph.addVertex(vertex);
processSignals(vertex, tokenizer);
unitMap.put(vertex, node);
} catch (ParseException e){
throw new ParseException(e.getMessage() + "node file, line", reader.getLineNumber());
}
}
}
private void parseEdges(LineNumberReader reader, Graph graph) throws ParseException, IOException {
int cnt = 0;
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("
continue;
}
StringTokenizer tokenizer = new StringTokenizer(line);
if (!tokenizer.hasMoreTokens()) {
continue;
}
String first = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
throw new ParseException("Wrong edge format at line", reader.getLineNumber());
}
String second = tokenizer.nextToken();
try {
if (!nodeNames.containsKey(first) || !nodeNames.containsKey(second)) {
throw new ParseException("There's no such vertex in edge list at line", reader.getLineNumber());
}
Edge edge = new Edge(cnt++, 0);
Node from = nodeNames.get(first);
Node to = nodeNames.get(second);
graph.addEdge(from, to, edge);
unitMap.put(edge, first + "\t" + second);
processSignals(edge, tokenizer);
} catch (ParseException e){
throw new ParseException(e.getMessage() + "edge file, line", reader.getLineNumber());
}
}
}
private void processSignals(Unit unit, StringTokenizer tokenizer) throws ParseException {
List<String> tokens = new ArrayList<>();
while(tokenizer.hasMoreTokens()){
tokens.add(tokenizer.nextToken());
}
if(!tokens.isEmpty()){
for(String token : tokens){
if(signalNames.containsKey(token)){
int signal = signalNames.get(token);
signals.add(unit, signal);
} else {
signalNames.put(token, signals.add(unit));
}
}
} else {
throw new ParseException("Expected signal name: ", 0);
}
}
private void parseSignals(LineNumberReader reader) throws IOException, ParseException {
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.startsWith("
continue;
}
StringTokenizer tokenizer = new StringTokenizer(line);
if (!tokenizer.hasMoreTokens()) {
continue;
}
String signal = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
throw new ParseException("Expected weight of signal at line", reader.getLineNumber());
}
double weight = Double.parseDouble(tokenizer.nextToken());
if(!signalNames.containsKey(signal)){
throw new ParseException("Signal " + signal +
"doesn't appear in node/edge files", reader.getLineNumber());
}
int set = signalNames.get(signal);
signals.setWeight(set, weight);
for(Unit u : signals.set(set)){
u.setWeight(u.getWeight() + weight);
}
}
} catch (NumberFormatException e){
throw new ParseException("Wrong format of weight of signal at line", reader.getLineNumber());
}
}
public void write(List<Unit> units) throws IOException {
if (units == null) {
units = new ArrayList<>();
}
try(PrintWriter nodeWriter = new PrintWriter(nodeIn + ".out");
PrintWriter edgeWriter = new PrintWriter(edgeIn + ".out")){
for (Unit unit : units) {
if (!unitMap.containsKey(unit)) {
throw new IllegalStateException();
}
if(unit instanceof Node){
nodeWriter.println(unitMap.get(unit));
} else {
edgeWriter.println(unitMap.get(unit));
}
}
}
}
public Signals getSignals() {
return signals;
}
} |
package se.simonsoft.cms.item;
/**
* Shared implementation of equals, hashCode and toString.
*/
public abstract class ChecksumBase implements Checksum {
public ChecksumBase() {
super();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
} |
package seedu.emeraldo.logic.parser;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
import seedu.emeraldo.commons.util.StringUtil;
import seedu.emeraldo.logic.commands.*;
import static seedu.emeraldo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.emeraldo.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern PERSON_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
Pattern.compile("\"(?<description>.+)\""
+ "(?: by )?(?<dateTime>([^
+ "(?<tagArguments>(?: #[^#]+)*)"); // variable number of tags
public Parser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
return new ListCommand();
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
return new AddCommand(
matcher.group("description"),
matcher.group("dateTime"),
getTagsFromArgs(matcher.group("tagArguments"))
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Extracts the new person's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" #", "").split(" #"));
return new HashSet<>(tagStrings);
}
/**
* Parses arguments in the context of the delete person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
private Command prepareEdit(String arguments) {
// TODO Auto-generated method stub
return null;
}
/**
* Parses arguments in the context of the select person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = PERSON_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
} |
package seedu.task.commons.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
/**
* Helper functions for handling strings.
*/
public class StringUtil {
public static boolean containsIgnoreCase(String source, String query) {
String[] split = source.toLowerCase().split("\\s+");
List<String> strings = Arrays.asList(split);
return strings.stream().filter(s -> s.contains(query.toLowerCase())).count() > 0;
}
/**
* Returns a detailed message of the t, including the stack trace.
*/
public static String getDetails(Throwable t){
assert t != null;
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return t.getMessage() + "\n" + sw.toString();
}
/**
* Returns true if s represents an unsigned integer e.g. 1, 2, 3, ... <br>
* Will return false for null, empty string, "-1", "0", "+1", and " 2 " (untrimmed) "3 0" (contains whitespace).
* @param s Should be trimmed.
*/
public static boolean isUnsignedInteger(String s){
return s != null && s.matches("^0*[1-9]\\d*$");
}
} |
package server.service;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.UpdateResult;
import io.vertx.rxjava.core.Future;
import io.vertx.rxjava.core.Vertx;
import io.vertx.rxjava.ext.jdbc.JDBCClient;
import java.util.List;
import java.util.Map;
import static io.vertx.rxjava.core.Future.failedFuture;
import static io.vertx.rxjava.core.Future.future;
import static java.lang.System.currentTimeMillis;
import static server.service.DatabaseService.Column.*;
import static server.service.DatabaseService.SQLCommand.INSERT;
import static server.service.DatabaseService.SQLCommand.UPDATE;
import static server.service.DatabaseService.createDataMap;
import static server.util.CommonUtils.*;
import static server.util.StringUtils.*;
/**
* Database service implementation.
*/
public class DatabaseServiceImpl implements DatabaseService {
private static final String SQL_INSERT_EPISODE =
"INSERT IGNORE INTO Series (Username, SeriesId, EpisodeId, SeasonId, Time) VALUES (?, ?, ?, ?, ?)";
private static final String SQL_GET_YEARS_DIST =
"SELECT Year, COUNT(*) AS 'Count' FROM Views " +
"JOIN Movies ON Movies.Id = Views.MovieId " +
"WHERE Username = ? AND Start >= ? AND Start <= ?";
private static final String SQL_GET_WEEKDAYS_DIST =
"SELECT ((DAYOFWEEK(Start) + 5) % 7) AS Day, COUNT(*) AS 'Count' " +
"FROM Views " +
"WHERE Username = ? AND Start >= ? AND Start <= ?";
private static final String SQL_GET_TIME_DIST =
"SELECT HOUR(Start) AS Hour, COUNT(*) AS Count FROM Views " +
"WHERE Username = ? AND Start >= ? AND Start <= ? ";
private static final String SQL_GET_MONTH_YEAR_DIST =
"SELECT MONTH(Start) AS Month, YEAR(Start) AS Year, COUNT(MONTHNAME(Start)) AS Count " +
"FROM Views " +
"WHERE Username = ? AND Start >= ? AND Start <= ? ";
private static final String SQL_GET_ALL_TIME_META =
"SELECT DATE(Min(Start)) AS Start, COUNT(*) AS Count, " +
"SUM(TIMESTAMPDIFF(MINUTE, Start, End)) AS Runtime FROM Views " +
"WHERE Username = ?";
private static final String SQL_INSERT_USER =
"INSERT INTO Users (Username, Firstname, Lastname, Password, Salt) VALUES (?, ?, ?, ?, ?)";
private static final String SQL_QUERY_USERS = "SELECT * FROM Users " +
"JOIN Settings ON Users.Username = Settings.Username";
private static final String SQL_QUERY_USER = "SELECT * FROM Users " +
"JOIN Settings ON Users.Username = Settings.Username " +
"WHERE Users.Username = ?";
private static final String SQL_INSERT_VIEW =
"INSERT INTO Views (Username, MovieId, Start, End, WasFirst, WasCinema, Comment) " +
"VALUES (?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_QUERY_VIEWS =
"SELECT Views.Id, MovieId, Title, Start, WasFirst, WasCinema, Image, Comment, " +
"TIMESTAMPDIFF(MINUTE, Start, End) AS Runtime " +
"FROM Views " +
"JOIN Movies ON Views.MovieId = Movies.Id " +
"WHERE Username = ? AND Start >= ? AND Start <= ?";
private static final String SQL_GET_TOP_MOVIES_STAT =
"SELECT MovieId, Title, COUNT(*) AS Count, Image FROM Views " +
"JOIN Movies ON Movies.Id = Views.MovieId " +
"WHERE Username = ? AND Start >= ? AND Start <= ?";
private static final String SQL_QUERY_SETTINGS = "SELECT * FROM Settings WHERE Username = ?";
private static final String SQL_INSERT_MOVIE =
"INSERT IGNORE INTO Movies VALUES (?, ?, ?, ?)";
private static final String SQL_INSERT_SERIES =
"INSERT IGNORE INTO SeriesInfo VALUES (?, ?, ?)";
private static final String SQL_USERS_COUNT = "SELECT COUNT(*) AS Count FROM Users";
private static final String SQL_GET_MOVIE_VIEWS =
"SELECT Id, Start, WasCinema FROM Views" +
" WHERE Username = ? AND MovieId = ?" +
" ORDER BY Start DESC";
private static final String SQL_QUERY_VIEWS_META =
"SELECT Count(*) AS Count, SUM(TIMESTAMPDIFF(MINUTE, Start, End)) AS Runtime " +
"FROM Views " +
"JOIN Movies ON Views.MovieId = Movies.Id " +
"WHERE Username = ? AND Start >= ? AND Start <= ?";
private static final String SQL_REMOVE_VIEW =
"DELETE FROM Views WHERE Username = ? AND Id = ?";
private static final String SQL_REMOVE_EPISODE =
"DELETE FROM Series WHERE Username = ? AND EpisodeId = ?";
private static final String SQL_GET_SEEN_EPISODES = "SELECT EpisodeId FROM Series " +
"WHERE Username = ? AND SeriesId = ?";
private static final String SQL_GET_WATCHING_SERIES =
"SELECT Title, Image, Series.SeriesId, COUNT(Series.SeriesId) AS Count, Active FROM Series " +
"JOIN SeriesInfo ON Series.SeriesId = SeriesInfo.Id " +
"JOIN UserSeriesInfo ON Series.SeriesId = UserSeriesInfo.SeriesId " +
"WHERE Series.Username = ? AND UserSeriesInfo.Username = ? AND Active " +
"GROUP BY Series.SeriesId, Active " +
"ORDER BY Title;";
private static final String SQL_GET_LAST_VIEWS =
"SELECT Title, Start, MovieId, WEEKDAY(Start) AS 'week_day', WasCinema FROM Views " +
"JOIN Movies ON Movies.Id = Views.MovieId " +
"WHERE Username = ? " +
"ORDER BY Start DESC LIMIT 5";
private static final String SQL_GET_TOP_MOVIES =
"SELECT MovieId, Title, COUNT(*) AS Count, Image FROM Views " +
"JOIN Movies ON Movies.Id = Views.MovieId " +
"WHERE Username = ? " +
"GROUP BY MovieId ORDER BY Count DESC, AVG(Start) DESC LIMIT 5";
private static final String SQL_GET_TOTAL_MOVIE_COUNT =
"SELECT COUNT(*) AS 'total_movies', SUM(TIMESTAMPDIFF(MINUTE, Start, End)) AS Runtime FROM Views " +
"WHERE Username = ?";
private static final String SQL_GET_TOTAL_CINEMA_COUNT =
"SELECT COUNT(*) AS 'total_cinema' FROM Views " +
"WHERE Username = ? AND WasCinema = 1";
private static final String SQL_GET_NEW_MOVIE_COUNT =
"SELECT COUNT(WasFirst) AS 'new_movies' FROM Views " +
"WHERE Username = ? " +
"AND WasFirst = 1";
private static final String SQL_GET_TOTAL_RUNTIME =
"SELECT SUM(TIMESTAMPDIFF(MINUTE, Start, End)) AS Runtime FROM Views " +
"WHERE Username = ?";
private static final String SQL_GET_TOTAL_DISTINCT_MOVIES =
"SELECT COUNT(DISTINCT MovieId) AS 'unique_movies' FROM Views " +
"WHERE Username = ?";
private static final String SQL_INSERT_SEASON =
"INSERT IGNORE INTO Series (Username, SeriesId, EpisodeId, SeasonId, Time) VALUES";
private static final String SQL_REMOVE_SEASON =
"DELETE FROM Series WHERE Username = ? AND SeasonId = ?;";
private static final String SQL_INSERT_NEW_LIST =
"INSERT INTO ListsInfo (Username, ListName, TimeCreated) VALUES (?, ?, ?);";
private static final String SQL_GET_LISTS =
"SELECT Id, ListName FROM ListsInfo WHERE Username = ? AND Active ORDER BY TimeCreated ASC;";
private static final String SQL_GET_LISTS_SIZE =
"SELECT ListsInfo.Id as id, IFNULL((SELECT COUNT(ListId) FROM ListEntries " +
"WHERE Username = ? AND ListEntries.ListId = ListsInfo.Id GROUP BY ListId), 0) AS count, " +
"IFNULL((SELECT SUM(MovieId IN (SELECT DISTINCT MovieId FROM Views WHERE Username = ?)) AS seen " +
"FROM ListEntries WHERE Username = ? AND ListEntries.ListId = ListsInfo.Id " +
"GROUP BY ListId), 0) AS seen FROM ListsInfo WHERE Username = ? AND Active ORDER BY TimeCreated ASC;";
private static final String SQL_INSERT_INTO_LIST =
"INSERT IGNORE INTO ListEntries VALUES (?, ?, ?, ?);";
private static final String SQL_REMOVE_FROM_LIST =
"DELETE FROM ListEntries WHERE Username = ? AND ListId = ? && MovieId = ?;";
private static final String SQL_GET_IN_LISTS =
"SELECT ListId FROM ListEntries WHERE Username = ? AND MovieId = ?;";
private static final String SQL_GET_LIST_ENTRIES =
"SELECT MovieId, Title, ListName, Year, Image, Time, ListId, " +
"MovieId IN (SELECT DISTINCT Views.MovieId " +
"FROM ListEntries " +
"JOIN Views ON ListEntries.MovieId = Views.MovieId " +
"WHERE Views.Username = ? AND ListEntries.Username = ? AND " +
"ListId = ?) AS Seen FROM ListEntries " +
"JOIN Movies ON ListEntries.MovieId = Movies.Id " +
"JOIN ListsInfo ON ListsInfo.Id = ListEntries.ListId " +
"WHERE ListEntries.Username = ? AND ListId = ? " +
"ORDER BY Time DESC;";
private static final String SQL_CHANGE_LIST_NAME =
"UPDATE ListsInfo SET ListName = ? WHERE Username = ? AND Id = ?;";
private static final String SQL_DELETE_LIST =
"UPDATE ListsInfo SET Active = 0 WHERE Username = ? AND Id = ?;";
private static final String SQL_GET_LIST_SEEN_MOVIES =
"SELECT DISTINCT Views.MovieId FROM ListEntries " +
"JOIN Views ON ListEntries.MovieId = Views.MovieId " +
"WHERE Views.Username = ? AND " +
"ListEntries.Username = ? AND " +
"ListId = ?;";
private static final String SQL_GET_LIST_NAME =
"SELECT ListName FROM ListsInfo WHERE Username = ? AND Id = ?;";
private static final String SQL_GET_LAST_LISTS_HOME =
"SELECT ListId, ListName, MovieId, Title, Year FROM ListEntries " +
"JOIN Movies ON Movies.Id = ListEntries.MovieId " +
"JOIN ListsInfo ON ListsInfo.Id = ListEntries.ListId " +
"WHERE ListEntries.Username = ? AND ACTIVE " +
"ORDER BY Time DESC LIMIT 5";
private static final String SQL_GET_DELETED_LISTS =
"SELECT Id, ListName, TimeCreated FROM ListsInfo WHERE Username = ? AND NOT Active ORDER BY TimeCreated ASC;";
private static final String SQL_RESTORE_DELETED_LIST =
"UPDATE ListsInfo SET Active = 1 WHERE Username = ? AND Id = ?;";
private static final String SQL_INSERT_USER_SERIES_INFO =
"INSERT IGNORE INTO UserSeriesInfo (Username, SeriesId) VALUES (?, ?);";
private static final String SQL_SET_SERIES_INACTIVE =
"UPDATE UserSeriesInfo SET Active = 0 WHERE Username = ? AND SeriesId = ?;";
private static final String SQL_GET_INACTIVE_SERIES =
"SELECT Title, Image, Series.SeriesId, COUNT(Series.SeriesId) AS Count, Active FROM Series " +
"JOIN SeriesInfo ON Series.SeriesId = SeriesInfo.Id " +
"JOIN UserSeriesInfo ON Series.SeriesId = UserSeriesInfo.SeriesId " +
"WHERE Series.Username = ? AND UserSeriesInfo.Username = ? AND NOT Active " +
"GROUP BY Series.SeriesId, Active " +
"ORDER BY Title;";
private static final String SQL_SET_SERIES_ACTIVE =
"UPDATE UserSeriesInfo SET Active = 1 WHERE Username = ? AND SeriesId = ?;";
private static final String SQL_GET_TODAY_IN_HISTORY =
"SELECT MovieId, Title, Year(Start) AS Year, WasCinema FROM Views " +
"JOIN Movies ON Movies.Id = Views.MovieId " +
"WHERE Username = ? AND " +
"DAYOFMONTH(Start) = DAYOFMONTH(DATE(NOW())) AND " +
"MONTH(Start) = MONTH(DATE(NOW())) ORDER BY YEAR DESC;";
private static final String SQL_GET_HOME_STATISTICS =
"SELECT " +
"(SELECT COUNT(*) FROM Views WHERE Username = ?) " +
"AS 'total_views', " +
"(SELECT COUNT(WasFirst) FROM Views WHERE Username = ? AND WasFirst = 1) " +
"AS 'first_view', " +
"(SELECT COUNT(DISTINCT MovieId) FROM Views WHERE Username = ?) " +
"AS 'unique_movies', " +
"(SELECT COUNT(*) FROM Views WHERE Username = ? AND WasCinema = 1) " +
"AS 'total_cinema', " +
"(SELECT SUM(TIMESTAMPDIFF(MINUTE, Start, End)) FROM Views WHERE Username = ?) " +
"AS 'total_runtime';";
private static final String SQL_GET_OSCAR_AWARDS = "" +
"SELECT cate.Name " +
"FROM Awards awar " +
" JOIN Category cate ON cate.Id = awar.CategoryId " +
"WHERE awar.MovieId = ?" +
" AND awar.Status = 'W' " +
"ORDER BY cate.Id asc;";
private JDBCClient client;
protected DatabaseServiceImpl(Vertx vertx, JsonObject config) {
if (config.containsKey("mysql")) {
this.client = JDBCClient.createShared(vertx, config.getJsonObject("mysql"));
}
}
private Future<JsonObject> query(String sql, JsonArray params) {
return future(fut -> client.rxGetConnection()
.flatMap(conn -> conn.rxQueryWithParams(sql, params).doAfterTerminate(conn::close))
.map(ResultSet::toJson)
.subscribe(fut::complete, fut::fail));
}
private Future<JsonObject> updateOrInsert(String sql, JsonArray params) {
return future(fut -> client.rxGetConnection()
.flatMap(conn -> conn.rxUpdateWithParams(sql, params).doAfterTerminate(conn::close))
.map(UpdateResult::toJson)
.subscribe(fut::complete, fut::fail));
}
/**
* Inserts a Facebook, Google or IdCard user into database.
*/
@Override
public Future<JsonObject> insertUser(String username, String password, String firstname, String lastname) {
if (!nonNull(username, password, firstname, lastname) || contains("", username, firstname, lastname)) {
return failedFuture("Email, firstname and lastname must exist!");
}
return future(fut -> ifPresent(genString(), salt -> updateOrInsert(SQL_INSERT_USER, new JsonArray()
.add(username)
.add(firstname)
.add(lastname)
.add(hash(password, salt))
.add(salt)).rxSetHandler()
.doOnError(fut::fail)
.subscribe(res -> insert(Table.SETTINGS, createDataMap(username)).rxSetHandler()
.subscribe(result -> fut.complete(res), fut::fail))));
}
/**
* Inserts a view into views table.
*/
@Override
public Future<JsonObject> insertView(String user, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
return updateOrInsert(SQL_INSERT_VIEW, new JsonArray()
.add(user)
.add(json.getString("movieId"))
.add(movieDateToDBDate(json.getString("start")))
.add(movieDateToDBDate(json.getString("end")))
.add(json.getBoolean("wasFirst"))
.add(json.getBoolean("wasCinema"))
.add(json.getString("comment")));
}
/**
* Inserts a movie to movies table.
*/
@Override
public Future<JsonObject> insertMovie(int id, String movieTitle, int year, String posterPath) {
return updateOrInsert(SQL_INSERT_MOVIE, new JsonArray()
.add(id)
.add(movieTitle)
.add(year)
.add(posterPath));
}
@Override
public Future<JsonObject> insertSeries(int id, String seriesTitle, String posterPath) {
return updateOrInsert(SQL_INSERT_SERIES, new JsonArray()
.add(id)
.add(seriesTitle)
.add(posterPath));
}
@Override
public Future<JsonObject> insertEpisodeView(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
return updateOrInsert(SQL_INSERT_EPISODE, new JsonArray()
.add(username)
.add(json.getInteger("seriesId"))
.add(json.getInteger("episodeId"))
.add(json.getString("seasonId"))
.add(currentTimeMillis()));
}
@Override
public Future<JsonObject> getSeenEpisodes(String username, int seriesId) {
return query(SQL_GET_SEEN_EPISODES, new JsonArray().add(username).add(seriesId));
}
/**
* Gets settings for a user.
*/
@Override
public Future<JsonObject> getSettings(String username) {
return query(SQL_QUERY_SETTINGS, new JsonArray().add(username));
}
/**
* Updates data in a table.
*
* @param table to update data in
* @param data map of columns to update and data to be updated
* @return future of JsonObject containing update results
*/
@Override
public Future<JsonObject> update(Table table, Map<Column, String> data) { // TODO: 25.04.2017 test
if (data.get(USERNAME) == null) {
return failedFuture("Username required.");
} else if (data.size() == 1) {
return failedFuture("No columns specified.");
}
List<Column> columns = getSortedColumns(data);
return updateOrInsert(UPDATE.create(table, columns), getSortedValues(columns, data));
}
/**
* Inserts data to a table.
*
* @param table to insert data to
* @param data map of columns to insert to and data to be inserted
* @return future of JsonObject containing insertion results
*/
@Override
public Future<JsonObject> insert(Table table, Map<Column, String> data) { // TODO: 25.04.2017 test
if (data.get(USERNAME) == null) {
return failedFuture("Username required.");
}
List<Column> columns = getSortedColumns(data);
return updateOrInsert(INSERT.create(table, columns), getSortedValues(columns, data));
}
/**
* Gets data for a single user.
*/
@Override
public Future<JsonObject> getUser(String username) {
return query(SQL_QUERY_USER, new JsonArray().add(username));
}
/**
* Gets all users.
*/
@Override
public Future<JsonObject> getAllUsers() {
return query(SQL_QUERY_USERS, null);
}
/**
* Gets all movies views for user.
*/
@Override
public Future<JsonObject> getViews(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
//System.out.println(json.encodePrettily());
json.put("start", formToDBDate(json.getString("start"), false));
json.put("end", formToDBDate(json.getString("end"), true));
StringBuilder sb = new StringBuilder(SQL_QUERY_VIEWS);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
return query(sb.append(" ORDER BY Start DESC LIMIT ?, ?").toString(), new JsonArray()
.add(username)
.add(json.getString("start"))
.add(json.getString("end"))
.add(json.getInteger("page") * 10)
.add(10));
}
@Override
public Future<JsonObject> getTopMoviesStat(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
json.put("start", formToDBDate(json.getString("start"), false));
json.put("end", formToDBDate(json.getString("end"), true));
StringBuilder sb = new StringBuilder(SQL_GET_TOP_MOVIES_STAT);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
return query(sb.append(" GROUP BY MovieId ORDER BY Count DESC LIMIT 3").toString(), new JsonArray()
.add(username)
.add(json.getString("start"))
.add(json.getString("end")));
}
@Override
public Future<JsonObject> getYearsDistribution(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
json.put("start", formToDBDate(json.getString("start"), false));
json.put("end", formToDBDate(json.getString("end"), true));
StringBuilder sb = new StringBuilder(SQL_GET_YEARS_DIST);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
return query(sb.append(" GROUP BY Year ORDER BY Year DESC").toString(), new JsonArray()
.add(username)
.add(json.getString("start"))
.add(json.getString("end")));
}
@Override
public Future<JsonObject> getWeekdaysDistribution(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
json.put("start", formToDBDate(json.getString("start"), false));
json.put("end", formToDBDate(json.getString("end"), true));
StringBuilder sb = new StringBuilder(SQL_GET_WEEKDAYS_DIST);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
return query(sb.append(" GROUP BY Day ORDER BY Day").toString(), new JsonArray()
.add(username)
.add(json.getString("start"))
.add(json.getString("end")));
}
@Override
public Future<JsonObject> getTimeDistribution(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
json.put("start", formToDBDate(json.getString("start"), false));
json.put("end", formToDBDate(json.getString("end"), true));
StringBuilder sb = new StringBuilder(SQL_GET_TIME_DIST);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
return query(sb.append(" GROUP BY Hour").toString(), new JsonArray()
.add(username)
.add(json.getString("start"))
.add(json.getString("end")));
}
@Override
public Future<JsonObject> getMonthYearDistribution(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
json.put("start", formToDBDate(json.getString("start"), false));
json.put("end", formToDBDate(json.getString("end"), true));
StringBuilder sb = new StringBuilder(SQL_GET_MONTH_YEAR_DIST);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
return query(sb.append(" GROUP BY Month, Year ORDER BY Year, Month").toString(), new JsonArray()
.add(username)
.add(json.getString("start"))
.add(json.getString("end")));
}
/**
* Gets a specific movie views for user.
*/
@Override
public Future<JsonObject> getMovieViews(String username, String movieId) {
return query(SQL_GET_MOVIE_VIEWS, new JsonArray().add(username).add(movieId));
}
@Override
public Future<JsonObject> getAllTimeMeta(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
StringBuilder sb = new StringBuilder(SQL_GET_ALL_TIME_META);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
return query(sb.toString(), new JsonArray().add(username));
}
@Override
public Future<JsonObject> getViewsMeta(String username, String jsonParam) {
JsonObject json = new JsonObject(jsonParam);
System.out.println(json.encodePrettily());
json.put("start", formToDBDate(json.getString("start"), false));
json.put("end", formToDBDate(json.getString("end"), true));
StringBuilder sb = new StringBuilder(SQL_QUERY_VIEWS_META);
ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst"));
ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema"));
System.out.println("QUERY");
System.out.println(sb.toString());
return query(sb.toString(), new JsonArray()
.add(username)
.add(json.getString("start"))
.add(json.getString("end")));
}
@Override
public Future<JsonObject> removeView(String username, String id) {
return updateOrInsert(SQL_REMOVE_VIEW, new JsonArray().add(username).add(id));
}
@Override
public Future<JsonObject> removeEpisode(String username, String episodeId) {
return updateOrInsert(SQL_REMOVE_EPISODE, new JsonArray().add(username).add(episodeId));
}
@Override
public Future<JsonObject> getWatchingSeries(String username) {
return query(SQL_GET_WATCHING_SERIES, new JsonArray()
.add(username)
.add(username));
}
@Override
public Future<JsonObject> getLastMoviesHome(String username) {
return query(SQL_GET_LAST_VIEWS, new JsonArray().add(username));
}
@Override
public Future<JsonObject> getTopMoviesHome(String username) {
return query(SQL_GET_TOP_MOVIES, new JsonArray().add(username));
}
@Override
public Future<JsonObject> getTotalMovieCount(String username) {
return query(SQL_GET_TOTAL_MOVIE_COUNT, new JsonArray().add(username));
}
@Override
public Future<JsonObject> getNewMovieCount(String username) {
return query(SQL_GET_NEW_MOVIE_COUNT, new JsonArray().add(username));
}
@Override
public Future<JsonObject> getTotalRuntime(String username) {
return query(SQL_GET_TOTAL_RUNTIME, new JsonArray().add(username));
}
@Override
public Future<JsonObject> getTotalDistinctMoviesCount(String username) {
return query(SQL_GET_TOTAL_DISTINCT_MOVIES, new JsonArray().add(username));
}
@Override
public Future<JsonObject> getTotalCinemaCount(String username) {
return query(SQL_GET_TOTAL_CINEMA_COUNT, new JsonArray().add(username));
}
@Override
public Future<JsonObject> insertSeasonViews(String username, JsonObject seasonData, String seriesId) { // TODO: 18/05/2017 test
StringBuilder query = new StringBuilder(SQL_INSERT_SEASON);
JsonArray episodes = seasonData.getJsonArray("episodes");
JsonArray values = new JsonArray();
ifFalse(episodes.isEmpty(), () -> {
episodes.stream()
.map(obj -> (JsonObject) obj)
.peek(json -> query.append(" (?, ?, ?, ?, ?),"))
.forEach(json -> values
.add(username)
.add(seriesId)
.add(json.getInteger("id"))
.add(seasonData.getString("_id"))
.add(currentTimeMillis()));
query.deleteCharAt(query.length() - 1);
});
return updateOrInsert(query.toString(), values);
}
@Override
public Future<JsonObject> insertList(String username, String listName) {
return updateOrInsert(SQL_INSERT_NEW_LIST, new JsonArray()
.add(username)
.add(listName)
.add(currentTimeMillis()));
}
@Override
public Future<JsonObject> removeSeasonViews(String username, String seasonId) {
return updateOrInsert(SQL_REMOVE_SEASON, new JsonArray().add(username).add(seasonId));
}
@Override
public Future<JsonObject> getLists(String username) {
return query(SQL_GET_LISTS, new JsonArray()
.add(username));
}
@Override
public Future<JsonObject> getDeletedLists(String username) {
return query(SQL_GET_DELETED_LISTS, new JsonArray().add(username));
}
@Override
public Future<JsonObject> insertIntoList(String username, String jsonParam) {
return updateOrInsert(SQL_INSERT_INTO_LIST, new JsonArray()
.add(username)
.add(new JsonObject(jsonParam).getString("listId"))
.add(new JsonObject(jsonParam).getString("movieId"))
.add(currentTimeMillis()));
}
@Override
public Future<JsonObject> removeFromList(String username, String jsonParam) {
return updateOrInsert(SQL_REMOVE_FROM_LIST, new JsonArray()
.add(username)
.add(new JsonObject(jsonParam).getString("listId"))
.add(new JsonObject(jsonParam).getString("movieId")));
}
@Override
public Future<JsonObject> getInLists(String username, String movieId) {
return query(SQL_GET_IN_LISTS, new JsonArray()
.add(username)
.add(movieId));
}
@Override
public Future<JsonObject> getListEntries(String username, String listId) {
return query(SQL_GET_LIST_ENTRIES, new JsonArray()
.add(username)
.add(username)
.add(listId)
.add(username)
.add(listId));
}
@Override
public Future<JsonObject> changeListName(String username, String param) {
return updateOrInsert(SQL_CHANGE_LIST_NAME, new JsonArray()
.add(new JsonObject(param).getString("listName"))
.add(username)
.add(new JsonObject(param).getString("listId")));
}
@Override
public Future<JsonObject> deleteList(String username, String listId) {
return updateOrInsert(SQL_DELETE_LIST, new JsonArray()
.add(username)
.add(listId));
}
@Override
public Future<JsonObject> getListSeenMovies(String username, String listId) {
return query(SQL_GET_LIST_SEEN_MOVIES, new JsonArray()
.add(username)
.add(username)
.add(listId));
}
@Override
public Future<JsonObject> getListName(String username, String listId) {
return query(SQL_GET_LIST_NAME, new JsonArray()
.add(username)
.add(listId));
}
@Override
public Future<JsonObject> getLastListsHome(String username) {
return query(SQL_GET_LAST_LISTS_HOME, new JsonArray()
.add(username));
}
@Override
public Future<JsonObject> restoreDeletedList(String username, String listId) {
return updateOrInsert(SQL_RESTORE_DELETED_LIST, new JsonArray()
.add(username)
.add(listId));
}
@Override
public Future<JsonObject> getListsSize(String username) {
return query(SQL_GET_LISTS_SIZE, new JsonArray()
.add(username)
.add(username)
.add(username)
.add(username));
}
@Override
public Future<JsonObject> insertUserSeriesInfo(String username, String seriesId) {
return updateOrInsert(SQL_INSERT_USER_SERIES_INFO, new JsonArray()
.add(username)
.add(seriesId));
}
@Override
public Future<JsonObject> changeSeriesToInactive(String username, String seriesId) {
return updateOrInsert(SQL_SET_SERIES_INACTIVE, new JsonArray()
.add(username)
.add(seriesId));
}
@Override
public Future<JsonObject> getInactiveSeries(String username) {
return query(SQL_GET_INACTIVE_SERIES, new JsonArray()
.add(username)
.add(username));
}
@Override
public Future<JsonObject> changeSeriesToActive(String username, String seriesId) {
return updateOrInsert(SQL_SET_SERIES_ACTIVE, new JsonArray()
.add(username)
.add(seriesId));
}
@Override
public Future<JsonObject> getTodayInHistory(String username) {
return query(SQL_GET_TODAY_IN_HISTORY, new JsonArray()
.add(username));
}
/**
* Gets users count in database.
*/
@Override
public Future<JsonObject> getUsersCount() {
return future(fut -> query(SQL_USERS_COUNT, null).rxSetHandler()
.map(DatabaseService::getRows)
.map(array -> array.getJsonObject(0))
.subscribe(fut::complete, fut::fail));
}
@Override
public Future<JsonObject> getHomeStatistics(String username) {
return query(SQL_GET_HOME_STATISTICS, new JsonArray()
.add(username)
.add(username)
.add(username)
.add(username)
.add(username));
}
@Override
public Future<JsonObject> getOscarAwards(String movieId) {
return query(SQL_GET_OSCAR_AWARDS, new JsonArray()
.add(movieId));
}
} |
package sklearn2pmml.pipeline;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import h2o.estimators.BaseEstimator;
import numpy.core.NDArray;
import numpy.core.ScalarUtil;
import org.dmg.pmml.DataField;
import org.dmg.pmml.DataType;
import org.dmg.pmml.DerivedField;
import org.dmg.pmml.Extension;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.MiningBuildTask;
import org.dmg.pmml.MiningFunction;
import org.dmg.pmml.Model;
import org.dmg.pmml.OpType;
import org.dmg.pmml.Output;
import org.dmg.pmml.OutputField;
import org.dmg.pmml.PMML;
import org.dmg.pmml.Predicate;
import org.dmg.pmml.ResultFeature;
import org.dmg.pmml.True;
import org.dmg.pmml.Value;
import org.dmg.pmml.VerificationField;
import org.dmg.pmml.Visitor;
import org.dmg.pmml.VisitorAction;
import org.dmg.pmml.mining.MiningModel;
import org.dmg.pmml.mining.Segment;
import org.dmg.pmml.mining.Segmentation;
import org.dmg.pmml.mining.Segmentation.MultipleModelMethod;
import org.jpmml.converter.CMatrixUtil;
import org.jpmml.converter.CategoricalLabel;
import org.jpmml.converter.ContinuousLabel;
import org.jpmml.converter.Feature;
import org.jpmml.converter.Label;
import org.jpmml.converter.ModelUtil;
import org.jpmml.converter.Schema;
import org.jpmml.converter.ValueUtil;
import org.jpmml.converter.WildcardFeature;
import org.jpmml.converter.visitors.AbstractExtender;
import org.jpmml.model.visitors.AbstractVisitor;
import org.jpmml.sklearn.ClassDictUtil;
import org.jpmml.sklearn.PyClassDict;
import org.jpmml.sklearn.SkLearnEncoder;
import org.jpmml.sklearn.TupleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sklearn.Classifier;
import sklearn.ClassifierUtil;
import sklearn.Estimator;
import sklearn.HasClassifierOptions;
import sklearn.HasEstimator;
import sklearn.HasNumberOfFeatures;
import sklearn.Initializer;
import sklearn.Transformer;
import sklearn.TransformerUtil;
import sklearn.TypeUtil;
import sklearn.pipeline.Pipeline;
public class PMMLPipeline extends Pipeline implements HasEstimator<Estimator> {
public PMMLPipeline(){
this("sklearn2pmml", "PMMLPipeline");
}
public PMMLPipeline(String module, String name){
super(module, name);
}
public PMML encodePMML(){
List<? extends Transformer> transformers = getTransformers();
Estimator estimator = getEstimator();
Transformer predictTransformer = getPredictTransformer();
Transformer predictProbaTransformer = getPredictProbaTransformer();
Transformer applyTransformer = getApplyTransformer();
List<String> activeFields = getActiveFields();
List<String> probabilityFields = null;
List<String> targetFields = getTargetFields();
String repr = getRepr();
Verification verification = getVerification();
SkLearnEncoder encoder = new SkLearnEncoder();
Label label = null;
if(estimator.isSupervised()){
String targetField = null;
if(targetFields != null){
ClassDictUtil.checkSize(1, targetFields);
targetField = targetFields.get(0);
} // End if
if(targetField == null){
targetField = "y";
logger.warn("Attribute \'" + ClassDictUtil.formatMember(this, "target_fields") + "\' is not set. Assuming {} as the name of the target field", targetField);
}
MiningFunction miningFunction = estimator.getMiningFunction();
switch(miningFunction){
case CLASSIFICATION:
{
List<?> classes = ClassifierUtil.getClasses(estimator);
Map<String, Map<String, ?>> classExtensions = (Map)estimator.getOption(HasClassifierOptions.OPTION_CLASS_EXTENSIONS, null);
DataType dataType = TypeUtil.getDataType(classes, DataType.STRING);
List<String> categories = ClassifierUtil.formatTargetCategories(classes);
DataField dataField = encoder.createDataField(FieldName.create(targetField), OpType.CATEGORICAL, dataType, categories);
List<Visitor> visitors = new ArrayList<>();
if(classExtensions != null){
Collection<? extends Map.Entry<String, Map<String, ?>>> entries = classExtensions.entrySet();
for(Map.Entry<String, Map<String, ?>> entry : entries){
String name = entry.getKey();
Map<String, ?> values = entry.getValue();
Visitor valueExtender = new AbstractExtender(name){
@Override
public VisitorAction visit(Value pmmlValue){
Object value = values.get(pmmlValue.getValue());
if(value != null){
value = ScalarUtil.decode(value);
addExtension(pmmlValue, ValueUtil.formatValue(value));
}
return super.visit(pmmlValue);
}
};
visitors.add(valueExtender);
}
}
for(Visitor visitor : visitors){
visitor.applyTo(dataField);
}
label = new CategoricalLabel(dataField);
}
break;
case REGRESSION:
{
DataField dataField = encoder.createDataField(FieldName.create(targetField), OpType.CONTINUOUS, DataType.DOUBLE);
label = new ContinuousLabel(dataField);
}
break;
default:
throw new IllegalArgumentException();
}
}
List<Feature> features = new ArrayList<>();
PyClassDict featureInitializer = estimator;
try {
Transformer transformer = TransformerUtil.getHead(transformers);
if(transformer != null){
featureInitializer = transformer;
if(!(transformer instanceof Initializer)){
features = initFeatures(transformer, transformer.getOpType(), transformer.getDataType(), encoder);
}
features = encodeFeatures(features, encoder);
} else
{
features = initFeatures(estimator, estimator.getOpType(), estimator.getDataType(), encoder);
}
} catch(UnsupportedOperationException uoe){
throw new IllegalArgumentException("The first transformer or estimator object (" + ClassDictUtil.formatClass(featureInitializer) + ") does not specify feature type information", uoe);
}
int numberOfFeatures = estimator.getNumberOfFeatures();
if(numberOfFeatures > -1){
ClassDictUtil.checkSize(numberOfFeatures, features);
}
Schema schema = new Schema(label, features);
Model model = estimator.encodeModel(schema);
if(predictTransformer != null){
Output output;
if(model instanceof MiningModel){
MiningModel miningModel = (MiningModel)model;
Model finalModel = getFinalModel(miningModel);
output = ModelUtil.ensureOutput(finalModel);
} else
{
output = ModelUtil.ensureOutput(model);
}
FieldName name = FieldName.create("predict(" + (label.getName()).getValue() + ")");
OutputField predictField;
if(label instanceof ContinuousLabel){
predictField = ModelUtil.createPredictedField(name, label.getDataType(), OpType.CONTINUOUS)
.setFinalResult(false);
} else
if(label instanceof CategoricalLabel){
predictField = ModelUtil.createPredictedField(name, label.getDataType(), OpType.CATEGORICAL)
.setFinalResult(false);
} else
{
throw new IllegalArgumentException();
}
output.addOutputFields(predictField);
encodeOutput(predictTransformer, model, Collections.singletonList(predictField));
} // End if
if(predictProbaTransformer != null){
CategoricalLabel categoricalLabel = (CategoricalLabel)label;
List<OutputField> predictProbaFields = ModelUtil.createProbabilityFields(DataType.DOUBLE, categoricalLabel.getValues());
encodeOutput(predictProbaTransformer, model, predictProbaFields);
} // End if
if(applyTransformer != null){
OutputField nodeIdField = ModelUtil.createEntityIdField(FieldName.create("nodeId"))
.setDataType(DataType.INTEGER);
encodeOutput(applyTransformer, model, Collections.singletonList(nodeIdField));
} // End if
verification:
if(estimator.isSupervised()){
if(verification == null){
logger.warn("Model verification data is not set. Use method '" + ClassDictUtil.formatMember(this, "verify(X)") + "' to correct this deficiency");
break verification;
} // End if
if(activeFields == null){
throw new IllegalArgumentException();
}
int[] activeValuesShape = verification.getActiveValuesShape();
int[] targetValuesShape = verification.getTargetValuesShape();
ClassDictUtil.checkShapes(0, activeValuesShape, targetValuesShape);
ClassDictUtil.checkShapes(1, activeFields.size(), activeValuesShape);
List<?> activeValues = verification.getActiveValues();
List<?> targetValues = verification.getTargetValues();
int[] probabilityValuesShape = null;
List<? extends Number> probabilityValues = null;
boolean hasProbabilityValues = verification.hasProbabilityValues();
if(estimator instanceof BaseEstimator){
BaseEstimator baseEstimator = (BaseEstimator)estimator;
hasProbabilityValues &= baseEstimator.hasProbabilityDistribution();
} else
if(estimator instanceof Classifier){
Classifier classifier = (Classifier)estimator;
hasProbabilityValues &= classifier.hasProbabilityDistribution();
} else
{
hasProbabilityValues = false;
} // End if
if(hasProbabilityValues){
probabilityValuesShape = verification.getProbabilityValuesShape();
probabilityFields = new ArrayList<>();
CategoricalLabel categoricalLabel = (CategoricalLabel)label;
List<String> values = categoricalLabel.getValues();
for(String value : values){
probabilityFields.add("probability(" + value + ")"); // XXX
}
ClassDictUtil.checkShapes(0, activeValuesShape, probabilityValuesShape);
ClassDictUtil.checkShapes(1, probabilityFields.size(), probabilityValuesShape);
probabilityValues = verification.getProbabilityValues();
}
Number precision = verification.getPrecision();
Number zeroThreshold = verification.getZeroThreshold();
int rows = activeValuesShape[0];
Map<VerificationField, List<?>> data = new LinkedHashMap<>();
if(activeFields != null){
for(int i = 0; i < activeFields.size(); i++){
VerificationField verificationField = ModelUtil.createVerificationField(FieldName.create(activeFields.get(i)));
data.put(verificationField, CMatrixUtil.getColumn(activeValues, rows, activeFields.size(), i));
}
} // End if
if(probabilityFields != null){
for(int i = 0; i < probabilityFields.size(); i++){
VerificationField verificationField = ModelUtil.createVerificationField(FieldName.create(probabilityFields.get(i)))
.setPrecision(precision.doubleValue())
.setZeroThreshold(zeroThreshold.doubleValue());
data.put(verificationField, CMatrixUtil.getColumn(probabilityValues, rows, probabilityFields.size(), i));
}
} else
{
for(int i = 0; i < targetFields.size(); i++){
VerificationField verificationField = ModelUtil.createVerificationField(FieldName.create(targetFields.get(i)));
DataType dataType = label.getDataType();
switch(dataType){
case DOUBLE:
case FLOAT:
verificationField
.setPrecision(precision.doubleValue())
.setZeroThreshold(zeroThreshold.doubleValue());
break;
default:
break;
}
data.put(verificationField, CMatrixUtil.getColumn(targetValues, rows, targetFields.size(), i));
}
}
model.setModelVerification(ModelUtil.createModelVerification(data));
}
PMML pmml = encoder.encodePMML(model);
if(repr != null){
Extension extension = new Extension()
.addContent(repr);
MiningBuildTask miningBuildTask = new MiningBuildTask()
.addExtensions(extension);
pmml.setMiningBuildTask(miningBuildTask);
}
return pmml;
}
private List<Feature> initFeatures(PyClassDict object, OpType opType, DataType dataType, SkLearnEncoder encoder){
List<String> activeFields = getActiveFields();
if(activeFields == null){
int numberOfFeatures = -1;
if(object instanceof HasNumberOfFeatures){
HasNumberOfFeatures hasNumberOfFeatures = (HasNumberOfFeatures)object;
numberOfFeatures = hasNumberOfFeatures.getNumberOfFeatures();
} // End if
if(numberOfFeatures < 0){
throw new IllegalArgumentException("The first transformer or estimator object (" + ClassDictUtil.formatClass(object) + ") does not specify the number of input features");
}
activeFields = new ArrayList<>(numberOfFeatures);
for(int i = 0, max = numberOfFeatures; i < max; i++){
activeFields.add("x" + String.valueOf(i + 1));
}
logger.warn("Attribute \'" + ClassDictUtil.formatMember(this, "active_fields") + "\' is not set. Assuming {} as the names of active fields", activeFields);
}
List<Feature> result = new ArrayList<>();
for(String activeField : activeFields){
DataField dataField = encoder.createDataField(FieldName.create(activeField), opType, dataType);
result.add(new WildcardFeature(encoder, dataField));
}
return result;
}
private void encodeOutput(Transformer transformer, Model model, List<OutputField> outputFields){
SkLearnEncoder encoder = new SkLearnEncoder();
List<Feature> features = new ArrayList<>();
Set<FieldName> names = new HashSet<>();
for(OutputField outputField : outputFields){
FieldName name = outputField.getName();
DataField dataField = encoder.createDataField(name, outputField.getOpType(), outputField.getDataType());
features.add(new WildcardFeature(encoder, dataField));
names.add(name);
}
transformer.encodeFeatures(features, encoder);
class OutputFinder extends AbstractVisitor {
private Output output = null;
@Override
public VisitorAction visit(Output output){
if(output.hasOutputFields()){
List<OutputField> outputFields = output.getOutputFields();
Set<FieldName> definedNames = new HashSet<>();
for(OutputField outputField : outputFields){
FieldName name = outputField.getName();
definedNames.add(name);
}
if(definedNames.containsAll(names)){
setOutput(output);
return VisitorAction.TERMINATE;
}
}
return super.visit(output);
}
public Output getOutput(){
return this.output;
}
private void setOutput(Output output){
this.output = output;
}
}
OutputFinder outputFinder = new OutputFinder();
outputFinder.applyTo(model);
Output output = outputFinder.getOutput();
if(output == null){
throw new IllegalArgumentException();
}
Map<FieldName, DerivedField> derivedFields = encoder.getDerivedFields();
for(DerivedField derivedField : derivedFields.values()){
OutputField outputField = new OutputField(derivedField.getName(), derivedField.getDataType())
.setOpType(derivedField.getOpType())
.setResultFeature(ResultFeature.TRANSFORMED_VALUE)
.setExpression(derivedField.getExpression());
output.addOutputFields(outputField);
}
}
@Override
public List<? extends Transformer> getTransformers(){
List<Object[]> steps = getSteps();
if(steps.size() > 0){
steps = steps.subList(0, steps.size() - 1);
}
return TupleUtil.extractElementList(steps, 1, Transformer.class);
}
@Override
public Estimator getEstimator(){
List<Object[]> steps = getSteps();
if(steps.size() < 1){
throw new IllegalArgumentException("Expected one or more elements, got zero elements");
}
Object[] lastStep = steps.get(steps.size() - 1);
return TupleUtil.extractElement(lastStep, 1, Estimator.class);
}
@Override
public List<Object[]> getSteps(){
return super.getSteps();
}
public PMMLPipeline setSteps(List<Object[]> steps){
put("steps", steps);
return this;
}
public Transformer getPredictTransformer(){
return getTransformer("predict_transformer");
}
public Transformer getPredictProbaTransformer(){
return getTransformer("predict_proba_transformer");
}
public Transformer getApplyTransformer(){
return getTransformer("apply_transformer");
}
private Transformer getTransformer(String key){
Object transformer = get(key);
if(transformer == null){
return null;
}
return get(key, Transformer.class);
}
public List<String> getActiveFields(){
if(!containsKey("active_fields")){
return null;
}
return (List)getArray("active_fields", String.class);
}
public PMMLPipeline setActiveFields(List<String> activeFields){
put("active_fields", toArray(activeFields));
return this;
}
public List<String> getTargetFields(){
// SkLearn2PMML 0.24.3
if(containsKey("target_field")){
return Collections.singletonList((String)get("target_field"));
} // End if
// SkLearn2PMML 0.25+
if(!containsKey("target_fields")){
return null;
}
return (List)getArray("target_fields", String.class);
}
public PMMLPipeline setTargetFields(List<String> targetFields){
put("target_fields", toArray(targetFields));
return this;
}
public String getRepr(){
return (String)get("repr_");
}
public PMMLPipeline setRepr(String repr){
put("repr_", repr);
return this;
}
public Verification getVerification(){
return (Verification)get("verification");
}
public PMMLPipeline setVerification(Verification verification){
put("verification", verification);
return this;
}
static
private Model getFinalModel(MiningModel miningModel){
Segmentation segmentation = miningModel.getSegmentation();
MultipleModelMethod multipleModelMethod = segmentation.getMultipleModelMethod();
switch(multipleModelMethod){
case SELECT_FIRST:
case SELECT_ALL:
throw new IllegalArgumentException();
case MODEL_CHAIN:
{
List<Segment> segments = segmentation.getSegments();
Segment lastSegment = segments.get(segments.size() - 1);
Predicate predicate = lastSegment.getPredicate();
if(!(predicate instanceof True)){
throw new IllegalArgumentException();
}
Model model = lastSegment.getModel();
if(model instanceof MiningModel){
MiningModel finalMiningModel = (MiningModel)model;
return getFinalModel(finalMiningModel);
}
return model;
}
default:
break;
}
return miningModel;
}
static
private NDArray toArray(List<String> strings){
NDArray result = new NDArray();
result.put("data", strings);
result.put("fortran_order", Boolean.FALSE);
return result;
}
private static final Logger logger = LoggerFactory.getLogger(PMMLPipeline.class);
} |
package tacoo.monex.stock.summary;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class AllPrint {
private static final String YYYY_MM_DD = "yyyy/MM/dd";
static String baseDate = "";
public static void main(String[] args) {
AllPrint.printSummary(new File("19990101-20151229.csv"));
}
public static void printSummary(File csvFile) {
try (CSVParser parser = CSVFormat.EXCEL.parse(new InputStreamReader(
new FileInputStream(csvFile), "sjis"))) {
final Map<String, Integer> headerMap = new HashMap<>();
Map<String, Money> sums = new HashMap<>();
List<CSVRecord> csvDataList = new ArrayList<>();
filterHeaderAndMRF(parser, headerMap, csvDataList);
csvDataList.sort(new CSVRecordComparator(headerMap));
String year = "";
SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
DecimalFormat df = new DecimalFormat("
Map<String, Stock> stocks = new HashMap<>();
Map<String, String> stockCodeAndName = new HashMap<>();
for (CSVRecord r : csvDataList) {
Date date = sdf.parse(r.get(headerMap.get(baseDate)));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
String tmp = calendar.get(Calendar.YEAR) + "";
if (!"".equals(year) && !tmp.equals(year)) {
Money lastOne = sums.get(year);
Map<String, Stock> carryOverStocks = new HashMap<>();
for (String k : stocks.keySet()) {
Stock stock = stocks.get(k);
carryOverStocks.put(k, stock.clone());
}
lastOne.stocks = carryOverStocks;
}
year = calendar.get(Calendar.YEAR) + "";
Money money = sums.get(year);
if (money == null) {
money = new Money();
sums.put(year, money);
}
String tradeType = r.get(headerMap.get(""));
if ("".equals(tradeType)
|| "".equals(tradeType)
|| "".equals(tradeType)) {
money.credit += df.parse(r.get(headerMap.get("()"))).intValue();
} else if ("".equals(tradeType)
|| "".equals(tradeType)) {
money.credit -= df.parse(r.get(headerMap.get("()"))).intValue();
} else if ("".equals(tradeType)
|| "".equals(tradeType)) {
int tax = -df.parse(r.get(headerMap.get("()"))).intValue();
money.incomeTax += tax;
} else if ("".equals(tradeType)
|| "".equals(tradeType)) {
int tax = df.parse(r.get(headerMap.get("()"))).intValue();
money.incomeTax += tax;
} else if ("".equals(tradeType)
|| "".equals(tradeType)
|| "".equals(tradeType)
|| "".equals(tradeType)) {
money.yield += df.parse(r.get(headerMap.get("()"))).intValue();
} else if ("".equals(tradeType)) {
int value = df.parse(r.get(headerMap.get("()"))).intValue();
int qty = df.parse(r.get(headerMap.get("//"))).intValue();
int salesTax1 = df.parse(r.get(headerMap.get(""))).intValue();
int salesTax2 = df.parse(r.get(headerMap.get("()"))).intValue();
money.salesTaxFee += salesTax1;
money.salesTaxFee += salesTax2;
String stockCode = r.get(headerMap.get("")).trim();
String stockName = r.get(headerMap.get("")).trim();
stockCodeAndName.put(stockCode, stockName);
Stock stock = stocks.get(stockCode);
if (stock == null) {
stock = new Stock();
stocks.put(stockCode, stock);
}
int ave = ave(stock.total, stock.quantity, value, qty);
stock.name = stockCode + "-" + stockName;
stock.quantity += qty;
stock.total -= value;
stock.averagePrice = ave;
} else if ("".equals(tradeType)) {
int value = df.parse(r.get(headerMap.get("()"))).intValue();
int qty = df.parse(r.get(headerMap.get("//"))).intValue();
int salesTax1 = df.parse(r.get(headerMap.get(""))).intValue();
int salesTax2 = df.parse(r.get(headerMap.get("()"))).intValue();
money.salesTaxFee += salesTax1;
money.salesTaxFee += salesTax2;
String stockCode = r.get(headerMap.get("")).trim();
String stockName = r.get(headerMap.get("")).trim();
stockCodeAndName.put(stockCode, stockName);
Stock stock = stocks.get(stockCode);
if (stock == null) {
stock = new Stock();
stocks.put(stockCode, stock);
}
stock.name = stockCode + "-" + stockName;
int basePrice = stock.averagePrice * qty;
stock.quantity -= qty;
stock.total += basePrice;
money.taxableGain += value - basePrice;
if (stock.quantity == 0) {
money.nonTaxableGain += stock.total;
stocks.remove(stockCode);
}
} else {
System.out.println("unknown record found: " + r);
}
}
Money lastOne = sums.get(year);
Map<String, Stock> carryOverStocks = new HashMap<>();
for (String k : stocks.keySet()) {
Stock stock = stocks.get(k);
carryOverStocks.put(k, stock.clone());
}
lastOne.stocks = carryOverStocks;
String[] keys = sums.keySet().toArray(new String[0]);
Arrays.sort(keys, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
System.out.println(String.format("%7s%13s%13s%13s%13s%13s%13s%13s"
, "Year"
, "Credit"
, "Gain"
, "Gain(NoTax)"
, "Yield"
, "SalesTax/Fee"
, "IncomeTax"
, "Earned"));
int totalCredit = 0;
int totalGain = 0;
int totalNoTaxGain = 0;
int totalYeild = 0;
int totalSalesTax = 0;
int totalIncomeTax = 0;
for (String k : keys) {
Money money = sums.get(k);
System.out.println(String.format("%7s%13d%13d%13d%13d%13s%13d%13d"
, k
, money.credit
, money.taxableGain
, money.nonTaxableGain
, money.yield
, "(" + money.salesTaxFee + ")"
, money.incomeTax
, money.taxableGain + money.nonTaxableGain + money.yield - money.incomeTax));
totalCredit += money.credit;
totalGain += money.taxableGain;
totalNoTaxGain += money.nonTaxableGain;
totalYeild += money.yield;
totalSalesTax += money.salesTaxFee;
totalIncomeTax += money.incomeTax;
}
System.out.println();
System.out.println("Current Stocks");
System.out.println(String.format("%8s%13s%10s"
, "Quantity"
, "Amount"
, "Name"));
Money money = sums.get(keys[keys.length - 1]);
int totalStock = 0;
for (String id : money.stocks.keySet()) {
Stock stock = money.stocks.get(id);
System.out.println(String.format("%8d%13d %s", stock.quantity, stock.total, stock.name));
totalStock += stock.total;
}
System.out.println();
System.out.println("Total");
System.out.println(String.format("%13s%13s%13s%13s%13s%13s"
, "Credit"
, "Gain"
, "Gain(NoTax)"
, "Yield"
, "SalesTax/Fee"
, "IncomeTax"));
System.out.println(String.format("%13d%13d%13d%13d%13s%13d"
, totalCredit
, totalGain
, totalNoTaxGain
, totalYeild
, "(" + totalSalesTax + ")"
, totalIncomeTax));
System.out.println();
double doubleValue = BigDecimal.valueOf(totalGain + totalNoTaxGain + totalYeild - totalIncomeTax)
.divide(BigDecimal.valueOf(totalCredit), 4, RoundingMode.HALF_UP)
.multiply(BigDecimal.valueOf(100))
.doubleValue();
System.out.println(String.format("%-20s%,.2f%%", "Performance:", doubleValue));
System.out.println(String.format("%-20s%13d", "Total Stock Amount:", totalStock));
} catch (Exception e) {
e.printStackTrace();
}
}
private static int ave(int baseValue, int baseQty, int addedValue, int addedQty) {
int totalValue = Math.abs(baseValue) + Math.abs(addedValue);
int totalQty = Math.abs(baseQty) + Math.abs(addedQty);
return BigDecimal.valueOf(totalValue).divide(BigDecimal.valueOf(totalQty), 0, RoundingMode.UP).intValue();
}
private static void filterHeaderAndMRF(CSVParser parser, final Map<String, Integer> headerMap, List<CSVRecord> csvDataList) {
for (CSVRecord r : parser) {
if (r.getRecordNumber() == 1) {
continue;
}
if (r.getRecordNumber() == 2) {
headerMap.putAll(getHeader(r));
} else {
String name = r.get(headerMap.get(""));
if ("".equals(name)) {
continue;
}
csvDataList.add(r);
}
}
}
private static Map<String, Integer> getHeader(CSVRecord r) {
Map<String, Integer> headerMap = new HashMap<String, Integer>();
int i = 0;
for (String k : r) {
headerMap.put(k, i);
i++;
}
return headerMap;
}
private static final class CSVRecordComparator implements Comparator<CSVRecord> {
private final SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
private final Map<String, Integer> headerMap;
private CSVRecordComparator(Map<String, Integer> headerMap) {
this.headerMap = headerMap;
}
@Override
public int compare(CSVRecord r1, CSVRecord r2) {
try {
Date d1 = sdf.parse(r1.get(headerMap.get(baseDate)));
Date d2 = sdf.parse(r2.get(headerMap.get(baseDate)));
int comp1 = d1.compareTo(d2);
if (comp1 != 0) {
return comp1;
}
String t1 = r1.get(headerMap.get(""));
String t2 = r2.get(headerMap.get(""));
if (t1.equals("") && t2.equals("")) {
return 0;
} else if (t1.equals("")) {
return 1;
} else if (t2.equals("")) {
return -1;
}
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}
static class Money {
int credit = 0;
int yield = 0;
int incomeTax = 0;
int salesTaxFee = 0;
int taxableGain = 0;
int nonTaxableGain = 0;
Map<String, Stock> stocks = new HashMap<String, Stock>();
@Override
public String toString() {
return "Money [credit=" + credit + ", yield=" + yield + ", incomeTax=" + incomeTax + ", salesTaxFee=" + salesTaxFee + ", taxableGain=" + taxableGain
+ ", nonTaxableGain=" + nonTaxableGain + ", stocks=" + stocks + "]";
}
}
static class Stock {
String name;
int quantity;
int total;
int averagePrice;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Stock other = (Stock) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Stock [name=" + name + ", quantity=" + quantity + ", total=" + total + ", averagePrice=" + averagePrice + "]";
}
public Stock clone() {
Stock stock = new Stock();
stock.name = this.name;
stock.quantity = this.quantity;
stock.total = this.total;
stock.averagePrice = this.averagePrice;
return stock;
}
}
} |
package tlc2.tool;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.Collectors;
import tla2sany.semantic.ExprNode;
import tlc2.TLCGlobals;
import tlc2.module.TLCGetSet;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.output.StatePrinter;
import tlc2.tool.SimulationWorker.SimulationWorkerError;
import tlc2.tool.SimulationWorker.SimulationWorkerResult;
import tlc2.tool.coverage.CostModelCreator;
import tlc2.tool.impl.FastTool;
import tlc2.tool.impl.Tool;
import tlc2.tool.liveness.ILiveCheck;
import tlc2.tool.liveness.LiveCheck;
import tlc2.tool.liveness.LiveCheck1;
import tlc2.tool.liveness.LiveException;
import tlc2.tool.liveness.NoOpLiveCheck;
import tlc2.util.DotActionWriter;
import tlc2.util.RandomGenerator;
import tlc2.util.statistics.DummyBucketStatistics;
import tlc2.value.IValue;
import tlc2.value.impl.IntValue;
import tlc2.value.impl.RecordValue;
import tlc2.value.impl.StringValue;
import tlc2.value.impl.Value;
import util.Assert.TLCRuntimeException;
import util.FileUtil;
import util.FilenameToStream;
import util.UniqueString;
public class Simulator {
public static boolean EXPERIMENTAL_LIVENESS_SIMULATION = Boolean
.getBoolean(Simulator.class.getName() + ".experimentalLiveness");
private final String traceActions;
/* Constructors */
// SZ Feb 20, 2009: added the possibility to pass the SpecObject
public Simulator(String specFile, String configFile, String traceFile, boolean deadlock, int traceDepth,
long traceNum, RandomGenerator rng, long seed, FilenameToStream resolver,
int numWorkers) throws IOException {
this(new FastTool(extracted(specFile), configFile, resolver, Tool.Mode.Simulation), "", traceFile, deadlock,
traceDepth, traceNum, null, rng, seed, resolver, numWorkers);
}
private static String extracted(String specFile) {
int lastSep = specFile.lastIndexOf(FileUtil.separatorChar);
return specFile.substring(lastSep + 1);
}
public Simulator(ITool tool, String metadir, String traceFile, boolean deadlock, int traceDepth,
long traceNum, String traceActions, RandomGenerator rng, long seed, FilenameToStream resolver,
int numWorkers) throws IOException {
this.tool = tool;
this.checkDeadlock = deadlock && tool.getModelConfig().getCheckDeadlock();
this.checkLiveness = !this.tool.livenessIsTrue();
this.invariants = this.tool.getInvariants();
if (traceDepth != -1) {
// this.actionTrace = new Action[traceDepth]; // SZ: never read
// locally
this.traceDepth = traceDepth;
} else {
// this.actionTrace = new Action[0]; // SZ: never read locally
this.traceDepth = Integer.MAX_VALUE;
}
this.traceFile = traceFile;
this.traceNum = traceNum;
this.traceActions = traceActions;
this.rng = rng;
this.seed = seed;
this.aril = 0;
// Initialization for liveness checking
if (this.checkLiveness) {
if (EXPERIMENTAL_LIVENESS_SIMULATION) {
final String tmpDir = System.getProperty("java.io.tmpdir");
liveCheck = new LiveCheck(this.tool.getLiveness(), tmpDir, new DummyBucketStatistics());
} else {
liveCheck = new LiveCheck1(this.tool.getLiveness());
}
} else {
liveCheck = new NoOpLiveCheck(tool, metadir);
}
this.numWorkers = numWorkers;
this.workers = new ArrayList<>(numWorkers);
for (int i = 0; i < this.numWorkers; i++) {
this.workers.add(new SimulationWorker(i, this.tool, this.workerResultQueue, this.rng.nextLong(),
this.traceDepth, this.traceNum, this.traceActions, this.checkDeadlock, this.traceFile,
this.liveCheck, this.numOfGenStates, this.numOfGenTraces, this.welfordM2AndMean));
}
if (TLCGlobals.isCoverageEnabled()) {
CostModelCreator.create(this.tool);
}
//TODO Eventually derive Simulator from AbstractChecker.
AbstractChecker.scheduleTermination(new TimerTask() {
@Override
public void run() {
Simulator.this.stop();
}
});
}
/* Fields */
private final ILiveCheck liveCheck;
private final ITool tool;
private final Action[] invariants; // the invariants to be checked
private final boolean checkDeadlock; // check deadlock?
private final boolean checkLiveness; // check liveness?
// The total number of states/traces generated by all workers. May be written to
// concurrently, so we use a LongAdder to reduce potential contention.
private final LongAdder numOfGenStates = new LongAdder();
private final LongAdder numOfGenTraces = new LongAdder();
private final AtomicLong welfordM2AndMean = new AtomicLong();
// private Action[] actionTrace; // SZ: never read locally
private final String traceFile;
// The maximum length of a simulated trace.
private final int traceDepth;
// The maximum number of total traces to generate.
private final long traceNum;
// The number of worker threads to use for simulation.
private int numWorkers = 1;
private final RandomGenerator rng;
private final long seed;
private long aril;
// Each simulation worker pushes their results onto this shared queue.
protected final BlockingQueue<SimulationWorkerResult> workerResultQueue = new LinkedBlockingQueue<>();
/**
* Timestamp of when simulation started.
*/
private final long startTime = System.currentTimeMillis();
protected final List<SimulationWorker> workers;
/**
* Returns whether a given error code is considered "continuable". That is, if
* any worker returns this error, should we consider continuing to run the
* simulator. These errors are considered "fatal" since they most likely
* indicate an error in the way the spec is written.
*/
protected boolean isNonContinuableError(int ec) {
return ec == EC.TLC_INVARIANT_EVALUATION_FAILED ||
ec == EC.TLC_ACTION_PROPERTY_EVALUATION_FAILED ||
ec == EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_NEXT;
}
/**
* Shut down all of the given workers and make sure they have stopped.
*/
private void shutdownAndJoinWorkers(final List<SimulationWorker> workers) throws InterruptedException {
for (SimulationWorker worker : workers) {
worker.interrupt();
worker.join();
}
}
/*
* This method does random simulation on a TLA+ spec.
*
* It runs until an error is encountered or we have generated the maximum number of traces.
*
* @return an error code, or <code>EC.NO_ERROR</code> on success
*/
public int simulate() throws Exception {
final int res = this.tool.checkAssumptions();
if (res != EC.NO_ERROR) {
return res;
}
TLCState curState = null;
//TODO: Refactor to check validity and inModel via IStateFunctor.
final StateVec initStates;
// Compute the initial states.
try {
// The init states are calculated only ever once and never change
// in the loops below. Ideally the variable would be final.
final StateVec inits = this.tool.getInitStates();
initStates = new StateVec(inits.size());
// This counter should always be initialized at zero.
assert (this.numOfGenStates.longValue() == 0);
this.numOfGenStates.add(inits.size());
MP.printMessage(EC.TLC_COMPUTING_INIT_PROGRESS, this.numOfGenStates.toString());
// Check all initial states for validity.
for (int i = 0; i < inits.size(); i++) {
curState = inits.elementAt(i);
if (this.tool.isGoodState(curState)) {
for (int j = 0; j < this.invariants.length; j++) {
if (!this.tool.isValid(this.invariants[j], curState)) {
// We get here because of invariant violation.
return MP.printError(EC.TLC_INVARIANT_VIOLATED_INITIAL,
new String[] { this.tool.getInvNames()[j], curState.toString() });
}
}
} else {
return MP.printError(EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_INITIAL, curState.toString());
}
if (tool.isInModel(curState)) {
initStates.addElement(curState);
}
}
} catch (Exception e) {
final int errorCode;
if (curState != null) {
errorCode = MP.printError(EC.TLC_INITIAL_STATE,
new String[] { (e.getMessage() == null) ? e.toString() : e.getMessage(), curState.toString() });
} else {
errorCode = MP.printError(EC.GENERAL, e); // LL changed call 7 April 2012
}
this.printSummary();
return errorCode;
}
if (this.numOfGenStates.longValue() == 0) {
return MP.printError(EC.TLC_NO_STATES_SATISFYING_INIT);
}
// It appears deepNormalize brings the states into a canonical form to
// speed up equality checks.
initStates.deepNormalize();
// Start progress report thread.
final ProgressReport report = new ProgressReport();
report.start();
// Start simulating.
this.aril = rng.getAril();
int errorCode = simulate(initStates);
if (errorCode == EC.NO_ERROR) {
// see tlc2.tool.Worker.doPostCheckAssumption()
final ExprNode sn = (ExprNode) this.tool.getPostConditionSpec();
try {
if (sn != null && !this.tool.isValid(sn)) {
MP.printError(EC.TLC_ASSUMPTION_FALSE, sn.toString());
}
} catch (Exception e) {
// tool.isValid(sn) failed to evaluate...
MP.printError(EC.TLC_ASSUMPTION_EVALUATION_ERROR, new String[] { sn.toString(), e.getMessage() });
}
}
// Do a final progress report.
report.isRunning = false;
synchronized (report) {
report.notify();
}
// Wait for the progress reporter thread to finish.
report.join();
return errorCode;
}
protected int simulate(final StateVec initStates) throws InterruptedException {
// Start up multiple simulation worker threads, each with their own unique seed.
final Set<Integer> runningWorkers = new HashSet<>();
for (int i = 0; i < this.workers.size(); i++) {
SimulationWorker worker = workers.get(i);
worker.start(initStates);
runningWorkers.add(i);
}
int errorCode = EC.NO_ERROR;
// Continuously consume results from all worker threads.
while (true) {
final SimulationWorkerResult result = workerResultQueue.take();
// If the result is an error, print it.
if (result.isError()) {
SimulationWorkerError error = result.error();
// We assume that if a worker threw an unexpected exception, there is a bug
// somewhere, so we print out the exception and terminate. In the case of a
// liveness error, which is reported as an exception, we also terminate.
if (error.exception != null) {
if (error.exception instanceof LiveException) {
// In case of a liveness error, there is no need to print out
// the behavior since the liveness checker should take care of that itself.
this.printSummary();
errorCode = ((LiveException)error.exception).errorCode;
} else if (error.exception instanceof TLCRuntimeException) {
final TLCRuntimeException exception = (TLCRuntimeException)error.exception;
printBehavior(exception, error.state, error.stateTrace);
errorCode = exception.errorCode;
} else {
printBehavior(EC.GENERAL, new String[] { MP.ECGeneralMsg("", error.exception) }, error.state,
error.stateTrace);
errorCode = EC.GENERAL;
}
break;
}
// Print the trace for all other errors.
printBehavior(error);
// For certain, "fatal" errors, we shut down all workers and terminate,
// regardless of the "continue" parameter, since these errors likely indicate a bug in the spec.
if (isNonContinuableError(error.errorCode)) {
errorCode = error.errorCode;
break;
}
// If the 'continue' option is false, then we always terminate on the
// first error, shutting down all workers. Otherwise, we continue receiving
// results from the worker threads.
if (!TLCGlobals.continuation) {
errorCode = error.errorCode;
break;
}
if (errorCode == EC.NO_ERROR)
{
errorCode = EC.GENERAL;
}
}
// If the result is OK, this indicates that the worker has terminated, so we
// make note of this. If all of the workers have terminated, there is no need to
// continue waiting for results, so we should terminate.
else {
runningWorkers.remove(result.workerId());
if(runningWorkers.isEmpty()) {
break;
}
}
}
// Shut down all workers.
this.shutdownAndJoinWorkers(workers);
return errorCode;
}
protected final void printBehavior(final TLCRuntimeException exception, final TLCState state, final StateVec stateTrace) {
MP.printTLCRuntimeException(exception);
printBehavior(state, stateTrace);
}
protected final void printBehavior(SimulationWorkerError error) {
printBehavior(error.errorCode, error.parameters, error.state, error.stateTrace);
}
/**
* Prints out the simulation behavior, in case of an error. (unless we're at
* maximum depth, in which case don't!)
*/
protected final void printBehavior(final int errorCode, final String[] parameters, final TLCState state, final StateVec stateTrace) {
MP.printError(errorCode, parameters);
printBehavior(state, stateTrace);
this.printSummary();
}
private final void printBehavior(final TLCState state, final StateVec stateTrace) {
if (this.traceDepth == Long.MAX_VALUE) {
MP.printMessage(EC.TLC_ERROR_STATE);
StatePrinter.printStandaloneErrorState(state);
} else {
if (!stateTrace.isLastElement(state)) {
// MAK 09/24/2019: this method is called with state being the stateTrace's
// last element or not.
stateTrace.addElement(state);
}
MP.printError(EC.TLC_BEHAVIOR_UP_TO_THIS_POINT);
// MAK 09/24/2019: For space reasons, TLCState does not store the state's action.
// This is why the loop below creates TLCStateInfo instances out of the pair cur
// -> last to print the action's name as part of the error trace. This is
// especially useful for Error-Trace Explorer in the Toolbox.
TLCState lastState = null;
TLCStateInfo sinfo;
int omitted = 0;
for (int i = 0; i < stateTrace.size(); i++) {
final TLCState curState = stateTrace.elementAt(i);
// Last state's successor is itself.
final TLCState sucState = stateTrace.elementAt(Math.min(i + 1, stateTrace.size() - 1));
if (lastState != null) {
// Contrary to BFS/ModelChecker, simulation remembers the action (its id) during
// trace exploration to print the error-trace without re-evaluating the
// next-state relation for lastStates -> cusState (tool.getState(curState,
// lastState)) to determine the action. This would fail for specs whose next-state
// relation is probabilistic (ie. TLC!RandomElement or Randomization.tla). In other
// words, tool.getState(curState,lastState) would return for some pairs of states.
sinfo = new TLCStateInfo(curState);
} else {
sinfo = new TLCStateInfo(curState);
StatePrinter.printInvariantViolationStateTraceState(tool.evalAlias(sinfo, sucState), lastState,
curState.getLevel());
lastState = curState;
continue;
}
// MAK 09/25/2019: It is possible for
// tlc2.tool.SimulationWorker.simulateRandomTrace() to produce traces with
// *non-terminal* stuttering steps, i.e. it might produce traces such
// as s0,s1,s1,s2,s3,s3,s3,...sN* (where sN* represents an infinite suffix of
// "terminal" stuttering steps). In other words, it produces traces s.t.
// a trace has finite (sub-)sequence of stuttering steps.
// The reason is that simulateRandomTrace, with non-zero probability, selects
// a stuttering step as the current state's successor. Guarding against it
// would require to fingerprint states (i.e. check equality) for each selected
// successor state (which is considered too expensive).
// A trace with finite stuttering can be reduced to a shorter - hence
// better readable - trace with only infinite stuttering at the end. This
// takes mostly care of the confusing Toolbox behavior where a trace with
// finite stuttering is silently reduced by breadth-first-search when trace
// expressions are evaluated (see https://github.com/tlaplus/tlaplus/issues/400#issuecomment-650418597).
if (TLCGlobals.printDiffsOnly && curState.fingerPrint() == lastState.fingerPrint()) {
omitted++;
} else {
// print the state's actual level and not a monotonically increasing state
// number => Numbering will have gaps with difftrace.
StatePrinter.printInvariantViolationStateTraceState(tool.evalAlias(sinfo, sucState), lastState, curState.getLevel());
}
lastState = curState;
}
if (omitted > 0) {
assert TLCGlobals.printDiffsOnly;
MP.printMessage(EC.GENERAL, String.format(
"difftrace requested: Shortened behavior by omitting finite stuttering (%s states), which is an artifact of simulation mode.\n",
omitted));
}
}
}
public IValue getLocalValue(int idx) {
for (SimulationWorker w : workers) {
return w.getLocalValue(idx);
}
return null;
}
public void setAllValues(int idx, IValue val) {
for (SimulationWorker w : workers) {
w.setLocalValue(idx, val);
}
}
public List<IValue> getAllValues(int idx) {
return workers.stream().map(w -> w.getLocalValue(idx)).collect(Collectors.toList());
}
/**
* Prints the summary
*/
protected final void printSummary() {
this.reportCoverage();
try {
this.writeActionFlowGraph();
} catch (Exception e) {
// SZ Jul 10, 2009: changed from error to bug
MP.printTLCBug(EC.TLC_REPORTER_DIED, null);
}
/*
* This allows the toolbox to easily display the last set of state space
* statistics by putting them in the same form as all other progress statistics.
*/
if (TLCGlobals.tool) {
MP.printMessage(EC.TLC_PROGRESS_SIMU, String.valueOf(numOfGenStates.longValue()));
}
MP.printMessage(EC.TLC_STATS_SIMU, new String[] { String.valueOf(numOfGenStates.longValue()),
String.valueOf(this.seed), String.valueOf(this.aril) });
}
/**
* Reports coverage
*/
public final void reportCoverage() {
if (TLCGlobals.isCoverageEnabled()) {
CostModelCreator.report(this.tool, this.startTime );
}
}
public final ITool getTool() {
return this.tool;
}
/**
* Reports progress information
*/
final class ProgressReport extends Thread {
volatile boolean isRunning = true;
public void run() {
int count = TLCGlobals.coverageInterval / TLCGlobals.progressInterval;
try {
while (isRunning) {
synchronized (this) {
this.wait(TLCGlobals.progressInterval);
}
final long genTrace = numOfGenTraces.longValue();
final long m2AndMean = welfordM2AndMean.get();
final long mean = m2AndMean & 0x00000000FFFFFFFFL; // could be int.
final long m2 = m2AndMean >>> 32;
MP.printMessage(EC.TLC_PROGRESS_SIMU,
String.valueOf(numOfGenStates.longValue()),
String.valueOf(genTrace),
String.valueOf(mean),
String.valueOf(Math.round(m2 / (genTrace + 1d))), // Var(X), +1 to prevent div-by-zero.
String.valueOf(Math.round(Math.sqrt(m2 / (genTrace + 1d))))); // SD, +1 to prevent div-by-zero.
if (count > 1) {
count
} else {
reportCoverage();
count = TLCGlobals.coverageInterval / TLCGlobals.progressInterval;
}
writeActionFlowGraph();
}
} catch (Exception e) {
// SZ Jul 10, 2009: changed from error to bug
MP.printTLCBug(EC.TLC_REPORTER_DIED, null);
}
}
}
private void writeActionFlowGraph() throws IOException {
if (traceActions == "BASIC") {
writeActionFlowGraphBasic();
} else if (traceActions == "FULL") {
writeActionFlowGraphFull();
}
}
private void writeActionFlowGraphFull() throws IOException {
// The number of actions is expected to be low (dozens commons and hundreds a
// rare). This is why the code below isn't optimized for performance.
final Action[] actions = Simulator.this.tool.getActions();
final int len = actions.length;
// Clusters of actions that have the same context:
// CONSTANT Proc
// A(p) == p \in {...} /\ v' = 42...
// Next == \E p \in Proc : A(p)
final Map<String, Set<Integer>> clusters = new HashMap<>();
for (int i = 0; i < len; i++) {
final String con = actions[i].con.toString();
if (!clusters.containsKey(con)) {
clusters.put(con, new HashSet<>());
}
clusters.get(con).add(i);
}
// Write clusters to dot file (override previous file).
final DotActionWriter dotActionWriter = new DotActionWriter(
Simulator.this.tool.getRootName() + "_actions.dot", "");
for (Entry<String, Set<Integer>> cluster : clusters.entrySet()) {
// key is a unique set of chars accepted/valid as a graphviz cluster id.
final String key = Integer.toString(Math.abs(cluster.getKey().hashCode()));
dotActionWriter.writeSubGraphStart(key, cluster.getKey().toString());
final Set<Integer> ids = cluster.getValue();
for (Integer id : ids) {
dotActionWriter.write(actions[id], id);
}
dotActionWriter.writeSubGraphEnd();
}
// Element-wise sum the statistics from all workers.
long[][] aggregateActionStats = new long[len][len];
final List<SimulationWorker> workers = Simulator.this.workers;
for (SimulationWorker sw : workers) {
final long[][] s = sw.actionStats;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
aggregateActionStats[i][j] += s[i][j];
}
}
}
// Write stats to dot file as edges between the action vertices.
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
long l = aggregateActionStats[i][j];
if (l > 0L) {
// LogLog l (to keep the graph readable) and round to two decimal places (to not
// write a gazillion decimal places truncated by graphviz anyway).
final double loglogWeight = Math.log10(Math.log10(l+1)); // +1 to prevent negative inf.
dotActionWriter.write(i, j,
BigDecimal.valueOf(loglogWeight).setScale(2, RoundingMode.HALF_UP)
.doubleValue());
} else {
dotActionWriter.write(i, j);
}
}
}
// Close dot file.
dotActionWriter.close();
}
private void writeActionFlowGraphBasic() throws IOException {
// The number of actions is expected to be low (dozens commons and hundreds a
// rare). This is why the code below isn't optimized for performance.
final Action[] actions = Simulator.this.tool.getActions();
final int len = actions.length;
// Create a map from id to action name.
final Map<Integer, String> idToActionName = new HashMap<>();
for (int i = 0; i < len; i++) {
final String actionName;
if (actions[i].isNamed()) {
actionName = actions[i].getName().toString();
} else {
// If we have an unnamed action, action name will be
// the string representation of the action (which has information
// about line, column etc).
actionName = actions[i].toString();
}
idToActionName.put(i, actionName);
}
// Override previous basic file.
final DotActionWriter dotActionWriter = new DotActionWriter(
Simulator.this.tool.getRootName() + "_actions.dot", "");
// Identify actions in the dot file.
final List<String> distinctActionNames = idToActionName.values().stream().distinct().sorted().collect(Collectors.toList());
for (int i = 0; i < distinctActionNames.size(); i ++) {
final String actionName = distinctActionNames.get(i);
// Uses the position in `distinctActionNames` as the id.
dotActionWriter.write(actionName, i);
}
// Element-wise sum the statistics from all workers.
long[][] aggregateActionStats = new long[len][len];
final List<SimulationWorker> workers = Simulator.this.workers;
for (SimulationWorker sw : workers) {
final long[][] s = sw.actionStats;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
aggregateActionStats[i][j] += s[i][j];
}
}
}
// Having the aggregated action stats, reduce it to account for only
// the distinct action names.
long[][] reducedAggregateActionStats = new long[distinctActionNames.size()][distinctActionNames.size()];
for (int i = 0; i < len; i++) {
// Find origin id.
final int originActionId = distinctActionNames.indexOf(idToActionName.get(i));
for (int j = 0; j < len; j++) {
// Find next id.
final int nextActionId = distinctActionNames.indexOf(idToActionName.get(j));
reducedAggregateActionStats[originActionId][nextActionId] += aggregateActionStats[i][j];
}
}
// Write stats to dot file as edges between the action vertices.
for (int i = 0; i < distinctActionNames.size(); i++) {
for (int j = 0; j < distinctActionNames.size(); j++) {
long l = reducedAggregateActionStats[i][j];
if (l > 0L) {
// LogLog l (to keep the graph readable) and round to two decimal places (to not
// write a gazillion decimal places truncated by graphviz anyway).
final double loglogWeight = Math.log10(Math.log10(l+1)); // +1 to prevent negative inf.
dotActionWriter.write(i, j,
BigDecimal.valueOf(loglogWeight).setScale(2, RoundingMode.HALF_UP)
.doubleValue());
} else {
dotActionWriter.write(i, j);
}
}
}
// Close dot file.
dotActionWriter.close();
}
public final StateVec getTrace(final TLCState s) {
if (Thread.currentThread() instanceof SimulationWorker) {
final SimulationWorker w = (SimulationWorker) Thread.currentThread();
return w.getTrace(s);
} else {
assert numWorkers == 1 && workers.size() == numWorkers;
return workers.get(0).getTrace(s);
}
}
public final StateVec getTrace() {
if (Thread.currentThread() instanceof SimulationWorker) {
final SimulationWorker w = (SimulationWorker) Thread.currentThread();
return w.getTrace();
} else {
assert numWorkers == 1 && workers.size() == numWorkers;
return workers.get(0).getTrace();
}
}
public TLCStateInfo[] getTraceInfo(final int level) {
if (Thread.currentThread() instanceof SimulationWorker) {
final SimulationWorker w = (SimulationWorker) Thread.currentThread();
return w.getTraceInfo(level);
} else {
assert numWorkers == 1 && workers.size() == numWorkers;
return workers.get(0).getTraceInfo(level);
}
}
public void stop() {
for (SimulationWorker worker : workers) {
worker.setStopped();
worker.interrupt();
}
}
public RandomGenerator getRNG() {
if (Thread.currentThread() instanceof SimulationWorker) {
final SimulationWorker w = (SimulationWorker) Thread.currentThread();
return w.getRNG();
} else {
return this.rng;
}
}
public int getTraceDepth() {
return this.traceDepth;
}
public final Value getStatistics() {
final UniqueString[] n = new UniqueString[3];
final Value[] v = new Value[n.length];
n[0] = TRACES;
v[0] = TLCGetSet.narrowToIntValue(numOfGenTraces.longValue());
n[1] = TLCGetSet.DURATION;
v[1] = TLCGetSet.narrowToIntValue((System.currentTimeMillis() - startTime) / 1000L);
n[2] = TLCGetSet.GENERATED;
v[2] = TLCGetSet.narrowToIntValue(numOfGenStates.longValue());
return new RecordValue(n, v, false);
}
private static final UniqueString TRACES = UniqueString.uniqueStringOf("traces");
public final Value getConfig() {
final UniqueString[] n = new UniqueString[3];
final Value[] v = new Value[n.length];
n[0] = TLCGetSet.MODE;
v[0] = Tool.isProbabilistic() ? new StringValue("generate") : new StringValue("simulate");
n[1] = DEPTH;
v[1] = IntValue.gen(this.traceDepth == Integer.MAX_VALUE ? -1 : this.traceDepth);
n[2] = TRACES;
v[2] = IntValue.gen((int) (this.numWorkers * traceNum));
return new RecordValue(n, v, false);
}
private static final UniqueString DEPTH = UniqueString.uniqueStringOf("depth");
} |
package com.trendrr.oss.networking.http;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.trendrr.oss.DynMap;
import com.trendrr.oss.Regex;
import com.trendrr.oss.StringHelper;
import com.trendrr.oss.TypeCast;
import com.trendrr.oss.exceptions.TrendrrException;
import com.trendrr.oss.exceptions.TrendrrIOException;
import com.trendrr.oss.exceptions.TrendrrNetworkingException;
import com.trendrr.oss.exceptions.TrendrrParseException;
import com.trendrr.oss.networking.SocketChannelWrapper;
/**
* Simple http class.
*
* This makes it much easier to deal with headers, and funky requests. Apache httpclient is unusable...
*
*
* @author Dustin Norlander
* @created Jun 13, 2012
*
*/
public class Http {
protected static Log log = LogFactory.getLog(Http.class);
public static void main(String ...strings) throws Exception {
// String test = "11\n{ \"status\":\"OK\" }\n0";
// byte[] a = readLine('\n',new ByteArrayInputStream(test.getBytes()));
// System.out.println("a is: "+a.toString()+" of length "+ a.length);
HttpRequest request = new HttpRequest();
request.setUrl("http://www.google.com/#hl=en&output=search&sclient=psy-ab&q=test&oq=test&aq=f&aqi=g4");
request.setMethod("GET");
// request.setMethod("POST");
// request.setContent("application/json", "this is a test".getBytes());
HttpResponse response = request(request);
System.out.println(new String(response.getContent()));
}
public static HttpResponse request(HttpRequest request) throws TrendrrException {
String host = request.getHost();
int port = 80;
if (host.contains(":")) {
String tmp[] = host.split("\\:");
host = tmp[0];
port = TypeCast.cast(Integer.class, tmp[1]);
}
Socket socket = null;
try {
if (request.isSSL()) {
System.out.println("SSL!");
//uhh, what the hell do we do here?
if (port == 80) {
port = 443;
}
SocketFactory socketFactory = SSLSocketFactory.getDefault();
socket = socketFactory.createSocket(host, port);
return doRequest(request, socket);
} else {
socket = new Socket(host, port);
return doRequest(request, socket);
}
} catch (IOException x) {
throw new TrendrrIOException(x);
} catch (Exception x) {
throw new TrendrrException(x);
} finally {
try {
if (socket != null)
{
socket.close();
}
} catch (Exception x) {}
}
}
private static HttpResponse doRequest(HttpRequest request, Socket socket) throws IOException, TrendrrParseException {
//TODO: socket timeouts
// Create streams to securely send and receive data to the server
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(request.toByteArray());
// Read from in and write to out...
String t;
ByteArrayOutputStream contentoutput = new ByteArrayOutputStream();
// s.getInputStream().r
StringBuilder headerBuilder = new StringBuilder();
while(!(t = readLine(in)).isEmpty()) {
System.out.println("t is--"+t+"--end");
System.out.println("t.length="+t.length());
headerBuilder.append(t).append("\r\n");
}
String headers = headerBuilder.toString();
System.out.println("headers="+headers+"--end");
HttpResponse response = HttpResponse.parse(headers);
byte[] content = null;
if (response.getHeader("Content-Length") != null) {
content = new byte[getContentLength(response)];
in.read(content);
contentoutput.write(content, 0, content.length);
} else {
String chunked = response.getHeader("Transfer-Encoding");
if (chunked != null && chunked.equalsIgnoreCase("chunked")) {
int length = 1;
String lengthstr = "";
while((lengthstr = readLine(in)) != null){
System.out.println("line:"+lengthstr);
if(lengthstr.isEmpty()){
System.out.println("lengthstr is empty, skipping");
continue;
}else {
length = Integer.parseInt(lengthstr,16);
System.out.println("length: "+length);
if(length==0){
System.out.println("last chunk has been read");
break;
}
content = new byte[length];
int numread;
int total=0;
while(total < length &&
(numread = in.read(content,0,content.length-total)) != -1){
System.out.println("written: "+numread);
// System.out.println("content: "+new String(content));
contentoutput.write(content, 0, numread);
total+=numread;
}
}
}
}
}
contentoutput.close();
in.close();
out.close();
response.setContent(contentoutput.toByteArray());
return response;
}
/**
* Method reads string until occurrence of "\r\n" or "\n", consistent with HTTP protocol
* @param in stream to read in from
* @return String consists of characters upto and excluding the newline characters
*/
private static String readLine(InputStream in) throws IOException{
byte current = 'a';
byte[] temp = new byte[1000];//is this large enough to handle any header content?
int offset=-1;
while((char)current != '\n'){
offset++;
in.read(temp, offset, 1);
// System.out.println("result at: "+offset+"="+(char)temp[offset]);
current = temp[offset];
}
int resultlen = 0;
if(offset > 0){
if((char)temp[offset-1]=='\r'){//in case of "\r\n" termination, we ignore the \r
resultlen = offset-1;
}else{
resultlen = offset;//in case of lone "\n" termination
}
}
byte[] result = new byte[resultlen];
for(int i=0; i<result.length; i++){
result[i]=temp[i];
}
return new String(result);
}
private static int getContentLength(HttpResponse response) {
int length = TypeCast.cast(Integer.class, response.getHeader("Content-Length"), 0);
return length;
}
public static String get(String url) throws TrendrrNetworkingException {
return get(url, null);
}
/**
* Shortcut to do a simple GET request. returns the content on 200, else throws an exception
* @param url
* @param params
* @return
* @throws TrendrrNetworkingException
*/
public static String get(String url, DynMap params) throws TrendrrNetworkingException {
try {
if (!url.contains("?")) {
url += "?";
}
if (params != null) {
url += params.toURLString();
}
HttpRequest request = new HttpRequest();
request.setUrl(url);
request.setMethod("GET");
HttpResponse response = request(request);
if (response.getStatusCode() == 200) {
return new String(response.getContent(), "utf8");
}
//TODO: some kind of http exception.
throw new TrendrrNetworkingException("Error from response") {
};
} catch (TrendrrNetworkingException e) {
throw e;
}catch (Exception x) {
throw new TrendrrIOException(x);
}
}
public static String post(String url, DynMap params) throws TrendrrNetworkingException {
try {
//TODO: update for using request.
URL u = new URL(url);
URLConnection c = u.openConnection();
c.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(c.getOutputStream());
wr.write(params.toURLString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(
c.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (Exception x) {
throw new TrendrrIOException(x);
}
}
} |
package br.com.caelum.tubaina;
import java.io.IOException;
import java.util.List;
import br.com.caelum.tubaina.parser.Parser;
import br.com.caelum.tubaina.parser.RegexConfigurator;
import br.com.caelum.tubaina.parser.Tag;
import br.com.caelum.tubaina.parser.html.desktop.FlatHtmlGenerator;
import br.com.caelum.tubaina.parser.html.desktop.Generator;
import br.com.caelum.tubaina.parser.html.desktop.HtmlParser;
import br.com.caelum.tubaina.parser.html.desktop.SingleHtmlGenerator;
import br.com.caelum.tubaina.parser.html.kindle.KindleGenerator;
import br.com.caelum.tubaina.parser.html.kindle.KindleParser;
import br.com.caelum.tubaina.parser.latex.LatexGenerator;
import br.com.caelum.tubaina.parser.latex.LatexParser;
import br.com.caelum.tubaina.parser.latex.LinkTag;
public enum ParseType {
LATEX {
@Override
public Parser getParser(RegexConfigurator conf, boolean noAnswer, boolean showNotes, String linkParameter) throws IOException {
List<Tag> tags = conf.read("/regex.properties", "/latex.properties");
tags.add(new LinkTag("\\\\link{$1}$2"));
return new LatexParser(tags, showNotes, noAnswer);
}
@Override
public Generator getGenerator(Parser parser, TubainaBuilderData data) {
return new LatexGenerator(parser, data);
}
},
HTMLFLAT {
@Override
public Parser getParser(RegexConfigurator conf, boolean noAnswer, boolean showNotes, String linkParameter) throws IOException {
List<Tag> tags = conf.read("/regex.properties", "/html.properties");
tags.add(new LinkTag("<a href=\"$1"+linkParameter+"\">$1</a>$2"));
return new HtmlParser(tags, noAnswer, showNotes);
}
@Override
protected Generator getGenerator(Parser parser, TubainaBuilderData data) {
return new FlatHtmlGenerator(parser, data);
}
},
HTML {
@Override
public Parser getParser(RegexConfigurator conf, boolean noAnswer, boolean showNotes, String linkParameter) throws IOException {
List<Tag> tags = conf.read("/regex.properties", "/html.properties");
tags.add(new LinkTag("<a href=\"$1"+linkParameter+"\">$1</a>$2"));
return new HtmlParser(tags, noAnswer, showNotes);
}
@Override
protected Generator getGenerator(Parser parser, TubainaBuilderData data) {
return new SingleHtmlGenerator(parser, data);
}
},
KINDLE {
@Override
public Parser getParser(RegexConfigurator conf, boolean noAnswer, boolean showNotes, String linkParameter) throws IOException {
List<Tag> tags = conf.read("/regex.properties", "/kindle.properties");
tags.add(new LinkTag("<a href=\"$1"+linkParameter+"\">$1</a>$2"));
return new KindleParser(tags, noAnswer, showNotes);
}
@Override
protected Generator getGenerator(Parser parser, TubainaBuilderData data) {
return new KindleGenerator(parser, data);
}
};
public String getType() {
return this.toString().toLowerCase();
}
protected abstract Generator getGenerator(Parser parser, TubainaBuilderData data);
protected abstract Parser getParser(RegexConfigurator conf, boolean noAnswer, boolean showNotes, String linkParameter) throws IOException;
} |
package co.uk.zerod.dao;
import co.uk.zerod.domain.TableName;
import co.uk.zerod.wip.MigrationId;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;
import static co.uk.zerod.wip.MigrationId.migrationId;
public class SqlMigrationDao extends BaseSqlDao implements MigrationDao {
private final TableName migrationTableName;
public SqlMigrationDao(TableName migrationTableName, DataSource dataSource) {
super(dataSource);
this.migrationTableName = migrationTableName;
}
@Override
public void registerMigration(MigrationId migrationId) {
try (Connection connection = dataSource.getConnection()) {
if (isMigrationStored(migrationId, connection)) {
return;
}
try {
PreparedStatement ps = connection.prepareStatement("INSERT INTO " + migrationTableName + " (migration_id) VALUES (?)");
ps.setString(1, migrationId.value());
ps.execute();
} catch (SQLException e) {
if (!isMigrationStored(migrationId, connection)) {
throw new IllegalStateException("Unable to store migration '" + migrationId + "'", e);
}
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
private boolean isMigrationStored(MigrationId migrationId, Connection connection) throws SQLException {
PreparedStatement ps;
boolean isMigrationStored;
ps = connection.prepareStatement("SELECT * FROM " + migrationTableName + " WHERE migration_id = ?");
ps.setString(1, migrationId.value());
try (ResultSet rs = ps.executeQuery()) {
isMigrationStored = rs.next();
}
return isMigrationStored;
}
@Override
public Set<MigrationId> findAllMigrations() {
return selectDistinct(
"SELECT * FROM " + migrationTableName,
rs -> migrationId(rs.getString("migration_id"))
);
}
} |
package rest;
import java.util.List;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import tm.RotondAndesTM;
import vos.Informacion;
import vos.Restaurante;
import vos.Usuario;
@Path("restaurantes")
public class RestauranteServices {
/**
* Atributo que usa la anotacion @Context para tener el ServletContext de la conexion actual.
*/
@Context
private ServletContext context;
/**
* Metodo que retorna el path de la carpeta WEB-INF /ConnectionData en el deploy actual dentro del servidor.
* @return path de la carpeta WEB-INF/ConnectionData en el deploy actual.
*/
private String getPath() {
return context.getRealPath("WEB-INF/ConnectionData");
}
private String doErrorMessage(Exception e){
return "{ \"ERROR\": \""+ e.getMessage() + "\"}" ;
}
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response getRestaurantes() {
RotondAndesTM tm = new RotondAndesTM(getPath());
List<Restaurante> restaurantes;
try {
restaurantes = tm.darRestaurantes();
} catch (Exception e) {
return Response.status(500).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(restaurantes).build();
}
/**
* RFC9
* @param informacionEq informacion = restuarante-fechaInicial-FechaFinal-criterioAgrupamiento
* el resto de Informacion = null
* @return
*/
@PUT
@Path( "consumoAlto" )
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON })
public Response getConsumoAltoRestaurante(Informacion informacionEq) {
RotondAndesTM tm = new RotondAndesTM(getPath());
List<Usuario> usuarios;
try {
usuarios = tm.darUsuariosMayorConsumo(informacionEq.getInformacion());
} catch (Exception e) {
return Response.status(500).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(usuarios).build();
}
/**
* RFC10
* @param informacionEq informacion = restuarante-fechaInicial-FechaFinal-criterioAgrupamiento
* el resto de Informacion = null
* @return
*/
@PUT
@Path( "consumoBajo" )
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON })
public Response getConsumoBajoRestaurante(Informacion informacionEq) {
RotondAndesTM tm = new RotondAndesTM(getPath());
List<Usuario> usuarios;
try {
usuarios = tm.darUsuariosMenorConsumo(informacionEq.getInformacion());
} catch (Exception e) {
return Response.status(500).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(usuarios).build();
}
// @GET
// @Path( "{id: \\d+}" )
// @Produces( { MediaType.APPLICATION_JSON } )
// public Response getVideo( @PathParam( "id" ) Long id )
// VideoAndesTM tm = new VideoAndesTM( getPath( ) );
// try
// Video v = tm.buscarVideoPorId( id );
// return Response.status( 200 ).entity( v ).build( );
// catch( Exception e )
// return Response.status( 500 ).entity( doErrorMessage( e ) ).build( );
// @GET
// @Path( "{nombre}" )
// @Produces( { MediaType.APPLICATION_JSON } )
// public Response getVideoName( @QueryParam("nombre") String name) {
// VideoAndesTM tm = new VideoAndesTM(getPath());
// List<Video> videos;
// try {
// if (name == null || name.length() == 0)
// throw new Exception("Nombre del video no valido");
// videos = tm.buscarVideosPorName(name);
// } catch (Exception e) {
// return Response.status(500).entity(doErrorMessage(e)).build();
// return Response.status(200).entity(videos).build();
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addRestaurante(Restaurante restaurante) {
RotondAndesTM tm = new RotondAndesTM(getPath());
try {
tm.addRestaurante(restaurante);
} catch (Exception e) {
return Response.status(500).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(restaurante).build();
}
// @PUT
// @Consumes(MediaType.APPLICATION_JSON)
// @Produces(MediaType.APPLICATION_JSON)
// public Response updateVideo(Video video) {
// VideoAndesTM tm = new VideoAndesTM(getPath());
// try {
// tm.updateVideo(video);
// } catch (Exception e) {
// return Response.status(500).entity(doErrorMessage(e)).build();
// return Response.status(200).entity(video).build();
// @DELETE
// @Consumes(MediaType.APPLICATION_JSON)
// @Produces(MediaType.APPLICATION_JSON)
// public Response deleteVideo(Video video) {
// VideoAndesTM tm = new VideoAndesTM(getPath());
// try {
// tm.deleteVideo(video);
// } catch (Exception e) {
// return Response.status(500).entity(doErrorMessage(e)).build();
// return Response.status(200).entity(video).build();
/**
* Requerimiento F13
* @param nombre
*/
@PUT
@Path("surtir")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response getRestaurantes(Informacion info) {
RotondAndesTM tm = new RotondAndesTM(getPath());
try {
tm.surtirRestaurante(info.getInformacion());
} catch (Exception e) {
return Response.status(400).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(new Informacion()).build();
}
} |
package com.ireul.nerf.schedule;
import com.ireul.nerf.application.Application;
import org.quartz.*;
import org.quartz.utils.Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
/**
* This abstract class implements {@link Job} and provides injections
* <p><b>Most people may use this class rather than implements {@link Job}</b></p>
*
* @author Ryan Wade
*/
@SuppressWarnings("WeakerAccess")
public abstract class BaseJob implements Job {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Get the logger
*
* @return Logger
*/
public Logger logger() {
return logger;
}
/**
* Key in {@link JobExecutionContext#get(Object)} for injector
*/
public static final String kINJECTOR = "__NERF_INJECTOR";
/**
* Key in {@link JobExecutionContext#getMergedJobDataMap()} for current retry count
*/
public static final String kRETRY_COUNT = "__NERF_RETRY_COUNT";
private JobExecutionContext executionContext;
/**
* Get the current {@link JobExecutionContext}
*
* @return context
*/
public JobExecutionContext executionContext() {
return this.executionContext;
}
/**
* Get the current {@link Scheduler}
*
* @return scheduler
*/
public Scheduler scheduler() {
return executionContext().getScheduler();
}
/**
* should retry if {@link #execute(JobDataMap)} throws something, subclass may override
*
* @return should retry, default to true
*/
public boolean shouldRetry() {
return true;
}
/**
* max retry count of this job, subclass may override
*
* @return max retry count, default to 5
*/
public int maxRetry() {
return 5;
}
/**
* delay in seconds before next retry, subclass may override
*
* @return delay in seconds, default to 1
*/
public int retryDelay() {
return 1;
}
private boolean retry() {
// check shouldRetry()
if (!shouldRetry()) return false;
// determine if max retry reached
JobDataMap dataMap = executionContext().getMergedJobDataMap();
int retryCount = 0;
// if max retry exceeded just return
if (dataMap.get(kRETRY_COUNT) != null) {
retryCount = dataMap.getInt(kRETRY_COUNT);
if (retryCount >= maxRetry()) {
logger().error("Max retry exceeded for " + getClass().getCanonicalName());
return false;
}
}
// update retryCount
retryCount = retryCount + 1;
dataMap.put(kRETRY_COUNT, retryCount);
// reschedule
try {
JobDetail jobDetail = executionContext().getJobDetail();
scheduler()
.scheduleJob(
newJob(getClass())
.withIdentity(Key.createUniqueName(jobDetail.getKey().getGroup()))
.usingJobData(dataMap)
.withDescription(jobDetail.getDescription())
.build(),
newTrigger()
.startAt(new Date(System.currentTimeMillis() + retryDelay() * 1000))
.build()
);
logger().info("Retrying " + getClass().getCanonicalName());
} catch (SchedulerException e) {
logger().error("Failed to retry " + getClass().getCanonicalName(), e);
return false;
}
return true;
}
@Override
public final void execute(JobExecutionContext context) throws JobExecutionException {
// set executionContext
this.executionContext = context;
// inject
Application application = (Application) context.get(kINJECTOR);
application.injectTo(this);
// execute
boolean isSuccess = true;
try {
execute(context.getMergedJobDataMap());
} catch (Throwable throwable) {
// log the error
logger().error("Error occurred", throwable);
// mark false
isSuccess = false;
}
// check success
if (isSuccess) {
onSuccess(context.getMergedJobDataMap());
} else {
if (!retry()) {
onFailure(context.getMergedJobDataMap());
}
}
}
/**
* Subclasses should implement this method, JobExecutionContext is already set and injections are done
*
* @param dataMap dataMap of current job
* @throws Exception any error occurred will be captured
*/
public abstract void execute(JobDataMap dataMap) throws Exception;
/**
* Method to invoke after job successfully completed
*/
public void onSuccess(JobDataMap dataMap) {
}
/**
* Method to invoke after all retries failed
*/
public void onFailure(JobDataMap dataMap) {
}
} |
package com.laxture.lib.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONObject;
import android.text.TextUtils;
public class StringUtil {
private static final String ELIPSE_CHARACTOR="…";
/**
*
* @param rs
* @param length
* @return
*/
public static String getElipseString(String rs, int length) {
if (Checker.isEmpty(rs)) return "";
if (rs.length() <= length) return rs;
return rs.substring(0, length)+ELIPSE_CHARACTOR;
}
public static String join(Collection<String> stringList) {
if (Checker.isEmpty(stringList)) return "";
StringBuilder sb = new StringBuilder();
for (String str : stringList) {
sb.append(str).append(",");
}
if (sb.length() > 0) sb.delete(sb.length()-1, sb.length());
return sb.toString();
}
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
}
/**
* 0.5
* @param rs
* @param length
* @return
*/
public static String getElipseStringWide(String rs,int length){
if(TextUtils.isEmpty(rs)){
return "";
}
int totalCount=length*2;
int count=0;
int i=0;
boolean needCut=false;
for(i=0;i<rs.length();i++){
count+=(isChinese(rs.charAt(i))?2:1);
if(count>totalCount){
needCut=true;
break;
}
}
if(needCut){
return rs.substring(0,i)+ ELIPSE_CHARACTOR;
}
return rs;
}
/**
* 0.666
* @param rs
* @param length
* @return
*/
public static String getElipseStringWide2(String rs, int length){
if(TextUtils.isEmpty(rs)){
return "";
}
int totalCount=length*2;
float count=0;
int i=0;
boolean needCut=false;
for(i=0;i<rs.length();i++){
count+=(isChinese(rs.charAt(i))
|| rs.charAt(i) == 'W' || rs.charAt(i) == 'w') ? 2 : 1.5;
if(count>totalCount){
needCut=true;
break;
}
}
if(needCut){
return rs.substring(0,i)+ ELIPSE_CHARACTOR;
}
return rs;
}
/**
*
* @param inputStream
* @return
*/
public static String getFromStream(InputStream inputStream){
return getFromStream(inputStream, "UTF-8");
}
/**
*
* @return
*/
public static String getFromStream(InputStream is, String codec) {
try {
InputStreamReader isr;
if (TextUtils.isEmpty(codec)) {
isr=new InputStreamReader(is);
} else {
isr=new InputStreamReader(is, codec);
}
BufferedReader in = new BufferedReader(isr);
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
in.close();
return buffer.toString();
} catch (Exception e) {
return null;
}
}
/**
* fix JSON with null like {"abc":null}
* @param object
* @param key
* @return
*/
public String optStringFromJSON(JSONObject object, String key) {
if (object == null || object.isNull(key)) return null;
return object.optString(key);
}
/**
* fix JSON with null like [null]
* @param object
* @param index
* @return
*/
public String optStringFromJSON(JSONArray object, int index) {
if (object == null || object.isNull(index)) return null;
return object.optString(index);
}
} |
package com.machinezoo.sourceafis;
class Score {
int matchedMinutiae;
double matchedMinutiaeScore;
double matchedFractionOfProbeMinutiae;
double matchedFractionOfCandidateMinutiae;
double matchedFractionOfAllMinutiaeScore;
int matchedEdges;
double matchedEdgesScore;
int minutiaeWithSeveralEdges;
double minutiaeWithSeveralEdgesScore;
int correctMinutiaTypeCount;
double correctMinutiaTypeScore;
double accurateEdgeLengthScore;
double accurateMinutiaAngleScore;
double totalScore;
double shapedScore;
void compute(MatchBuffer match) {
matchedMinutiae = match.count;
matchedMinutiaeScore = Parameters.pairCountScore * matchedMinutiae;
matchedFractionOfProbeMinutiae = match.count / (double)match.probe.minutiae.length;
matchedFractionOfCandidateMinutiae = match.count / (double)match.candidate.minutiae.length;
matchedFractionOfAllMinutiaeScore = Parameters.pairFractionScore * (matchedFractionOfProbeMinutiae + matchedFractionOfCandidateMinutiae) / 2;
matchedEdges = match.count;
minutiaeWithSeveralEdges = 0;
correctMinutiaTypeCount = 0;
for (int i = 0; i < match.count; ++i) {
MinutiaPair pair = match.tree[i];
matchedEdges += pair.supportingEdges;
if (pair.supportingEdges >= Parameters.minSupportingEdges)
++minutiaeWithSeveralEdges;
if (match.probe.minutiae[pair.probe].type == match.candidate.minutiae[pair.candidate].type)
++correctMinutiaTypeCount;
}
matchedEdgesScore = Parameters.edgeCountScore * matchedEdges;
minutiaeWithSeveralEdgesScore = Parameters.supportedCountScore * minutiaeWithSeveralEdges;
correctMinutiaTypeScore = Parameters.correctTypeScore * correctMinutiaTypeCount;
int innerDistanceRadius = (int)Math.round(Parameters.distanceErrorFlatness * Parameters.maxDistanceError);
int innerAngleRadius = (int)Math.round(Parameters.angleErrorFlatness * Parameters.maxAngleError);
int distanceErrorSum = 0;
int angleErrorSum = 0;
for (int i = 1; i < match.count; ++i) {
MinutiaPair pair = match.tree[i];
EdgeShape probeEdge = new EdgeShape(match.probe.minutiae[pair.probeRef], match.probe.minutiae[pair.probe]);
EdgeShape candidateEdge = new EdgeShape(match.candidate.minutiae[pair.candidateRef], match.candidate.minutiae[pair.candidate]);
distanceErrorSum += Math.max(innerDistanceRadius, Math.abs(probeEdge.length - candidateEdge.length));
angleErrorSum += Math.max(innerAngleRadius, Angle.distance(probeEdge.referenceAngle, candidateEdge.referenceAngle));
angleErrorSum += Math.max(innerAngleRadius, Angle.distance(probeEdge.neighborAngle, candidateEdge.neighborAngle));
}
accurateEdgeLengthScore = 0;
accurateMinutiaAngleScore = 0;
if (match.count >= 2) {
double pairedDistanceError = Parameters.maxDistanceError * (match.count - 1);
accurateEdgeLengthScore = Parameters.distanceAccuracyScore * (pairedDistanceError - distanceErrorSum) / pairedDistanceError;
double pairedAngleError = Parameters.maxAngleError * (match.count - 1) * 2;
accurateMinutiaAngleScore = Parameters.angleAccuracyScore * (pairedAngleError - angleErrorSum) / pairedAngleError;
}
totalScore = matchedMinutiaeScore
+ matchedFractionOfAllMinutiaeScore
+ minutiaeWithSeveralEdgesScore
+ matchedEdgesScore
+ correctMinutiaTypeScore
+ accurateEdgeLengthScore
+ accurateMinutiaAngleScore;
shapedScore = shape(totalScore);
}
private static double shape(double raw) {
if (raw < Parameters.thresholdMaxFMR)
return 0;
if (raw < Parameters.thresholdFMR2)
return interpolate(raw, Parameters.thresholdMaxFMR, Parameters.thresholdFMR2, 0, 3);
if (raw < Parameters.thresholdFMR10)
return interpolate(raw, Parameters.thresholdFMR2, Parameters.thresholdFMR10, 3, 7);
if (raw < Parameters.thresholdFMR100)
return interpolate(raw, Parameters.thresholdFMR10, Parameters.thresholdFMR100, 10, 10);
if (raw < Parameters.thresholdFMR1000)
return interpolate(raw, Parameters.thresholdFMR100, Parameters.thresholdFMR1000, 20, 10);
if (raw < Parameters.thresholdFMR10_000)
return interpolate(raw, Parameters.thresholdFMR1000, Parameters.thresholdFMR10_000, 30, 10);
if (raw < Parameters.thresholdFMR100_000)
return interpolate(raw, Parameters.thresholdFMR10_000, Parameters.thresholdFMR100_000, 40, 10);
return (raw - Parameters.thresholdFMR100_000) / (Parameters.thresholdFMR100_000 - Parameters.thresholdFMR100) * 30 + 50;
}
private static double interpolate(double raw, double min, double max, double start, double length) {
return (raw - min) / (max - min) * length + start;
}
} |
package com.qiniu.storage;
import com.qiniu.common.*;
import com.qiniu.http.Dns;
import com.qiniu.http.ProxyConfiguration;
import com.qiniu.util.StringUtils;
import java.util.List;
/**
* SDK
*/
public final class Configuration implements Cloneable {
/**
* Region
*/
public Region region;
/**
* Zone
*/
@Deprecated
public Zone zone;
/**
* https ,
*/
public boolean useHttpsDomains = true;
public boolean useAccUpHost = true;
/**
* , Form
*/
public int putThreshold = Constants.BLOCK_SIZE;
/**
* (10s)
*/
public int connectTimeout = Constants.CONNECT_TIMEOUT;
public int writeTimeout = Constants.WRITE_TIMEOUT;
/**
* (30s)
*/
public int readTimeout = Constants.READ_TIMEOUT;
/**
* HTTP
*/
public int dispatcherMaxRequests = Constants.DISPATCHER_MAX_REQUESTS;
/**
* HTTPHost
*/
public int dispatcherMaxRequestsPerHost = Constants.DISPATCHER_MAX_REQUESTS_PER_HOST;
/**
* HTTP
*/
public int connectionPoolMaxIdleCount = Constants.CONNECTION_POOL_MAX_IDLE_COUNT;
/**
* HTTP
*/
public int connectionPoolMaxIdleMinutes = Constants.CONNECTION_POOL_MAX_IDLE_MINUTES;
public int retryMax = 5;
/**
* dns
*/
public Dns dns;
/*
* ,host,
*/
@Deprecated
public boolean useDnsHostFirst;
public ProxyConfiguration proxy;
public static String defaultRsHost = "rs.qiniu.com";
public static String defaultApiHost = "api.qiniu.com";
public static String defaultUcHost = "uc.qbox.me";
public Configuration() {
}
public Configuration(Region region) {
this.region = region;
}
@Deprecated
public Configuration(Zone zone) {
this.zone = zone;
}
public Configuration clone() {
try {
return (Configuration) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public String upHost(String upToken) throws QiniuException {
return upHost(upToken, false);
}
public String upHost(String upToken, boolean changeHost) throws QiniuException {
makeSureRegion();
RegionReqInfo regionReqInfo = new RegionReqInfo(upToken);
List<String> accHosts = region.getAccUpHost(regionReqInfo);
List<String> srcHosts = region.getSrcUpHost(regionReqInfo);
return getScheme() + getHelper().upHost(accHosts, srcHosts, changeHost);
}
@Deprecated
public String upHostBackup(String upToken) throws QiniuException {
return upHost(upToken, true);
}
public String ioHost(String ak, String bucket) {
makeSureRegion();
RegionReqInfo regionReqInfo = new RegionReqInfo(ak, bucket);
return getScheme() + region.getIovipHost(regionReqInfo);
}
public String apiHost(String ak, String bucket) {
makeSureRegion();
RegionReqInfo regionReqInfo = new RegionReqInfo(ak, bucket);
return getScheme() + region.getApiHost(regionReqInfo);
}
public String rsHost(String ak, String bucket) {
makeSureRegion();
RegionReqInfo regionReqInfo = new RegionReqInfo(ak, bucket);
return getScheme() + region.getRsHost(regionReqInfo);
}
public String rsfHost(String ak, String bucket) {
makeSureRegion();
RegionReqInfo regionReqInfo = new RegionReqInfo(ak, bucket);
return getScheme() + region.getRsfHost(regionReqInfo);
}
public String rsHost() {
return getScheme() + defaultRsHost;
}
public String apiHost() {
return getScheme() + defaultApiHost;
}
public String ucHost() {
return getScheme() + defaultUcHost;
}
private String getScheme() {
return useHttpsDomains ? "https:
}
private void makeSureRegion() {
if (region == null) {
if (zone != null) {
region = toRegion(zone);
} else {
region = Region.autoRegion();
}
}
}
private UpHostHelper helper;
private UpHostHelper getHelper() {
if (helper == null) {
helper = new UpHostHelper(this, 60 * 15);
}
return helper;
}
private Region toRegion(Zone zone) {
if (zone == null || zone instanceof AutoZone) {
return Region.autoRegion();
}
// useAccUpHost default value is true
// from the zone useAccUpHost must be true, (it is a new field)
// true, acc map the upHttp, upHttps
// false, src map to the backs
// non autozone, zoneRegionInfo is useless
return new Region.Builder()
.region(zone.getRegion())
.accUpHost(getHosts(zone.getUpHttps(null), zone.getUpHttp(null)))
.srcUpHost(getHosts(zone.getUpBackupHttps(null), zone.getUpBackupHttp(null)))
.iovipHost(getHost(zone.getIovipHttps(null), zone.getIovipHttp(null)))
.rsHost(getHost(zone.getRsHttps(), zone.getRsHttp()))
.rsfHost(getHost(zone.getRsfHttps(), zone.getRsfHttp()))
.apiHost(getHost(zone.getApiHttps(), zone.getApiHttp()))
.build();
}
private String getHost(String https, String http) {
if (useHttpsDomains) {
return https;
} else {
return http;
}
}
private String[] getHosts(String https, String http) {
if (useHttpsDomains) {
return new String[]{toDomain(https)};
} else {
String s1 = toDomain(http);
String s2 = toDomain(https);
if (s2 != s1) {
return new String[]{s1, s2};
}
return new String[]{s1};
}
}
private String toDomain(String d1) {
if (StringUtils.isNullOrEmpty(d1)) {
return null;
}
int s = d1.indexOf(":
if (s > -1) {
return d1.substring(s + 3);
}
return d1;
}
} |
package com.softartisans.timberwolf;
import com.cloudera.alfredo.client.AuthenticationException;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import com.cloudera.alfredo.client.AuthenticatedURL;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Driver class to grab emails and put them in HBase.
*/
final class App
{
@Option(required = true, name = "--exchange-url",
usage = "The URL of your Exchange Web Services endpoint.\nFor "
+ "example: https://example.contoso.com/ews/exchange.asmx")
private String exchangeUrl;
@Option(required = false, name = "--exchange-user",
usage = "The username that will be used to authenticate with "
+ "Exchange Web Services.")
private String exchangeUser;
@Option(required = false, name = "--exchange-password",
usage = "The password that will be used to authenticate with "
+ "Exchange Web Services.")
private String exchangePassword;
@Option(required = false, name = "--get-email-for",
usage = "The user for whom to retrieve email.")
private String targetUser;
@Option(required = false, name = "--hbase-quorum",
usage = "The Zookeeper quorum used to connect to HBase.")
private String hbaseQuorum;
@Option(required = false, name = "--hbase-port",
usage = "The port used to connect to HBase.")
private String hbasePort;
@Option(required = false, name = "--hbase-table",
usage = "The HBase table name that email data will be imported "
+ "into.")
private String hbaseTableName;
@Option(name = "--hbase-column-family.",
usage = "The column family for the imported email data. Default "
+ "family is 'h'.")
private String hbaseColumnFamily = "h";
private App()
{
}
public static void main(final String[] args)
throws IOException, AuthenticationException
{
new App().run(args);
}
private void run(final String[] args)
throws IOException, AuthenticationException
{
CmdLineParser parser = new CmdLineParser(this);
try
{
parser.parseArgument(args);
}
catch (CmdLineException e)
{
System.err.println(e.getMessage());
System.err.println("java timberwolf [options...] arguments...");
parser.printUsage(System.err);
System.err.println();
return;
}
Logger log = LoggerFactory.getLogger(App.class);
BasicConfigurator.configure();
log.info("Timberwolf invoked with the following arguments:");
log.info("Exchange URL: {}", exchangeUrl);
log.info("Exchange User: {}", exchangeUser);
log.info("Exchange Password: {}", exchangePassword);
log.info("Target User: {}", targetUser);
log.info("HBase Quorum: {}", hbaseQuorum);
log.info("HBase Port: {}", hbasePort);
log.info("HBase Table Name: {}", hbaseTableName);
log.info("HBase Column Family: {}", hbaseColumnFamily);
String fi = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:soap=\"http:
byte[] bytes = fi.getBytes("UTF-8");
// InputStream findItems = App.class.getResourceAsStream("/findItems.xml");
int totalLength = bytes.length;
// ByteArrayOutputStream tempStream = new ByteArrayOutputStream();
// byte[] buffer = new byte[1024];
// int length = 0;
// while ((length = findItems.read(buffer)) >= 0)
// totalLength+=length;
// tempStream.write(buffer);
AuthenticatedURL.Token token = new AuthenticatedURL.Token();
URL url = new URL(exchangeUrl);
HttpURLConnection conn = new AuthenticatedURL().openConnection(url,
token);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Length", "" + totalLength);
conn.getOutputStream().write(bytes);
System.out.println();
System.out.println("Token value: " + token);
System.out.println("Status code: " + conn.getResponseCode() + " " + conn.getResponseMessage());
System.out.println();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}
System.out.println();
}
} |
package com.team2502.robot2017;
@SuppressWarnings({ "WeakerAccess" })
public class RobotMap
{
private static final int UNDEFINED = -1;
private RobotMap() {}
public static final class Joystick
{
public static final int JOYSTICK_DRIVE_LEFT = 1;
public static final int JOYSTICK_DRIVE_RIGHT = 0;
public static final int JOYSTICK_FUNCTION = 2;
private Joystick() {}
public static final class Button
{
public static final int SWITCH_DRIVE_TRANSMISSION = 1;
public static final int SHOOTER_TOGGLE = 5;
public static final int SHOOTER_INCREASE_SPEED = 11;
public static final int SHOOTER_DECREASE_SPEED = 12;
private Button() {}
}
}
public static final class Electrical
{
public static final int PRESSURE_SENSOR = 0;
public static final int DISTANCE_SENSOR = 1;
private Electrical() {}
}
public static final class Motor
{
public static final int LEFT_TALON_0 = 2;
public static final int LEFT_TALON_1 = 4;
public static final int RIGHT_TALON_0 = 1;
public static final int RIGHT_TALON_1 = 3;
public static final int FLYWHEEL_TALON_0 = 5;
public static final int FEEDER_TALON_0 = 6; //coleson
public static final int FEEDER_TALON_1 = 7; //banebot
public static final int ACTIVE_INTAKE = 8;
private Motor() {}
}
public static final class Solenoid
{
// TRANSMISSION is for shifting drivetrain gear ratio.
public static final int TRANSMISSION_SWITCH = 0;
// GEARBOX is for the actual box that carries gears.
public static final int GEARBOX_SOLENOID0 = 1;
public static final int GEARBOX_SOLENOID1 = 2;
public static final int GEARBOX_SOLENOID2 = 3;
public static final int GEARBOX_SOLENOID3 = 4;
private Solenoid() {}
}
} |
package com.urbanairship.datacube;
import com.google.common.collect.Maps;
import java.util.Map;
public class Batch<T extends Op> {
private Map<Address, T> map;
/**
* Normally you should not create your own Batches but instead have {@link DataCubeIo} create
* them for you. You can use this if you intend to bypass the high-level magic and you really
* know what you're doing.
*/
public Batch() {
this.map = Maps.newHashMap();
}
/**
* Normally you should not create your own Batches but instead have {@link DataCubeIo} create
* them for you. You can use this if you intend to bypass the high-level magic and you really
* know what you're doing.
*
* @param map some Ops to wrap in this Batch
*/
public Batch(Map<Address, T> map) {
this.map = map;
}
public void putAll(Batch<T> b) {
this.putAll(b.getMap());
}
@SuppressWarnings("unchecked")
public void putAll(Map<Address, T> other) {
for (Map.Entry<Address, T> entry : other.entrySet()) {
Address c = entry.getKey();
T alreadyExistingVal = map.get(entry.getKey());
T newVal;
if (alreadyExistingVal == null) {
newVal = entry.getValue();
} else {
newVal = (T) alreadyExistingVal.add(entry.getValue());
}
this.map.put(c, newVal);
}
}
public Map<Address, T> getMap() {
return map;
}
public String toString() {
return map.toString();
}
public void reset() {
map = Maps.newHashMap();
}
} |
@API(owner = "witchworks", apiVersion = "0.6", provides = "WitchWorksAPI")
package com.witchworks.api;
import net.minecraftforge.fml.common.API; |
package com.xiaoleilu.hutool;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.xiaoleilu.hutool.exceptions.UtilException;
/**
*
*
* @author xiaoleilu
*
*/
public class SecureUtil {
public final static String MD2 = "MD2";
public final static String MD4 = "MD4";
public final static String MD5 = "MD5";
public final static String SHA1 = "SHA-1";
public final static String SHA256 = "SHA-256";
public final static String RIPEMD128 = "RIPEMD128";
public final static String RIPEMD160 = "RIPEMD160";
/** base64 */
public static char[] base64EncodeTable = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
/**
*
*
* @param source
* @param algorithmName
* @param charset
* @return
*/
public static String encrypt(String source, String algorithmName, String charset) {
return encrypt(StrUtil.encode(source, charset), algorithmName);
}
/**
*
*
* @param bytes byte
* @param algorithmName
* @return
*/
public static String encrypt(byte[] bytes, String algorithmName) {
return Conver.toHex(encryptWithoutHex(bytes, algorithmName));
}
/**
* Hex
*
* @param bytes byte
* @param algorithmName
* @return
*/
public static byte[] encryptWithoutHex(byte[] bytes, String algorithmName) {
MessageDigest md = null;
try {
if (StrUtil.isBlank(algorithmName)) {
algorithmName = MD5;
}
md = MessageDigest.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw new UtilException(StrUtil.format("No such algorithm name for: {}", algorithmName));
}
return md.digest(bytes);
}
/**
* SHA-1
*
* @param source
* @param charset
* @return
*/
public static String sha1(String source, String charset) {
return encrypt(source, SHA1, charset);
}
/**
* MD5
*
* @param source
* @param charset
* @return
*/
public static String md5(String source, String charset) {
return encrypt(source, MD5, charset);
}
/**
* base64
*
* @param source
* @param charset
* @return
*/
public static String base64(String source, String charset) {
return base64(StrUtil.encode(source, charset));
}
/**
* Base64;
*
* @param bytes byte
* @return
*/
public static String base64(byte[] bytes) {
StringBuilder sb = new StringBuilder();
int len = bytes.length;
int len3 = len / 3;
for (int i = 0; i < len3; i++) {
int b1 = (bytes[i * 3] >> 2) & 0x3F;
char c1 = base64EncodeTable[b1];
sb.append(c1);
int b2 = ((bytes[i * 3] << 4 & 0x3F) + (bytes[i * 3 + 1] >> 4)) & 0x3F;
char c2 = base64EncodeTable[b2];
sb.append(c2);
int b3 = ((bytes[i * 3 + 1] << 2 & 0x3C) + (bytes[i * 3 + 2] >> 6)) & 0x3F;
char c3 = base64EncodeTable[b3];
sb.append(c3);
int b4 = bytes[i * 3 + 2] & 0x3F;
char c4 = base64EncodeTable[b4];
sb.append(c4);
}
int less = len % 3;
if (less == 1) {
int b1 = bytes[len3 * 3] >> 2 & 0x3F;
char c1 = base64EncodeTable[b1];
sb.append(c1);
int b2 = (bytes[len3 * 3] << 4 & 0x30) & 0x3F;
char c2 = base64EncodeTable[b2];
sb.append(c2);
sb.append("==");
} else if (less == 2) {
int b1 = bytes[len3 * 3] >> 2 & 0x3F;
char c1 = base64EncodeTable[b1];
sb.append(c1);
int b2 = ((bytes[len3 * 3] << 4 & 0x30) + (bytes[len3 * 3 + 1] >> 4)) & 0x3F;
char c2 = base64EncodeTable[b2];
sb.append(c2);
int b3 = (bytes[len3 * 3 + 1] << 2 & 0x3C) & 0x3F;
char c3 = base64EncodeTable[b3];
sb.append(c3);
sb.append("=");
}
return sb.toString();
}
/**
* base64
*
* @param source base64
* @param charset
* @return
*/
public static String decodeBase64(String source, String charset) {
return decodeBase64(StrUtil.encode(source, charset));
}
/**
* Base64;
*
* @param bytes
* @return
*/
public static String decodeBase64(byte[] bytes) {
int len = bytes.length;
int len4 = len / 4;
StringBuilder sb = new StringBuilder();
int i = 0;
for (i = 0; i < len4 - 1; i++) {
byte b1 = (byte) ((char2Index((char) bytes[i * 4]) << 2) + (char2Index((char) bytes[i * 4 + 1]) >> 4));
sb.append((char) b1);
byte b2 = (byte) ((char2Index((char) bytes[i * 4 + 1]) << 4) + (char2Index((char) bytes[i * 4 + 2]) >> 2));
sb.append((char) b2);
byte b3 = (byte) ((char2Index((char) bytes[i * 4 + 2]) << 6) + (char2Index((char) bytes[i * 4 + 3])));
sb.append((char) b3);
}
for (int j = 0; j < 3; j++) {
int index = i * 4 + j;
if ((char) bytes[index + 1] != '=') {
if (j == 0) {
byte b = (byte) ((char2Index((char) bytes[index]) << 2) + (char2Index((char) bytes[index + 1]) >> 4));
sb.append((char) b);
} else if (j == 1) {
byte b = (byte) ((char2Index((char) bytes[index]) << 4) + (char2Index((char) bytes[index + 1]) >> 2));
sb.append((char) b);
} else if (j == 2) {
byte b = (byte) ((char2Index((char) bytes[index]) << 6) + (char2Index((char) bytes[index + 1])));
sb.append((char) b);
}
} else {
break;
}
}
return sb.toString();
}
/**
* ;
*
* @param ch
* @return
*/
private static int char2Index(char ch) {
if (ch >= 'A' && ch <= 'Z') {
return ch - 'A';
} else if (ch >= 'a' && ch <= 'z') {
return 26 + ch - 'a';
} else if (ch >= '0' && ch <= '9') {
return 52 + ch - '0';
} else if (ch == '+') {
return 62;
} else if (ch == '/') {
return 63;
}
return 0;
}
} |
package com.zaxxer.hikari.pool;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_AUTOCOMMIT;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_CATALOG;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_ISOLATION;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_NETTIMEOUT;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_READONLY;
import static com.zaxxer.hikari.util.UtilityElf.createInstance;
import java.lang.management.ManagementFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.metrics.MetricsTracker;
import com.zaxxer.hikari.util.ClockSource;
import com.zaxxer.hikari.util.DriverDataSource;
import com.zaxxer.hikari.util.PropertyElf;
import com.zaxxer.hikari.util.UtilityElf;
abstract class PoolBase
{
private final Logger LOGGER = LoggerFactory.getLogger(PoolBase.class);
protected final HikariConfig config;
protected final String poolName;
protected long connectionTimeout;
protected long validationTimeout;
private static final String[] RESET_STATES = {"readOnly", "autoCommit", "isolation", "catalog", "netTimeout"};
private static final int UNINITIALIZED = -1;
private static final int TRUE = 1;
private static final int FALSE = 0;
private int networkTimeout;
private int transactionIsolation;
private int isNetworkTimeoutSupported;
private int isQueryTimeoutSupported;
private DataSource dataSource;
private final String catalog;
private final boolean isReadOnly;
private final boolean isAutoCommit;
private final boolean isUseJdbc4Validation;
private final boolean isIsolateInternalQueries;
private final AtomicReference<Throwable> lastConnectionFailure;
private final Executor netTimeoutExecutor;
private volatile boolean isValidChecked;
PoolBase(final HikariConfig config)
{
this.config = config;
this.networkTimeout = -1;
this.catalog = config.getCatalog();
this.isReadOnly = config.isReadOnly();
this.isAutoCommit = config.isAutoCommit();
this.transactionIsolation = UtilityElf.getTransactionIsolation(config.getTransactionIsolation());
this.isQueryTimeoutSupported = UNINITIALIZED;
this.isNetworkTimeoutSupported = UNINITIALIZED;
this.isUseJdbc4Validation = config.getConnectionTestQuery() == null;
this.isIsolateInternalQueries = config.isIsolateInternalQueries();
this.poolName = config.getPoolName();
this.connectionTimeout = config.getConnectionTimeout();
this.validationTimeout = config.getValidationTimeout();
this.lastConnectionFailure = new AtomicReference<>();
this.netTimeoutExecutor = new SynchronousExecutor();
initializeDataSource();
}
/** {@inheritDoc} */
@Override
public String toString()
{
return poolName;
}
abstract void releaseConnection(final PoolEntry poolEntry);
// JDBC methods
void quietlyCloseConnection(final Connection connection, final String closureReason)
{
if (connection != null) {
try {
LOGGER.debug("{} - Closing connection {}: {}", poolName, connection, closureReason);
try {
setNetworkTimeout(connection, TimeUnit.SECONDS.toMillis(15));
}
finally {
connection.close(); // continue with the close even if setNetworkTimeout() throws
}
}
catch (Throwable e) {
LOGGER.debug("{} - Closing connection {} failed", poolName, connection, e);
}
}
}
boolean isConnectionAlive(final Connection connection)
{
try {
if (isUseJdbc4Validation) {
return connection.isValid((int) TimeUnit.MILLISECONDS.toSeconds(validationTimeout));
}
setNetworkTimeout(connection, validationTimeout);
try (Statement statement = connection.createStatement()) {
if (isNetworkTimeoutSupported != TRUE) {
setQueryTimeout(statement, (int) TimeUnit.MILLISECONDS.toSeconds(validationTimeout));
}
statement.execute(config.getConnectionTestQuery());
}
if (isIsolateInternalQueries && !isReadOnly && !isAutoCommit) {
connection.rollback();
}
setNetworkTimeout(connection, networkTimeout);
return true;
}
catch (SQLException e) {
lastConnectionFailure.set(e);
LOGGER.warn("{} - Connection {} failed alive test with exception {}", poolName, connection, e.getMessage());
return false;
}
}
Throwable getLastConnectionFailure()
{
return lastConnectionFailure.getAndSet(null);
}
public DataSource getUnwrappedDataSource()
{
return dataSource;
}
// PoolEntry methods
PoolEntry newPoolEntry() throws Exception
{
return new PoolEntry(newConnection(), this, isReadOnly, isAutoCommit);
}
void resetConnectionState(final Connection connection, final ProxyConnection proxyConnection, final int dirtyBits) throws SQLException
{
int resetBits = 0;
if ((dirtyBits & DIRTY_BIT_READONLY) != 0 && proxyConnection.getReadOnlyState() != isReadOnly) {
connection.setReadOnly(isReadOnly);
resetBits |= DIRTY_BIT_READONLY;
}
if ((dirtyBits & DIRTY_BIT_AUTOCOMMIT) != 0 && proxyConnection.getAutoCommitState() != isAutoCommit) {
connection.setAutoCommit(isAutoCommit);
resetBits |= DIRTY_BIT_AUTOCOMMIT;
}
if ((dirtyBits & DIRTY_BIT_ISOLATION) != 0 && proxyConnection.getTransactionIsolationState() != transactionIsolation) {
connection.setTransactionIsolation(transactionIsolation);
resetBits |= DIRTY_BIT_ISOLATION;
}
if ((dirtyBits & DIRTY_BIT_CATALOG) != 0 && catalog != null && !catalog.equals(proxyConnection.getCatalogState())) {
connection.setCatalog(catalog);
resetBits |= DIRTY_BIT_CATALOG;
}
if ((dirtyBits & DIRTY_BIT_NETTIMEOUT) != 0 && proxyConnection.getNetworkTimeoutState() != networkTimeout) {
setNetworkTimeout(connection, networkTimeout);
resetBits |= DIRTY_BIT_NETTIMEOUT;
}
if (resetBits != 0 && LOGGER.isDebugEnabled()) {
LOGGER.debug("{} - Reset ({}) on connection {}", poolName, stringFromResetBits(resetBits), connection);
}
}
// JMX methods
/**
* Register MBeans for HikariConfig and HikariPool.
*
* @param pool a HikariPool instance
*/
void registerMBeans(final HikariPool hikariPool)
{
if (!config.isRegisterMbeans()) {
return;
}
try {
final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
if (!mBeanServer.isRegistered(beanConfigName)) {
mBeanServer.registerMBean(config, beanConfigName);
mBeanServer.registerMBean(hikariPool, beanPoolName);
}
else {
LOGGER.error("{} - You cannot use the same pool name for separate pool instances.", poolName);
}
}
catch (Exception e) {
LOGGER.warn("{} - Unable to register management beans.", poolName, e);
}
}
/**
* Unregister MBeans for HikariConfig and HikariPool.
*/
void unregisterMBeans()
{
if (!config.isRegisterMbeans()) {
return;
}
try {
final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
if (mBeanServer.isRegistered(beanConfigName)) {
mBeanServer.unregisterMBean(beanConfigName);
mBeanServer.unregisterMBean(beanPoolName);
}
}
catch (Exception e) {
LOGGER.warn("{} - Unable to unregister management beans.", poolName, e);
}
}
// Private methods
/**
* Create/initialize the underlying DataSource.
*
* @return a DataSource instance
*/
private void initializeDataSource()
{
final String jdbcUrl = config.getJdbcUrl();
final String username = config.getUsername();
final String password = config.getPassword();
final String dsClassName = config.getDataSourceClassName();
final String driverClassName = config.getDriverClassName();
final Properties dataSourceProperties = config.getDataSourceProperties();
DataSource dataSource = config.getDataSource();
if (dsClassName != null && dataSource == null) {
dataSource = createInstance(dsClassName, DataSource.class);
PropertyElf.setTargetFromProperties(dataSource, dataSourceProperties);
}
else if (jdbcUrl != null && dataSource == null) {
dataSource = new DriverDataSource(jdbcUrl, driverClassName, dataSourceProperties, username, password);
}
if (dataSource != null) {
setLoginTimeout(dataSource, connectionTimeout);
}
this.dataSource = dataSource;
}
Connection newConnection() throws Exception
{
Connection connection = null;
try {
String username = config.getUsername();
String password = config.getPassword();
connection = (username == null) ? dataSource.getConnection() : dataSource.getConnection(username, password);
setupConnection(connection);
lastConnectionFailure.set(null);
return connection;
}
catch (Exception e) {
lastConnectionFailure.set(e);
quietlyCloseConnection(connection, "(Failed to create/set connection)");
throw e;
}
}
/**
* Setup a connection initial state.
*
* @param connection a Connection
* @throws SQLException thrown from driver
*/
private void setupConnection(final Connection connection) throws SQLException
{
networkTimeout = getAndSetNetworkTimeout(connection, connectionTimeout);
checkValidationMode(connection);
connection.setAutoCommit(isAutoCommit);
connection.setReadOnly(isReadOnly);
final int defaultLevel = connection.getTransactionIsolation();
transactionIsolation = (transactionIsolation < 0 || defaultLevel == Connection.TRANSACTION_NONE)
? defaultLevel
: transactionIsolation;
if (transactionIsolation != defaultLevel) {
connection.setTransactionIsolation(transactionIsolation);
}
if (catalog != null) {
connection.setCatalog(catalog);
}
executeSql(connection, config.getConnectionInitSql(), isIsolateInternalQueries && !isAutoCommit, false);
setNetworkTimeout(connection, networkTimeout);
}
/**
* Execute isValid() or connection test query.
*
* @param connection a Connection to check
*/
private void checkValidationMode(final Connection connection) throws SQLException
{
if (!isValidChecked) {
if (isUseJdbc4Validation) {
try {
connection.isValid(1);
}
catch (Throwable e) {
LOGGER.debug("{} - Connection.isValid() is not supported, configure connection test query. ({})", poolName, e.getMessage());
throw e;
}
}
else {
try {
executeSql(connection, config.getConnectionTestQuery(), false, isIsolateInternalQueries && !isAutoCommit);
}
catch (Throwable e) {
LOGGER.debug("{} - Failed to execute connection test query. ({})", poolName, e.getMessage());
throw e;
}
}
isValidChecked = true;
}
}
/**
* Set the query timeout, if it is supported by the driver.
*
* @param statement a statement to set the query timeout on
* @param timeoutSec the number of seconds before timeout
*/
private void setQueryTimeout(final Statement statement, final int timeoutSec)
{
if (isQueryTimeoutSupported != FALSE) {
try {
statement.setQueryTimeout(timeoutSec);
isQueryTimeoutSupported = TRUE;
}
catch (Throwable e) {
if (isQueryTimeoutSupported == UNINITIALIZED) {
isQueryTimeoutSupported = FALSE;
LOGGER.debug("{} - Statement.setQueryTimeout() is not supported ({})", poolName, e.getMessage());
}
}
}
}
/**
* Set the network timeout, if <code>isUseNetworkTimeout</code> is <code>true</code> and the
* driver supports it. Return the pre-existing value of the network timeout.
*
* @param connection the connection to set the network timeout on
* @param timeoutMs the number of milliseconds before timeout
* @return the pre-existing network timeout value
*/
private int getAndSetNetworkTimeout(final Connection connection, final long timeoutMs)
{
if (isNetworkTimeoutSupported != FALSE) {
try {
final int originalTimeout = connection.getNetworkTimeout();
connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs);
isNetworkTimeoutSupported = TRUE;
return originalTimeout;
}
catch (Throwable e) {
if (isNetworkTimeoutSupported == UNINITIALIZED) {
isNetworkTimeoutSupported = FALSE;
LOGGER.debug("{} - Connection.setNetworkTimeout() is not supported ({})", poolName, e.getMessage());
}
}
}
return 0;
}
/**
* Set the network timeout, if <code>isUseNetworkTimeout</code> is <code>true</code> and the
* driver supports it.
*
* @param connection the connection to set the network timeout on
* @param timeoutMs the number of milliseconds before timeout
* @throws SQLException throw if the connection.setNetworkTimeout() call throws
*/
private void setNetworkTimeout(final Connection connection, final long timeoutMs) throws SQLException
{
if (isNetworkTimeoutSupported == TRUE) {
connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs);
}
}
/**
* Execute the user-specified init SQL.
*
* @param connection the connection to initialize
* @param sql the SQL to execute
* @param isAutoCommit whether to commit the SQL after execution or not
* @throws SQLException throws if the init SQL execution fails
*/
private void executeSql(final Connection connection, final String sql, final boolean isCommit, final boolean isRollback) throws SQLException
{
if (sql != null) {
try (Statement statement = connection.createStatement()) {
//con created few ms before, set query timeout is omitted
statement.execute(sql);
if (!isReadOnly) {
if (isCommit) {
connection.commit();
}
else if (isRollback) {
connection.rollback();
}
}
}
}
}
private static class SynchronousExecutor implements Executor
{
/** {@inheritDoc} */
@Override
public void execute(Runnable command)
{
try {
command.run();
}
catch (Throwable t) {
LoggerFactory.getLogger(PoolBase.class).debug("Exception executing {}", command, t);
}
}
}
/**
* Set the loginTimeout on the specified DataSource.
*
* @param dataSource the DataSource
* @param connectionTimeout the timeout in milliseconds
*/
private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout)
{
if (connectionTimeout != Integer.MAX_VALUE) {
try {
dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout)));
}
catch (Throwable e) {
LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e);
}
}
}
/**
* This will create a string for debug logging. Given a set of "reset bits", this
* method will return a concatenated string, for example:
*
* Input : 0b00110
* Output: "autoCommit, isolation"
*
* @param bits a set of "reset bits"
* @return a string of which states were reset
*/
private String stringFromResetBits(final int bits)
{
final StringBuilder sb = new StringBuilder();
for (int ndx = 0; ndx < RESET_STATES.length; ndx++) {
if ( (bits & (0b1 << ndx)) != 0) {
sb.append(RESET_STATES[ndx]).append(", ");
}
}
sb.setLength(sb.length() - 2); // trim trailing comma
return sb.toString();
}
static class MetricsTrackerDelegate implements AutoCloseable
{
final MetricsTracker tracker;
protected MetricsTrackerDelegate()
{
this.tracker = null;
}
MetricsTrackerDelegate(MetricsTracker tracker)
{
this.tracker = tracker;
}
@Override
public void close()
{
tracker.close();
}
void recordConnectionUsage(final PoolEntry poolEntry)
{
tracker.recordConnectionUsageMillis(poolEntry.getMillisSinceBorrowed());
}
/**
* @param poolEntry
* @param now
*/
void recordBorrowStats(final PoolEntry poolEntry, final long startTime)
{
final long now = ClockSource.INSTANCE.currentTime();
poolEntry.lastBorrowed = now;
tracker.recordConnectionAcquiredNanos(ClockSource.INSTANCE.elapsedNanos(startTime, now));
}
}
static final class NopMetricsTrackerDelegate extends MetricsTrackerDelegate
{
@Override
void recordConnectionUsage(final PoolEntry poolEntry)
{
// no-op
}
@Override
public void close()
{
// no-op
}
@Override
void recordBorrowStats(final PoolEntry poolEntry, final long startTime)
{
// no-op
}
}
} |
package cubicchunks.converter.lib;
import com.flowpowered.nbt.CompoundTag;
import com.flowpowered.nbt.stream.NBTInputStream;
import com.flowpowered.nbt.stream.NBTOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.Callable;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.InflaterInputStream;
public class Utils {
public static boolean isValidPath(String text) {
try {
Files.exists(Paths.get(text));
return true;
} catch (InvalidPathException e) {
return false;
}
}
public static boolean fileExists(String text) {
try {
return Files.exists(Paths.get(text));
} catch (InvalidPathException e) {
return false;
}
}
public static int countFiles(Path f) throws IOException {
try {
return countFiles_do(f);
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
private static int countFiles_do(Path f) {
if (Files.isRegularFile(f)) {
return 1;
} else if (!Files.isDirectory(f)) {
throw new UnsupportedOperationException();
}
try {
return Files.list(f).map(p -> countFiles_do(p)).reduce((x, y) -> x + y).orElse(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static void copyEverythingExcept(Path file, Path srcDir, Path dstDir, Predicate<Path> excluded, Consumer<Path> onCopy) throws IOException {
try {
Files.list(file).forEach(f -> {
if (!excluded.test(f)) {
try {
copyFile(f, srcDir, dstDir);
if (Files.isRegularFile(f)) {
onCopy.accept(f);
}
if (Files.isDirectory(f)) {
copyEverythingExcept(f, srcDir, dstDir, excluded, onCopy);
} else if (!Files.isRegularFile(f)) {
throw new UnsupportedOperationException();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
});
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
public static void copyFile(Path srcFile, Path srcDir, Path dstDir) throws IOException {
Path relative = srcDir.relativize(srcFile);
Path dstFile = dstDir.resolve(relative);
if (Files.exists(dstFile) && Files.isDirectory(dstFile)) {
return; // already exists, stop here to avoid DirectoryNotEmptyException
}
Files.createDirectories(dstFile.getParent());
Files.copy(srcFile, dstFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
}
public static CompoundTag readCompressed(InputStream is) throws IOException {
int i = is.read();
BufferedInputStream data;
if (i == 1) {
data = new BufferedInputStream(new GZIPInputStream(is));
} else if (i == 2) {
data = new BufferedInputStream(new InflaterInputStream(is));
} else {
throw new UnsupportedOperationException();
}
return (CompoundTag) new NBTInputStream(data, false).readTag();
}
public static ByteBuffer writeCompressed(CompoundTag tag, boolean compress) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
NBTOutputStream nbtOut = new NBTOutputStream(new BufferedOutputStream(new GZIPOutputStream(bytes) {{
if (!compress) this.def.setLevel(Deflater.NO_COMPRESSION);
}}), false);
nbtOut.writeTag(tag);
nbtOut.close();
bytes.flush();
return ByteBuffer.wrap(bytes.toByteArray());
}
private enum OS {
WINDOWS, MACOS, SOLARIS, LINUX, UNKNOWN;
}
private static OS getPlatform() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
return OS.WINDOWS;
}
if (osName.contains("mac")) {
return OS.MACOS;
}
if (osName.contains("linux")) {
return OS.LINUX;
}
if (osName.contains("unix")) {
return OS.LINUX;
}
return OS.UNKNOWN;
}
public static Path getApplicationDirectory() {
String userHome = System.getProperty("user.home", ".");
Path workingDirectory;
switch (getPlatform()) {
case LINUX:
case SOLARIS:
workingDirectory = Paths.get(userHome, ".minecraft/");
break;
case WINDOWS:
String applicationData = System.getenv("APPDATA");
String folder = applicationData != null ? applicationData : userHome;
workingDirectory = Paths.get(folder, ".minecraft/");
break;
case MACOS:
workingDirectory = Paths.get(userHome, "Library/Application Support/minecraft");
break;
default:
workingDirectory = Paths.get(userHome, "minecraft/");
}
return workingDirectory;
}
} |
package de.cronn.jira.sync;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import de.cronn.jira.sync.config.JiraProjectSync;
import de.cronn.jira.sync.config.JiraSyncConfig;
import de.cronn.jira.sync.domain.JiraIssue;
import de.cronn.jira.sync.domain.JiraProject;
import de.cronn.jira.sync.link.JiraIssueLinker;
import de.cronn.jira.sync.service.JiraService;
import de.cronn.jira.sync.strategy.ExistingTargetJiraIssueSyncStrategy;
import de.cronn.jira.sync.strategy.IssueSyncStrategy;
import de.cronn.jira.sync.strategy.MissingTargetJiraIssueSyncStrategy;
import de.cronn.jira.sync.strategy.SyncResult;
@Component
@EnableConfigurationProperties(JiraSyncConfig.class)
public class JiraSyncTask implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(JiraSyncTask.class);
private final JiraService jiraSource;
private final JiraService jiraTarget;
private final JiraSyncConfig jiraSyncConfig;
private final JiraIssueLinker jiraIssueLinker;
private final MissingTargetJiraIssueSyncStrategy missingTargetJiraIssueSyncStrategy;
private final ExistingTargetJiraIssueSyncStrategy existingTargetJiraIssueSyncStrategy;
public JiraSyncTask(JiraService jiraSource, JiraService jiraTarget, JiraSyncConfig jiraSyncConfig, JiraIssueLinker jiraIssueLinker, MissingTargetJiraIssueSyncStrategy missingTargetJiraIssueSyncStrategy, ExistingTargetJiraIssueSyncStrategy existingTargetJiraIssueSyncStrategy) {
this.jiraSource = jiraSource;
this.jiraTarget = jiraTarget;
this.jiraSyncConfig = jiraSyncConfig;
this.jiraIssueLinker = jiraIssueLinker;
this.missingTargetJiraIssueSyncStrategy = missingTargetJiraIssueSyncStrategy;
this.existingTargetJiraIssueSyncStrategy = existingTargetJiraIssueSyncStrategy;
}
@Override
public void run(String... args) throws Exception {
if (jiraSyncConfig.isAutostart()) {
sync();
} else {
log.info("not auto-starting sync");
}
}
public List<ProjectSyncResult> sync() {
if (jiraSyncConfig.getSource() == null || jiraSyncConfig.getTarget() == null) {
log.warn("Source or target is not defined");
return Collections.emptyList();
}
try {
jiraSource.login(jiraSyncConfig.getSource(), true);
jiraTarget.login(jiraSyncConfig.getTarget(), false);
log.info("going to link source={} with target={}", jiraSource, jiraTarget);
log.info("jiraSource server info: {}", jiraSource.getServerInfo());
log.info("jiraTarget server info: {}", jiraTarget.getServerInfo());
Map<String, JiraProjectSync> projects = jiraSyncConfig.getProjects();
if (projects.isEmpty()) {
log.warn("No projects configured");
return Collections.emptyList();
}
return syncProjects(projects);
} catch (Exception e) {
log.error("Synchronisation failed", e);
throw e;
} finally {
jiraSource.close();
jiraTarget.close();
}
}
private List<ProjectSyncResult> syncProjects(Map<String, JiraProjectSync> projects) {
List<ProjectSyncResult> projectSyncResults = new ArrayList<>();
for (JiraProjectSync projectSync : projects.values()) {
ProjectSyncResult syncResult = syncProject(jiraSource, jiraTarget, projectSync);
projectSyncResults.add(syncResult);
}
List<JiraProjectSync> failedProjects = findFailedProjects(projectSyncResults);
if (!failedProjects.isEmpty()) {
String formattedProjects = failedProjects.stream().map(this::format).collect(Collectors.joining(", "));
throw new JiraSyncException("Synchronisation failed with :" + formattedProjects);
}
return projectSyncResults;
}
private List<JiraProjectSync> findFailedProjects(List<ProjectSyncResult> projectSyncResults) {
return projectSyncResults.stream().filter(ProjectSyncResult::hasFailed)
.map(ProjectSyncResult::getProjectSync)
.collect(Collectors.toList());
}
private String format(JiraProjectSync projectSync) {
return MessageFormat.format("[{0} -> {1}]", projectSync.getSourceProject(), projectSync.getTargetProject());
}
private ProjectSyncResult syncProject(JiraService jiraSource, JiraService jiraTarget, JiraProjectSync projectSync) {
log.info("syncing project {}", format(projectSync));
String sourceFilterId = projectSync.getSourceFilterId();
Assert.notNull(sourceFilterId, "sourceFilterId must be configured");
List<JiraIssue> issues = jiraSource.getIssuesByFilterId(sourceFilterId, jiraSyncConfig.getFieldMapping().keySet());
Map<SyncResult, Long> resultCounts = new EnumMap<>(SyncResult.class);
for (SyncResult syncResult : SyncResult.values()) {
resultCounts.put(syncResult, 0L);
}
for (JiraIssue sourceIssue : issues) {
SyncResult syncResult = syncIssue(sourceIssue, jiraSource, jiraTarget, projectSync);
log.info("'{}' {}", sourceIssue.getKey(), syncResult.getDisplayName());
resultCounts.compute(syncResult, (k, v) -> v + 1);
}
for (Entry<SyncResult, Long> entry : resultCounts.entrySet()) {
log.info("{} {} issues: {}", format(projectSync), entry.getKey().getDisplayName(), entry.getValue());
}
return new ProjectSyncResult(projectSync, resultCounts);
}
private SyncResult syncIssue(JiraIssue sourceIssue, JiraService jiraSource, JiraService jiraTarget, JiraProjectSync projectSync) {
JiraProject project = sourceIssue.getFields().getProject();
if (!project.getKey().equals(projectSync.getSourceProject())) {
throw new JiraSyncException("Filter returned issue " + sourceIssue + " from unexpected project " + project);
}
try {
JiraIssue targetIssue = jiraIssueLinker.resolveIssue(sourceIssue, jiraSource, jiraTarget);
IssueSyncStrategy syncStrategy = getSyncStrategy(targetIssue);
return syncStrategy.sync(jiraSource, jiraTarget, sourceIssue, targetIssue, projectSync);
} catch (JiraSyncException e) {
log.error("Issue synchronisation failed", e);
return SyncResult.FAILED;
}
}
private IssueSyncStrategy getSyncStrategy(JiraIssue targetIssue) {
if (targetIssue == null) {
return missingTargetJiraIssueSyncStrategy;
} else {
return existingTargetJiraIssueSyncStrategy;
}
}
} |
package de.prob2.ui.menu;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import de.be4.classicalb.core.parser.exceptions.BException;
import de.codecentric.centerdevice.MenuToolkit;
import de.prob.scripting.Api;
import de.prob.statespace.AnimationSelector;
import de.prob.statespace.StateSpace;
import de.prob.statespace.Trace;
import de.prob2.ui.ProB2;
import de.prob2.ui.dotty.DottyStage;
import de.prob2.ui.formula.FormulaGenerator;
import de.prob2.ui.groovy.GroovyConsoleView;
import de.prob2.ui.groovy.GroovyObjectView;
import de.prob2.ui.modelchecking.ModelcheckingController;
import de.prob2.ui.modelchecking.ModelcheckingStage;
import de.prob2.ui.preferences.PreferencesStage;
import de.prob2.ui.states.BlacklistStage;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextInputDialog;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
@Singleton
public class MenuController extends MenuBar {
private final Api api;
private final AnimationSelector animationSelector;
private final BlacklistStage blacklistStage;
private final PreferencesStage preferencesStage;
private final ModelcheckingController modelcheckingController;
private final Stage mcheckStage;
private final FormulaGenerator formulaGenerator;
private final Stage groovyConsoleStage;
private final Stage groovyObjectStage;
private Window window;
private DottyStage dottyStage;
@FXML
private void handleLoadDefault() {
FXMLLoader loader = ProB2.injector.getInstance(FXMLLoader.class);
loader.setLocation(getClass().getResource("../main.fxml"));
try {
loader.load();
} catch (IOException e) {
System.err.println("Failed to load FXML-File!");
e.printStackTrace();
}
Parent root = loader.getRoot();
Scene scene = new Scene(root, window.getHeight(), window.getWidth());
((Stage) window).setScene(scene);
}
@FXML
private void handleLoadPerspective() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open File");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("FXML Files", "*.fxml"));
File selectedFile = fileChooser.showOpenDialog(window);
if (selectedFile != null)
try {
FXMLLoader loader = ProB2.injector.getInstance(FXMLLoader.class);
loader.setLocation(new URL("file://" + selectedFile.getPath()));
loader.load();
Parent root = loader.getRoot();
Scene scene = new Scene(root, window.getHeight(), window.getWidth());
((Stage) window).setScene(scene);
} catch (IOException e) {
System.err.println("Failed to load FXML-File!");
e.printStackTrace();
}
}
@FXML
private void handleOpen(ActionEvent event) {
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open File");
fileChooser.getExtensionFilters().addAll(
// new FileChooser.ExtensionFilter("All Files", "*.*"),
new FileChooser.ExtensionFilter("Classical B Files", "*.mch", "*.ref", "*.imp")
// new FileChooser.ExtensionFilter("EventB Files", "*.eventb", "*.bum",
// "*.buc"),
// new FileChooser.ExtensionFilter("CSP Files", "*.cspm")
);
final File selectedFile = fileChooser.showOpenDialog(this.window);
if (selectedFile == null) {
return;
}
switch (fileChooser.getSelectedExtensionFilter().getDescription()) {
case "Classical B Files":
final StateSpace newSpace;
try {
newSpace = this.api.b_load(selectedFile.getAbsolutePath());
} catch (IOException | BException e) {
e.printStackTrace();
Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e);
alert.getDialogPane().getStylesheets().add("prob.css");
alert.showAndWait();
return;
}
final Trace currentTrace = this.animationSelector.getCurrentTrace();
// if (currentTrace != null) {
// this.animationSelector.removeTrace(currentTrace);
this.animationSelector.addNewAnimation(new Trace(newSpace));
modelcheckingController.resetView();
break;
default:
throw new IllegalStateException(
"Unknown file type selected: " + fileChooser.getSelectedExtensionFilter().getDescription());
}
}
@FXML
private void handleEditBlacklist(ActionEvent event) {
this.blacklistStage.show();
this.blacklistStage.toFront();
}
@FXML
private void handlePreferences(ActionEvent event) {
this.preferencesStage.show();
this.preferencesStage.toFront();
}
@FXML
private void handleFormulaInput(ActionEvent event) {
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("Enter Formula for Visualization");
dialog.setHeaderText("Enter Formula for Vistualization");
dialog.setContentText("Enter Formula: ");
dialog.getDialogPane().getStylesheets().add("prob.css");
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
formulaGenerator.setFormula(formulaGenerator.parse(result.get()));
}
}
@FXML
private void handleModelCheck(ActionEvent event) {
this.mcheckStage.showAndWait();
this.mcheckStage.toFront();
}
@FXML
private void handleDotty(ActionEvent event) {
this.dottyStage.showAndWait();
}
@FXML
public void handleGroovyConsole(ActionEvent event) {
this.groovyConsoleStage.show();
this.groovyConsoleStage.toFront();
}
@FXML
public void handleGroovyObjects(ActionEvent event) {
this.groovyObjectStage.show();
this.groovyObjectStage.toFront();
}
@FXML
public void initialize() {
this.sceneProperty().addListener((observable, from, to) -> {
if (to != null) {
to.windowProperty().addListener((observable1, from1, to1) -> {
this.window = to1;
this.mcheckStage.initOwner(this.window);
});
}
});
}
@Inject
private MenuController(final FXMLLoader loader, final Api api, final AnimationSelector animationSelector,
final BlacklistStage blacklistStage, final PreferencesStage preferencesStage,
final ModelcheckingStage modelcheckingStage, final ModelcheckingController modelcheckingController,
final FormulaGenerator formulaGenerator, final DottyStage dottyStage, final GroovyConsoleView groovyConsoleView, final GroovyObjectView groovyObjectView) {
this.api = api;
this.animationSelector = animationSelector;
this.blacklistStage = blacklistStage;
this.preferencesStage = preferencesStage;
this.formulaGenerator = formulaGenerator;
this.modelcheckingController = modelcheckingController;
this.mcheckStage = modelcheckingStage;
this.dottyStage = dottyStage;
this.groovyConsoleStage = new Stage();
this.groovyConsoleStage.setTitle("Groovy Console");
this.groovyConsoleStage.setScene(new Scene(groovyConsoleView));
this.groovyConsoleStage.initModality(Modality.NONE);
this.groovyConsoleStage.setResizable(false);
this.groovyObjectStage = new Stage();
this.groovyObjectStage.setTitle("Groovy Objects View");
this.groovyObjectStage.setScene(new Scene(groovyObjectView));
this.groovyObjectStage.initModality(Modality.NONE);
this.groovyObjectStage.setResizable(true);
try {
loader.setLocation(getClass().getResource("menu.fxml"));
loader.setRoot(this);
loader.setController(this);
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
if (System.getProperty("os.name", "").toLowerCase().contains("mac")) {
// Mac-specific menu stuff
this.setUseSystemMenuBar(true);
MenuToolkit tk = MenuToolkit.toolkit();
// Create Mac-style application menu
Menu applicationMenu = tk.createDefaultApplicationMenu("ProB 2");
this.getMenus().add(0, applicationMenu);
tk.setApplicationMenu(applicationMenu);
// Move About menu item from Help to application menu
Menu helpMenu = this.getMenus().get(this.getMenus().size() - 1);
MenuItem aboutItem = helpMenu.getItems().get(helpMenu.getItems().size() - 1);
aboutItem.setText("About ProB 2");
helpMenu.getItems().remove(aboutItem);
applicationMenu.getItems().set(0, aboutItem);
// Create Mac-style Window menu
Menu windowMenu = new Menu("Window");
windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(),
tk.createCycleWindowsItem(), new SeparatorMenuItem(), tk.createBringAllToFrontItem(),
new SeparatorMenuItem());
tk.autoAddWindowMenuItems(windowMenu);
this.getMenus().add(this.getMenus().size() - 1, windowMenu);
// Make this the global menu bar
tk.setGlobalMenuBar(this);
}
}
} |
package factors.discrete;
import factors.Factor;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Implementation of a discrete factor. This implementation keeps track of the
* scope, cardinality, and values of a factor as a basic representation of
* a joint probability table or conditional probability distribution.
*
* @see factors.Factor
*
* @version 1.0.0
*
* @author Sean McMillan
*/
public class DiscreteFactor implements Factor {
private ObjectArrayList<String> variables;
private Object2ObjectOpenHashMap<String, String[]> assignments;
private int[] cardinality;
private double[] values;
private int size;
private Object2IntOpenHashMap<String> varIdx;
private Int2IntOpenHashMap indexOffset;
private Object2ObjectOpenHashMap<String, Int2ObjectOpenHashMap<IntArrayList>> indices;
public DiscreteFactor(String[] variables, int[] cardinality, double[] values) {
this.setVariables(variables);
this.setCardinality(cardinality);
this.setValues(values);
}
public Factor copy() {
return new DiscreteFactor(this.getScope(), this.getCardinality(),
this.getValues());
}
private void setVariables(String[] variables) {
this.variables = new ObjectArrayList<>();
Arrays.stream(variables)
.forEach(v -> this.variables.add(v));
}
@Override public String[] getScope() {
return this.variables.stream().toArray(String[]::new);
}
private void setCardinality(int[] cardinality) {
if (this.variables.size() != cardinality.length) {
throw new RuntimeException("variables and cardinality must have same size.");
}
this.cardinality = cardinality.clone();
this.setAssignments();
this.createIndices();
}
public int[] getCardinality() {
return this.cardinality.clone();
}
private void setAssignments() {
this.assignments = new Object2ObjectOpenHashMap<>();
IntStream.range(0, this.variables.size())
.forEach(i -> this.assignments.put(this.variables.get(i),
IntStream.range(0, this.cardinality[i])
.mapToObj(Integer::toString)
.toArray(String[]::new)));
}
private void createIndices() {
this.varIdx = new Object2IntOpenHashMap<>(this.variables.size());
this.size = Arrays.stream(this.cardinality)
.reduce(1, (a, b) -> a * b);
int i = 0;
for(String variable : this.variables) {
this.varIdx.put(variable, i++);
}
this.indexOffset = getOffsets(this.cardinality);
}
private Int2IntOpenHashMap getOffsets(int[] cardinality) {
Int2IntOpenHashMap offsets = new Int2IntOpenHashMap();
for(int i = 0;i < cardinality.length;++i) {
int offset = 1;
for(int c = i + 1;c < cardinality.length;++c) {
offset *= cardinality[c];
}
offsets.put(i, offset);
}
return offsets;
}
public String[] getAssignment(String variable) {
return this.assignments.get(variable);
}
public String[] getAssignment(int index) {
return this.assignments.get(this.variables.get(index));
}
private void setValues(double[] values) {
if (values.length != this.size) {
throw new RuntimeException(
String.format("Incorrect size of values variables. Expecting array " +
"of size %d. Instead received array of size %d.",
this.size, values.length));
}
this.values = values.clone();
this.indices = new Object2ObjectOpenHashMap<>();
for(int v = 0;v < this.variables.size();++v) {
String variable = this.variables.get(v);
this.indices.put(variable, new Int2ObjectOpenHashMap<>());
IntStream.range(0, this.cardinality[v])
.forEach(c -> this.indices.get(variable)
.put(c, new IntArrayList()));
}
for(int i = 0;i < this.values.length;++i) {
for(int v = 0;v < this.variables.size();++v) {
String variable = this.variables.get(v);
int vIdx = this.varIdx.getInt(variable);
int offsetVal = this.indexOffset.get(vIdx);
Int2ObjectOpenHashMap<IntArrayList> idxVal = this.indices.get(variable);
idxVal.get((i / offsetVal) % this.cardinality[v]).add(i);
}
}
}
public double[] getValues() {
return this.values.clone();
}
@Override public Factor normalize(boolean inPlace) {
DiscreteFactor result = inPlace ? this : (DiscreteFactor)this.copy();
double sum = Arrays.stream(result.getValues()).sum();
double[] normalizedValues = Arrays.stream(result.getValues())
.map(v -> v / sum)
.toArray();
result.setValues(normalizedValues);
return result;
}
@Override public Factor reduce(List<Pair<String, Integer>> variables,
boolean inPlace) {
IntArrayList reductionVarIdxs = new IntArrayList();
IntOpenHashSet reductionIdxs = new IntOpenHashSet();
IntStream.range(0, this.variables.size())
.forEach(reductionVarIdxs::add);
for(Pair<String, Integer> varAss : variables) {
String variable = varAss.getLeft();
int assignment = varAss.getRight();
if(!this.varIdx.containsKey(variable)) {
throw new RuntimeException(String.format("Variable %s not in scope\n",
variable));
} else {
reductionVarIdxs.rem(this.varIdx.getInt(variable));
IntArrayList assIdx = this.indices.get(variable).get(assignment);
if(assIdx == null) {
throw new RuntimeException(String.format("Variable: %s has no " +
"assignment: %d\n", variable, assignment));
} else {
if (reductionIdxs.isEmpty()) {
reductionIdxs.addAll(assIdx);
} else {
reductionIdxs.retainAll(assIdx);
}
}
}
}
String[] newScope = this.variables.stream()
.filter(v -> reductionVarIdxs.contains(this.varIdx.getInt(v)))
.toArray(String[]::new);
int[] newCardinality = Arrays.stream(reductionVarIdxs.toIntArray())
.map(i -> this.cardinality[i])
.toArray();
int[] sortedReducedIdxs = reductionIdxs.toIntArray();
Arrays.sort(sortedReducedIdxs);
double[] newValues = Arrays.stream(sortedReducedIdxs)
.mapToDouble(i -> this.values[i])
.toArray();
if(inPlace) {
this.setVariables(newScope);
this.setCardinality(newCardinality);
this.setValues(newValues);
}
return inPlace ? this :
new DiscreteFactor(newScope, newCardinality, newValues);
}
@Override public Factor marginalize(String[] variables, boolean inPlace) {
ObjectArrayList<String> newScope = new ObjectArrayList<>();
newScope.addAll(this.variables);
IntArrayList newCardinality = new IntArrayList();
newCardinality.addAll(Arrays.stream(this.cardinality)
.boxed()
.collect(Collectors.toList()));
for(String variable : variables) {
if (!newScope.contains(variable)) {
throw new RuntimeException(String.format("Variable %s not in scope or"
+ "already removed during marginalization\n", variable));
}
int idx = newScope.indexOf(variable);
newScope.remove(idx);
newCardinality.removeInt(idx);
}
if(inPlace) {
this.setVariables(Arrays.stream(newScope.toArray())
.toArray(String[]::new));
this.setCardinality(newCardinality.toIntArray());
}
Int2IntOpenHashMap newIdxOffset = this.getOffsets(newCardinality.toIntArray());
DoubleArrayList marginalizedValues = new DoubleArrayList();
for(int i = 0;i < this.size;++i) {
IntOpenHashSet idxToSum = new IntOpenHashSet();
for(int v = 0;v < this.variables.size();++v) {
String variable = this.variables.get(v);
int vIdx = this.varIdx.getInt(variable);
int offset = newIdxOffset.get(vIdx);
int assIdx = (i / offset) % this.cardinality[v];
IntArrayList assignments = this.indices.get(variable).get(assIdx);
if (idxToSum.isEmpty()) {
idxToSum.addAll(assignments);
} else {
idxToSum.retainAll(assignments);
}
}
marginalizedValues.add(idxToSum.stream()
.mapToDouble(index -> this.values[index])
.sum());
}
this.setValues(marginalizedValues.toDoubleArray());
return this;
}
} |
package frc.team4215.stronghold;
import java.util.ArrayList;
import edu.wpi.first.wpilibj.I2C;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.internal.HardwareTimer;
public class I2CGyro {
private static I2C gyro;
private static boolean pingFlag;
private static double lastTime = 0;
private static double coeff = 0.00875;
private static HardwareTimer hardTimer = new HardwareTimer();
private static Timer.Interface timer;
private final static byte WHO_AM_I = 0x0F, CTRL_REG = 0x20, OUT_REG = 0x28,
FIFO_CTRL_REG = 0x2E;
private static double[] angles;
private static double[] lastAngleSpeed;
private static double[] HOWDOYOUCALLTHIS;
private static int limit = 15;
private static byte[] ID = new byte[1], dataBuffer = new byte[1];
private static Thread threadPing;
protected static void velInteg() {
gyro.read(I2CGyro.FIFO_CTRL_REG, 1, dataBuffer);
double[] vel = new double[3];
double deltat = .08;
int loopCount = dataBuffer[0] & 0x1F;
ArrayList<double[]> gyroList = new ArrayList<double[]>();
for (int i = 0; i < loopCount; i++) {
pingGyro();
gyroList.add(lastAngleSpeed);
}
for (int i = 0; i < loopCount; i++) {
double[] cur = gyroList.get(i);
for (int j = 0; j < 3; j++)
vel[j] = cur[j];
}
for (int j = 0; j < 3; j++)
HOWDOYOUCALLTHIS[j] += vel[j] * deltat;
}
public static void initGyro() {
// Instantiating the gyro Object
gyro = new I2C(I2C.Port.kOnboard, 0x1D);
/*
* Setting up the Gyro references are on the Github wiki
*/
gyro.write(CTRL_REG, 0x3F);
gyro.write(CTRL_REG + 1, 0x00);
gyro.write(CTRL_REG + 2, 0x00);
gyro.write(CTRL_REG + 3, 0x00);
gyro.write(CTRL_REG + 4, 0x00);
boolean worked = gyro.read(WHO_AM_I, 1, ID);
if (ID[0] == 0xD4) {
RobotModule.logger.info("Gyro active!");
} else {
RobotModule.logger.error("Gyro not operating, please check wiring! "
+ Integer.toBinaryString(ID[0]));
}
/*
* The gyroscope only gives us angular velocity so we need to
* integrate it.
*/
timer = hardTimer.newTimer();
// Resetting the tracker variables
lastAngleSpeed = new double[] { 0, 0, 0 };
angles = new double[] { 0, 0, 0 };
}
public static void pingGyro() {
double newTime = timer.get();
double deltat = (newTime - lastTime);
lastTime = newTime;
double[] angularSpeed = new double[3];
/*
* The angular velocities are stored in registers 0x28-0x2D. And
* are stored in two's complement form with the first byte being
* the right half of the number and the second being the left half.
*/
gyro.write(0x2E, 0x10);
gyro.read(OUT_REG, 1, dataBuffer);
byte gL = dataBuffer[0];
gyro.read(OUT_REG + 1, 1, dataBuffer);
byte gH = dataBuffer[0];
angularSpeed[0] = concatCorrect(gL, gH);
gyro.read(OUT_REG + 2, 1, dataBuffer);
gL = dataBuffer[0];
gyro.read(OUT_REG + 3, 1, dataBuffer);
gH = dataBuffer[0];
angularSpeed[1] = concatCorrect(gL, gH);
gyro.read(OUT_REG + 4, 1, dataBuffer);
gL = dataBuffer[0];
gyro.read(OUT_REG + 5, 1, dataBuffer);
gH = dataBuffer[0];
angularSpeed[2] = concatCorrect(gL, gH);
double cX, cY, cZ;
/*
* Since we only get angular velocities we need to integrate it to
* get it's angular position - Adjusted algorithms so that it is
* hopefully less erratic
*/
cX = angles[0] + .5 * (angularSpeed[0] + lastAngleSpeed[0]) * deltat;
cY = angles[1] + .5 * (angularSpeed[1] + lastAngleSpeed[1]) * deltat;
cZ = angles[2] + .5 * (angularSpeed[2] + lastAngleSpeed[2]) * deltat;
/*
* Since an angle of more or less then 360 degrees makes little
* useful sense we find remainder of the current position divided
* by 360
*/
cX = cX % 360;
if (cX < 0) cX += 360;
cY = cY % 360;
if (cY < 0) cY += 360;
cZ = cZ % 360;
if (cZ < 0) cZ += 360;
angles = new double[] { cX, cY, cZ };
lastAngleSpeed = angularSpeed;
}
/**
* Assigns piece of code that runs the pingGyro method constantly to
* pinger
*/
public static void pingerStart() {
Runnable pinger = () -> {
timer.start();
while (pingFlag) {
pingGyro();
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// I then run the code autonoumously
threadPing = new Thread(pinger);
pingFlag = true;
threadPing.start();
}
public static void pingerStop() {
pingFlag = false;
}
private static double concatCorrect(byte h, byte l) {
int high = Byte.toUnsignedInt(h);
int low = Byte.toUnsignedInt(l);
int test = ((0xFF & high) << 8) + (0xFF & low);
test = (test > 0x7FFF) ? test - 0xFFFF : test;
double testTwo = (coeff * test) / 20;
// Makes sure that any offset is eliminated
if (Math.abs(testTwo) > limit) return testTwo;
else return 0;
}
/**
* Gives the current angular position of the robot Returns a array of
* three doubles
*
* @return angles
*/
public static double[] getAngles() {
return angles;
}
/**
* Gives the last angular speed sensed by the robot
*/
public static double[] getAngSpeed() {
return lastAngleSpeed;
}
} |
package hudson.plugins.dry;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.core.FilesParser;
import hudson.plugins.analysis.core.HealthAwarePublisher;
import hudson.plugins.analysis.core.ParserResult;
import hudson.plugins.analysis.util.PluginLogger;
import hudson.plugins.dry.parser.DuplicationParserRegistry;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* Publishes the results of the duplicate code analysis (freestyle project type).
*
* @author Ulli Hafner
*/
public class DryPublisher extends HealthAwarePublisher {
/** Unique ID of this class. */
private static final long serialVersionUID = 6711252664481150129L;
/** Default DRY pattern. */
private static final String DEFAULT_PATTERN = "**/cpd.xml";
/** Ant file-set pattern of files to work with. */
private final String pattern;
/**
* Creates a new instance of <code>PmdPublisher</code>.
*
* @param pattern
* Ant file-set pattern to scan for DRY files
* @param threshold
* Annotation threshold to be reached if a build should be considered as
* unstable.
* @param newThreshold
* New annotations threshold to be reached if a build should be
* considered as unstable.
* @param failureThreshold
* Annotation threshold to be reached if a build should be considered as
* failure.
* @param newFailureThreshold
* New annotations threshold to be reached if a build should be
* considered as failure.
* @param healthy
* Report health as 100% when the number of warnings is less than
* this value
* @param unHealthy
* Report health as 0% when the number of warnings is greater
* than this value
* @param thresholdLimit
* determines which warning priorities should be considered when
* evaluating the build stability and health
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param useDeltaValues
* determines whether the absolute annotations delta or the
* actual annotations set difference should be used to evaluate
* the build stability
*/
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
@DataBoundConstructor
public DryPublisher(final String pattern, final String threshold, final String newThreshold,
final String failureThreshold, final String newFailureThreshold,
final String healthy, final String unHealthy,
final String thresholdLimit, final String defaultEncoding, final boolean useDeltaValues) {
super(threshold, newThreshold, failureThreshold, newFailureThreshold,
healthy, unHealthy, thresholdLimit, defaultEncoding, useDeltaValues, "DRY");
this.pattern = pattern;
}
// CHECKSTYLE:ON
/**
* Returns the Ant file-set pattern of files to work with.
*
* @return Ant file-set pattern of files to work with
*/
public String getPattern() {
return pattern;
}
/** {@inheritDoc} */
@Override
public Action getProjectAction(final AbstractProject<?, ?> project) {
return new DryProjectAction(project);
}
/** {@inheritDoc} */
@Override
public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
logger.log("Collecting duplicate code analysis files...");
FilesParser dryCollector = new FilesParser(logger, StringUtils.defaultIfEmpty(getPattern(), DEFAULT_PATTERN), new DuplicationParserRegistry(),
isMavenBuild(build), isAntBuild(build));
ParserResult project = build.getWorkspace().act(dryCollector);
DryResult result = new DryResult(build, getDefaultEncoding(), project);
build.getActions().add(new DryResultAction(build, this, result));
return result;
}
/** {@inheritDoc} */
@Override
public DryDescriptor getDescriptor() {
return (DryDescriptor)super.getDescriptor();
}
} |
package hudson.plugins.git;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractDescribableImpl;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Result;
import hudson.plugins.git.extensions.impl.PerBuildTag;
import hudson.plugins.git.opt.PreBuildMergeOptions;
import hudson.scm.SCM;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import hudson.util.FormValidation;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.PushCommand;
import org.kohsuke.stapler.*;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class GitPublisher extends Recorder implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Store a config version so we're able to migrate config on various
* functionality upgrades.
*/
private Long configVersion;
private boolean pushMerge;
private boolean pushOnlyIfSuccess;
private boolean forcePush;
private List<TagToPush> tagsToPush;
// Pushes HEAD to these locations
private List<BranchToPush> branchesToPush;
// notes support
private List<NoteToPush> notesToPush;
@DataBoundConstructor
public GitPublisher(List<TagToPush> tagsToPush,
List<BranchToPush> branchesToPush,
List<NoteToPush> notesToPush,
boolean pushOnlyIfSuccess,
boolean pushMerge,
boolean forcePush) {
this.tagsToPush = tagsToPush;
this.branchesToPush = branchesToPush;
this.notesToPush = notesToPush;
this.pushMerge = pushMerge;
this.pushOnlyIfSuccess = pushOnlyIfSuccess;
this.forcePush = forcePush;
this.configVersion = 2L;
}
public boolean isPushOnlyIfSuccess() {
return pushOnlyIfSuccess;
}
public boolean isPushMerge() {
return pushMerge;
}
public boolean isForcePush() {
return forcePush;
}
public boolean isPushTags() {
if (tagsToPush == null) {
return false;
}
return !tagsToPush.isEmpty();
}
public boolean isPushBranches() {
if (branchesToPush == null) {
return false;
}
return !branchesToPush.isEmpty();
}
public boolean isPushNotes() {
if (notesToPush == null) {
return false;
}
return !notesToPush.isEmpty();
}
public List<TagToPush> getTagsToPush() {
if (tagsToPush == null) {
tagsToPush = new ArrayList<>();
}
return tagsToPush;
}
public List<BranchToPush> getBranchesToPush() {
if (branchesToPush == null) {
branchesToPush = new ArrayList<>();
}
return branchesToPush;
}
public List<NoteToPush> getNotesToPush() {
if (notesToPush == null) {
notesToPush = new ArrayList<>();
}
return notesToPush;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
private String replaceAdditionalEnvironmentalVariables(String input, AbstractBuild<?, ?> build){
if (build == null){
return input;
}
String buildResult = "";
Result result = build.getResult();
if (result != null) {
buildResult = result.toString();
}
String buildDuration = build.getDurationString().replaceAll("and counting", "");
input = input.replaceAll("\\$BUILDRESULT", buildResult);
input = input.replaceAll("\\$BUILDDURATION", buildDuration);
return input;
}
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, final BuildListener listener)
throws InterruptedException, IOException {
// during matrix build, the push back would happen at the very end only once for the whole matrix,
// not for individual configuration build.
if (build.getClass().getName().equals("hudson.matrix.MatrixRun")) {
return true;
}
SCM scm = build.getProject().getScm();
if (!(scm instanceof GitSCM)) {
return false;
}
final GitSCM gitSCM = (GitSCM) scm;
final String projectName = build.getProject().getName();
final int buildNumber = build.getNumber();
final Result buildResult = build.getResult();
// If pushOnlyIfSuccess is selected and the build is not a success, don't push.
if (pushOnlyIfSuccess && buildResult.isWorseThan(Result.SUCCESS)) {
listener.getLogger().println("Build did not succeed and the project is configured to only push after a successful build, so no pushing will occur.");
return true;
}
else {
EnvVars environment = build.getEnvironment(listener);
final GitClient git = gitSCM.createClient(listener, environment, build, build.getWorkspace());
URIish remoteURI;
// If we're pushing the merge back...
if (pushMerge) {
try {
if (gitSCM.getExtensions().get(PerBuildTag.class) != null) {
// if PerBuildTag, then tag every build
// We delete the old tag generated by the SCM plugin
String buildnumber = "jenkins-" + projectName.replace(" ", "_") + "-" + buildNumber;
if (git.tagExists(buildnumber))
git.deleteTag(buildnumber);
// And add the success / fail state into the tag.
buildnumber += "-" + buildResult.toString();
git.tag(buildnumber, "Jenkins Build #" + buildNumber);
}
PreBuildMergeOptions mergeOptions = gitSCM.getMergeOptions();
String mergeTarget = environment.expand(mergeOptions.getMergeTarget());
if (mergeOptions.doMerge() && buildResult.isBetterOrEqualTo(Result.SUCCESS)) {
RemoteConfig remote = mergeOptions.getMergeRemote();
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
listener.getLogger().println("Pushing HEAD to branch " + mergeTarget + " of " + remote.getName() + " repository");
remoteURI = remote.getURIs().get(0);
PushCommand push = git.push().to(remoteURI).ref("HEAD:" + mergeTarget).force(forcePush);
push.execute();
} else {
//listener.getLogger().println("Pushing result " + buildnumber + " to origin repository");
//git.push(null);
}
} catch (FormException | GitException e) {
e.printStackTrace(listener.error("Failed to push merge to origin repository"));
return false;
}
}
if (isPushTags()) {
for (final TagToPush t : tagsToPush) {
if (t.getTagName() == null)
throw new AbortException("No tag to push defined");
if (t.getTargetRepoName() == null)
throw new AbortException("No target repo to push to defined");
final String tagName = environment.expand(t.getTagName());
final String tagMessage = hudson.Util.fixNull(environment.expand(t.getTagMessage()));
final String targetRepo = environment.expand(t.getTargetRepoName());
try {
// Lookup repository with unexpanded name as GitSCM stores them unexpanded
RemoteConfig remote = gitSCM.getRepositoryByName(t.getTargetRepoName());
if (remote == null)
throw new AbortException("No repository found for target repo name " + targetRepo);
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
boolean tagExists = git.tagExists(tagName.replace(' ', '_'));
if (t.isCreateTag() || t.isUpdateTag()) {
if (tagExists && !t.isUpdateTag()) {
throw new AbortException("Tag " + tagName + " already exists and Create Tag is specified, so failing.");
}
if (tagMessage.length()==0) {
git.tag(tagName, "Jenkins Git plugin tagging with " + tagName);
} else {
git.tag(tagName, tagMessage);
}
}
else if (!tagExists) {
throw new AbortException("Tag " + tagName + " does not exist and Create Tag is not specified, so failing.");
}
listener.getLogger().println("Pushing tag " + tagName + " to repo "
+ targetRepo);
remoteURI = remote.getURIs().get(0);
PushCommand push = git.push().to(remoteURI).ref(tagName).force(forcePush);
push.execute();
} catch (GitException e) {
e.printStackTrace(listener.error("Failed to push tag " + tagName + " to " + targetRepo));
return false;
}
}
}
if (isPushBranches()) {
for (final BranchToPush b : branchesToPush) {
if (b.getBranchName() == null)
throw new AbortException("No branch to push defined");
if (b.getTargetRepoName() == null)
throw new AbortException("No branch repo to push to defined");
final String branchName = environment.expand(b.getBranchName());
final String targetRepo = environment.expand(b.getTargetRepoName());
try {
// Lookup repository with unexpanded name as GitSCM stores them unexpanded
RemoteConfig remote = gitSCM.getRepositoryByName(b.getTargetRepoName());
if (remote == null)
throw new AbortException("No repository found for target repo name " + targetRepo);
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
remoteURI = remote.getURIs().get(0);
if (b.getRebaseBeforePush()) {
listener.getLogger().println("Fetch and rebase with " + branchName + " of " + targetRepo);
git.fetch_().from(remoteURI, remote.getFetchRefSpecs()).execute();
if (!git.revParse("HEAD").equals(git.revParse(targetRepo + "/" + branchName))) {
git.rebase().setUpstream(targetRepo + "/" + branchName).execute();
} else {
listener.getLogger().println("No rebase required. HEAD equals " + targetRepo + "/" + branchName);
}
}
listener.getLogger().println("Pushing HEAD to branch " + branchName + " at repo "
+ targetRepo);
PushCommand push = git.push().to(remoteURI).ref("HEAD:" + branchName).force(forcePush);
push.execute();
} catch (GitException e) {
e.printStackTrace(listener.error("Failed to push branch " + branchName + " to " + targetRepo));
return false;
}
}
}
if (isPushNotes()) {
for (final NoteToPush b : notesToPush) {
if (b.getnoteMsg() == null)
throw new AbortException("No note to push defined");
b.setEmptyTargetRepoToOrigin();
String noteMsgTmp = environment.expand(b.getnoteMsg());
final String noteMsg = replaceAdditionalEnvironmentalVariables(noteMsgTmp, build);
final String noteNamespace = environment.expand(b.getnoteNamespace());
final String targetRepo = environment.expand(b.getTargetRepoName());
final boolean noteReplace = b.getnoteReplace();
try {
// Lookup repository with unexpanded name as GitSCM stores them unexpanded
RemoteConfig remote = gitSCM.getRepositoryByName(b.getTargetRepoName());
if (remote == null) {
listener.getLogger().println("No repository found for target repo name " + targetRepo);
return false;
}
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
listener.getLogger().println("Adding note to namespace \""+noteNamespace +"\":\n" + noteMsg + "\n******" );
if ( noteReplace )
git.addNote( noteMsg, noteNamespace );
else
git.appendNote( noteMsg, noteNamespace );
remoteURI = remote.getURIs().get(0);
/**
* Handles migration from earlier version - if we were pushing merges, we'll be
* instantiated but tagsToPush will be null rather than empty.
* @return This.
*/
private Object readResolve() {
// Default unspecified to v0
if(configVersion == null)
this.configVersion = 0L;
if (this.configVersion < 1L) {
if (tagsToPush == null) {
this.pushMerge = true;
}
}
return this;
}
@Extension(ordinal=-1)
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return "Git Publisher";
}
@Override
public String getHelpFile() {
return "/plugin/git/gitPublisher.html";
}
/**
* Performs on-the-fly validation on the file mask wildcard.
*
* I don't think this actually ever gets called, but I'm modernizing it anyway.
* @param project project context for evaluation
* @param value string to be evaluated
* @return form validation result
* @throws IOException on input or output error
*/
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value)
throws IOException {
return FilePath.validateFileMask(project.getSomeWorkspace(),value);
}
public FormValidation doCheckTagName(@QueryParameter String value) {
return checkFieldNotEmpty(value, Messages.GitPublisher_Check_TagName());
}
public FormValidation doCheckBranchName(@QueryParameter String value) {
return checkFieldNotEmpty(value, Messages.GitPublisher_Check_BranchName());
}
public FormValidation doCheckNoteMsg(@QueryParameter String value) {
return checkFieldNotEmpty(value, Messages.GitPublisher_Check_Note());
}
public FormValidation doCheckRemote(
@AncestorInPath AbstractProject project, StaplerRequest req)
throws IOException, ServletException {
String remote = req.getParameter("value");
boolean isMerge = req.getParameter("isMerge") != null;
// Added isMerge because we don't want to allow empty remote names
// for tag/branch pushes.
if (remote.length() == 0 && isMerge)
return FormValidation.ok();
FormValidation validation = checkFieldNotEmpty(remote,
Messages.GitPublisher_Check_RemoteName());
if (validation.kind != FormValidation.Kind.OK)
return validation;
if (!(project.getScm() instanceof GitSCM)) {
return FormValidation.warning("Project not currently configured to use Git; cannot check remote repository");
}
GitSCM scm = (GitSCM) project.getScm();
if (scm.getRepositoryByName(remote) == null)
return FormValidation
.error("No remote repository configured with name '"
+ remote + "'");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
private FormValidation checkFieldNotEmpty(String value, String field) {
value = StringUtils.strip(value);
if (value == null || value.equals("")) {
return FormValidation.error(Messages.GitPublisher_Check_Required(field));
}
return FormValidation.ok();
}
}
public static abstract class PushConfig extends AbstractDescribableImpl<PushConfig> implements Serializable {
private static final long serialVersionUID = 1L;
private String targetRepoName;
public PushConfig(String targetRepoName) {
this.targetRepoName = Util.fixEmptyAndTrim(targetRepoName);
}
public String getTargetRepoName() {
return targetRepoName;
}
public void setTargetRepoName(String targetRepoName) {
this.targetRepoName = targetRepoName;
}
public void setEmptyTargetRepoToOrigin(){
if (targetRepoName == null || targetRepoName.trim().length()==0){
targetRepoName = "origin";
}
}
}
public static final class BranchToPush extends PushConfig {
private String branchName;
private boolean rebaseBeforePush;
public String getBranchName() {
return branchName;
}
@DataBoundConstructor
public BranchToPush(String targetRepoName, String branchName) {
super(targetRepoName);
this.branchName = Util.fixEmptyAndTrim(branchName);
}
@DataBoundSetter
public void setRebaseBeforePush(boolean shouldRebase) {
this.rebaseBeforePush = shouldRebase;
}
public boolean getRebaseBeforePush() {
return rebaseBeforePush;
}
@Extension
public static class DescriptorImpl extends Descriptor<PushConfig> {
@Override
public String getDisplayName() {
return "";
}
}
}
public static final class TagToPush extends PushConfig {
private String tagName;
private String tagMessage;
private boolean createTag;
private boolean updateTag;
public String getTagName() {
return tagName;
}
public String getTagMessage() {
return tagMessage;
}
public boolean isCreateTag() {
return createTag;
}
public boolean isUpdateTag() {
return updateTag;
}
@DataBoundConstructor
public TagToPush(String targetRepoName, String tagName, String tagMessage, boolean createTag, boolean updateTag) {
super(targetRepoName);
this.tagName = Util.fixEmptyAndTrim(tagName);
this.tagMessage = tagMessage;
this.createTag = createTag;
this.updateTag = updateTag;
}
@Extension
public static class DescriptorImpl extends Descriptor<PushConfig> {
@Override
public String getDisplayName() {
return "";
}
}
}
public static final class NoteToPush extends PushConfig {
private String noteMsg;
private String noteNamespace;
private boolean noteReplace;
public String getnoteMsg() {
return noteMsg;
}
public String getnoteNamespace() {
return noteNamespace;
}
public boolean getnoteReplace() {
return noteReplace;
}
@DataBoundConstructor
public NoteToPush( String targetRepoName, String noteMsg, String noteNamespace, boolean noteReplace ) {
super(targetRepoName);
this.noteMsg = Util.fixEmptyAndTrim(noteMsg);
this.noteReplace = noteReplace;
if ( noteNamespace != null && noteNamespace.trim().length()!=0)
this.noteNamespace = Util.fixEmptyAndTrim(noteNamespace);
else
this.noteNamespace = "master";
}
@Extension
public static class DescriptorImpl extends Descriptor<PushConfig> {
@Override
public String getDisplayName() {
return "";
}
}
}
} |
package id.ac.unpar.siamodels;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeSet;
public class Mahasiswa {
protected final String npm;
protected String nama;
protected final List<Nilai> riwayatNilai;
protected String photoPath;
protected List<JadwalKuliah> jadwalKuliahList;
protected SortedMap<LocalDate, Integer> nilaiTOEFL;
public Mahasiswa(String npm) throws NumberFormatException {
super();
if (!npm.matches("[0-9]{10}")) {
throw new NumberFormatException("NPM tidak valid: " + npm);
}
this.npm = npm;
this.riwayatNilai = new ArrayList<>();
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getNpm() {
return npm;
}
public String getPhotoPath() {
return photoPath;
}
public void setPhotoPath(String photoPath) {
this.photoPath = photoPath;
}
public List<JadwalKuliah> getJadwalKuliahList() {
return jadwalKuliahList;
}
public void setJadwalKuliahList(List<JadwalKuliah> jadwalKuliahList) {
this.jadwalKuliahList = jadwalKuliahList;
}
public String getEmailAddress() {
if (npm.matches("[2]{1}[0]{1}\\d{8}") && Integer.parseInt(npm.substring(0, 4)) < 2017) {
return npm.substring(4, 6) + npm.substring(2, 4) + npm.substring(7, 10) + "@student.unpar.ac.id";
} else {
return npm + "@student.unpar.ac.id";
}
}
public List<Nilai> getRiwayatNilai() {
return riwayatNilai;
}
public SortedMap<LocalDate, Integer> getNilaiTOEFL() {
return nilaiTOEFL;
}
public void setNilaiTOEFL(SortedMap<LocalDate, Integer> nilaiTOEFL) {
this.nilaiTOEFL = nilaiTOEFL;
}
/**
* Menghitung IPK mahasiswa sampai saat ini, dengan aturan:
* <ul>
* <li>Kuliah yang tidak lulus tidak dihitung
* <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>.
* </ul>
* Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah
* mengandung nilai per mata kuliah!
*
* @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum
* mengambil satu kuliah pun.
* @deprecated Gunakan {@link #calculateIPLulus()}, nama lebih konsisten
* dengan DPS.
*/
public double calculateIPKLulus() throws ArrayIndexOutOfBoundsException {
return calculateIPTempuh(true);
}
/**
* Menghitung IP mahasiswa sampai saat ini, dengan aturan:
* <ul>
* <li>Kuliah yang tidak lulus tidak dihitung
* <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>.
* </ul>
* Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah
* mengandung nilai per mata kuliah!
*
* @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum
* mengambil satu kuliah pun.
*/
public double calculateIPLulus() throws ArrayIndexOutOfBoundsException {
return calculateIPTempuh(true);
}
/**
* Menghitung IP mahasiswa sampai saat ini, dengan aturan:
* <ul>
* <li>Perhitungan kuliah yang tidak lulus ditentukan parameter
* <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>.
* </ul>
*
* @param lulusSaja set true jika ingin membuang mata kuliah tidak
* lulus, false jika ingin semua (sama dengan "IP N. Terbaik" di DPS)
* Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah
* mengandung nilai per mata kuliah!
* @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum
* mengambil satu kuliah pun.
*/
public double calculateIPTempuh(boolean lulusSaja) throws ArrayIndexOutOfBoundsException {
List<Nilai> localRiwayatNilai = getRiwayatNilai();
if (localRiwayatNilai.isEmpty()) {
return Double.NaN;
}
Map<String, Double> nilaiTerbaik = new HashMap<>();
int totalSKS = 0;
// Cari nilai lulus terbaik setiap kuliah
for (Nilai nilai : localRiwayatNilai) {
if (nilai.getNilaiAkhir().equals("")) {
continue;
}
if (lulusSaja && nilai.getNilaiAkhir().equals("E")) {
continue;
}
String kodeMK = nilai.getMataKuliah().getKode();
Double angkaAkhir = nilai.getAngkaAkhir();
int sks = nilai.getMataKuliah().getSks();
if (!nilaiTerbaik.containsKey(kodeMK)) {
totalSKS += sks;
nilaiTerbaik.put(kodeMK, sks * angkaAkhir);
} else if (sks * angkaAkhir > nilaiTerbaik.get(kodeMK)) {
nilaiTerbaik.put(kodeMK, sks * angkaAkhir);
}
}
// Hitung IPK dari nilai-nilai terbaik
double totalNilai = 0.0;
for (Double nilaiAkhir : nilaiTerbaik.values()) {
totalNilai += nilaiAkhir;
}
return totalNilai / totalSKS;
}
/**
* Menghitung IP Kumulatif mahasiswa sampai saat ini, dengan aturan:
* <ul>
* <li>Jika pengambilan beberapa kali, diambil semua.
* </ul>
* Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah
* mengandung nilai per mata kuliah!
*
* @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum
* mengambil satu kuliah pun.
*/
public double calculateIPKumulatif() throws ArrayIndexOutOfBoundsException {
List<Nilai> localRiwayatNilai = getRiwayatNilai();
if (localRiwayatNilai.isEmpty()) {
return Double.NaN;
}
double totalNilai = 0.0;
int totalSKS = 0;
// Cari nilai setiap kuliah
for (Nilai nilai : localRiwayatNilai) {
if (nilai.getNilaiAkhir().equals("")) {
continue;
}
Double angkaAkhir = nilai.getAngkaAkhir();
int sks = nilai.getMataKuliah().getSks();
totalSKS += sks;
totalNilai += sks * angkaAkhir;
}
return totalNilai / totalSKS;
}
/**
* Menghitung IPK mahasiswa sampai saat ini, dengan aturan:
* <ul>
* <li>Perhitungan kuliah yang tidak lulus ditentukan parameter
* <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>.
* </ul>
*
* @param lulusSaja set true jika ingin membuang mata kuliah tidak lulus
* Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah
* mengandung nilai per mata kuliah!
* @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum
* mengambil satu kuliah pun.
* @deprecated Gunakan {@link #calculateIPKTempuh(boolean)}, nama lebih
* konsisten dengan DPS.
*/
public double calculateIPKTempuh(boolean lulusSaja) throws ArrayIndexOutOfBoundsException {
return calculateIPTempuh(lulusSaja);
}
/**
* Menghitung IPS semester terakhir sampai saat ini, dengan aturan:
* <ul>
* <li>Kuliah yang tidak lulus <em>dihitung</em>.
* </ul>
* Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah
* mengandung nilai per mata kuliah!
*
* @return nilai IPS sampai saat ini
* @throws ArrayIndexOutOfBoundsException jika belum ada nilai satupun
*/
public double calculateIPS() throws ArrayIndexOutOfBoundsException {
List<Nilai> localRiwayatNilai = getRiwayatNilai();
if (localRiwayatNilai.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("Minimal harus ada satu nilai untuk menghitung IPS");
}
int lastIndex = localRiwayatNilai.size() - 1;
TahunSemester tahunSemester = localRiwayatNilai.get(lastIndex).getTahunSemester();
double totalNilai = 0;
double totalSKS = 0;
for (int i = lastIndex; i >= 0; i
Nilai nilai = localRiwayatNilai.get(i);
if (nilai.tahunSemester.equals(tahunSemester)) {
if (nilai.getAngkaAkhir() != null) {
totalNilai += nilai.getMataKuliah().getSks() * nilai.getAngkaAkhir();
totalSKS += nilai.getMataKuliah().getSks();
}
} else {
break;
}
}
return totalNilai / totalSKS;
}
/**
* Menghitung jumlah SKS lulus mahasiswa saat ini. Sebelum memanggil
* method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai
* per mata kuliah!
*
* @return SKS Lulus
*/
public int calculateSKSLulus() throws ArrayIndexOutOfBoundsException {
return calculateSKSTempuh(true);
}
/**
* Menghitung jumlah SKS tempuh mahasiswa saat ini. Sebelum memanggil
* method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai
* per mata kuliah!
*
* @param lulusSaja set true jika ingin membuang SKS tidak lulus
* @return SKS tempuh
*/
public int calculateSKSTempuh(boolean lulusSaja) throws ArrayIndexOutOfBoundsException {
List<Nilai> localRiwayatNilai = getRiwayatNilai();
Set<String> sksTerhitung = new HashSet<>();
int totalSKS = 0;
// Tambahkan SKS setiap kuliah
for (Nilai nilai : localRiwayatNilai) {
if (nilai.getNilaiAkhir().equals("")) {
continue;
}
if (lulusSaja && nilai.getNilaiAkhir().equals("E")) {
continue;
}
String kodeMK = nilai.getMataKuliah().getKode();
if (!sksTerhitung.contains(kodeMK)) {
totalSKS += nilai.getMataKuliah().getSks();
sksTerhitung.add(kodeMK);
}
}
return totalSKS;
}
/**
* Mendapatkan seluruh tahun semester di mana mahasiswa ini tercatat
* sebagai mahasiswa aktif, dengan strategi memeriksa riwayat nilainya.
* Jika ada satu nilai saja pada sebuah tahun semester, maka dianggap
* aktif pada semester tersebut.
*
* @return kumpulan tahun semester di mana mahasiswa ini aktif
*/
public Set<TahunSemester> calculateTahunSemesterAktif() {
Set<TahunSemester> tahunSemesterAktif = new TreeSet<>();
List<Nilai> localRiwayatNilai = getRiwayatNilai();
for (Nilai nilai : localRiwayatNilai) {
tahunSemesterAktif.add(nilai.getTahunSemester());
}
return tahunSemesterAktif;
}
/**
* Memeriksa apakah mahasiswa ini sudah lulus mata kuliah tertentu.
* Kompleksitas O(n). Sebelum memanggil method ini,
* {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata
* kuliah! Note: jika yang dimiliki adalah {@link MataKuliah},
* gunakanlah {@link MataKuliah#getKode()}.
*
* @param kodeMataKuliah kode mata kuliah yang ingin diperiksa
* kelulusannya.
* @return true jika sudah pernah mengambil dan lulus, false jika belum
*/
public boolean hasLulusKuliah(String kodeMataKuliah) {
for (Nilai nilai : riwayatNilai) {
if (nilai.getMataKuliah().getKode().equals(kodeMataKuliah)) {
String na = nilai.getNilaiAkhir();
if (!na.equals("") && na.compareTo("A") >= 0 && na.compareTo("D") <= 0) {
return true;
}
}
}
return false;
}
public Double getNilaiAkhirMataKuliah(String kodeMataKuliah) {
Double aa = 0.0;
for (Nilai nilai : riwayatNilai) {
if (nilai.getMataKuliah().getKode().equals(kodeMataKuliah)) {
aa = nilai.getAngkaAkhir();
return aa;
}
}
return aa;
}
/**
* Memeriksa apakah mahasiswa ini sudah pernah menempuh mata kuliah
* tertentu. Kompleksitas O(n). Sebelum memanggil method ini,
* {@link #getRiwayatNilai()} harus sudah ada isinya! Note: jika yang
* dimiliki adalah {@link MataKuliah}, gunakanlah
* {@link MataKuliah#getKode()}.
*
* @param kodeMataKuliah kode mata kuliah yang ingin diperiksa.
* @return true jika sudah pernah mengambil, false jika belum
*/
public boolean hasTempuhKuliah(String kodeMataKuliah) {
for (Nilai nilai : riwayatNilai) {
if (nilai.getMataKuliah().getKode().equals(kodeMataKuliah)) {
return true;
}
}
return false;
}
/**
* Mendapatkan tahun angkatan mahasiswa ini, berdasarkan NPM nya
*
* @return tahun angkatan
*/
public int getTahunAngkatan() {
return Integer.parseInt(getNpm().substring(0, 4));
}
@Override
public String toString() {
return "Mahasiswa [npm=" + npm + ", nama=" + nama + "]";
}
/**
* Merepresentasikan nilai yang ada di riwayat nilai mahasiswa
*
* @author pascal
*
*/
public static class Nilai {
/**
* Tahun dan Semester kuliah ini diambil
*/
protected final TahunSemester tahunSemester;
/**
* Mata kuliah yang diambil
*/
protected final MataKuliah mataKuliah;
/**
* Kelas kuliah
*/
protected final Character kelas;
/**
* Nilai ART
*/
protected final Map<String, Double> nilaiTugas;
/**
* Nilai UTS
*/
protected final Double nilaiUTS;
/**
* Nilai UAS
*/
protected final Double nilaiUAS;
/**
* Nilai Akhir
*/
protected final String nilaiAkhir;
public Nilai(TahunSemester tahunSemester, MataKuliah mataKuliah, String nilaiAkhir) {
super();
this.tahunSemester = tahunSemester;
this.mataKuliah = mataKuliah;
this.nilaiAkhir = nilaiAkhir;
this.kelas = null;
this.nilaiTugas = null;
this.nilaiUTS = null;
this.nilaiUAS = null;
}
public Nilai(TahunSemester tahunSemester, MataKuliah mataKuliah, Character kelas, Map<String, Double> nilaiTugas, Double nilaiUTS, Double nilaiUAS, String nilaiAkhir) {
super();
this.tahunSemester = tahunSemester;
this.mataKuliah = mataKuliah;
this.nilaiAkhir = nilaiAkhir;
this.kelas = kelas;
this.nilaiTugas = nilaiTugas;
this.nilaiUTS = nilaiUTS;
this.nilaiUAS = nilaiUAS;
}
public MataKuliah getMataKuliah() {
return mataKuliah;
}
/**
* Mengembalikan nilai akhir dalam bentuk huruf (A, B, C, D,
* ..., atau K)
*
* @return nilai akhir dalam huruf, atau null jika tidak ada.
*/
public String getNilaiAkhir() {
return nilaiAkhir;
}
/**
* Mendapatkan nilai akhir dalam bentuk angka
*
* @return nilai akhir dalam angka, atau null jika
* {@link #getNilaiAkhir() mengembalikan 'K' atau null}
*/
public Double getAngkaAkhir() {
if (nilaiAkhir.equals("")) {
return null;
}
switch (nilaiAkhir) {
case "A":
return 4.0;
case "A-":
return 3.67;
case "B+":
return 3.33;
case "B":
return 3.0;
case "B-":
return 2.67;
case "C+":
return 2.33;
case "C":
return 2.0;
case "C-":
return 1.67;
case "D":
return 1.0;
case "E":
return 0.0;
case "K":
return null;
}
return null;
}
public TahunSemester getTahunSemester() {
return tahunSemester;
}
public int getTahunAjaran() {
return tahunSemester.getTahun();
}
public Semester getSemester() {
return tahunSemester.getSemester();
}
@Override
public String toString() {
return "Nilai [tahunSemester=" + tahunSemester + ", mataKuliah=" + mataKuliah + ", nilaiAkhir="
+ nilaiAkhir + "]";
}
/**
* Pembanding antara satu nilai dengan nilai lainnya, secara
* kronologis waktu pengambilan.
*
* @author pascal
*
*/
public static class ChronologicalComparator implements Comparator<Nilai> {
@Override
public int compare(Nilai o1, Nilai o2) {
return o1.getTahunSemester().compareTo(o2.getTahunSemester());
}
}
}
/**
* Status dari mahasiswa
*/
public static enum Status {
SEMUA("00"),
AKTIF("01"),
GENCAT("02"),
CUTI_SEBELUM_FRS("03"),
CUTI_SETELAH_FRS("04"),
KELUAR("05"),
LULUS("06"),
DROP_OUT("07"),
SISIPAN("08");
private final String siakadCode;
Status(String siakadCode) {
this.siakadCode = siakadCode;
}
/**
* Mendapatkan kode pada SIAKAD
*
* @return kode SIAKAD
*/
public String getSIAKADCode() {
return this.siakadCode;
}
/**
* Mendapatkan enum yang sesuai dari kode SIAKAD nya
*
* @param siakadCode kode SIAKAD
* @return enum yang sesuai
*/
public static Status fromSIAKADCode(String siakadCode) {
for (Status status : Status.values()) {
if (status.getSIAKADCode().equals(siakadCode)) {
return status;
}
}
return null;
}
}
} |
package info.faceland.mint;
import com.tealcube.minecraft.bukkit.TextUtils;
import com.tealcube.minecraft.bukkit.bullion.GoldDropEvent;
import com.tealcube.minecraft.bukkit.facecore.ui.ActionBarMessage;
import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils;
import com.tealcube.minecraft.bukkit.hilt.HiltItemStack;
import com.tealcube.minecraft.bukkit.shade.apache.commons.lang3.math.NumberUtils;
import com.tealcube.minecraft.bukkit.shade.google.common.base.CharMatcher;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryPickupItemEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.nunnerycode.mint.MintPlugin;
import java.text.DecimalFormat;
import java.util.*;
public class MintListener implements Listener {
private static final DecimalFormat DF = new DecimalFormat("
private final MintPlugin plugin;
private final Set<UUID> dead;
public MintListener(MintPlugin mintPlugin) {
this.plugin = mintPlugin;
this.dead = new HashSet<>();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onMintEvent(MintEvent mintEvent) {
if (mintEvent.getUuid().equals("")) {
return;
}
UUID uuid;
try {
uuid = UUID.fromString(mintEvent.getUuid());
} catch (IllegalArgumentException e) {
uuid = Bukkit.getPlayer(mintEvent.getUuid()).getUniqueId();
}
Player player = Bukkit.getPlayer(uuid);
if (player == null) {
return;
}
PlayerInventory pi = player.getInventory();
HiltItemStack wallet = null;
ItemStack[] contents = pi.getContents();
for (ItemStack is : contents) {
if (is == null || is.getType() == Material.AIR) {
continue;
}
HiltItemStack his = new HiltItemStack(is);
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) {
wallet = his;
}
}
if (wallet == null) {
wallet = new HiltItemStack(Material.PAPER);
}
pi.removeItem(wallet);
player.updateInventory();
double b = plugin.getEconomy().getBalance(player);
wallet.setName(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")));
wallet.setLore(TextUtils.args(
TextUtils.color(plugin.getSettings().getStringList("config.wallet.lore")),
new String[][]{{"%amount%", DF.format(b)},
{"%currency%", b == 1.00D ? plugin.getEconomy().currencyNameSingular()
: plugin.getEconomy().currencyNamePlural()}}));
if (pi.getItem(17) != null && pi.getItem(17).getType() != Material.AIR) {
ItemStack old = new HiltItemStack(pi.getItem(17));
pi.setItem(17, wallet);
pi.addItem(old);
} else {
pi.setItem(17, wallet);
}
player.updateInventory();
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDeathEvent(final EntityDeathEvent event) {
if (event instanceof PlayerDeathEvent || dead.contains(event.getEntity().getUniqueId())) {
return;
}
dead.add(event.getEntity().getUniqueId());
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
dead.remove(event.getEntity().getUniqueId());
}
}, 20L * 5);
EntityType entityType = event.getEntityType();
double reward = plugin.getSettings().getDouble("rewards." + entityType.name(), 0D);
Location worldSpawn = event.getEntity().getWorld().getSpawnLocation();
Location entityLoc = event.getEntity().getLocation();
double distanceSquared = Math.pow(worldSpawn.getX() - entityLoc.getX(), 2) + Math.pow(worldSpawn.getZ() -
entityLoc.getZ(),
2);
reward += reward * (distanceSquared / Math.pow(10D, 2D))
* plugin.getSettings().getDouble("config.per-ten-blocks-mult", 0.0);
if (reward == 0D) {
return;
}
GoldDropEvent gde = new GoldDropEvent(event.getEntity().getKiller(), event.getEntity(), reward);
Bukkit.getPluginManager().callEvent(gde);
HiltItemStack his = new HiltItemStack(Material.GOLD_NUGGET);
his.setName(ChatColor.GOLD + "REWARD!");
his.setLore(Arrays.asList(DF.format(gde.getAmount())));
event.getDrops().add(his);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemPickupEvent(PlayerPickupItemEvent event) {
if (event.isCancelled()) {
return;
}
if (event.getItem() == null || event.getItem().getItemStack() == null) {
return;
}
Item item = event.getItem();
HiltItemStack hiltItemStack = new HiltItemStack(item.getItemStack());
int stacksize = hiltItemStack.getAmount();
if (hiltItemStack.getType() != Material.GOLD_NUGGET) {
return;
}
if (!hiltItemStack.getName().equals(ChatColor.GOLD + "REWARD!")) {
return;
}
String name = item.getCustomName();
if (name == null) {
return;
}
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.CHICKEN_EGG_POP, 0.8F, 2);
String stripped = ChatColor.stripColor(name);
String replaced = CharMatcher.JAVA_LETTER.removeFrom(stripped).trim();
int wallet = (int)plugin.getEconomy().getBalance(event.getPlayer());
double amount = stacksize * NumberUtils.toDouble(replaced);
plugin.getEconomy().depositPlayer(event.getPlayer(), amount);
event.getItem().remove();
event.setCancelled(true);
if (wallet/250 < (wallet + ((int)amount))/250) {
String message = "<dark green>Wallet: <white>" + plugin.getEconomy().format(plugin.getEconomy().getBalance(
event.getPlayer())).replace(" ", ChatColor.GREEN + " ");
ActionBarMessage.send(event.getPlayer(), message);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerDeathEvent(final PlayerDeathEvent event) {
if (dead.contains(event.getEntity().getUniqueId())) {
return;
}
dead.add(event.getEntity().getUniqueId());
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
dead.remove(event.getEntity().getUniqueId());
}
}, 20L * 5);
Player player = event.getEntity();
World world = player.getWorld();
int maximumKeptBits;
if (event.getEntity().hasPermission("mint.keep")) {
maximumKeptBits = 1000;
} else {
maximumKeptBits = 100;
}
double amount = plugin.getEconomy().getBalance(event.getEntity()) - maximumKeptBits;
if (amount > 0) {
HiltItemStack his = new HiltItemStack(Material.GOLD_NUGGET);
his.setName(ChatColor.GOLD + "REWARD!");
his.setLore(Arrays.asList(DF.format(amount) + ""));
world.dropItemNaturally(player.getLocation(), his);
plugin.getEconomy().setBalance(event.getEntity(), maximumKeptBits);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawnEvent(PlayerRespawnEvent event) {
Player player = event.getPlayer();
plugin.getEconomy().withdrawPlayer(player, 1);
plugin.getEconomy().depositPlayer(player, 1);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawnEvent(ItemSpawnEvent event) {
if (event.getEntity().getItemStack().getType() == Material.GOLD_NUGGET) {
HiltItemStack nuggetStack = new HiltItemStack(event.getEntity().getItemStack());
if (!nuggetStack.getName().equals(ChatColor.GOLD + "REWARD!") || nuggetStack.getLore().isEmpty()) {
return;
}
String s = nuggetStack.getLore().get(0);
String stripped = ChatColor.stripColor(s);
double amount = NumberUtils.toDouble(stripped);
if (amount <= 0.00D) {
event.setCancelled(true);
return;
}
HiltItemStack nugget = new HiltItemStack(Material.GOLD_NUGGET);
nugget.setName(ChatColor.GOLD + "REWARD!");
event.getEntity().setItemStack(nugget);
event.getEntity().setCustomName(ChatColor.YELLOW + plugin.getEconomy().format(amount));
event.getEntity().setCustomNameVisible(true);
}
if (event.getEntity().getItemStack().getType() == Material.PAPER) {
HiltItemStack iS = new HiltItemStack(event.getEntity().getItemStack());
if (iS.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name")))) {
event.getEntity().remove();
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onCraftItem(CraftItemEvent event) {
for (ItemStack is : event.getInventory().getMatrix()) {
if (is == null || is.getType() != Material.PAPER) {
continue;
}
HiltItemStack his = new HiltItemStack(is);
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name")))) {
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onInventoryClickEvent(InventoryClickEvent event) {
ItemStack is = event.getCurrentItem();
if (is == null || is.getType() == Material.AIR) {
return;
}
HiltItemStack his = new HiltItemStack(is);
if (his.getLore().size() < 1) {
return;
}
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) {
event.setCancelled(true);
}
}
@EventHandler
public void onInventoryClose(InventoryCloseEvent event) {
if (!event.getInventory().getName()
.equals(TextUtils.color(plugin.getSettings().getString("language.pawn-shop-name")))) {
return;
}
double value = 0D;
int amountSold = 0;
for (ItemStack itemStack : event.getInventory().getContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
continue;
}
HiltItemStack hiltItemStack = new HiltItemStack(itemStack);
if (hiltItemStack.getName()
.equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) {
continue;
}
List<String> lore = hiltItemStack.getLore();
double amount = plugin.getSettings().getDouble("prices.materials." + hiltItemStack.getType().name(), 0D);
if (!lore.isEmpty()) {
amount += plugin.getSettings().getDouble("prices.options.lore.base-price", 3D);
amount += plugin.getSettings().getDouble("prices.options.lore" + ".per-line", 1D) * lore.size();
}
String strippedName = ChatColor.stripColor(hiltItemStack.getName());
if (strippedName.startsWith("Socket Gem")) {
value += plugin.getSettings().getDouble("prices.special.gems") * hiltItemStack.getAmount();
} else if (plugin.getSettings().isSet("prices.names." + strippedName)) {
value += plugin.getSettings().getDouble("prices.names." + strippedName, 0D) * hiltItemStack.getAmount();
} else {
value += amount * hiltItemStack.getAmount();
}
}
for (HumanEntity entity : event.getViewers()) {
if (!(entity instanceof Player)) {
continue;
}
if (value > 0) {
plugin.getEconomy().depositPlayer((Player) entity, value);
MessageUtils.sendMessage(entity, plugin.getSettings().getString("language.pawn-success"),
new String[][]{{"%amount%", "" + amountSold},
{"%currency%", plugin.getEconomy().format(value)}});
}
}
}
@EventHandler
public void onInventoryPickupItem(InventoryPickupItemEvent event) {
HiltItemStack his = new HiltItemStack(event.getItem().getItemStack());
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", ""))) ||
his.getName().equals(
ChatColor.GOLD + "REWARD!")) {
event.setCancelled(true);
}
}
} |
package io.github.data4all.util;
import io.github.data4all.Exceptions;
import io.github.data4all.logger.Log;
import io.github.data4all.model.DeviceOrientation;
import io.github.data4all.model.data.TransformationParamBean;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Point;
/**
* A gallery holds images for being tagged later.
*
* @author tbrose
*/
public class Gallery {
/**
* The name of the gallery folder.
*/
private static final String DIRECTORY_NAME = "gallery";
/**
* The ending of the image file itself.
*/
private static final String ENDING_JPEG = ".jpeg";
/**
* The ending if the information file of an image.
*/
private static final String ENDING_INFO = ".info";
private static final String LOG_TAG = Gallery.class.getSimpleName();
/**
* The working directory of this gallery.
*/
private final File workingDirectory;
/**
* This class holds the informations in the information file for return
* purpose.
*
* @author tbrose
*/
public static class Informations {
private final TransformationParamBean parameters;
private final DeviceOrientation orientation;
private final Point dimension;
private Informations(TransformationParamBean parameters,
DeviceOrientation orientation, Point dimension) {
this.parameters = parameters;
this.orientation = orientation;
this.dimension = dimension;
}
/**
* @return The camera and device parameters.
*/
public TransformationParamBean getParameters() {
return parameters;
}
/**
* @return The device orientation.
*/
public DeviceOrientation getOrientation() {
return orientation;
}
/**
* @return The display dimension.
*/
public Point getDimension() {
return dimension;
}
}
/**
* Constructs a gallery to read from and write to.
*
* @param context
* The context of this gallery
*/
public Gallery(Context context) {
workingDirectory = new File(context.getFilesDir(), DIRECTORY_NAME);
}
/**
* Saves the given image to this gallery with the parameters, the
* orientation and the dimension linked to this image.
*
* @param imageData
* The raw image data, cannot be {@code null}
* @param parameters
* The camera-parameters, cannot be {@code null}
* @param orientation
* The orientation of the device, cannot be {@code null}
* @param dimension
* The screen dimension, cannot be {@code null}
* @throws IOException
* If the data cannot be stored
*/
public void addImage(final byte[] imageData,
TransformationParamBean parameters, DeviceOrientation orientation,
Point dimension) throws IOException {
Log.d(LOG_TAG, "adding image");
if (imageData == null) {
throw Exceptions.nullArgument("imageData");
} else if (parameters == null) {
throw Exceptions.nullArgument("parameters");
} else if (orientation == null) {
throw Exceptions.nullArgument("oriantation");
} else if (dimension == null) {
throw Exceptions.nullArgument("dimension");
} else {
final long time = System.currentTimeMillis();
final JSONObject json;
try {
json = encodeInformations(parameters, orientation, dimension);
} catch (JSONException e) {
throw new IOException(e);
}
try {
saveData(time, ENDING_JPEG, imageData);
} catch (IOException e) {
deleteData(time, ENDING_JPEG);
throw e;
}
try {
saveData(time, ENDING_INFO, json.toString().getBytes("UTF-8"));
} catch (IOException e) {
deleteData(time, ENDING_JPEG, ENDING_INFO);
throw e;
}
Log.d(LOG_TAG, "image added");
// ONLY for debug purpose: Log.v(LOG_TAG, "images: " + Arrays.toString(getImages()));
}
}
/**
* Receives the file of the image at the given timestamp.
*
* @param timestamp
* The timestamp of the image
* @return The file object of the image
* @throws FileNotFoundException
* If the image is not stored in this gallery
*/
public File getImageFile(long timestamp) throws FileNotFoundException {
final File result = buildPath(timestamp, ENDING_JPEG);
if (result.exists()) {
return result;
} else {
throw new FileNotFoundException("No image found for timestamp "
+ timestamp);
}
}
/**
* Receives the informations of the image at the given timestamp.
*
* @param timestamp
* The timestamp of the image
* @return The information object of the image
* @throws IOException
* If an I/O error occurs
* @throws FileNotFoundException
* If the image is not stored in this gallery
*/
public Informations getImageInformations(long timestamp) throws IOException {
final File result = buildPath(timestamp, ENDING_INFO);
if (result.exists()) {
FileInputStream stream = new FileInputStream(result);
byte[] content = IOUtils.toByteArray(stream);
IOUtils.closeQuietly(stream);
try {
final JSONObject jsonObject =
new JSONObject(new String(content, "UTF-8"));
return decodeInformations(jsonObject);
} catch (JSONException e) {
throw new IOException("Content cannot be parsed");
}
} else {
throw new FileNotFoundException("No image found for timestamp "
+ timestamp);
}
}
/**
* Lists the timestamp of all images in this gallery.
*
* @return An array with timestamps
*/
public long[] getImages() {
final File[] files = getImageFiles();
final long[] result = new long[files.length];
for (int i = 0; i < files.length; i++) {
final File f = files[i];
result[i] = Long.parseLong(f.getName().replace(ENDING_JPEG, ""));
}
return result;
}
/**
* Lists the file-objects of all images in this gallery.
*
* @return An array with files, never {@code null}
*/
public File[] getImageFiles() {
final List<File> images = new ArrayList<File>();
for (final File f : workingDirectory.listFiles()) {
if (f.getName().endsWith(ENDING_JPEG)) {
images.add(f);
}
}
return images.toArray(new File[images.size()]);
}
/**
* Let this gallery forget about the given image. If the picture does not
* exists, nothing will be deleted.<br/>
* This operation cannot be undone!
*
* @param timestamp
* The timestamp of the image
*/
public void deleteImage(long timestamp) {
deleteData(timestamp, ENDING_JPEG, ENDING_INFO);
}
/**
* Add a file to the gallery folder.
*
* @param timestamp
* The timestamp of the image
* @param ending
* The file ending
* @param content
* The content of the file
* @throws IOException
* If an I/O error occurs
*/
private void saveData(long timestamp, String ending, byte[] content)
throws IOException {
Log.d(LOG_TAG, "saving data " + timestamp + ending);
if (checkOrCreateWorkingDirectory()) {
FileOutputStream stream = null;
try {
final File file = buildPath(timestamp, ending);
stream = new FileOutputStream(file);
stream.write(content);
} finally {
IOUtils.closeQuietly(stream);
}
} else {
throw new IOException("Gallery folder cannot be created.");
}
}
/**
* Removes a file from the gallery folder.
*
* @param timestamp
* The timestamp of the image
* @param endings
* The file ending
*/
private void deleteData(long timestamp, String... endings) {
for (String ending : endings) {
final File file = buildPath(timestamp, ending);
if (file.exists()) {
file.delete();
}
}
}
/**
* Builds the file object for the given time and ending.
*
* @param timestamp
* The timestamp of the image
* @param ending
* The file-ending
* @return The full qualified file object for the gallery folder
*/
private File buildPath(long timestamp, String ending) {
return new File(workingDirectory, timestamp + ending);
}
/**
* Encodes the given informations of an image into a JSON.
*
* @param parameters
* The parameters of the image
* @param orientation
* The orientation of the device
* @param dimension
* The screen dimension of the device
* @return A JSONObject holding the infornations
* @throws JSONException
* If an JSON error occurs
*/
private JSONObject encodeInformations(TransformationParamBean parameters,
DeviceOrientation orientation, Point dimension)
throws JSONException {
final JSONObject json = new JSONObject();
return json
.put("parameters", parameters.toJSON())
.put("orentation", orientation.toJSON())
.put("dimension",
new JSONArray(Arrays.asList(dimension.x, dimension.y)));
}
/**
* Decodes the informations of an image from the given JSON.
*
* @param json
* @return
* @throws JSONException
*/
private Informations decodeInformations(JSONObject json)
throws JSONException {
TransformationParamBean parameters =
TransformationParamBean.fromJSON(json
.getJSONArray("parameters"));
DeviceOrientation oriantation =
DeviceOrientation.fromJSON((JSONArray) json
.getJSONArray("orientation"));
JSONArray dimension = json.getJSONArray("dimension");
return new Informations(parameters, oriantation, new Point(
dimension.getInt(0), dimension.getInt(1)));
}
/**
* Creates the working directory if it currently does not exists.
*
* @return If the working directory exists after the call of this method
*/
private final boolean checkOrCreateWorkingDirectory() {
return workingDirectory.exists() || workingDirectory.mkdirs();
}
} |
package jkit.gfx;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
/**
* A shape drawer that makes shapes easily visible.
*
* @author Joschi <josua.krause@gmail.com>
*/
public class EasyVisibleShapeDrawer extends AbstractShapeDrawer {
/** The stroke for the inner lines. */
private final Stroke inner;
/** The stroke for the outer lines. */
private final Stroke outer;
/** The foreground color. */
private final Color fg;
/** The background color. */
private final Color bg;
/** Creates a black and white shape drawer. */
public EasyVisibleShapeDrawer() {
this(Color.WHITE, Color.BLACK, 1, 1, new BasicStroke());
}
/**
* Creates a shape drawer.
*
* @param inner The inner color.
* @param outer The outer color.
* @param radius The radius of the inner line.
* @param outerRadius The radius of the outer line.
* @param base The base stroke.
*/
public EasyVisibleShapeDrawer(final Color inner, final Color outer,
final double radius, final double outerRadius, final BasicStroke base) {
this.inner = new BasicStroke((float) radius, base.getEndCap(), base.getLineJoin(),
base.getMiterLimit(), base.getDashArray(), base.getDashPhase());
this.outer = new BasicStroke((float) (radius + outerRadius + 1), base.getEndCap(),
base.getLineJoin(), base.getMiterLimit(), base.getDashArray(),
base.getDashPhase());
fg = inner;
bg = outer;
}
@Override
public void setColor(final Color color) {
// FIXME
}
@Override
public Drawable getDrawable(final Shape s) {
final Color fg = this.fg;
final Color bg = this.bg;
final Shape outerShape = outer.createStrokedShape(s);
final Shape innerShape = inner.createStrokedShape(s);
final Rectangle2D box = outerShape.getBounds2D();
return new Drawable() {
@Override
public void draw(final Graphics2D gfx) {
final Graphics2D g = (Graphics2D) gfx.create();
g.setColor(bg);
g.fill(outerShape);
g.setColor(fg);
g.fill(innerShape);
g.dispose();
}
@Override
protected Rectangle2D computeBounds() {
return box;
}
};
}
} |
package com.exedio.cope.console;
import java.io.File;
import java.util.Date;
import com.exedio.cope.ConnectProperties;
import com.exedio.cope.Model;
import com.exedio.cope.SetValue;
import com.exedio.cope.util.ConnectToken;
final class LogThread extends Thread
{
private static final Model loggerModel = new Model(LogModel.TYPE);
private final Model loggedModel;
private final String logPropertyFile;
private final Object lock = new Object();
private final String topic;
private volatile boolean proceed = true;
LogThread(final Model model, final String logPropertyFile)
{
this.loggedModel = model;
this.logPropertyFile = logPropertyFile;
this.topic = "LogThread(" + Integer.toString(System.identityHashCode(this), 36) + ") ";
assert model!=null;
assert logPropertyFile!=null;
}
@Override
public void run()
{
System.out.println(topic + "run() started");
try
{
sleepByWait(2000l);
if(!proceed)
return;
System.out.println(topic + "run() connecting");
ConnectToken loggerConnectToken = null;
final long connecting = System.currentTimeMillis();
try
{
loggerConnectToken =
ConnectToken.issue(loggerModel, new ConnectProperties(new File(logPropertyFile)), "logger");
System.out.println(topic + "run() connected (" + (System.currentTimeMillis() - connecting) + "ms)");
//loggerModel.tearDownDatabase(); loggerModel.createDatabase();
try
{
loggerModel.startTransaction("check");
loggerModel.checkDatabase();
loggerModel.commit();
}
finally
{
loggerModel.rollbackIfNotCommitted();
}
for(int running = 0; proceed; running++)
{
System.out.println(topic + "run() LOG " + running);
log(running);
sleepByWait(1000l);
}
}
finally
{
if(loggerConnectToken!=null)
{
System.out.println(topic + "run() disconnecting");
final long disconnecting = System.currentTimeMillis();
loggerConnectToken.returnIt();
System.out.println(topic + "run() disconnected (" + (System.currentTimeMillis() - disconnecting) + "ms)");
}
else
System.out.println(topic + "run() not connected");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void log(final int running)
{
// gather data
final Date date = new Date();
final long nextTransactionId = loggedModel.getNextTransactionId();
// process data
final SetValue[] setValues = new SetValue[]{
LogModel.date.map(date),
LogModel.running.map(running),
LogModel.nextTransactionId.map(nextTransactionId)};
// save data
try
{
loggerModel.startTransaction("log " + running);
new LogModel(setValues);
loggerModel.commit();
}
finally
{
loggerModel.rollbackIfNotCommitted();
}
}
private void sleepByWait(final long millis)
{
synchronized(lock)
{
System.out.println(topic + "run() sleeping (" + millis + "ms)");
final long sleeping = System.currentTimeMillis();
try
{
lock.wait(millis);
}
catch(InterruptedException e)
{
throw new RuntimeException(e);
}
System.out.println(topic + "run() slept (" + (System.currentTimeMillis()-sleeping) + "ms)");
}
}
void stopAndJoin()
{
System.out.println(topic + "stopAndJoin() entering");
proceed = false;
synchronized(lock)
{
System.out.println(topic + "stopAndJoin() notifying");
lock.notify();
}
System.out.println(topic + "stopAndJoin() notified");
final long joining = System.currentTimeMillis();
try
{
join();
}
catch(InterruptedException e)
{
throw new RuntimeException(e);
}
System.out.println(topic + "stopAndJoin() joined (" + (System.currentTimeMillis() - joining) + "ms)");
}
} |
package mondrian.rolap;
import mondrian.olap.*;
import mondrian.olap.CacheControl.CellRegion;
import mondrian.test.*;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Unit-test for cache-flushing functionality.
*
* @author jhyde
* @since Sep 27, 2006
*/
public class CacheControlTest extends FoodMartTestCase {
/**
* Creates a CacheControlTest.
*/
public CacheControlTest() {
}
/**
* Creates a CacheControlTest with the given name.
*/
public CacheControlTest(String name) {
super(name);
}
/**
* Returns the repository of result strings.
* @return repository of result strings
*/
DiffRepository getDiffRepos() {
return DiffRepository.lookup(CacheControlTest.class);
}
/**
* Flushes the entire contents of the cache. Utility method used to ensure
* that cache control tests are starting with a blank page.
*
* @param testContext Test context
*/
public static void flushCache(TestContext testContext) {
final CacheControl cacheControl =
testContext.getConnection().getCacheControl(null);
// Flush the entire cache.
CacheControl.CellRegion measuresRegion = null;
for (Cube cube
: testContext.getConnection().getSchema().getCubes())
{
measuresRegion =
cacheControl.createMeasuresRegion(cube);
cacheControl.flush(measuresRegion);
}
// Check the cache is empty.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cacheControl.printCacheState(pw, measuresRegion);
pw.flush();
assertEquals("", sw.toString());
}
/**
* Asserts that a cache state string is equal to an expected cache state,
* after segment ids have been masked out.
*
* @param tag Tag of resource in diff repository
* @param expected Expected state
* @param actual Actual state
*/
private void assertCacheStateEquals(
String tag, String expected, String actual)
{
String expected2 = expected.replaceAll("Segment #[0-9]+", "Segment ##");
String actual2 = actual.replaceAll("Segment #[0-9]+", "Segment ##");
getDiffRepos().assertEquals(tag, expected2, actual2);
}
/**
* Runs a simple query an asserts that the results are as expected.
*
* @param testContext Test context
*/
private void standardQuery(TestContext testContext) {
testContext.assertQueryReturns(
"select {[Time].[Time].Members} on columns,\n"
+ " {[Product].Children} on rows\n"
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Time].[1997]}\n"
+ "{[Time].[1997].[Q1]}\n"
+ "{[Time].[1997].[Q1].[1]}\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "{[Time].[1997].[Q1].[3]}\n"
+ "{[Time].[1997].[Q2]}\n"
+ "{[Time].[1997].[Q2].[4]}\n"
+ "{[Time].[1997].[Q2].[5]}\n"
+ "{[Time].[1997].[Q2].[6]}\n"
+ "{[Time].[1997].[Q3]}\n"
+ "{[Time].[1997].[Q3].[7]}\n"
+ "{[Time].[1997].[Q3].[8]}\n"
+ "{[Time].[1997].[Q3].[9]}\n"
+ "{[Time].[1997].[Q4]}\n"
+ "{[Time].[1997].[Q4].[10]}\n"
+ "{[Time].[1997].[Q4].[11]}\n"
+ "{[Time].[1997].[Q4].[12]}\n"
+ "{[Time].[1998]}\n"
+ "{[Time].[1998].[Q1]}\n"
+ "{[Time].[1998].[Q1].[1]}\n"
+ "{[Time].[1998].[Q1].[2]}\n"
+ "{[Time].[1998].[Q1].[3]}\n"
+ "{[Time].[1998].[Q2]}\n"
+ "{[Time].[1998].[Q2].[4]}\n"
+ "{[Time].[1998].[Q2].[5]}\n"
+ "{[Time].[1998].[Q2].[6]}\n"
+ "{[Time].[1998].[Q3]}\n"
+ "{[Time].[1998].[Q3].[7]}\n"
+ "{[Time].[1998].[Q3].[8]}\n"
+ "{[Time].[1998].[Q3].[9]}\n"
+ "{[Time].[1998].[Q4]}\n"
+ "{[Time].[1998].[Q4].[10]}\n"
+ "{[Time].[1998].[Q4].[11]}\n"
+ "{[Time].[1998].[Q4].[12]}\n"
+ "Axis
+ "{[Product].[Drink]}\n"
+ "{[Product].[Food]}\n"
+ "{[Product].[Non-Consumable]}\n"
+ "Row #0: 24,597\n"
+ "Row #0: 5,976\n"
+ "Row #0: 1,910\n"
+ "Row #0: 1,951\n"
+ "Row #0: 2,115\n"
+ "Row #0: 5,895\n"
+ "Row #0: 1,948\n"
+ "Row #0: 2,039\n"
+ "Row #0: 1,908\n"
+ "Row #0: 6,065\n"
+ "Row #0: 2,205\n"
+ "Row #0: 1,921\n"
+ "Row #0: 1,939\n"
+ "Row #0: 6,661\n"
+ "Row #0: 1,898\n"
+ "Row #0: 2,344\n"
+ "Row #0: 2,419\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #1: 191,940\n"
+ "Row #1: 47,809\n"
+ "Row #1: 15,604\n"
+ "Row #1: 15,142\n"
+ "Row #1: 17,063\n"
+ "Row #1: 44,825\n"
+ "Row #1: 14,393\n"
+ "Row #1: 15,055\n"
+ "Row #1: 15,377\n"
+ "Row #1: 47,440\n"
+ "Row #1: 17,036\n"
+ "Row #1: 15,741\n"
+ "Row #1: 14,663\n"
+ "Row #1: 51,866\n"
+ "Row #1: 14,232\n"
+ "Row #1: 18,278\n"
+ "Row #1: 19,356\n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #2: 50,236\n"
+ "Row #2: 12,506\n"
+ "Row #2: 4,114\n"
+ "Row #2: 3,864\n"
+ "Row #2: 4,528\n"
+ "Row #2: 11,890\n"
+ "Row #2: 3,838\n"
+ "Row #2: 3,987\n"
+ "Row #2: 4,065\n"
+ "Row #2: 12,343\n"
+ "Row #2: 4,522\n"
+ "Row #2: 4,035\n"
+ "Row #2: 3,786\n"
+ "Row #2: 13,497\n"
+ "Row #2: 3,828\n"
+ "Row #2: 4,648\n"
+ "Row #2: 5,021\n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n"
+ "Row #2: \n");
}
// Tests
/**
* Tests creation of a cell region against an abstract implementation of
* {@link CacheControl}.
*/
public void testCreateCellRegion() {
// Execute a query.
final TestContext testContext = getTestContext();
final RolapConnection connection =
((RolapConnection) testContext.getConnection());
final CacheControl cacheControl = new CacheControlImpl(connection);
final CacheControl.CellRegion region =
createCellRegion(testContext, cacheControl);
assertNotNull(region);
}
/**
* Creates a cell region, runs a query, then flushes the cache.
*/
public void testNormalize2() {
// Execute a query.
final TestContext testContext = getTestContext();
final CacheControl cacheControl =
testContext.getConnection().getCacheControl(null);
final CacheControl.CellRegion region =
createCellRegion(testContext, cacheControl);
CacheControlImpl.CellRegion normalizedRegion =
((CacheControlImpl) cacheControl).normalize(
(CacheControlImpl.CellRegionImpl) region);
assertEquals(
"Union("
+ "Crossjoin("
+ "Member([Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer]), "
+ "Member([Time].[1997].[Q1]), "
+ "Member([Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales], [Measures].[Sales Count], [Measures].[Customer Count], [Measures].[Promotion Sales])), "
+ "Crossjoin("
+ "Member([Product].[Drink].[Dairy]), "
+ "Member([Time].[1997].[Q1]), "
+ "Member([Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales], [Measures].[Sales Count], [Measures].[Customer Count], [Measures].[Promotion Sales])))",
normalizedRegion.toString());
}
/**
* Creates a cell region, runs a query, then flushes the cache.
*/
public void testFlush() {
assertQueryReturns(
"SELECT {[Product].[Product Department].MEMBERS} ON AXIS(0),\n"
+ "{{[Gender].[Gender].MEMBERS}, {[Gender].[All Gender]}} ON AXIS(1)\n"
+ "FROM [Sales 2] WHERE {[Measures].[Unit Sales]}",
"Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Product].[Drink].[Alcoholic Beverages]}\n"
+ "{[Product].[Drink].[Beverages]}\n"
+ "{[Product].[Drink].[Dairy]}\n"
+ "{[Product].[Food].[Baked Goods]}\n"
+ "{[Product].[Food].[Baking Goods]}\n"
+ "{[Product].[Food].[Breakfast Foods]}\n"
+ "{[Product].[Food].[Canned Foods]}\n"
+ "{[Product].[Food].[Canned Products]}\n"
+ "{[Product].[Food].[Dairy]}\n"
+ "{[Product].[Food].[Deli]}\n"
+ "{[Product].[Food].[Eggs]}\n"
+ "{[Product].[Food].[Frozen Foods]}\n"
+ "{[Product].[Food].[Meat]}\n"
+ "{[Product].[Food].[Produce]}\n"
+ "{[Product].[Food].[Seafood]}\n"
+ "{[Product].[Food].[Snack Foods]}\n"
+ "{[Product].[Food].[Snacks]}\n"
+ "{[Product].[Food].[Starchy Foods]}\n"
+ "{[Product].[Non-Consumable].[Carousel]}\n"
+ "{[Product].[Non-Consumable].[Checkout]}\n"
+ "{[Product].[Non-Consumable].[Health and Hygiene]}\n"
+ "{[Product].[Non-Consumable].[Household]}\n"
+ "{[Product].[Non-Consumable].[Periodicals]}\n"
+ "Axis
+ "{[Gender].[F]}\n"
+ "{[Gender].[M]}\n"
+ "{[Gender].[All Gender]}\n"
+ "Row #0: 3,439\n"
+ "Row #0: 6,776\n"
+ "Row #0: 1,987\n"
+ "Row #0: 3,771\n"
+ "Row #0: 9,841\n"
+ "Row #0: 1,821\n"
+ "Row #0: 9,407\n"
+ "Row #0: 867\n"
+ "Row #0: 6,513\n"
+ "Row #0: 5,990\n"
+ "Row #0: 2,001\n"
+ "Row #0: 13,011\n"
+ "Row #0: 841\n"
+ "Row #0: 18,713\n"
+ "Row #0: 947\n"
+ "Row #0: 14,936\n"
+ "Row #0: 3,459\n"
+ "Row #0: 2,696\n"
+ "Row #0: 368\n"
+ "Row #0: 887\n"
+ "Row #0: 7,841\n"
+ "Row #0: 13,278\n"
+ "Row #0: 2,168\n"
+ "Row #1: 3,399\n"
+ "Row #1: 6,797\n"
+ "Row #1: 2,199\n"
+ "Row #1: 4,099\n"
+ "Row #1: 10,404\n"
+ "Row #1: 1,496\n"
+ "Row #1: 9,619\n"
+ "Row #1: 945\n"
+ "Row #1: 6,372\n"
+ "Row #1: 6,047\n"
+ "Row #1: 2,131\n"
+ "Row #1: 13,644\n"
+ "Row #1: 873\n"
+ "Row #1: 19,079\n"
+ "Row #1: 817\n"
+ "Row #1: 15,609\n"
+ "Row #1: 3,425\n"
+ "Row #1: 2,566\n"
+ "Row #1: 473\n"
+ "Row #1: 892\n"
+ "Row #1: 8,443\n"
+ "Row #1: 13,760\n"
+ "Row #1: 2,126\n"
+ "Row #2: 6,838\n"
+ "Row #2: 13,573\n"
+ "Row #2: 4,186\n"
+ "Row #2: 7,870\n"
+ "Row #2: 20,245\n"
+ "Row #2: 3,317\n"
+ "Row #2: 19,026\n"
+ "Row #2: 1,812\n"
+ "Row #2: 12,885\n"
+ "Row #2: 12,037\n"
+ "Row #2: 4,132\n"
+ "Row #2: 26,655\n"
+ "Row #2: 1,714\n"
+ "Row #2: 37,792\n"
+ "Row #2: 1,764\n"
+ "Row #2: 30,545\n"
+ "Row #2: 6,884\n"
+ "Row #2: 5,262\n"
+ "Row #2: 841\n"
+ "Row #2: 1,779\n"
+ "Row #2: 16,284\n"
+ "Row #2: 27,038\n"
+ "Row #2: 4,294\n");
if (MondrianProperties.instance().DisableCaching.get()) {
return;
}
final TestContext testContext = getTestContext();
flushCache(testContext);
// Make sure MaxConstraint is high enough
int minConstraints = 3;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints,
minConstraints);
}
// Execute a query, to bring data into the cache.
standardQuery(testContext);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
final CacheControl cacheControl =
testContext.getConnection().getCacheControl(pw);
// Flush the cache. This time, flush is successful.
final CacheControl.CellRegion region =
createCellRegion(testContext, cacheControl);
cacheControl.flush(region);
pw.flush();
String tag = "output";
String expected = "${output}";
String actual = sw.toString();
assertCacheStateEquals(tag, expected, actual);
// Run query again, then inspect the contents of the cache.
standardQuery(testContext);
sw.getBuffer().setLength(0);
cacheControl.printCacheState(pw, region);
pw.flush();
assertCacheStateEquals("output2", "${output2}", sw.toString());
}
/**
* Creates a partial cell region, runs a query, then flushes the cache.
*/
public void testPartialFlush() {
if (MondrianProperties.instance().DisableCaching.get()) {
return;
}
final TestContext testContext = getTestContext();
flushCache(testContext);
// Execute a query.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
final CacheControl cacheControl =
testContext.getConnection().getCacheControl(pw);
// Create a region ([Measures].[Unit Sales], [Time].[1997].[Q1])
final CacheControl.CellRegion region =
createCellRegion1997_Q1_UnitSales(testContext, cacheControl);
// Execute a query, to bring data into the cache.
standardQuery(testContext);
// This time, flush is successful.
// The segment on "year" is entirely flushed.
// The segment on "year", "quarter" has "Q1" masked out.
// The segment on "year", "quarter", "month" has "Q1" masked out.
cacheControl.flush(region);
pw.flush();
assertCacheStateEquals("output", "${output}", sw.toString());
// Flush the same region again. Should be the same result.
sw.getBuffer().setLength(0);
cacheControl.flush(region);
pw.flush();
assertCacheStateEquals("output2", "${output2}", sw.toString());
// Create the region ([Time].[1997])
final CacheControl.CellRegion region2 =
createCellRegion1997(testContext, cacheControl);
// Flush a different region. Everything is in 1997, so the entire cache
// is emptied.
sw.getBuffer().setLength(0);
cacheControl.flush(region2);
pw.flush();
assertCacheStateEquals("output3", "${output3}", sw.toString());
// Create the region ([Gender].[F], [Product].[Drink] :
// [Product].[Food])
final CacheControl.CellRegion region3 =
createCellRegionFemaleFoodDrink(testContext, cacheControl);
// Flush a different region.
sw.getBuffer().setLength(0);
cacheControl.flush(region3);
pw.flush();
assertCacheStateEquals("output4", "${output4}", sw.toString());
// Run query again, just to make sure.
standardQuery(testContext);
}
/**
* Creates a partial cell region over a range, runs a query, then flushes
* the cache.
*/
public void testPartialFlushRange() {
if (MondrianProperties.instance().DisableCaching.get()) {
return;
}
final TestContext testContext = getTestContext();
flushCache(testContext);
// Execute a query.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
final CacheControl cacheControl =
testContext.getConnection().getCacheControl(pw);
// Create a region
// ([Measures].[Unit Sales],
// [Time].[1997].[Q2].[4] .. infinity)
final CacheControl.CellRegion region =
createCellRegionAprilOnwards(testContext, cacheControl);
// Execute a query, to bring data into the cache.
standardQuery(testContext);
// This time, flush is successful.
// The segment on "year" is entirely flushed.
// The segment on "year", "quarter" has "Q2", "Q3", "Q4" masked out.
// The segment on "year", "quarter", "month" has "Q3", "Q4" masked out,
// and "Q2" masked out if month > 6.
cacheControl.flush(region);
pw.flush();
assertCacheStateEquals("output", "${output}", sw.toString());
// Flush the same region again. Should be the same result.
sw.getBuffer().setLength(0);
cacheControl.flush(region);
pw.flush();
assertCacheStateEquals("output2", "${output2}", sw.toString());
// Run query again, then inspect the contents of the cache.
standardQuery(testContext);
sw.getBuffer().setLength(0);
cacheControl.printCacheState(pw, region);
pw.flush();
assertCacheStateEquals("output3", "${output3}", sw.toString());
}
/**
* Creates a cell region using a given {@link CacheControl}, and runs some
* sanity checks.
*
* @param testContext Test context
* @param cacheControl Cache control
*/
private CacheControl.CellRegion createCellRegion(
TestContext testContext,
CacheControl cacheControl)
{
// Flush a region of the cache.
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
// Region consists of [Time].[1997].[Q1] and its children, and products
// [Beer] and [Dairy].
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member memberQ1 = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Time", "1997", "Q1"), true);
final Member memberBeer = schemaReader.getMemberByUniqueName(
Id.Segment.toList(
"Product", "Drink", "Alcoholic Beverages", "Beer and Wine",
"Beer"),
true);
final Member memberDairy = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Product", "Drink", "Dairy"), true);
final CacheControl.CellRegion regionTimeQ1 =
cacheControl.createMemberRegion(memberQ1, true);
assertEquals("Member([Time].[1997].[Q1])", regionTimeQ1.toString());
final CacheControl.CellRegion regionProductBeer =
cacheControl.createMemberRegion(memberBeer, false);
assertEquals(
"Member([Product].[Drink]."
+ "[Alcoholic Beverages].[Beer and Wine].[Beer])",
regionProductBeer.toString());
final CacheControl.CellRegion regionProductDairy =
cacheControl.createMemberRegion(memberDairy, true);
final CacheControl.CellRegion regionProductUnion =
cacheControl.createUnionRegion(
regionProductBeer,
regionProductDairy);
assertEquals(
"Union(Member([Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer]), Member([Product].[Drink].[Dairy]))",
regionProductUnion.toString());
final CacheControl.CellRegion regionProductXTime =
cacheControl.createCrossjoinRegion(
regionProductUnion, regionTimeQ1);
assertEquals(
"Crossjoin(Union(Member([Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer]), Member([Product].[Drink].[Dairy])), Member([Time].[1997].[Q1]))",
regionProductXTime.toString());
try {
cacheControl.flush(regionProductXTime);
fail("expceted error");
} catch (RuntimeException e) {
assertContains(
"Region of cells to be flushed must contain measures.",
e.getMessage());
}
final CacheControl.CellRegion measuresRegion =
cacheControl.createMeasuresRegion(salesCube);
return cacheControl.createCrossjoinRegion(
regionProductXTime,
measuresRegion);
}
/**
* Creates a cell region using a given {@link CacheControl}, containing
* only [Time].[1997].[Q1] * {Measures}.
*
* @param testContext Test context
* @param cacheControl Cache control
*/
private CacheControl.CellRegion createCellRegion1997_Q1_UnitSales(
TestContext testContext,
CacheControl cacheControl)
{
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
// Region consists of [Time].[1997].[Q1] and its children.
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member memberQ1 = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Time", "1997", "Q1"), true);
final CacheControl.CellRegion regionTimeQ1 =
cacheControl.createMemberRegion(memberQ1, true);
assertEquals("Member([Time].[1997].[Q1])", regionTimeQ1.toString());
final CacheControl.CellRegion measuresRegion =
cacheControl.createMeasuresRegion(salesCube);
return cacheControl.createCrossjoinRegion(
regionTimeQ1,
measuresRegion);
}
/**
* Creates a cell region using a given {@link CacheControl}, containing
* only [Time].[1997].[Q1] * {Measures}.
*
* @param testContext Test context
* @param cacheControl Cache control
*/
private CacheControl.CellRegion createCellRegionAprilOnwards(
TestContext testContext,
CacheControl cacheControl)
{
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
// Region consists of [Time].[1997].[Q2].[4] and its children.
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member memberApril = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Time", "1997", "Q2", "4"), true);
final CacheControl.CellRegion regionTimeApril =
cacheControl.createMemberRegion(
true, memberApril, false, null, true);
assertEquals(
"Range([Time].[1997].[Q2].[4] inclusive to null)",
regionTimeApril.toString());
final CacheControl.CellRegion measuresRegion =
cacheControl.createMeasuresRegion(salesCube);
return cacheControl.createCrossjoinRegion(
regionTimeApril,
measuresRegion);
}
/**
* Creates a cell region using a given {@link CacheControl}, containing
* only [Time].[1997] * {Measures}.
*
* @param testContext Test context
* @param cacheControl Cache control
*/
private CacheControl.CellRegion createCellRegion1997(
TestContext testContext,
CacheControl cacheControl)
{
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
// Region consists of [Time].[1997] and its children.
final SchemaReader schemaReader = salesCube.getSchemaReader(null);
final Member member1997 = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Time", "1997"), true);
final CacheControl.CellRegion region1997 =
cacheControl.createMemberRegion(member1997, true);
assertEquals(
"Member([Time].[1997])",
region1997.toString());
final CacheControl.CellRegion measuresRegion =
cacheControl.createMeasuresRegion(salesCube);
return cacheControl.createCrossjoinRegion(
region1997,
measuresRegion);
}
/**
* Creates a cell region using a given {@link CacheControl}, containing
* only [Gender].[F] * {[Product].[Food], [Product].[Drink]} * {Measures}.
*
* @param testContext Test context
* @param cacheControl Cache control
*/
private CacheControl.CellRegion createCellRegionFemaleFoodDrink(
TestContext testContext,
CacheControl cacheControl)
{
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
// Region consists of [Product].[Food], [Product].[Drink] and their
// children.
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member memberFood = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Product", "Food"), true);
final Member memberDrink = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Product", "Drink"), true);
final Member memberFemale = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Gender", "F"), true);
final CacheControl.CellRegion regionProductFoodDrink =
cacheControl.createMemberRegion(
true, memberDrink, true, memberFood, true);
assertEquals(
"Range([Product].[Drink] inclusive to [Product].[Food] inclusive)",
regionProductFoodDrink.toString());
final CacheControl.CellRegion regionFemale =
cacheControl.createMemberRegion(memberFemale, true);
final CacheControl.CellRegion measuresRegion =
cacheControl.createMeasuresRegion(salesCube);
return cacheControl.createCrossjoinRegion(
regionProductFoodDrink,
measuresRegion,
regionFemale);
}
/**
* Asserts that a given string contains a given pattern.
*
* @param pattern Pattern to find
* @param message String
* @throws junit.framework.AssertionFailedError if pattern is not found
*/
static void assertContains(String pattern, String message) {
assertTrue(message, message.indexOf(pattern) > -1);
}
/**
* A number of negative tests, trying to do invalid things with cache
* flushing and getting errors.
*/
public void testNegative() {
final TestContext testContext = getTestContext();
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
final SchemaReader schemaReader = salesCube.getSchemaReader(null);
final CacheControl cacheControl =
new CacheControlImpl((RolapConnection) connection);
final Member memberQ1 =
schemaReader.withLocus().getMemberByUniqueName(
Id.Segment.toList("Time", "1997", "Q1"), true);
final Member memberBeer =
schemaReader.withLocus().getMemberByUniqueName(
Id.Segment.toList(
"Product", "Drink", "Alcoholic Beverages", "Beer and Wine"),
true);
final Member memberDairy =
schemaReader.withLocus().getMemberByUniqueName(
Id.Segment.toList("Product", "Drink", "Dairy"), true);
final CacheControl.CellRegion regionTimeQ1 =
cacheControl.createMemberRegion(memberQ1, false);
final CacheControl.CellRegion regionProductBeer =
cacheControl.createMemberRegion(memberBeer, false);
final CacheControl.CellRegion regionProductDairy =
cacheControl.createMemberRegion(memberDairy, true);
// Try to combine [Time] region with [Product] region.
// Cannot union regions with different dimensionality.
try {
final CacheControl.CellRegion cellRegion =
cacheControl.createUnionRegion(
regionTimeQ1,
regionProductBeer);
fail("expected exception, got " + cellRegion);
} catch (RuntimeException e) {
assertContains(
"Cannot union cell regions of different dimensionalities. "
+ "(Dimensionalities are '[[Time]]', '[[Product]]'.)",
e.getMessage());
}
final CacheControl.CellRegion regionTimeXProduct =
cacheControl.createCrossjoinRegion(
regionTimeQ1,
regionProductBeer);
assertNotNull(regionTimeXProduct);
assertEquals(2, regionTimeXProduct.getDimensionality().size());
assertEquals(
"Crossjoin(Member([Time].[1997].[Q1]), "
+ "Member([Product].[Drink].[Alcoholic Beverages]."
+ "[Beer and Wine]))",
regionTimeXProduct.toString());
// Try to combine ([Time], [Product]) region with ([Time]) region.
try {
final CacheControl.CellRegion cellRegion =
cacheControl.createUnionRegion(
regionTimeXProduct,
regionTimeQ1);
fail("expected exception, got " + cellRegion);
} catch (RuntimeException e) {
assertContains(
"Cannot union cell regions of different dimensionalities. "
+ "(Dimensionalities are '[[Time], [Product]]', '[[Time]]'.)",
e.getMessage());
}
// Try to combine ([Time], [Product]) region with ([Product]) region.
try {
final CacheControl.CellRegion cellRegion =
cacheControl.createUnionRegion(
regionTimeXProduct,
regionProductBeer);
fail("expected exception, got " + cellRegion);
} catch (RuntimeException e) {
assertContains(
"Cannot union cell regions of different dimensionalities. "
+ "(Dimensionalities are '[[Time], [Product]]', "
+ "'[[Product]]'.)",
e.getMessage());
}
// Try to combine ([Time]) region with ([Time], [Product]) region.
try {
final CacheControl.CellRegion cellRegion =
cacheControl.createUnionRegion(
regionTimeQ1,
regionTimeXProduct);
fail("expected exception, got " + cellRegion);
} catch (RuntimeException e) {
assertContains(
"Cannot union cell regions of different dimensionalities. "
+ "(Dimensionalities are '[[Time]]', '[[Time], [Product]]'.)",
e.getMessage());
}
// Union [Time] region with itself -- OK.
final CacheControl.CellRegion regionTimeUnionTime =
cacheControl.createUnionRegion(
regionTimeQ1,
regionTimeQ1);
assertNotNull(regionTimeUnionTime);
assertEquals(1, regionTimeUnionTime.getDimensionality().size());
// Union [Time] region with itself -- OK.
final CacheControl.CellRegion regionTimeXProductUnionTimeXProduct =
cacheControl.createUnionRegion(
regionTimeXProduct,
regionTimeXProduct);
assertNotNull(regionTimeXProductUnionTimeXProduct);
assertEquals(
2, regionTimeXProductUnionTimeXProduct.getDimensionality().size());
// Cartesian product two [Product] regions - not OK.
try {
final CacheControl.CellRegion cellRegion =
cacheControl.createCrossjoinRegion(
regionProductBeer,
regionProductDairy);
fail("expected exception, got " + cellRegion);
} catch (RuntimeException e) {
assertContains(
"Cannot crossjoin cell regions which have dimensions in common."
+ " (Dimensionalities are '[[Product]]', '[[Product]]'.)",
e.getMessage());
}
// Cartesian product [Product] and [Time] x [Product] regions - not OK.
try {
final CacheControl.CellRegion cellRegion =
cacheControl.createCrossjoinRegion(
regionProductBeer,
regionTimeXProduct);
fail("expected exception, got " + cellRegion);
} catch (RuntimeException e) {
assertContains(
"Cannot crossjoin cell regions which have dimensions in common."
+ " (Dimensionalities are "
+ "'[[Product]]', '[[Time], [Product]]'.)",
e.getMessage());
}
}
/**
* Tests crossjoin of regions, {@link CacheControl#createCrossjoinRegion}.
*/
public void testCrossjoin() {
final TestContext testContext = getTestContext();
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
final CacheControl cacheControl =
new CacheControlImpl((RolapConnection) connection);
// Region consists of [Time].[1997].[Q1] and its children, and products
// [Beer] and [Dairy].
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member memberQ1 = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Time", "1997", "Q1"), true);
final Member memberBeer = schemaReader.getMemberByUniqueName(
Id.Segment.toList(
"Product", "Drink", "Alcoholic Beverages", "Beer and Wine",
"Beer"),
true);
final CacheControl.CellRegion regionProductBeer =
cacheControl.createMemberRegion(memberBeer, false);
final Member memberFemale = schemaReader.getMemberByUniqueName(
Id.Segment.toList("Gender", "F"), true);
final CacheControl.CellRegion regionGenderFemale =
cacheControl.createMemberRegion(memberFemale, false);
final CacheControl.CellRegion regionTimeQ1 =
cacheControl.createMemberRegion(memberQ1, true);
final CacheControl.CellRegion regionTimeXProduct =
cacheControl.createCrossjoinRegion(
regionTimeQ1,
regionProductBeer);
// Compose a crossjoin with a non crossjoin
final CacheControl.CellRegion regionTimeXProductXGender =
cacheControl.createCrossjoinRegion(
regionTimeXProduct,
regionGenderFemale);
assertEquals(
"Crossjoin("
+ "Member([Time].[1997].[Q1]), "
+ "Member([Product].[Drink].[Alcoholic Beverages]."
+ "[Beer and Wine].[Beer]), "
+ "Member([Gender].[F]))",
regionTimeXProductXGender.toString());
assertEquals(
"[[Time], [Product], [Gender]]",
regionTimeXProductXGender.getDimensionality().toString());
// Three-way crossjoin, should be same as previous
final CacheControl.CellRegion regionTimeXProductXGender2 =
cacheControl.createCrossjoinRegion(
regionTimeQ1,
regionProductBeer,
regionGenderFemale);
assertEquals(
"Crossjoin("
+ "Member([Time].[1997].[Q1]), "
+ "Member([Product].[Drink].[Alcoholic Beverages]"
+ ".[Beer and Wine].[Beer]), "
+ "Member([Gender].[F]))",
regionTimeXProductXGender2.toString());
assertEquals(
"[[Time], [Product], [Gender]]",
regionTimeXProductXGender2.getDimensionality().toString());
// Compose a non crossjoin with a crossjoin
final CacheControl.CellRegion regionGenderXTimeXProduct =
cacheControl.createCrossjoinRegion(
regionGenderFemale,
regionTimeXProduct);
assertEquals(
"Crossjoin("
+ "Member([Gender].[F]), "
+ "Member([Time].[1997].[Q1]), "
+ "Member([Product].[Drink].[Alcoholic Beverages]"
+ ".[Beer and Wine].[Beer]))",
regionGenderXTimeXProduct.toString());
assertEquals(
"[[Gender], [Time], [Product]]",
regionGenderXTimeXProduct.getDimensionality().toString());
}
/**
* Helper method, creates a region consisting of a single member, given its
* unique name (e.g. "[Gender].[F]").
*/
CacheControl.CellRegion memberRegion(String uniqueName) {
final String[] names = uniqueName.split("\\.");
final List<Id.Segment> ids = new ArrayList<Id.Segment>(names.length);
for (int i = 0; i < names.length; i++) {
String name = names[i];
assert name.startsWith("[") && name.endsWith("]");
names[i] = name.substring(1, name.length() - 1);
ids.add(new Id.NameSegment(names[i]));
}
final TestContext testContext = getTestContext();
final Connection connection = testContext.getConnection();
final Cube salesCube = connection.getSchema().lookupCube("Sales", true);
final CacheControl cacheControl =
new CacheControlImpl((RolapConnection) connection);
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member member = schemaReader.getMemberByUniqueName(ids, true);
return cacheControl.createMemberRegion(member, false);
}
/**
* Tests the algorithm which converts a cache region specification into
* normal form.
*/
public void testNormalize() {
// Create
// Union(
// Crossjoin(
// [Marital Status].[S],
// Union(
// Crossjoin(
// [Gender].[F]
// [Time].[1997].[Q1])
// Crossjoin(
// [Gender].[M]
// [Time].[1997].[Q2]))
// Crossjoin(
// Crossjoin(
// [Marital Status].[S],
// [Gender].[F])
// [Time].[1997].[Q1])
final CacheControl cacheControl =
new CacheControlImpl(
(RolapConnection) getTestContext().getConnection());
final CacheControl.CellRegion region =
cacheControl.createUnionRegion(
cacheControl.createCrossjoinRegion(
memberRegion("[Marital Status].[S]"),
cacheControl.createUnionRegion(
cacheControl.createCrossjoinRegion(
memberRegion("[Gender].[F]"),
memberRegion("[Time].[1997].[Q1]")),
cacheControl.createCrossjoinRegion(
memberRegion("[Gender].[M]"),
memberRegion("[Time].[1997].[Q2]")))),
cacheControl.createCrossjoinRegion(
cacheControl.createCrossjoinRegion(
memberRegion("[Marital Status].[S]"),
memberRegion("[Gender].[F]")),
memberRegion("[Time].[1997].[Q1]")));
assertEquals(
"Union("
+ "Crossjoin("
+ "Member([Marital Status].[S]), "
+ "Union("
+ "Crossjoin("
+ "Member([Gender].[F]), "
+ "Member([Time].[1997].[Q1])), "
+ "Crossjoin(Member([Gender].[M]), "
+ "Member([Time].[1997].[Q2])))), "
+ "Crossjoin("
+ "Member([Marital Status].[S]), "
+ "Member([Gender].[F]), "
+ "Member([Time].[1997].[Q1])))",
region.toString());
final CacheControl.CellRegion normalizedRegion =
((CacheControlImpl) cacheControl).normalize(
(CacheControlImpl.CellRegionImpl) region);
assertEquals(
"Union("
+ "Crossjoin(Member([Marital Status].[S]), Member([Gender].[F]), Member([Time].[1997].[Q1])), "
+ "Crossjoin(Member([Marital Status].[S]), Member([Gender].[M]), Member([Time].[1997].[Q2])), "
+ "Crossjoin(Member([Marital Status].[S]), Member([Gender].[F]), Member([Time].[1997].[Q1])))",
normalizedRegion.toString());
}
public void testFlushNonPrimedContent() throws Exception {
final TestContext testContext = getTestContext();
flushCache(testContext);
final CacheControl cacheControl =
testContext.getConnection().getCacheControl(null);
final Cube cube =
testContext.getConnection()
.getSchema().lookupCube("Sales", true);
Hierarchy hier =
cube.getDimensions()[2].getHierarchies()[0];
Member hierMember = hier.getAllMember();
CellRegion measuresRegion = cacheControl.createMeasuresRegion(cube);
CellRegion hierRegion =
cacheControl.createMemberRegion(hierMember, true);
CellRegion flushRegion =
cacheControl.createCrossjoinRegion(measuresRegion, hierRegion);
cacheControl.flush(flushRegion);
}
public void testMondrian1094() throws Exception {
final String query =
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ "NON EMPTY {[Store].[All Stores].Children} ON ROWS \n"
+ "from [Sales] \n";
flushCache(getTestContext());
assertQueryReturns(
query,
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Store].[USA]}\n"
+ "Row #0: 266.773\n");
if (MondrianProperties.instance().DisableCaching.get()) {
return;
}
// Make sure MaxConstraint is high enough
int minConstraints = 3;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints,
minConstraints);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
final CacheControl cacheControl =
getConnection().getCacheControl(pw);
// Flush the cache.
final Cube salesCube =
getConnection().getSchema().lookupCube("Sales", true);
final Hierarchy storeHierarchy =
salesCube.lookupHierarchy(
new Id.NameSegment(
"Store",
Id.Quoting.UNQUOTED),
false);
/* final CacheControl.CellRegion measuresRegion =
cacheControl.createMeasuresRegion(salesCube);
final CacheControl.CellRegion hierarchyRegion =
cacheControl.createMemberRegion(
storeHierarchy.getAllMember(), true);
final CacheControl.CellRegion region =
cacheControl.createCrossjoinRegion(
measuresRegion, hierarchyRegion);
*/
CellRegion region = cacheControl.createMeasuresRegion(salesCube);
cacheControl.flush(region);
pw.flush();
String tag = "output";
String expected = "${output}";
String actual = sw.toString();
assertCacheStateEquals(tag, expected, actual);
}
// todo: Test flushing a segment which is unconstrained
// todo: Test flushing a segment where 2 or more axes are reduced. E.g.
// Given segment
// (state={CA, OR}, quarter={Q1, Q2, Q3}, year=1997)
// flush
// (state=OR, quarter=Q2)
// which leaves
// (state={CA, OR}, quarter={Q1, Q3}, year=1997)
// (state=CA, quarter=Q2, year=1997)
// For now, we kill the slice of the segment with the fewest values, which
// (quarter=Q2)
// leaving
// (state={CA, OR}, quarter={Q1, Q3}, year=1997)
// todo: Test flushing values which are not present in a segment. Need to
// reduce the scope of the segment.
// todo: Solve the fragmentation problem. Continually ask for later and
// later times. Two cases: the segment's specification contains the time
// asked for (and therefore the segment will later need to be pared back),
// and it doesn't. Either way, end up with a lot of segments which could
// be merged. Solve by triggering a coalesce or flush, but what should
// trigger that?
// todo: test which tries to constraint on calc member. Should get error.
// todo: test which tries to constrain on member of parent-child hierarchy
}
// End CacheControlTest.java |
package ljfa.tntutils.proxy;
import ljfa.tntutils.TNTUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
public class ClientProxy extends CommonProxy {
public ClientProxy() {
mc = Minecraft.getMinecraft();
}
/*@Override
public void init(FMLInitializationEvent event) {
super.init(event);
}*/
private Minecraft mc;
} |
package controllers;
//import jdk.nashorn.internal.ir.ObjectNode;
import models.Event;
import models.Question;
import models.User;
import models.UserStats;
import models.UserEventStats;
import models.ReportAnalytics;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import play.data.validation.Constraints;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import play.data.Form;
import views.html.dashboard.index;
import views.html.dashboard.help;
import views.html.dashboard.instructorDashboard;
import views.html.dashboard.manageEvents;
import views.html.dashboard.createEventConfirmation;
import views.html.dashboard.deleteEventConfirmation;
import views.html.dashboard.updateEventConfirmation;
import views.html.dashboard.report;
import views.html.chatRoom;
import views.html.eventSequence.eventStage1;
import views.html.instructorView;
import java.util.Collections;
import views.html.pastEvents.pastEventsForInstructors;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import scala.collection.JavaConverters;
import java.net.MalformedURLException;
import models.utils.AppException;
import play.Logger;
import java.util.Date;
import java.util.HashSet;
import static play.data.Form.form;
import java.text.*;
@Security.Authenticated(Secured.class)
public class Dashboard extends Controller {
public static Result index() {
User currentUser = User.findByEmail(request().username());
boolean isInstructor = currentUser.isInstructor;
if(isInstructor){
return ok(instructorDashboard.render((User.findByEmail(request().username())), Event.findEvent()));
}
else {
List<Event> eventList = currentUser.EventsParticipated;
User user = User.findByEmail(request().username());
UserStats userStats = UserStats.findUserStatsByUser(user);
return ok(index.render(user, userStats, eventList));
}
}
public static Result manageEvents() {
User currentUser = User.findByEmail(request().username());
Event eventSelected = Event.findEvent();
return ok(manageEvents.render(currentUser,eventSelected,form(CreateEventForm.class),User.findAllUsers(),Event.findAllEvents()));
}
public static Result listUserJs(String divID) {
List<User> userList=User.findAllUsers();
String output="";
for(User u: userList)
{
System.out.println(output);
output+=u.fullname+"|";
}
return ok(views.js.listUser.render(divID,output));
}
public static Result listEventJs(String divID) {
List<Event> eventList=Event.findAllEvents();
String output="";
for(Event e: eventList)
{
System.out.println(output);
output+=e.eventName+"|";
}
return ok(views.js.listEvent.render(divID,output));
}
public static Result createEvent() {
User instructor = User.findByEmail(request().username());
Form<CreateEventForm> form2 = form(CreateEventForm.class);
CreateEventForm f = form2.bindFromRequest().get();
System.out.println("Read event form!!" + f.eventName);
try
{
initEventStage(f,instructor);
}
catch (Exception ex)
{
System.out.println("Error in saving the event");
ex.printStackTrace();
}
return ok(createEventConfirmation.render((User.findByEmail(request().username())), Event.findEvent()));
}
private static void initEventStage(Dashboard.CreateEventForm createEventForm,User instructorUser) throws AppException,MalformedURLException,ParseException {
Event event = new Event();
//need to add the instructor
event.instructor=instructorUser;
//Adding event name
event.eventName=createEventForm.eventName;
//Converting string to date
//todo form changes
//Date date = new SimpleDateFormat("MM/dd/yyyy").parse(createEventForm.date);
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mmaa");
event.eventDateTime= formatter.parseDateTime(createEventForm.date + " " + createEventForm.startTime);
//Start and end time
event.startTime=createEventForm.startTime;
//Calculate end time using phase duration
//event.endTime=createEventForm.startTime+createEventForm.phaseDuration;
//Event Description
event.description=createEventForm.eventDescription;
System.out.println("hashtag :"+ event.description);
//Scripts for all stages
event.scriptPhase1=createEventForm.script1;
event.scriptPhase2=createEventForm.script2;
event.scriptPhase3=createEventForm.script3;
event.scriptPhase4=createEventForm.script4;
//Split the event descriptions
event.hashes=createEventForm.hashes;
System.out.println("hashtag :" + event.hashes);
String[] hashtags=event.getHashTags();
for(String s: hashtags)
{
System.out.println("hashtag element is:"+ s);
}
//Add participants
event.participants=new ArrayList<User>();
if(createEventForm.participants != null) {
createEventForm.participants.removeAll(Collections.singleton(null));
for (String t : createEventForm.participants) {
System.out.println("participants are: "+t);
User p = User.findByFullname(t);
System.out.println("participants fullname: "+p.fullname);
event.participants.add(p);
}
}
//create question objects
event.Questions=new ArrayList<Question>();
Question q=new Question();
q.questionString=createEventForm.question;
q.Option1=createEventForm.option1;
q.Option2=createEventForm.option2;
q.Option3=createEventForm.option3;
q.Option4=createEventForm.option4;
q.Answer=createEventForm.answer;
System.out.println("Answer for question 1"+q.Answer);
q.save();
event.Questions.add(q);
Question fq=new Question();
fq.questionString=createEventForm.fquestion;
fq.Option1=createEventForm.foption1;
fq.Option2=createEventForm.foption2;
fq.Option3=createEventForm.foption3;
fq.Option4=createEventForm.foption4;
fq.Answer=createEventForm.fanswer;
System.out.println("Answer for question 1"+fq.Answer);
fq.save();
event.Questions.add(fq);
//add durations for all the phases
event.phase1Duration=Integer.valueOf(createEventForm.phaseDuration);
event.phase2Duration=Integer.valueOf(createEventForm.phaseDuration);
event.phase3Duration=Integer.valueOf(createEventForm.phaseDuration);
//event active status
event.active=0;
//save the event
event.save();
}
public static Result deleteEvent(){
User instructor = User.findByEmail(request().username());
Form<deleteEventForm> dform = form(deleteEventForm.class);
deleteEventForm d = dform.bindFromRequest().get();
//Get the corresponding event
Event e=Event.findByName(d.eventNameToBeDeleted);
//Mark the event as deleted- status 3
e.active=3;
e.update();
return ok(deleteEventConfirmation.render((User.findByEmail(request().username())), e));
}
public static Result updateEvent(){
return ok(updateEventConfirmation.render((User.findByEmail(request().username())), Event.findEvent()));
}
public static Result getEventstoActivate()
{
List<Event> eventList = Event.getAllEventsToActivate();
StringBuilder output = new StringBuilder();
output.append("[");
for(int i=0;i<eventList.size();i++){
output.append("{");
output.append("\"eventId\":");
output.append("\"");
output.append(eventList.get(i).eventId);
output.append("\"");
output.append(",");
output.append("\"eventName\":");
output.append("\"");
output.append(eventList.get(i).eventName);
output.append("\"");
output.append(",");
output.append("\"Date\":");
output.append("\"");
output.append(eventList.get(i).eventDateTime);
output.append("\"");
output.append("},");
}
String response = output.toString();
response = response.substring(0, response.length()-1);
response = response + "]";
System.out.println(response);
// String s = "[{\"eventId\":\"jhhj\",\"eventName\":\"hjkghsjk\",\"Date\":\"jkdghs jkhsg\"}]";
return ok(response);
}
public static Result getEventSummary() {
User reportUser = User.findByEmail(request().username());
// Event reportEvent = Event.findByName(name);
Event reportEvent = Event.findEvent();
return ok(report.render(reportUser, reportEvent,Event.findAllEvents()));
}
public static Result help()
{
User reportUser = User.findByEmail(request().username());
return ok(help.render(reportUser));
}
public static Result activateEvent(Long eventId){
//Update the status of the event to 1 to mark that the event is activated.
//find event by eventID
Event event=Event.findById(eventId);
//Call function to mark the event as ongoing
event.markEventStatusAsOngoing();
//update the action to the database.
event.update();
return ok(eventId+" Activated");
}
public static Result generateIndividualEventSummary(String eventName){
//Report Analytics
ReportAnalytics ra=new ReportAnalytics();
//Event e=Event.findByName(eventName);
System.out.println("going to call report analytics function...");
ra.analyze(eventName);
String maxPercentPhase= ra.getMaxPercentPhase();
String hashTagMsgs=ra.getHashMsgs();
String collabMsg=ra.getCollabMsg();
System.out.println("Report Analytics Max Percent Phase:" + maxPercentPhase);
System.out.println("Report Analytics Hash Messages:" + hashTagMsgs);
System.out.println("Report Analytics collabMsg:" + collabMsg);
String output="";
if(maxPercentPhase!=null && hashTagMsgs!=null && collabMsg!=null) {
output = ra.getMaxPercentPhase() + "|" + ra.getHashMsgs() + "|" + ra.getCollabMsg();
//System.out.println("Event name "+e.eventName);
//Finding the user with highest upvotes
List<UserEventStats> usrEventStatsList = UserEventStats.findAllUserEventStats();
System.out.println("The user event statistics...");
int maxUpvotes = Integer.MIN_VALUE;
User mostUpvotedUser = new User();
for (int i = 0; i < usrEventStatsList.size(); i++) {
int currentUserUpvoteCount = usrEventStatsList.get(i).noOfUpVotesReceivedForEvent;
System.out.println("current user upvotes... " + currentUserUpvoteCount);
System.out.println("Fetching the current user..");
User currentUser = usrEventStatsList.get(i).user;
System.out.println("current user name.." + currentUser.fullname);
if (currentUserUpvoteCount > maxUpvotes) {
maxUpvotes = currentUserUpvoteCount;
mostUpvotedUser = currentUser;
}
}
if (maxUpvotes > 0)
output += "|" + " The most upvoted student for this event is " + mostUpvotedUser.fullname + " with " + maxUpvotes + " votes.";
else
output += "|" + " None of the students in this event were upvoted by his/her peers. ";
}
else
{
output="This event is not completed. You can view the reports for this event once it is complete";
}
return ok(output);
}
public static Result instructorView() {
// if(username == null || username.trim().equals("")) {
// flash("error", "Please choose a valid username.");
// return redirect(routes.Application.index());
User currUser = User.findByEmail(request().username());
// System.out.println("Request().username:"+ currUser.fullname);
// System.out.println("User email id is " + currUser.email);
return ok(instructorView.render(currUser));
}
public static Result instructorPastEventDiscussions() {
List<Event> completedEvents = Event.findAllCompletedEvents();
User reportUser = User.findByEmail(request().username());
return ok(pastEventsForInstructors.render(reportUser,completedEvents));
}
public static class CreateEventForm {
@Constraints.Required
public String eventName;
@Constraints.Required
public String eventDescription;
@Constraints.Required
public String hashes;
@Constraints.Required
public String script1;
@Constraints.Required
public String script2;
@Constraints.Required
public String script3;
@Constraints.Required
public String script4;
@Constraints.Required
public String question;
@Constraints.Required
public String option1;
@Constraints.Required
public String option2;
@Constraints.Required
public String option3;
@Constraints.Required
public String option4;
@Constraints.Required
public String answer;
@Constraints.Required
public String fquestion;
@Constraints.Required
public String foption1;
@Constraints.Required
public String foption2;
@Constraints.Required
public String foption3;
@Constraints.Required
public String foption4;
@Constraints.Required
public String fanswer;
@Constraints.Required
public String date;
//@Constraints.Required
//public String endTime;
@Constraints.Required
public String phaseDuration;
@Constraints.Required
public String startTime;
@Constraints.Required
public List<String> participants;
}
public static class deleteEventForm{
@Constraints.Required
public String eventNameToBeDeleted;
}
public static class reportForEvent {
@Constraints.Required
public String event;
}
} |
package manon.app.config;
import lombok.RequiredArgsConstructor;
import manon.model.user.UserRole;
import manon.service.user.PasswordEncoderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
import java.util.Collections;
import static manon.app.Globals.API.API;
import static manon.app.Globals.API.API_SYS;
import static manon.app.Globals.API.API_USER;
import static manon.app.Globals.API.API_USER_ADMIN;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, order = HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String ACTUATOR = UserRole.ACTUATOR.name();
private static final String ADMIN = UserRole.ADMIN.name();
private static final String PLAYER = UserRole.PLAYER.name();
private final PasswordEncoderService passwordEncoderService;
private final UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.cors()
.and()
.httpBasic()
.and()
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.authorizeRequests()
.antMatchers(API_SYS + "/info/up").permitAll() |
package mezz.jei.util;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import mezz.jei.config.IServerConfig;
import mezz.jei.config.ServerConfig;
import net.minecraft.Util;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraftforge.items.ItemHandlerHelper;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.RootCommandNode;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.item.ItemInput;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.MinecraftServer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundSource;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.network.chat.Component;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.TranslatableComponent;
import mezz.jei.network.Network;
import mezz.jei.network.packets.PacketCheatPermission;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Server-side-safe utilities for commands.
*/
public final class CommandUtilServer {
private static final Logger LOGGER = LogManager.getLogger();
private CommandUtilServer() {
}
public static String[] getGiveCommandParameters(Player sender, ItemStack itemStack, int amount) {
Component senderName = sender.getName();
Item item = itemStack.getItem();
ResourceLocation itemResourceLocation = item.getRegistryName();
if (itemResourceLocation == null) {
String stackInfo = ErrorUtil.getItemStackInfo(itemStack);
throw new IllegalArgumentException("item.getRegistryName() returned null for: " + stackInfo);
}
List<String> commandStrings = new ArrayList<>();
commandStrings.add(senderName.getString());
String itemArgument = itemResourceLocation.toString();
CompoundTag tagCompound = itemStack.getTag();
if (tagCompound != null) {
itemArgument += tagCompound;
}
commandStrings.add(itemArgument);
commandStrings.add(String.valueOf(amount));
return commandStrings.toArray(new String[0]);
}
public static void writeChatMessage(Player player, String translationKey, ChatFormatting color) {
TranslatableComponent component = new TranslatableComponent(translationKey);
component.getStyle().applyFormat(color);
player.sendMessage(component, Util.NIL_UUID);
}
public static boolean hasPermissionForCheatMode(Player sender) {
IServerConfig serverConfig = ServerConfig.getInstance();
if (serverConfig.isCheatModeEnabledForCreative() &&
sender.isCreative()) {
return true;
}
CommandSourceStack commandSource = sender.createCommandSourceStack();
if (serverConfig.isCheatModeEnabledForOp()) {
MinecraftServer minecraftServer = sender.getServer();
if (minecraftServer != null) {
int opPermissionLevel = minecraftServer.getOperatorUserPermissionLevel();
return commandSource.hasPermission(opPermissionLevel);
}
}
if (serverConfig.isCheatModeEnabledForGive()) {
CommandNode<CommandSourceStack> giveCommand = getGiveCommand(sender);
if (giveCommand != null) {
return giveCommand.canUse(commandSource);
}
}
return false;
}
/**
* Gives a player an item.
*/
public static void executeGive(ServerPlayer sender, ItemStack itemStack, GiveMode giveMode) {
if (hasPermissionForCheatMode(sender)) {
if (giveMode == GiveMode.INVENTORY) {
giveToInventory(sender, itemStack);
} else if (giveMode == GiveMode.MOUSE_PICKUP) {
mousePickupItemStack(sender, itemStack);
}
} else {
Network.sendPacketToClient(new PacketCheatPermission(false), sender);
}
}
public static void setHotbarSlot(ServerPlayer sender, ItemStack itemStack, int hotbarSlot) {
if (hasPermissionForCheatMode(sender)) {
if (!Inventory.isHotbarSlot(hotbarSlot)) {
LOGGER.error("Tried to set slot that is not in the hotbar: {}", hotbarSlot);
return;
}
ItemStack stackInSlot = sender.getInventory().getItem(hotbarSlot);
if (ItemStack.matches(stackInSlot, itemStack)) {
return;
}
ItemStack itemStackCopy = itemStack.copy();
sender.getInventory().setItem(hotbarSlot, itemStack);
sender.level.playSound(null, sender.getX(), sender.getY(), sender.getZ(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 0.2F, ((sender.getRandom().nextFloat() - sender.getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F);
sender.inventoryMenu.broadcastChanges();
notifyGive(sender, itemStackCopy);
} else {
Network.sendPacketToClient(new PacketCheatPermission(false), sender);
}
}
public static void mousePickupItemStack(Player sender, ItemStack itemStack) {
AbstractContainerMenu containerMenu = sender.containerMenu;
ItemStack itemStackCopy = itemStack.copy();
ItemStack existingStack = containerMenu.getCarried();
final int giveCount;
if (ItemHandlerHelper.canItemStacksStack(existingStack, itemStack)) {
int newCount = Math.min(existingStack.getMaxStackSize(), existingStack.getCount() + itemStack.getCount());
giveCount = newCount - existingStack.getCount();
existingStack.setCount(newCount);
} else {
containerMenu.setCarried(itemStack);
giveCount = itemStack.getCount();
}
if (sender instanceof ServerPlayer serverPlayerEntity) {
itemStackCopy.setCount(giveCount);
notifyGive(serverPlayerEntity, itemStackCopy);
containerMenu.broadcastChanges();
}
}
/**
* Gives a player an item.
*
* @see GiveCommand#giveItem(CommandSource, ItemInput, Collection, int)
*/
@SuppressWarnings("JavadocReference")
private static void giveToInventory(Player entityplayermp, ItemStack itemStack) {
ItemStack itemStackCopy = itemStack.copy();
boolean flag = entityplayermp.getInventory().add(itemStack);
if (flag && itemStack.isEmpty()) {
itemStack.setCount(1);
ItemEntity entityitem = entityplayermp.drop(itemStack, false);
if (entityitem != null) {
entityitem.makeFakeItem();
}
entityplayermp.level.playSound(null, entityplayermp.getX(), entityplayermp.getY(), entityplayermp.getZ(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 0.2F, ((entityplayermp.getRandom().nextFloat() - entityplayermp.getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F);
entityplayermp.inventoryMenu.broadcastChanges();
} else {
ItemEntity entityitem = entityplayermp.drop(itemStack, false);
if (entityitem != null) {
entityitem.setNoPickUpDelay();
entityitem.setOwner(entityplayermp.getUUID());
}
}
notifyGive(entityplayermp, itemStackCopy);
}
private static void notifyGive(Player entityPlayerMP, ItemStack stack) {
CommandSourceStack commandSource = entityPlayerMP.createCommandSourceStack();
int count = stack.getCount();
Component stackTextComponent = stack.getDisplayName();
Component displayName = entityPlayerMP.getDisplayName();
TranslatableComponent message = new TranslatableComponent("commands.give.success.single", count, stackTextComponent, displayName);
commandSource.sendSuccess(message, true);
}
@Nullable
private static CommandNode<CommandSourceStack> getGiveCommand(Player sender) {
MinecraftServer minecraftServer = sender.getServer();
if (minecraftServer == null) {
return null;
}
Commands commandManager = minecraftServer.getCommands();
CommandDispatcher<CommandSourceStack> dispatcher = commandManager.getDispatcher();
RootCommandNode<CommandSourceStack> root = dispatcher.getRoot();
return root.getChild("give");
}
} |
package net.authorize.sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import net.authorize.sample.VisaCheckout.*;
import net.authorize.sample.PaymentTransactions.*;
import net.authorize.sample.PaypalExpressCheckout.*;
import net.authorize.sample.PaypalExpressCheckout.Void;
import net.authorize.sample.RecurringBilling.*;
import net.authorize.sample.TransactionReporting.*;
import net.authorize.sample.CustomerProfiles.*;
public class SampleCode {
public static void main( String[] args )
{
if (args.length == 0)
{
SelectMethod();
}
else if (args.length == 1)
{
RunMethod(args[0]);
return;
}
else
{
ShowUsage();
}
System.out.println("");
System.out.print("Press <Return> to finish ...");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
int i = Integer.parseInt(br.readLine());
}catch(Exception ex){
}
}
private static void ShowUsage()
{
System.out.println("Usage : java -jar SampleCode.jar [CodeSampleName]");
System.out.println("");
System.out.println("Run with no parameter to select a method. Otherwise pass a method name.");
System.out.println("");
System.out.println("Code Sample Names: ");
ShowMethods();
}
private static void SelectMethod()
{
System.out.println("Code Sample Names: ");
System.out.println("");
ShowMethods();
System.out.println("");
System.out.print("Type a sample name & then press <Return> : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
RunMethod(br.readLine());
}catch(Exception ex){
System.out.print("Error no such method");
}
}
private static void ShowMethods()
{
System.out.println(" DecryptVisaCheckoutData");
System.out.println(" CreateVisaCheckoutTransaction");
System.out.println(" ChargeCreditCard");
System.out.println(" AuthorizeCreditCard");
System.out.println(" RefundTransaction");
System.out.println(" VoidTransaction");
System.out.println(" CreateCustomerProfileFromTransaction");
System.out.println(" CaptureOnly");
System.out.println(" CapturePreviouslyAuthorizedAmount");
System.out.println(" DebitBankAccount");
System.out.println(" CreditBankAccount");
System.out.println(" ChargeTokenizedCreditCard");
System.out.println(" ChargeCustomerProfile");
System.out.println(" CreateSubscription");
System.out.println(" GetSubscriptionStatus");
System.out.println(" CancelSubscription");
System.out.println(" UpdateSubscription");
System.out.println(" GetListOfSubscriptions");
System.out.println(" GetBatchStatistics");
//System.out.println(" GetSettledBatchList");
System.out.println(" GetTransactionList");
System.out.println(" GetUnsettledTransactionList");
System.out.println(" GetTransactionDetails");
System.out.println(" CreateCustomerProfile");
System.out.println(" CreateCustomerProfileIds");
System.out.println(" CreateCustomerPaymentProfile");
System.out.println(" CreateCustomerShippingAddress");
System.out.println(" DeleteCustomerPaymentProfile");
System.out.println(" DeleteCustomerProfile");
System.out.println(" DeleteCustomerShippingAddress");
System.out.println(" GetCustomerPaymentProfile");
System.out.println(" GetCustomerProfile");
System.out.println(" GetCustomerShippingAddress");
System.out.println(" GetHostedProfilePage");
System.out.println(" UpdateCustomerPaymentProfile");
System.out.println(" UpdateCustomerShippingAddress");
System.out.println(" PayPalAuthorizeCapture");
System.out.println(" PayPalVoid");
System.out.println(" PayPalAuthorizationOnly");
System.out.println(" PayPalAuthorizeCaptureContinue");
System.out.println(" PayPalGetDetails");
System.out.println(" PayPalPriorAuthorizationCapture");
System.out.println(" PayPalAuthorizeOnlyContinue");
System.out.println(" PayPalCredit");
}
private static void RunMethod(String methodName)
{
// These are default transaction keys.
String apiLoginId = "5KP3u95bQpv";
String transactionKey = "4Ktq966gC55GAX7S";
//Update the payedId with which you want to run the sample code
String payerId = "";
//Update the transactionId with which you want to run the sample code
String transactionId = "";
switch (methodName) {
case "VisaCheckoutDecrypt":
DecryptVisaCheckoutData.run(apiLoginId, transactionKey);
break;
case "VisaCheckoutTransaction":
CreateVisaCheckoutTransaction.run(apiLoginId, transactionKey);
break;
case "ChargeCreditCard":
ChargeCreditCard.run(apiLoginId, transactionKey);
break;
case "VoidTransaction":
VoidTransaction.run(apiLoginId, transactionKey);
break;
case "AuthorizeCreditCard":
AuthorizeCreditCard.run(apiLoginId, transactionKey);
break;
case "RefundTransaction":
RefundTransaction.run(apiLoginId, transactionKey);
break;
case "CreateCustomerProfileFromTransaction":
CreateCustomerProfileFromTransaction.run(apiLoginId, transactionKey);
break;
case "CaptureOnly":
CaptureOnly.run(apiLoginId, transactionKey);
break;
case "CapturePreviouslyAuthorizedAmount":
CapturePreviouslyAuthorizedAmount.run(apiLoginId, transactionKey);
break;
case "DebitBankAccount":
DebitBankAccount.run(apiLoginId, transactionKey);
break;
case "CreditBankAccount":
CreditBankAccount.run(apiLoginId, transactionKey);
break;
case "ChargeTokenizedCreditCard":
ChargeTokenizedCreditCard.run(apiLoginId, transactionKey);
break;
case "ChargeCustomerProfile":
ChargeCustomerProfile.run(apiLoginId, transactionKey);
break;
case "CreateSubscription":
CreateSubscription.run(apiLoginId, transactionKey);
break;
case "GetSubscriptionStatus":
GetSubscriptionStatus.run(apiLoginId, transactionKey);
break;
case "CancelSubscription":
CancelSubscription.run(apiLoginId, transactionKey);
break;
case "UpdateSubscription":
UpdateSubscription.run(apiLoginId, transactionKey);
break;
case "GetListOfSubscriptions":
GetListOfSubscriptions.run(apiLoginId, transactionKey);
break;
case "GetBatchStatistics":
GetBatchStatistics.run(apiLoginId, transactionKey);
break;
/*case "GetSettledBatchList":
GetSettledBatchList.run(apiLoginId, transactionKey);
break;*/
case "GetTransactionList":
GetTransactionList.run(apiLoginId, transactionKey);
break;
case "GetUnsettledTransactionList":
GetUnsettledTransactionList.run(apiLoginId, transactionKey);
break;
case "GetTransactionDetails":
GetTransactionDetails.run(apiLoginId, transactionKey);
break;
case "CreateCustomerProfile":
CreateCustomerProfile.run(apiLoginId, transactionKey);
break;
case "CreateCustomerPaymentProfile":
CreateCustomerPaymentProfile.run(apiLoginId, transactionKey);
break;
case "CreateCustomerShippingAddress":
CreateCustomerShippingAddress.run(apiLoginId, transactionKey);
break;
case "DeleteCustomerPaymentProfile":
DeleteCustomerPaymentProfile.run(apiLoginId, transactionKey);
break;
case "DeleteCustomerProfile":
DeleteCustomerProfile.run(apiLoginId, transactionKey);
break;
case "DeleteCustomerShippingAddress":
DeleteCustomerShippingAddress.run(apiLoginId, transactionKey);
break;
case "GetCustomerPaymentProfile":
GetCustomerPaymentProfile.run(apiLoginId, transactionKey);
break;
case "GetCustomerProfile":
GetCustomerProfile.run(apiLoginId, transactionKey);
break;
case "GetCustomerProfileIds":
GetCustomerProfileIds.run(apiLoginId, transactionKey);
break;
case "GetCustomerShippingAddress":
GetCustomerShippingAddress.run(apiLoginId, transactionKey);
break;
case "GetHostedProfilePage":
GetHostedProfilePage.run(apiLoginId, transactionKey);
break;
case "UpdateCustomerPaymentProfile":
UpdateCustomerPaymentProfile.run(apiLoginId, transactionKey);
break;
case "UpdateCustomerShippingAddress":
UpdateCustomerShippingAddress.run(apiLoginId, transactionKey);
break;
case "PayPalAuthorizeCapture":
AuthorizationAndCapture.run(apiLoginId, transactionKey);
break;
case "PayPalVoid":
Void.run(apiLoginId, transactionKey);
break;
case "PayPalAuthorizationOnly":
AuthorizationOnly.run(apiLoginId, transactionKey);
break;
case "PayPalAuthorizeCaptureContinue":
AuthorizationAndCaptureContinue.run(apiLoginId, transactionKey, transactionId, payerId);
break;
case "PayPalAuthorizeOnlyContinue":
AuthorizationOnlyContinued.run(apiLoginId, transactionKey, transactionId, payerId);
break;
case "PayPalCredit":
Credit.run(apiLoginId, transactionKey, transactionId);
break;
case "PayPalGetDetails":
GetDetails.run(apiLoginId, transactionKey);
case "PaypalPriorAuthorizationCapture":
transactionId = "2241801682"; // Use a valid transaction ID here
PriorAuthorizationCapture.run(apiLoginId, transactionKey, transactionId);
break;
default:
ShowUsage();
break;
}
}
} |
package net.authorize.sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import net.authorize.sample.VisaCheckout.*;
import net.authorize.sample.PaymentTransactions.*;
import net.authorize.sample.PayPalExpressCheckout.*;
import net.authorize.sample.PayPalExpressCheckout.Void;
import net.authorize.sample.RecurringBilling.*;
import net.authorize.sample.TransactionReporting.*;
import net.authorize.sample.CustomerProfiles.*;
import net.authorize.sample.MobileInAppTransactions.*;
import net.authorize.sample.FraudManagement.*;
import net.authorize.sample.AcceptSuite.GetAcceptCustomerProfilePage;
import net.authorize.sample.AcceptSuite.GetAnAcceptPaymentPage;
public class SampleCode {
public static void main( String[] args )
{
if (args.length == 0)
{
SelectMethod();
}
else if (args.length == 1)
{
RunMethod(args[0]);
return;
}
else
{
ShowUsage();
}
System.out.println("");
System.out.print("Press <Return> to finish ...");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
int i = Integer.parseInt(br.readLine());
}catch(Exception ex) {
}
}
private static void ShowUsage()
{
System.out.println("Usage : java -jar SampleCode.jar [CodeSampleName]");
System.out.println("");
System.out.println("Run with no parameter to select a method. Otherwise pass a method name.");
System.out.println("");
System.out.println("Code Sample Names: ");
ShowMethods();
}
private static void SelectMethod()
{
System.out.println("Code Sample Names: ");
System.out.println("");
ShowMethods();
System.out.println("");
System.out.print("Type a sample name & then press <Return> : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
RunMethod(br.readLine());
}catch(Exception ex) {
System.out.println(ex.toString());
}
}
private static void ShowMethods()
{
System.out.println(" DecryptVisaCheckoutData");
System.out.println(" CreateVisaCheckoutTransaction");
System.out.println(" ChargeCreditCard");
System.out.println(" AuthorizeCreditCard");
System.out.println(" RefundTransaction");
System.out.println(" VoidTransaction");
System.out.println(" CreateCustomerProfileFromTransaction");
System.out.println(" CaptureFundsAuthorizedThroughAnotherChannel");
System.out.println(" CapturePreviouslyAuthorizedAmount");
System.out.println(" DebitBankAccount");
System.out.println(" CreditBankAccount");
System.out.println(" ChargeTokenizedCreditCard");
System.out.println(" CreateAnApplePayTransaction");
System.out.println(" CreateAnAndroidPayTransaction");
System.out.println(" CreateAnAcceptTransaction");
System.out.println(" ChargeCustomerProfile");
System.out.println(" CreateSubscription");
System.out.println(" CreateSubscriptionFromCustomerProfile");
System.out.println(" GetSubscription");
System.out.println(" GetSubscriptionStatus");
System.out.println(" CancelSubscription");
System.out.println(" UpdateSubscription");
System.out.println(" GetListOfSubscriptions");
System.out.println(" GetBatchStatistics");
System.out.println(" GetSettledBatchList");
System.out.println(" GetTransactionList");
System.out.println(" GetUnsettledTransactionList");
System.out.println(" GetTransactionDetails");
System.out.println(" CreateCustomerProfile");
System.out.println(" CreateCustomerPaymentProfile");
System.out.println(" CreateCustomerShippingAddress");
System.out.println(" DeleteCustomerPaymentProfile");
System.out.println(" DeleteCustomerProfile");
System.out.println(" DeleteCustomerShippingAddress");
System.out.println(" GetCustomerPaymentProfile");
System.out.println(" GetCustomerPaymentProfileList");
System.out.println(" GetCustomerProfile");
System.out.println(" GetCustomerProfileIds");
System.out.println(" GetCustomerProfileTransactionList");
System.out.println(" GetCustomerShippingAddress");
System.out.println(" GetAcceptCustomerProfilePage");
System.out.println(" UpdateCustomerProfile");
System.out.println(" UpdateCustomerPaymentProfile");
System.out.println(" UpdateCustomerShippingAddress");
System.out.println(" ValidateCustomerPaymentProfile");
System.out.println(" PayPalAuthorizeCapture");
System.out.println(" PayPalVoid");
System.out.println(" PayPalAuthorizationOnly");
System.out.println(" PayPalAuthorizeCaptureContinued");
System.out.println(" PayPalGetDetails");
System.out.println(" PayPalPriorAuthorizationCapture");
System.out.println(" PayPalAuthorizeOnlyContinued");
System.out.println(" PayPalCredit");
System.out.println(" UpdateSplitTenderGroup");
System.out.println(" GetMerchantDetails");
System.out.println(" GetHeldTransactionList");
System.out.println(" ApproveOrDeclineHeldTransaction");
System.out.println(" GetAnAcceptPaymentPage");
}
private static void RunMethod(String methodName)
{
// These are default transaction keys.
String apiLoginId = "5KP3u95bQpv";
String transactionKey = "346HZ32z3fP4hTG2";
//Update the payedId with which you want to run the sample code
String payerId = "6ZSCSYG33VP8Q";
//Update the transactionId with which you want to run the sample code
String transactionId = "123456";
String customerProfileId = "36596285";
String customerPaymentProfileId = "33086593";
String customerAddressId = "1873761911";
String emailId = "test@test.com";
String subscriptionId = "2925606";
Double amount = 123.45;
// Proxy server settings.
// Enable these lines for using Sample Codes behind a proxy server
// System.setProperty("https.proxyUse", "true");
// System.setProperty("https.proxyHost", "example.proxy.server");
// System.setProperty("https.proxyPort", "portNumber");
// System.setProperty("https.proxyUserName", "exampleUsername");
// System.setProperty("https.proxyPassword", "examplePassword");
switch (methodName) {
case "DecryptVisaCheckoutData":
DecryptVisaCheckoutData.run(apiLoginId, transactionKey);
break;
case "CreateVisaCheckoutTransaction":
CreateVisaCheckoutTransaction.run(apiLoginId, transactionKey);
break;
case "ChargeCreditCard":
ChargeCreditCard.run(apiLoginId, transactionKey, amount);
break;
case "VoidTransaction":
VoidTransaction.run(apiLoginId, transactionKey, transactionId);
break;
case "AuthorizeCreditCard":
AuthorizeCreditCard.run(apiLoginId, transactionKey, amount);
break;
case "RefundTransaction":
RefundTransaction.run(apiLoginId, transactionKey , amount, transactionId);
break;
case "CreateCustomerProfileFromTransaction":
CreateCustomerProfileFromTransaction.run(apiLoginId, transactionKey, amount, emailId);
break;
case "CaptureFundsAuthorizedThroughAnotherChannel":
CaptureFundsAuthorizedThroughAnotherChannel.run(apiLoginId, transactionKey, amount);
break;
case "CapturePreviouslyAuthorizedAmount":
CapturePreviouslyAuthorizedAmount.run(apiLoginId, transactionKey, transactionId);
break;
case "DebitBankAccount":
DebitBankAccount.run(apiLoginId, transactionKey, amount);
break;
case "CreditBankAccount":
CreditBankAccount.run(apiLoginId, transactionKey, transactionId, amount);
break;
case "ChargeTokenizedCreditCard":
ChargeTokenizedCreditCard.run(apiLoginId, transactionKey, amount);
break;
case "CreateAnApplePayTransaction":
CreateAnApplePayTransaction.run(apiLoginId, transactionKey);
break;
case "CreateAnAndroidPayTransaction":
CreateAnAndroidPayTransaction.run(apiLoginId, transactionKey);
break;
case "CreateAnAcceptTransaction":
CreateAnAcceptTransaction.run(apiLoginId, transactionKey);
break;
case "ChargeCustomerProfile":
ChargeCustomerProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId, amount);
break;
case "ChargeCustomerProfilesMT":
ChargeCustomerProfilesMT.run();
break;
case "CreateSubscription":
CreateSubscription.run(apiLoginId, transactionKey, (short)12, amount);
break;
case "CreateSubscriptionFromCustomerProfile":
CreateSubscriptionFromCustomerProfile.run(apiLoginId, transactionKey, (short)12, amount, customerProfileId, customerPaymentProfileId, customerAddressId);
break;
case "GetSubscription":
GetSubscription.run(apiLoginId, transactionKey, subscriptionId);
break;
case "GetSubscriptionStatus":
GetSubscriptionStatus.run(apiLoginId, transactionKey, subscriptionId);
break;
case "CancelSubscription":
CancelSubscription.run(apiLoginId, transactionKey, subscriptionId);
break;
case "UpdateSubscription":
UpdateSubscription.run(apiLoginId, transactionKey, subscriptionId);
break;
case "GetListOfSubscriptions":
GetListOfSubscriptions.run(apiLoginId, transactionKey);
break;
case "GetBatchStatistics":
GetBatchStatistics.run(apiLoginId, transactionKey);
break;
case "GetSettledBatchList":
GetSettledBatchList.run(apiLoginId, transactionKey);
break;
case "GetTransactionList":
GetTransactionList.run(apiLoginId, transactionKey);
break;
case "GetUnsettledTransactionList":
GetUnsettledTransactionList.run(apiLoginId, transactionKey);
break;
case "GetTransactionDetails":
GetTransactionDetails.run(apiLoginId, transactionKey, transactionId);
break;
case "CreateCustomerProfile":
CreateCustomerProfile.run(apiLoginId, transactionKey, emailId);
break;
case "CreateCustomerPaymentProfile":
CreateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId);
break;
case "CreateCustomerShippingAddress":
CreateCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId);
break;
case "DeleteCustomerPaymentProfile":
DeleteCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "DeleteCustomerProfile":
DeleteCustomerProfile.run(apiLoginId, transactionKey, customerProfileId);
break;
case "DeleteCustomerShippingAddress":
DeleteCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId);
break;
case "GetCustomerPaymentProfile":
GetCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "GetCustomerPaymentProfileList":
GetCustomerPaymentProfileList.run(apiLoginId, transactionKey);
break;
case "GetCustomerProfile":
GetCustomerProfile.run(apiLoginId, transactionKey, customerProfileId);
break;
case "GetCustomerProfileIds":
GetCustomerProfileIds.run(apiLoginId, transactionKey);
break;
case "GetCustomerProfileTransactionList":
customerProfileId = "1811474252";
GetCustomerProfileTransactionList.run(apiLoginId, transactionKey, customerProfileId);
break;
case "GetCustomerShippingAddress":
GetCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId);
break;
case "GetAcceptCustomerProfilePage":
GetAcceptCustomerProfilePage.run(apiLoginId, transactionKey, customerProfileId);
break;
case "UpdateCustomerProfile":
UpdateCustomerProfile.run(apiLoginId, transactionKey, customerProfileId);
break;
case "UpdateCustomerPaymentProfile":
UpdateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "UpdateCustomerShippingAddress":
UpdateCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId);
break;
case "ValidateCustomerPaymentProfile":
ValidateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "PayPalAuthorizeCapture":
AuthorizationAndCapture.run(apiLoginId, transactionKey, amount);
break;
case "PayPalVoid":
Void.run(apiLoginId, transactionKey, transactionId);
break;
case "PayPalAuthorizationOnly":
AuthorizationOnly.run(apiLoginId, transactionKey, amount);
break;
case "PayPalAuthorizeCaptureContinued":
AuthorizationAndCaptureContinued.run(apiLoginId, transactionKey, transactionId, payerId, amount);
break;
case "PayPalAuthorizeOnlyContinued":
AuthorizationOnlyContinued.run(apiLoginId, transactionKey, transactionId, payerId, amount);
break;
case "PayPalCredit":
Credit.run(apiLoginId, transactionKey, transactionId);
break;
case "PayPalGetDetails":
GetDetails.run(apiLoginId, transactionKey, transactionId);
case "PayPalPriorAuthorizationCapture":
PriorAuthorizationCapture.run(apiLoginId, transactionKey, transactionId);
break;
case "UpdateSplitTenderGroup":
UpdateSplitTenderGroup.run(apiLoginId, transactionKey);
break;
case "GetMerchantDetails":
GetMerchantDetails.run(apiLoginId, transactionKey);
break;
case "GetHeldTransactionList":
GetHeldTransactionList.run(apiLoginId, transactionKey);
break;
case "ApproveOrDeclineHeldTransaction":
ApproveOrDeclineHeldTransaction.run(apiLoginId, transactionKey, transactionId);
break;
case "GetAnAcceptPaymentPage":
GetAnAcceptPaymentPage.run(apiLoginId, transactionKey, amount);
break;
default:
ShowUsage();
break;
}
}
} |
package net.jforum.search;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.*;
import net.jforum.dao.AttachmentDAO;
import net.jforum.dao.DataAccessDriver;
import net.jforum.entities.Attachment;
import net.jforum.entities.AttachmentInfo;
import net.jforum.entities.Post;
import net.jforum.exceptions.SearchException;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.xml.sax.ContentHandler;
/**
* @author Rafael Steil
* @version $Id$
*/
public class LuceneIndexer
{
private static final Logger LOGGER = Logger.getLogger(LuceneIndexer.class);
private LuceneSettings settings;
private Directory ramDirectory;
private IndexWriter ramWriter;
private int ramNumDocs;
private List<NewDocumentAdded> newDocumentAddedList = new ArrayList<NewDocumentAdded>();
private boolean indexAttachments = SystemGlobals.getBoolValue(ConfigKeys.LUCENE_INDEX_ATTACHMENTS);
private AttachmentDAO attachDAO;
private String attachDir = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR);
public LuceneIndexer(final LuceneSettings settings)
{
this.settings = settings;
this.createRAMWriter();
this.attachDAO = DataAccessDriver.getInstance().newAttachmentDAO();
}
public void watchNewDocuDocumentAdded(NewDocumentAdded newDoc)
{
this.newDocumentAddedList.add(newDoc);
}
public void batchCreate(final Post post)
{
synchronized (LOGGER) {
try {
final Document document = this.createDocument(post);
this.ramWriter.addDocument(document);
this.flushRAMDirectoryIfNecessary();
}
catch (IOException e) {
throw new SearchException(e);
}
}
}
private void createRAMWriter()
{
try {
if (this.ramWriter != null) {
this.ramWriter.close();
}
this.ramDirectory = new RAMDirectory();
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
this.ramWriter = new IndexWriter(this.ramDirectory, conf);
this.ramNumDocs = SystemGlobals.getIntValue(ConfigKeys.LUCENE_INDEXER_RAM_NUMDOCS);
}
catch (IOException e) {
throw new SearchException(e);
}
}
private void flushRAMDirectoryIfNecessary()
{
if (this.ramWriter.maxDoc() >= this.ramNumDocs) {
this.flushRAMDirectory();
}
}
public void flushRAMDirectory()
{
synchronized (LOGGER) {
IndexWriter writer = null;
try {
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(this.settings.directory(), conf);
this.ramWriter.commit();
this.ramWriter.close();
writer.addIndexes(new Directory[] { this.ramDirectory });
writer.forceMergeDeletes();
this.createRAMWriter();
}
catch (IOException e) {
throw new SearchException(e);
}
finally {
if (writer != null) {
try {
writer.commit();
writer.close();
this.notifyNewDocumentAdded();
}
catch (Exception e) {
LOGGER.error(e.toString(), e);
}
}
}
}
}
public void create(final Post post)
{
synchronized (LOGGER) {
IndexWriter writer = null;
try {
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(this.settings.directory(), conf);
final Document document = this.createDocument(post);
writer.addDocument(document);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Indexed " + document);
}
}
catch (Exception e) {
LOGGER.error(e.toString(), e);
}
finally {
if (writer != null) {
try {
writer.commit();
writer.close();
this.notifyNewDocumentAdded();
}
catch (Exception e) {
LOGGER.error(e.toString(), e);
}
}
}
}
}
public void update(final Post post)
{
if (this.performDelete(post)) {
this.create(post);
}
}
private Document createDocument(final Post post)
{
Document doc = new Document();
doc.add(new Field(SearchFields.Keyword.POST_ID, String.valueOf(post.getId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.FORUM_ID, String.valueOf(post.getForumId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.TOPIC_ID, String.valueOf(post.getTopicId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.USER_ID, String.valueOf(post.getUserId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.DATE, this.settings.formatDateTime(post.getTime()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Indexed.SUBJECT, post.getSubject(), Store.NO, Index.ANALYZED));
doc.add(new Field(SearchFields.Indexed.CONTENTS, post.getText(), Store.NO, Index.ANALYZED));
if (indexAttachments && post.hasAttachments()) {
for (Attachment att : attachDAO.selectAttachments(post.getId())) {
AttachmentInfo info = att.getInfo();
String realFilename = info.getRealFilename();
doc.add(new Field(SearchFields.Indexed.CONTENTS, info.getComment(), Field.Store.NO, Field.Index.ANALYZED));
File f = new File(attachDir + File.separatorChar + info.getPhysicalFilename());
LOGGER.debug("indexing "+f.getName());
InputStream is = null;
try {
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
is = new FileInputStream(f);
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler(-1);
//-1 disables the character size limit; otherwise only the first 100.000 characters are indexed
ParseContext context = new ParseContext();
context.set(Parser.class, parser);
Set textualMetadataFields = new HashSet();
textualMetadataFields.add(TikaCoreProperties.TITLE);
textualMetadataFields.add(TikaCoreProperties.COMMENTS);
textualMetadataFields.add(TikaCoreProperties.KEYWORDS);
textualMetadataFields.add(TikaCoreProperties.DESCRIPTION);
textualMetadataFields.add(TikaCoreProperties.KEYWORDS);
parser.parse(is, handler, metadata, context);
doc.add(new Field(SearchFields.Indexed.CONTENTS, handler.toString(), Field.Store.NO, Field.Index.ANALYZED));
String[] names = metadata.names();
for (int j=0; j<names.length; j++) {
String value = metadata.get(names[j]);
if (textualMetadataFields.contains(names[j])) {
doc.add(new Field(SearchFields.Indexed.CONTENTS, value, Field.Store.NO, Field.Index.ANALYZED));
}
}
} catch (Exception ex) {
LOGGER.info("error indexing "+f.getName()+": " + ex.getMessage());
} finally {
try { is.close(); } catch (Exception e) { /* ignore */ }
}
}
}
return doc;
}
private void notifyNewDocumentAdded()
{
for (Iterator<NewDocumentAdded> iter = this.newDocumentAddedList.iterator(); iter.hasNext(); ) {
iter.next().newDocumentAdded();
}
}
public void delete(final Post post)
{
this.performDelete(post);
}
private boolean performDelete(final Post post)
{
synchronized (LOGGER) {
IndexWriter writer = null;
boolean status = false;
try {
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(this.settings.directory(), conf);
writer.deleteDocuments(new Term(SearchFields.Keyword.POST_ID, String.valueOf(post.getId())));
status = true;
}
catch (IOException e) {
LOGGER.error(e.toString(), e);
}
finally {
if (writer != null) {
try {
writer.commit();
writer.close();
this.flushRAMDirectory();
}
catch (IOException e) {
LOGGER.error(e.toString(), e);
}
}
}
return status;
}
}
} |
package net.sf.jabref;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.*;
import java.util.prefs.BackingStoreException;
import java.util.prefs.InvalidPreferencesFormatException;
import java.util.prefs.Preferences;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.*;
import net.sf.jabref.gui.*;
import net.sf.jabref.gui.actions.CleanUpAction;
import net.sf.jabref.gui.entryeditor.EntryEditorTabList;
import net.sf.jabref.gui.keyboard.KeyBinds;
import net.sf.jabref.gui.preftabs.ImportSettingsTab;
import net.sf.jabref.importer.fileformat.ImportFormat;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.labelPattern.GlobalLabelPattern;
import net.sf.jabref.logic.util.OS;
import net.sf.jabref.model.entry.CustomEntryType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.jabref.exporter.CustomExportList;
import net.sf.jabref.exporter.ExportComparator;
import net.sf.jabref.external.DroppedFileHandler;
import net.sf.jabref.external.ExternalFileType;
import net.sf.jabref.external.UnknownExternalFileType;
import net.sf.jabref.importer.CustomImportList;
import net.sf.jabref.logic.remote.RemotePreferences;
import net.sf.jabref.specialfields.SpecialFieldsUtils;
import net.sf.jabref.logic.util.strings.StringUtil;
public class JabRefPreferences {
private static final Log LOGGER = LogFactory.getLog(JabRefPreferences.class);
/**
* HashMap that contains all preferences which are set by default
*/
public final HashMap<String, Object> defaults = new HashMap<String, Object>();
/* contents of the defaults HashMap that are defined in this class.
* There are more default parameters in this map which belong to separate preference classes.
*/
public static final String EMACS_PATH = "emacsPath";
public static final String EMACS_ADDITIONAL_PARAMETERS = "emacsParameters";
public static final String EMACS_23 = "emacsUseV23InsertString";
public static final String FONT_FAMILY = "fontFamily";
public static final String WIN_LOOK_AND_FEEL = "lookAndFeel";
public static final String LATEX_EDITOR_PATH = "latexEditorPath";
public static final String TEXSTUDIO_PATH = "TeXstudioPath";
public static final String WIN_EDT_PATH = "winEdtPath";
public static final String TEXMAKER_PATH = "texmakerPath";
public static final String LANGUAGE = "language";
public static final String NAMES_LAST_ONLY = "namesLastOnly";
public static final String ABBR_AUTHOR_NAMES = "abbrAuthorNames";
public static final String NAMES_NATBIB = "namesNatbib";
public static final String NAMES_FIRST_LAST = "namesFf";
public static final String NAMES_AS_IS = "namesAsIs";
public static final String TABLE_COLOR_CODES_ON = "tableColorCodesOn";
public static final String ENTRY_EDITOR_HEIGHT = "entryEditorHeight";
public static final String PREVIEW_PANEL_HEIGHT = "previewPanelHeight";
public static final String AUTO_RESIZE_MODE = "autoResizeMode";
public static final String WINDOW_MAXIMISED = "windowMaximised";
public static final String SIZE_Y = "sizeY";
public static final String SIZE_X = "sizeX";
public static final String POS_Y = "posY";
public static final String POS_X = "posX";
public static final String VIM_SERVER = "vimServer";
public static final String VIM = "vim";
public static final String LYXPIPE = "lyxpipe";
public static final String USE_DEFAULT_LOOK_AND_FEEL = "useDefaultLookAndFeel";
public static final String PROXY_PORT = "proxyPort";
public static final String PROXY_HOSTNAME = "proxyHostname";
public static final String USE_PROXY = "useProxy";
public static final String TABLE_PRIMARY_SORT_FIELD = "priSort";
public static final String TABLE_PRIMARY_SORT_DESCENDING = "priDescending";
public static final String TABLE_SECONDARY_SORT_FIELD = "secSort";
public static final String TABLE_SECONDARY_SORT_DESCENDING = "secDescending";
public static final String TABLE_TERTIARY_SORT_FIELD = "terSort";
public static final String TABLE_TERTIARY_SORT_DESCENDING = "terDescending";
public static final String SAVE_IN_ORIGINAL_ORDER = "saveInOriginalOrder";
public static final String SAVE_IN_SPECIFIED_ORDER = "saveInSpecifiedOrder";
public static final String SAVE_PRIMARY_SORT_FIELD = "savePriSort";
public static final String SAVE_PRIMARY_SORT_DESCENDING = "savePriDescending";
public static final String SAVE_SECONDARY_SORT_FIELD = "saveSecSort";
public static final String SAVE_SECONDARY_SORT_DESCENDING = "saveSecDescending";
public static final String SAVE_TERTIARY_SORT_FIELD = "saveTerSort";
public static final String SAVE_TERTIARY_SORT_DESCENDING = "saveTerDescending";
public static final String EXPORT_IN_ORIGINAL_ORDER = "exportInOriginalOrder";
public static final String EXPORT_IN_SPECIFIED_ORDER = "exportInSpecifiedOrder";
public static final String EXPORT_PRIMARY_SORT_FIELD = "exportPriSort";
public static final String EXPORT_PRIMARY_SORT_DESCENDING = "exportPriDescending";
public static final String EXPORT_SECONDARY_SORT_FIELD = "exportSecSort";
public static final String EXPORT_SECONDARY_SORT_DESCENDING = "exportSecDescending";
public static final String EXPORT_TERTIARY_SORT_FIELD = "exportTerSort";
public static final String EXPORT_TERTIARY_SORT_DESCENDING = "exportTerDescending";
public static final String NEWLINE = "newline";
public static final String COLUMN_WIDTHS = "columnWidths";
public static final String COLUMN_NAMES = "columnNames";
public static final String SIDE_PANE_COMPONENT_PREFERRED_POSITIONS = "sidePaneComponentPreferredPositions";
public static final String SIDE_PANE_COMPONENT_NAMES = "sidePaneComponentNames";
public static final String XMP_PRIVACY_FILTERS = "xmpPrivacyFilters";
public static final String USE_XMP_PRIVACY_FILTER = "useXmpPrivacyFilter";
public static final String SEARCH_AUTO_COMPLETE = "searchAutoComplete";
public static final String INCREMENT_S = "incrementS";
public static final String SEARCH_ALL = "searchAll";
public static final String SEARCH_GEN = "searchGen";
public static final String SEARCH_OPT = "searchOpt";
public static final String SEARCH_REQ = "searchReq";
public static final String CASE_SENSITIVE_SEARCH = "caseSensitiveSearch";
public static final String DEFAULT_AUTO_SORT = "defaultAutoSort";
public static final String SHOW_SOURCE = "showSource";
public static final String DEFAULT_SHOW_SOURCE = "defaultShowSource";
public static final String STRINGS_SIZE_Y = "stringsSizeY";
public static final String STRINGS_SIZE_X = "stringsSizeX";
public static final String STRINGS_POS_Y = "stringsPosY";
public static final String STRINGS_POS_X = "stringsPosX";
public static final String LAST_EDITED = "lastEdited";
public static final String OPEN_LAST_EDITED = "openLastEdited";
public static final String BACKUP = "backup";
public static final String ENTRY_TYPE_FORM_WIDTH = "entryTypeFormWidth";
public static final String ENTRY_TYPE_FORM_HEIGHT_FACTOR = "entryTypeFormHeightFactor";
public static final String AUTO_OPEN_FORM = "autoOpenForm";
public static final String FILE_WORKING_DIRECTORY = "fileWorkingDirectory";
public static final String IMPORT_WORKING_DIRECTORY = "importWorkingDirectory";
public static final String EXPORT_WORKING_DIRECTORY = "exportWorkingDirectory";
public static final String WORKING_DIRECTORY = "workingDirectory";
public static final String NUMBER_COL_WIDTH = "numberColWidth";
public static final String SHORTEST_TO_COMPLETE = "shortestToComplete";
public static final String AUTOCOMPLETE_FIRSTNAME_MODE = "autoCompFirstNameMode";
public static final String AUTOCOMPLETE_FIRSTNAME_MODE_BOTH = "both"; // here are the possible values for _MODE:
public static final String AUTO_COMP_LAST_FIRST = "autoCompLF";
public static final String AUTO_COMP_FIRST_LAST = "autoCompFF";
public static final String AUTO_COMPLETE_FIELDS = "autoCompleteFields";
public static final String AUTO_COMPLETE = "autoComplete";
public static final String HIGH_LIGHT_WORDS = "highLightWords";
public static final String REG_EXP_SEARCH = "regExpSearch";
public static final String SELECT_S = "selectS";
public static final String EDITOR_EMACS_KEYBINDINGS = "editorEMACSkeyBindings";
public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CA = "editorEMACSkeyBindingsRebindCA";
public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CF = "editorEMACSkeyBindingsRebindCF";
public static final String GROUP_SHOW_NUMBER_OF_ELEMENTS = "groupShowNumberOfElements";
public static final String GROUP_AUTO_HIDE = "groupAutoHide";
public static final String GROUP_AUTO_SHOW = "groupAutoShow";
public static final String GROUP_EXPAND_TREE = "groupExpandTree";
public static final String GROUP_SHOW_DYNAMIC = "groupShowDynamic";
public static final String GROUP_SHOW_ICONS = "groupShowIcons";
public static final String GROUPS_DEFAULT_FIELD = "groupsDefaultField";
public static final String GROUP_SELECT_MATCHES = "groupSelectMatches";
public static final String GROUP_SHOW_OVERLAPPING = "groupShowOverlapping";
public static final String GROUP_INVERT_SELECTIONS = "groupInvertSelections";
public static final String GROUP_INTERSECT_SELECTIONS = "groupIntersectSelections";
public static final String GROUP_FLOAT_SELECTIONS = "groupFloatSelections";
public static final String EDIT_GROUP_MEMBERSHIP_MODE = "groupEditGroupMembershipMode";
public static final String GROUP_KEYWORD_SEPARATOR = "groupKeywordSeparator";
public static final String AUTO_ASSIGN_GROUP = "autoAssignGroup";
public static final String LIST_OF_FILE_COLUMNS = "listOfFileColumns";
public static final String EXTRA_FILE_COLUMNS = "extraFileColumns";
public static final String ARXIV_COLUMN = "arxivColumn";
public static final String FILE_COLUMN = "fileColumn";
public static final String PREFER_URL_DOI = "preferUrlDoi";
public static final String URL_COLUMN = "urlColumn";
public static final String PDF_COLUMN = "pdfColumn";
public static final String DISABLE_ON_MULTIPLE_SELECTION = "disableOnMultipleSelection";
public static final String CTRL_CLICK = "ctrlClick";
public static final String INCOMPLETE_ENTRY_BACKGROUND = "incompleteEntryBackground";
public static final String FIELD_EDITOR_TEXT_COLOR = "fieldEditorTextColor";
public static final String ACTIVE_FIELD_EDITOR_BACKGROUND_COLOR = "activeFieldEditorBackgroundColor";
public static final String INVALID_FIELD_BACKGROUND_COLOR = "invalidFieldBackgroundColor";
public static final String VALID_FIELD_BACKGROUND_COLOR = "validFieldBackgroundColor";
public static final String MARKED_ENTRY_BACKGROUND5 = "markedEntryBackground5";
public static final String MARKED_ENTRY_BACKGROUND4 = "markedEntryBackground4";
public static final String MARKED_ENTRY_BACKGROUND3 = "markedEntryBackground3";
public static final String MARKED_ENTRY_BACKGROUND2 = "markedEntryBackground2";
public static final String MARKED_ENTRY_BACKGROUND1 = "markedEntryBackground1";
public static final String MARKED_ENTRY_BACKGROUND0 = "markedEntryBackground0";
public static final String VERY_GRAYED_OUT_TEXT = "veryGrayedOutText";
public static final String VERY_GRAYED_OUT_BACKGROUND = "veryGrayedOutBackground";
public static final String GRAYED_OUT_TEXT = "grayedOutText";
public static final String GRAYED_OUT_BACKGROUND = "grayedOutBackground";
public static final String GRID_COLOR = "gridColor";
public static final String TABLE_TEXT = "tableText";
public static final String TABLE_OPT_FIELD_BACKGROUND = "tableOptFieldBackground";
public static final String TABLE_REQ_FIELD_BACKGROUND = "tableReqFieldBackground";
public static final String TABLE_BACKGROUND = "tableBackground";
public static final String TABLE_SHOW_GRID = "tableShowGrid";
public static final String TABLE_ROW_PADDING = "tableRowPadding";
public static final String MENU_FONT_SIZE = "menuFontSize";
public static final String MENU_FONT_STYLE = "menuFontStyle";
public static final String MENU_FONT_FAMILY = "menuFontFamily";
public static final String OVERRIDE_DEFAULT_FONTS = "overrideDefaultFonts";
public static final String FONT_SIZE = "fontSize";
public static final String FONT_STYLE = "fontStyle";
public static final String HISTORY_SIZE = "historySize";
public static final String GENERAL_FIELDS = "generalFields";
public static final String RENAME_ON_MOVE_FILE_TO_FILE_DIR = "renameOnMoveFileToFileDir";
public static final String MEMORY_STICK_MODE = "memoryStickMode";
public static final String PRESERVE_FIELD_FORMATTING = "preserveFieldFormatting";
public static final String DEFAULT_OWNER = "defaultOwner";
public static final String GROUPS_VISIBLE_ROWS = "groupsVisibleRows";
public static final String DEFAULT_ENCODING = "defaultEncoding";
public static final String SEARCH_PANEL_VISIBLE = "searchPanelVisible";
public static final String TOOLBAR_VISIBLE = "toolbarVisible";
public static final String HIGHLIGHT_GROUPS_MATCHING_ALL = "highlightGroupsMatchingAll";
public static final String HIGHLIGHT_GROUPS_MATCHING_ANY = "highlightGroupsMatchingAny";
public static final String SHOW_ONE_LETTER_HEADING_FOR_ICON_COLUMNS = "showOneLetterHeadingForIconColumns";
public static final String UPDATE_TIMESTAMP = "updateTimestamp";
public static final String TIME_STAMP_FIELD = "timeStampField";
public static final String TIME_STAMP_FORMAT = "timeStampFormat";
public static final String OVERWRITE_TIME_STAMP = "overwriteTimeStamp";
public static final String USE_TIME_STAMP = "useTimeStamp";
public static final String WARN_ABOUT_DUPLICATES_IN_INSPECTION = "warnAboutDuplicatesInInspection";
public static final String UNMARK_ALL_ENTRIES_BEFORE_IMPORTING = "unmarkAllEntriesBeforeImporting";
public static final String MARK_IMPORTED_ENTRIES = "markImportedEntries";
public static final String GENERATE_KEYS_AFTER_INSPECTION = "generateKeysAfterInspection";
public static final String USE_IMPORT_INSPECTION_DIALOG_FOR_SINGLE = "useImportInspectionDialogForSingle";
public static final String USE_IMPORT_INSPECTION_DIALOG = "useImportInspectionDialog";
public static final String NON_WRAPPABLE_FIELDS = "nonWrappableFields";
public static final String PUT_BRACES_AROUND_CAPITALS = "putBracesAroundCapitals";
public static final String RESOLVE_STRINGS_ALL_FIELDS = "resolveStringsAllFields";
public static final String DO_NOT_RESOLVE_STRINGS_FOR = "doNotResolveStringsFor";
public static final String AUTO_DOUBLE_BRACES = "autoDoubleBraces";
public static final String PREVIEW_PRINT_BUTTON = "previewPrintButton";
public static final String PREVIEW_1 = "preview1";
public static final String PREVIEW_0 = "preview0";
public static final String ACTIVE_PREVIEW = "activePreview";
public static final String PREVIEW_ENABLED = "previewEnabled";
// Currently, it is not possible to specify defaults for specific entry types
// When this should be made possible, the code to inspect is net.sf.jabref.gui.preftabs.LabelPatternPrefTab.storeSettings() -> LabelPattern keypatterns = getLabelPattern(); etc
public static final String DEFAULT_LABEL_PATTERN = "defaultLabelPattern";
public static final String SEARCH_ALL_BASES = "searchAllBases";
public static final String SHOW_SEARCH_IN_DIALOG = "showSearchInDialog";
public static final String FLOAT_SEARCH = "floatSearch";
public static final String GRAY_OUT_NON_HITS = "grayOutNonHits";
public static final String CONFIRM_DELETE = "confirmDelete";
public static final String WARN_BEFORE_OVERWRITING_KEY = "warnBeforeOverwritingKey";
public static final String AVOID_OVERWRITING_KEY = "avoidOverwritingKey";
public static final String DISPLAY_KEY_WARNING_DIALOG_AT_STARTUP = "displayKeyWarningDialogAtStartup";
public static final String DIALOG_WARNING_FOR_EMPTY_KEY = "dialogWarningForEmptyKey";
public static final String DIALOG_WARNING_FOR_DUPLICATE_KEY = "dialogWarningForDuplicateKey";
public static final String ALLOW_TABLE_EDITING = "allowTableEditing";
public static final String OVERWRITE_OWNER = "overwriteOwner";
public static final String USE_OWNER = "useOwner";
public static final String WRITEFIELD_ADDSPACES = "writeFieldAddSpaces";
public static final String WRITEFIELD_CAMELCASENAME = "writeFieldCamelCase";
public static final String WRITEFIELD_SORTSTYLE = "writefieldSortStyle";
public static final String WRITEFIELD_USERDEFINEDORDER = "writefieldUserdefinedOrder";
public static final String WRITEFIELD_WRAPFIELD = "wrapFieldLine";
public static final String AUTOLINK_EXACT_KEY_ONLY = "autolinkExactKeyOnly";
public static final String SHOW_FILE_LINKS_UPGRADE_WARNING = "showFileLinksUpgradeWarning";
public static final String SEARCH_DIALOG_HEIGHT = "searchDialogHeight";
public static final String SEARCH_DIALOG_WIDTH = "searchDialogWidth";
public static final String IMPORT_INSPECTION_DIALOG_HEIGHT = "importInspectionDialogHeight";
public static final String IMPORT_INSPECTION_DIALOG_WIDTH = "importInspectionDialogWidth";
public static final String SIDE_PANE_WIDTH = "sidePaneWidth";
public static final String LAST_USED_EXPORT = "lastUsedExport";
public static final String FILECHOOSER_DISABLE_RENAME = "filechooserDisableRename";
public static final String USE_NATIVE_FILE_DIALOG_ON_MAC = "useNativeFileDialogOnMac";
public static final String FLOAT_MARKED_ENTRIES = "floatMarkedEntries";
public static final String CITE_COMMAND = "citeCommand";
public static final String EXTERNAL_JOURNAL_LISTS = "externalJournalLists";
public static final String PERSONAL_JOURNAL_LIST = "personalJournalList";
public static final String GENERATE_KEYS_BEFORE_SAVING = "generateKeysBeforeSaving";
public static final String EMAIL_SUBJECT = "emailSubject";
public static final String OPEN_FOLDERS_OF_ATTACHED_FILES = "openFoldersOfAttachedFiles";
public static final String KEY_GEN_ALWAYS_ADD_LETTER = "keyGenAlwaysAddLetter";
public static final String KEY_GEN_FIRST_LETTER_A = "keyGenFirstLetterA";
public static final String INCLUDE_EMPTY_FIELDS = "includeEmptyFields";
public static final String VALUE_DELIMITERS2 = "valueDelimiters";
public static final String BIBLATEX_MODE = "biblatexMode";
public static final String ENFORCE_LEGAL_BIBTEX_KEY = "enforceLegalBibtexKey";
public static final String PROMPT_BEFORE_USING_AUTOSAVE = "promptBeforeUsingAutosave";
public static final String AUTO_SAVE_INTERVAL = "autoSaveInterval";
public static final String AUTO_SAVE = "autoSave";
public static final String USE_LOCK_FILES = "useLockFiles";
public static final String RUN_AUTOMATIC_FILE_SEARCH = "runAutomaticFileSearch";
public static final String NUMERIC_FIELDS = "numericFields";
public static final String DEFAULT_REG_EXP_SEARCH_EXPRESSION_KEY = "defaultRegExpSearchExpression";
public static final String REG_EXP_SEARCH_EXPRESSION_KEY = "regExpSearchExpression";
public static final String AUTOLINK_USE_REG_EXP_SEARCH_KEY = "useRegExpSearch";
public static final String DB_CONNECT_USERNAME = "dbConnectUsername";
public static final String DB_CONNECT_DATABASE = "dbConnectDatabase";
public static final String DB_CONNECT_HOSTNAME = "dbConnectHostname";
public static final String DB_CONNECT_SERVER_TYPE = "dbConnectServerType";
public static final String BIB_LOC_AS_PRIMARY_DIR = "bibLocAsPrimaryDir";
public static final String BIB_LOCATION_AS_FILE_DIR = "bibLocationAsFileDir";
public static final String SELECTED_FETCHER_INDEX = "selectedFetcherIndex";
public static final String WEB_SEARCH_VISIBLE = "webSearchVisible";
public static final String ALLOW_FILE_AUTO_OPEN_BROWSE = "allowFileAutoOpenBrowse";
public static final String CUSTOM_TAB_NAME = "customTabName_";
public static final String CUSTOM_TAB_FIELDS = "customTabFields_";
public static final String USER_FILE_DIR_INDIVIDUAL = "userFileDirIndividual";
public static final String USER_FILE_DIR_IND_LEGACY = "userFileDirInd_Legacy";
public static final String USER_FILE_DIR = "userFileDir";
public static final String USE_UNIT_FORMATTER_ON_SEARCH = "useUnitFormatterOnSearch";
public static final String USE_CASE_KEEPER_ON_SEARCH = "useCaseKeeperOnSearch";
public static final String USE_CONVERT_TO_EQUATION = "useConvertToEquation";
public static final String USE_IEEE_ABRV = "useIEEEAbrv";
//non-default preferences
private static final String CUSTOM_TYPE_NAME = "customTypeName_";
private static final String CUSTOM_TYPE_REQ = "customTypeReq_";
private static final String CUSTOM_TYPE_OPT = "customTypeOpt_";
private static final String CUSTOM_TYPE_PRIOPT = "customTypePriOpt_";
public static final String PDF_PREVIEW = "pdfPreview";
public static final String AUTOCOMPLETE_FIRSTNAME_MODE_ONLY_FULL = "fullOnly";
public static final String AUTOCOMPLETE_FIRSTNAME_MODE_ONLY_ABBR = "abbrOnly";
// This String is used in the encoded list in prefs of external file type
// modifications, in order to indicate a removed default file type:
private static final String FILE_TYPE_REMOVED_FLAG = "REMOVED";
private static final char[][] VALUE_DELIMITERS = new char[][] { {'"', '"'}, {'{', '}'}};
public String WRAPPED_USERNAME;
public final String MARKING_WITH_NUMBER_PATTERN;
private int SHORTCUT_MASK = -1;
private final Preferences prefs;
private KeyBinds keyBinds = new KeyBinds();
private KeyBinds defaultKeyBinds = new KeyBinds();
private final HashSet<String> putBracesAroundCapitalsFields = new HashSet<String>(4);
private final HashSet<String> nonWrappableFields = new HashSet<String>(5);
private static GlobalLabelPattern keyPattern;
// Object containing custom export formats:
public final CustomExportList customExports;
/**
* Set with all custom {@link ImportFormat}s
*/
public final CustomImportList customImports;
// Object containing info about customized entry editor tabs.
private EntryEditorTabList tabList;
// Map containing all registered external file types:
private final TreeSet<ExternalFileType> externalFileTypes = new TreeSet<ExternalFileType>();
private final ExternalFileType HTML_FALLBACK_TYPE = new ExternalFileType("URL", "html", "text/html", "", "www", IconTheme.getImage("www"));
// The following field is used as a global variable during the export of a database.
// By setting this field to the path of the database's default file directory, formatters
// that should resolve external file paths can access this field. This is an ugly hack
// to solve the problem of formatters not having access to any context except for the
// string to be formatted and possible formatter arguments.
public String[] fileDirForDatabase;
// Similarly to the previous variable, this is a global that can be used during
// the export of a database if the database filename should be output. If a database
// is tied to a file on disk, this variable is set to that file before export starts:
public File databaseFile;
// The following field is used as a global variable during the export of a database.
// It is used to hold custom name formatters defined by a custom export filter.
// It is set before the export starts:
public HashMap<String, String> customExportNameFormatters;
// The only instance of this class:
private static JabRefPreferences singleton;
public static JabRefPreferences getInstance() {
if (JabRefPreferences.singleton == null) {
JabRefPreferences.singleton = new JabRefPreferences();
}
return JabRefPreferences.singleton;
}
// The constructor is made private to enforce this as a singleton class:
private JabRefPreferences() {
try {
if (new File("jabref.xml").exists()) {
importPreferences("jabref.xml");
}
} catch (IOException e) {
LOGGER.info("Could not import preferences from jabref.xml:" + e.getLocalizedMessage(), e);
}
// load user preferences
prefs = Preferences.userNodeForPackage(JabRef.class);
defaults.put(TEXMAKER_PATH, OS.guessProgramPath("texmaker", "Texmaker"));
defaults.put(WIN_EDT_PATH, OS.guessProgramPath("WinEdt", "WinEdt Team\\WinEdt"));
defaults.put(LATEX_EDITOR_PATH, OS.guessProgramPath("LEd", "LEd"));
defaults.put(TEXSTUDIO_PATH, OS.guessProgramPath("texstudio", "TeXstudio"));
if (OS.OS_X) {
//defaults.put("pdfviewer", "/Applications/Preview.app");
//defaults.put("psviewer", "/Applications/Preview.app");
//defaults.put("htmlviewer", "/Applications/Safari.app");
defaults.put(EMACS_PATH, "emacsclient");
defaults.put(EMACS_23, true);
defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-n -e");
defaults.put(FONT_FAMILY, "SansSerif");
defaults.put(WIN_LOOK_AND_FEEL, UIManager.getSystemLookAndFeelClassName());
} else if (OS.WINDOWS) {
//defaults.put("pdfviewer", "cmd.exe /c start /b");
//defaults.put("psviewer", "cmd.exe /c start /b");
//defaults.put("htmlviewer", "cmd.exe /c start /b");
defaults.put(WIN_LOOK_AND_FEEL, "com.jgoodies.looks.windows.WindowsLookAndFeel");
defaults.put(EMACS_PATH, "emacsclient.exe");
defaults.put(EMACS_23, true);
defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-n -e");
defaults.put(FONT_FAMILY, "Arial");
} else {
//defaults.put("pdfviewer", "evince");
//defaults.put("psviewer", "gv");
//defaults.put("htmlviewer", "firefox");
defaults.put(WIN_LOOK_AND_FEEL, "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
defaults.put(FONT_FAMILY, "SansSerif");
// linux
defaults.put(EMACS_PATH, "gnuclient");
defaults.put(EMACS_23, false);
defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-batch -eval");
}
defaults.put(USE_PROXY, Boolean.FALSE);
defaults.put(PROXY_HOSTNAME, "my proxy host");
defaults.put(PROXY_PORT, "my proxy port");
defaults.put(PDF_PREVIEW, Boolean.FALSE);
defaults.put(USE_DEFAULT_LOOK_AND_FEEL, Boolean.TRUE);
defaults.put(LYXPIPE, System.getProperty("user.home") + File.separator + ".lyx/lyxpipe");
defaults.put(VIM, "vim");
defaults.put(VIM_SERVER, "vim");
defaults.put(POS_X, 0);
defaults.put(POS_Y, 0);
defaults.put(SIZE_X, 840);
defaults.put(SIZE_Y, 680);
defaults.put(WINDOW_MAXIMISED, Boolean.FALSE);
defaults.put(AUTO_RESIZE_MODE, JTable.AUTO_RESIZE_ALL_COLUMNS);
defaults.put(PREVIEW_PANEL_HEIGHT, 200);
defaults.put(ENTRY_EDITOR_HEIGHT, 400);
defaults.put(TABLE_COLOR_CODES_ON, Boolean.FALSE);
defaults.put(NAMES_AS_IS, Boolean.FALSE); // "Show names unchanged"
defaults.put(NAMES_FIRST_LAST, Boolean.FALSE); // "Show 'Firstname Lastname'"
defaults.put(NAMES_NATBIB, Boolean.TRUE); // "Natbib style"
defaults.put(ABBR_AUTHOR_NAMES, Boolean.TRUE); // "Abbreviate names"
defaults.put(NAMES_LAST_ONLY, Boolean.TRUE); // "Show last names only"
// system locale as default
defaults.put(LANGUAGE, Locale.getDefault().getLanguage());
// Sorting preferences
defaults.put(TABLE_PRIMARY_SORT_FIELD, "author");
defaults.put(TABLE_PRIMARY_SORT_DESCENDING, Boolean.FALSE);
defaults.put(TABLE_SECONDARY_SORT_FIELD, "year");
defaults.put(TABLE_SECONDARY_SORT_DESCENDING, Boolean.TRUE);
defaults.put(TABLE_TERTIARY_SORT_FIELD, "title");
defaults.put(TABLE_TERTIARY_SORT_DESCENDING, Boolean.FALSE);
// if both are false, then the entries are saved in table order
defaults.put(SAVE_IN_ORIGINAL_ORDER, Boolean.FALSE);
defaults.put(SAVE_IN_SPECIFIED_ORDER, Boolean.TRUE);
// save order: if SAVE_IN_SPECIFIED_ORDER, then use following criteria
defaults.put(SAVE_PRIMARY_SORT_FIELD, "bibtexkey");
defaults.put(SAVE_PRIMARY_SORT_DESCENDING, Boolean.FALSE);
defaults.put(SAVE_SECONDARY_SORT_FIELD, "author");
defaults.put(SAVE_SECONDARY_SORT_DESCENDING, Boolean.FALSE);
defaults.put(SAVE_TERTIARY_SORT_FIELD, "title");
defaults.put(SAVE_TERTIARY_SORT_DESCENDING, Boolean.FALSE);
// export order
defaults.put(EXPORT_IN_ORIGINAL_ORDER, Boolean.FALSE);
defaults.put(EXPORT_IN_SPECIFIED_ORDER, Boolean.FALSE);
// export order: if EXPORT_IN_SPECIFIED_ORDER, then use following criteria
defaults.put(EXPORT_PRIMARY_SORT_FIELD, "bibtexkey");
defaults.put(EXPORT_PRIMARY_SORT_DESCENDING, Boolean.FALSE);
defaults.put(EXPORT_SECONDARY_SORT_FIELD, "author");
defaults.put(EXPORT_SECONDARY_SORT_DESCENDING, Boolean.FALSE);
defaults.put(EXPORT_TERTIARY_SORT_FIELD, "title");
defaults.put(EXPORT_TERTIARY_SORT_DESCENDING, Boolean.TRUE);
defaults.put(NEWLINE, System.lineSeparator());
defaults.put(SIDE_PANE_COMPONENT_NAMES, "");
defaults.put(SIDE_PANE_COMPONENT_PREFERRED_POSITIONS, "");
defaults.put(COLUMN_NAMES, "entrytype;author;title;year;journal;bibtexkey");
defaults.put(COLUMN_WIDTHS, "75;300;470;60;130;100");
defaults.put(PersistenceTableColumnListener.ACTIVATE_PREF_KEY,
PersistenceTableColumnListener.DEFAULT_ENABLED);
defaults.put(XMP_PRIVACY_FILTERS, "pdf;timestamp;keywords;owner;note;review");
defaults.put(USE_XMP_PRIVACY_FILTER, Boolean.FALSE);
defaults.put(NUMBER_COL_WIDTH, GUIGlobals.NUMBER_COL_LENGTH);
defaults.put(WORKING_DIRECTORY, System.getProperty("user.home"));
defaults.put(EXPORT_WORKING_DIRECTORY, System.getProperty("user.home"));
defaults.put(IMPORT_WORKING_DIRECTORY, System.getProperty("user.home"));
defaults.put(FILE_WORKING_DIRECTORY, System.getProperty("user.home"));
defaults.put(AUTO_OPEN_FORM, Boolean.TRUE);
defaults.put(ENTRY_TYPE_FORM_HEIGHT_FACTOR, 1);
defaults.put(ENTRY_TYPE_FORM_WIDTH, 1);
defaults.put(BACKUP, Boolean.TRUE);
defaults.put(OPEN_LAST_EDITED, Boolean.TRUE);
defaults.put(LAST_EDITED, null);
defaults.put(STRINGS_POS_X, 0);
defaults.put(STRINGS_POS_Y, 0);
defaults.put(STRINGS_SIZE_X, 600);
defaults.put(STRINGS_SIZE_Y, 400);
defaults.put(DEFAULT_SHOW_SOURCE, Boolean.FALSE);
defaults.put(SHOW_SOURCE, Boolean.TRUE);
defaults.put(DEFAULT_AUTO_SORT, Boolean.FALSE);
defaults.put(CASE_SENSITIVE_SEARCH, Boolean.FALSE);
defaults.put(SEARCH_REQ, Boolean.TRUE);
defaults.put(SEARCH_OPT, Boolean.TRUE);
defaults.put(SEARCH_GEN, Boolean.TRUE);
defaults.put(SEARCH_ALL, Boolean.FALSE);
defaults.put(INCREMENT_S, Boolean.FALSE);
defaults.put(SEARCH_AUTO_COMPLETE, Boolean.TRUE);
defaults.put(SELECT_S, Boolean.FALSE);
defaults.put(REG_EXP_SEARCH, Boolean.TRUE);
defaults.put(HIGH_LIGHT_WORDS, Boolean.TRUE);
defaults.put(EDITOR_EMACS_KEYBINDINGS, Boolean.FALSE);
defaults.put(EDITOR_EMACS_KEYBINDINGS_REBIND_CA, Boolean.TRUE);
defaults.put(EDITOR_EMACS_KEYBINDINGS_REBIND_CF, Boolean.TRUE);
defaults.put(AUTO_COMPLETE, Boolean.TRUE);
defaults.put(AUTO_COMPLETE_FIELDS, "author;editor;title;journal;publisher;keywords;crossref");
defaults.put(AUTO_COMP_FIRST_LAST, Boolean.FALSE); // "Autocomplete names in 'Firstname Lastname' format only"
defaults.put(AUTO_COMP_LAST_FIRST, Boolean.FALSE); // "Autocomplete names in 'Lastname, Firstname' format only"
defaults.put(SHORTEST_TO_COMPLETE, 2);
defaults.put(AUTOCOMPLETE_FIRSTNAME_MODE, JabRefPreferences.AUTOCOMPLETE_FIRSTNAME_MODE_BOTH);
defaults.put(GROUP_FLOAT_SELECTIONS, Boolean.TRUE);
defaults.put(GROUP_INTERSECT_SELECTIONS, Boolean.TRUE);
defaults.put(GROUP_INVERT_SELECTIONS, Boolean.FALSE);
defaults.put(GROUP_SHOW_OVERLAPPING, Boolean.FALSE);
defaults.put(GROUP_SELECT_MATCHES, Boolean.FALSE);
defaults.put(GROUPS_DEFAULT_FIELD, "keywords");
defaults.put(GROUP_SHOW_ICONS, Boolean.TRUE);
defaults.put(GROUP_SHOW_DYNAMIC, Boolean.TRUE);
defaults.put(GROUP_EXPAND_TREE, Boolean.TRUE);
defaults.put(GROUP_AUTO_SHOW, Boolean.TRUE);
defaults.put(GROUP_AUTO_HIDE, Boolean.TRUE);
defaults.put(GROUP_SHOW_NUMBER_OF_ELEMENTS, Boolean.FALSE);
defaults.put(AUTO_ASSIGN_GROUP, Boolean.TRUE);
defaults.put(GROUP_KEYWORD_SEPARATOR, ", ");
defaults.put(EDIT_GROUP_MEMBERSHIP_MODE, Boolean.FALSE);
defaults.put(HIGHLIGHT_GROUPS_MATCHING_ANY, Boolean.FALSE);
defaults.put(HIGHLIGHT_GROUPS_MATCHING_ALL, Boolean.FALSE);
defaults.put(TOOLBAR_VISIBLE, Boolean.TRUE);
defaults.put(SEARCH_PANEL_VISIBLE, Boolean.FALSE);
defaults.put(DEFAULT_ENCODING, "UTF-8");
defaults.put(GROUPS_VISIBLE_ROWS, 8);
defaults.put(DEFAULT_OWNER, System.getProperty("user.name"));
defaults.put(PRESERVE_FIELD_FORMATTING, Boolean.FALSE);
defaults.put(MEMORY_STICK_MODE, Boolean.FALSE);
defaults.put(RENAME_ON_MOVE_FILE_TO_FILE_DIR, Boolean.TRUE);
// The general fields stuff is made obsolete by the CUSTOM_TAB_... entries.
defaults.put(GENERAL_FIELDS, "crossref;keywords;file;doi;url;urldate;"
+ "pdf;comment;owner");
defaults.put(HISTORY_SIZE, 8);
defaults.put(FONT_STYLE, java.awt.Font.PLAIN);
defaults.put(FONT_SIZE, 12);
defaults.put(OVERRIDE_DEFAULT_FONTS, Boolean.FALSE);
defaults.put(MENU_FONT_FAMILY, "Times");
defaults.put(MENU_FONT_STYLE, java.awt.Font.PLAIN);
defaults.put(MENU_FONT_SIZE, 11);
defaults.put(TABLE_ROW_PADDING, GUIGlobals.TABLE_ROW_PADDING);
defaults.put(TABLE_SHOW_GRID, Boolean.FALSE);
// Main table color settings:
defaults.put(TABLE_BACKGROUND, "255:255:255");
defaults.put(TABLE_REQ_FIELD_BACKGROUND, "230:235:255");
defaults.put(TABLE_OPT_FIELD_BACKGROUND, "230:255:230");
defaults.put(TABLE_TEXT, "0:0:0");
defaults.put(GRID_COLOR, "210:210:210");
defaults.put(GRAYED_OUT_BACKGROUND, "210:210:210");
defaults.put(GRAYED_OUT_TEXT, "40:40:40");
defaults.put(VERY_GRAYED_OUT_BACKGROUND, "180:180:180");
defaults.put(VERY_GRAYED_OUT_TEXT, "40:40:40");
defaults.put(MARKED_ENTRY_BACKGROUND0, "255:255:180");
defaults.put(MARKED_ENTRY_BACKGROUND1, "255:220:180");
defaults.put(MARKED_ENTRY_BACKGROUND2, "255:180:160");
defaults.put(MARKED_ENTRY_BACKGROUND3, "255:120:120");
defaults.put(MARKED_ENTRY_BACKGROUND4, "255:75:75");
defaults.put(MARKED_ENTRY_BACKGROUND5, "220:255:220");
defaults.put(VALID_FIELD_BACKGROUND_COLOR, "255:255:255");
defaults.put(INVALID_FIELD_BACKGROUND_COLOR, "255:0:0");
defaults.put(ACTIVE_FIELD_EDITOR_BACKGROUND_COLOR, "220:220:255");
defaults.put(FIELD_EDITOR_TEXT_COLOR, "0:0:0");
defaults.put(INCOMPLETE_ENTRY_BACKGROUND, "250:175:175");
defaults.put(CTRL_CLICK, Boolean.FALSE);
defaults.put(DISABLE_ON_MULTIPLE_SELECTION, Boolean.FALSE);
defaults.put(PDF_COLUMN, Boolean.FALSE);
defaults.put(URL_COLUMN, Boolean.TRUE);
defaults.put(PREFER_URL_DOI, Boolean.FALSE);
defaults.put(FILE_COLUMN, Boolean.TRUE);
defaults.put(ARXIV_COLUMN, Boolean.FALSE);
defaults.put(EXTRA_FILE_COLUMNS, Boolean.FALSE);
defaults.put(LIST_OF_FILE_COLUMNS, "");
defaults.put(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED, SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY, SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY, SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING, SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE, SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED, SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ, SpecialFieldsUtils.PREF_SHOWCOLUMN_READ_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS, SpecialFieldsUtils.PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS_DEFAULT);
defaults.put(SpecialFieldsUtils.PREF_SERIALIZESPECIALFIELDS, SpecialFieldsUtils.PREF_SERIALIZESPECIALFIELDS_DEFAULT);
defaults.put(SHOW_ONE_LETTER_HEADING_FOR_ICON_COLUMNS, Boolean.FALSE);
defaults.put(USE_OWNER, Boolean.FALSE);
defaults.put(OVERWRITE_OWNER, Boolean.FALSE);
defaults.put(ALLOW_TABLE_EDITING, Boolean.FALSE);
defaults.put(DIALOG_WARNING_FOR_DUPLICATE_KEY, Boolean.TRUE);
defaults.put(DIALOG_WARNING_FOR_EMPTY_KEY, Boolean.TRUE);
defaults.put(DISPLAY_KEY_WARNING_DIALOG_AT_STARTUP, Boolean.TRUE);
defaults.put(AVOID_OVERWRITING_KEY, Boolean.FALSE);
defaults.put(WARN_BEFORE_OVERWRITING_KEY, Boolean.TRUE);
defaults.put(CONFIRM_DELETE, Boolean.TRUE);
defaults.put(GRAY_OUT_NON_HITS, Boolean.TRUE);
defaults.put(FLOAT_SEARCH, Boolean.TRUE);
defaults.put(SHOW_SEARCH_IN_DIALOG, Boolean.FALSE);
defaults.put(SEARCH_ALL_BASES, Boolean.FALSE);
defaults.put(DEFAULT_LABEL_PATTERN, "[authors3][year]");
defaults.put(PREVIEW_ENABLED, Boolean.TRUE);
defaults.put(ACTIVE_PREVIEW, 0);
defaults.put(PREVIEW_0, "<font face=\"arial\">"
+ "<b><i>\\bibtextype</i><a name=\"\\bibtexkey\">\\begin{bibtexkey} (\\bibtexkey)</a>"
+ "\\end{bibtexkey}</b><br>__NEWLINE__"
+ "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}<BR>\\end{author}__NEWLINE__"
+ "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} "
+ "<i>(\\format[IfPlural(Eds.,Ed.)]{\\editor})</i><BR>\\end{editor}__NEWLINE__"
+ "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}<BR>__NEWLINE__"
+ "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}__NEWLINE__"
+ "\\begin{journal} <em>\\format[HTMLChars]{\\journal}, </em>\\end{journal}__NEWLINE__"
// Include the booktitle field for @inproceedings, @proceedings, etc.
+ "\\begin{booktitle} <em>\\format[HTMLChars]{\\booktitle}, </em>\\end{booktitle}__NEWLINE__"
+ "\\begin{school} <em>\\format[HTMLChars]{\\school}, </em>\\end{school}__NEWLINE__"
+ "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__"
+ "\\begin{publisher} <em>\\format[HTMLChars]{\\publisher}, </em>\\end{publisher}__NEWLINE__"
+ "\\begin{year}<b>\\year</b>\\end{year}\\begin{volume}<i>, \\volume</i>\\end{volume}"
+ "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}__NEWLINE__"
+ "\\begin{abstract}<BR><BR><b>Abstract: </b> \\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__"
+ "\\begin{review}<BR><BR><b>Review: </b> \\format[HTMLChars]{\\review} \\end{review}"
+ "</dd>__NEWLINE__<p></p></font>");
defaults.put(PREVIEW_1, "<font face=\"arial\">"
+ "<b><i>\\bibtextype</i><a name=\"\\bibtexkey\">\\begin{bibtexkey} (\\bibtexkey)</a>"
+ "\\end{bibtexkey}</b><br>__NEWLINE__"
+ "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}<BR>\\end{author}__NEWLINE__"
+ "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} "
+ "<i>(\\format[IfPlural(Eds.,Ed.)]{\\editor})</i><BR>\\end{editor}__NEWLINE__"
+ "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}<BR>__NEWLINE__"
+ "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}__NEWLINE__"
+ "\\begin{journal} <em>\\format[HTMLChars]{\\journal}, </em>\\end{journal}__NEWLINE__"
// Include the booktitle field for @inproceedings, @proceedings, etc.
+ "\\begin{booktitle} <em>\\format[HTMLChars]{\\booktitle}, </em>\\end{booktitle}__NEWLINE__"
+ "\\begin{school} <em>\\format[HTMLChars]{\\school}, </em>\\end{school}__NEWLINE__"
+ "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__"
+ "\\begin{publisher} <em>\\format[HTMLChars]{\\publisher}, </em>\\end{publisher}__NEWLINE__"
+ "\\begin{year}<b>\\year</b>\\end{year}\\begin{volume}<i>, \\volume</i>\\end{volume}"
+ "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}"
+ "</dd>__NEWLINE__<p></p></font>");
// TODO: Currently not possible to edit this setting:
defaults.put(PREVIEW_PRINT_BUTTON, Boolean.FALSE);
defaults.put(AUTO_DOUBLE_BRACES, Boolean.FALSE);
defaults.put(DO_NOT_RESOLVE_STRINGS_FOR, "url");
defaults.put(RESOLVE_STRINGS_ALL_FIELDS, Boolean.FALSE);
defaults.put(PUT_BRACES_AROUND_CAPITALS, "");//"title;journal;booktitle;review;abstract");
defaults.put(NON_WRAPPABLE_FIELDS, "pdf;ps;url;doi;file");
defaults.put(USE_IMPORT_INSPECTION_DIALOG, Boolean.TRUE);
defaults.put(USE_IMPORT_INSPECTION_DIALOG_FOR_SINGLE, Boolean.TRUE);
defaults.put(GENERATE_KEYS_AFTER_INSPECTION, Boolean.TRUE);
defaults.put(MARK_IMPORTED_ENTRIES, Boolean.TRUE);
defaults.put(UNMARK_ALL_ENTRIES_BEFORE_IMPORTING, Boolean.TRUE);
defaults.put(WARN_ABOUT_DUPLICATES_IN_INSPECTION, Boolean.TRUE);
defaults.put(USE_TIME_STAMP, Boolean.FALSE);
defaults.put(OVERWRITE_TIME_STAMP, Boolean.FALSE);
defaults.put(TIME_STAMP_FORMAT, "yyyy-MM-dd");
defaults.put(TIME_STAMP_FIELD, BibtexFields.TIMESTAMP);
defaults.put(UPDATE_TIMESTAMP, Boolean.FALSE);
defaults.put(GENERATE_KEYS_BEFORE_SAVING, Boolean.FALSE);
// behavior of JabRef before 2.10: both: false
defaults.put(WRITEFIELD_ADDSPACES, Boolean.TRUE);
defaults.put(WRITEFIELD_CAMELCASENAME, Boolean.TRUE);
//behavior of JabRef before LWang_AdjustableFieldOrder 1
//0 sorted order (2.10 default), 1 unsorted order (2.9.2 default), 2 user defined
defaults.put(WRITEFIELD_SORTSTYLE, 0);
defaults.put(WRITEFIELD_USERDEFINEDORDER, "author;title;journal;year;volume;number;pages;month;note;volume;pages;part;eid");
defaults.put(WRITEFIELD_WRAPFIELD, Boolean.FALSE);
defaults.put(RemotePreferences.USE_REMOTE_SERVER, Boolean.FALSE);
defaults.put(RemotePreferences.REMOTE_SERVER_PORT, 6050);
defaults.put(PERSONAL_JOURNAL_LIST, null);
defaults.put(EXTERNAL_JOURNAL_LISTS, null);
defaults.put(CITE_COMMAND, "\\cite"); // obsoleted by the app-specific ones (not any more?)
defaults.put(FLOAT_MARKED_ENTRIES, Boolean.TRUE);
defaults.put(USE_NATIVE_FILE_DIALOG_ON_MAC, Boolean.FALSE);
defaults.put(FILECHOOSER_DISABLE_RENAME, Boolean.TRUE);
defaults.put(LAST_USED_EXPORT, null);
defaults.put(SIDE_PANE_WIDTH, -1);
defaults.put(IMPORT_INSPECTION_DIALOG_WIDTH, 650);
defaults.put(IMPORT_INSPECTION_DIALOG_HEIGHT, 650);
defaults.put(SEARCH_DIALOG_WIDTH, 650);
defaults.put(SEARCH_DIALOG_HEIGHT, 500);
defaults.put(SHOW_FILE_LINKS_UPGRADE_WARNING, Boolean.TRUE);
defaults.put(AUTOLINK_EXACT_KEY_ONLY, Boolean.FALSE);
defaults.put(NUMERIC_FIELDS, "mittnum;author");
defaults.put(RUN_AUTOMATIC_FILE_SEARCH, Boolean.FALSE);
defaults.put(USE_LOCK_FILES, Boolean.TRUE);
defaults.put(AUTO_SAVE, Boolean.TRUE);
defaults.put(AUTO_SAVE_INTERVAL, 5);
defaults.put(PROMPT_BEFORE_USING_AUTOSAVE, Boolean.TRUE);
defaults.put(ENFORCE_LEGAL_BIBTEX_KEY, Boolean.TRUE);
defaults.put(BIBLATEX_MODE, Boolean.FALSE);
// Curly brackets ({}) are the default delimiters, not quotes (") as these cause trouble when they appear within the field value:
// Currently, JabRef does not escape them
defaults.put(VALUE_DELIMITERS2, 1);
defaults.put(INCLUDE_EMPTY_FIELDS, Boolean.FALSE);
defaults.put(KEY_GEN_FIRST_LETTER_A, Boolean.TRUE);
defaults.put(KEY_GEN_ALWAYS_ADD_LETTER, Boolean.FALSE);
defaults.put(EMAIL_SUBJECT, Localization.lang("References"));
defaults.put(OPEN_FOLDERS_OF_ATTACHED_FILES, Boolean.FALSE);
defaults.put(ALLOW_FILE_AUTO_OPEN_BROWSE, Boolean.TRUE);
defaults.put(WEB_SEARCH_VISIBLE, Boolean.FALSE);
defaults.put(SELECTED_FETCHER_INDEX, 0);
defaults.put(BIB_LOCATION_AS_FILE_DIR, Boolean.TRUE);
defaults.put(BIB_LOC_AS_PRIMARY_DIR, Boolean.FALSE);
defaults.put(DB_CONNECT_SERVER_TYPE, "MySQL");
defaults.put(DB_CONNECT_HOSTNAME, "localhost");
defaults.put(DB_CONNECT_DATABASE, "jabref");
defaults.put(DB_CONNECT_USERNAME, "root");
CleanUpAction.putDefaults(defaults);
// defaults for DroppedFileHandler UI
defaults.put(DroppedFileHandler.DFH_LEAVE, Boolean.FALSE);
defaults.put(DroppedFileHandler.DFH_COPY, Boolean.TRUE);
defaults.put(DroppedFileHandler.DFH_MOVE, Boolean.FALSE);
defaults.put(DroppedFileHandler.DFH_RENAME, Boolean.FALSE);
//defaults.put("lastAutodetectedImport", "");
//defaults.put("autoRemoveExactDuplicates", Boolean.FALSE);
//defaults.put("confirmAutoRemoveExactDuplicates", Boolean.TRUE);
//defaults.put("tempDir", System.getProperty("java.io.tmpdir"));
//Util.pr(System.getProperty("java.io.tempdir"));
//defaults.put("keyPattern", new LabelPattern(KEY_PATTERN));
defaults.put(ImportSettingsTab.PREF_IMPORT_ALWAYSUSE, Boolean.FALSE);
defaults.put(ImportSettingsTab.PREF_IMPORT_DEFAULT_PDF_IMPORT_STYLE, ImportSettingsTab.DEFAULT_STYLE);
// use BibTeX key appended with filename as default pattern
defaults.put(ImportSettingsTab.PREF_IMPORT_FILENAMEPATTERN, ImportSettingsTab.DEFAULT_FILENAMEPATTERNS[1]);
restoreKeyBindings();
customExports = new CustomExportList(new ExportComparator());
customImports = new CustomImportList(this);
//defaults.put("oooWarning", Boolean.TRUE);
updateSpecialFieldHandling();
WRAPPED_USERNAME = '[' + get(DEFAULT_OWNER) + ']';
MARKING_WITH_NUMBER_PATTERN = "\\[" + get(DEFAULT_OWNER).replaceAll("\\\\", "\\\\\\\\") + ":(\\d+)\\]";
String defaultExpression = "**/.*[bibtexkey].*\\\\.[extension]";
defaults.put(DEFAULT_REG_EXP_SEARCH_EXPRESSION_KEY, defaultExpression);
defaults.put(REG_EXP_SEARCH_EXPRESSION_KEY, defaultExpression);
defaults.put(AUTOLINK_USE_REG_EXP_SEARCH_KEY, Boolean.FALSE);
defaults.put(USE_IEEE_ABRV, Boolean.FALSE);
defaults.put(USE_CONVERT_TO_EQUATION, Boolean.FALSE);
defaults.put(USE_CASE_KEEPER_ON_SEARCH, Boolean.TRUE);
defaults.put(USE_UNIT_FORMATTER_ON_SEARCH, Boolean.TRUE);
defaults.put(USER_FILE_DIR, Globals.FILE_FIELD + "Directory");
try {
defaults.put(USER_FILE_DIR_IND_LEGACY, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER) + '@' + InetAddress.getLocalHost().getHostName()); // Legacy setting name - was a bug: @ not allowed inside BibTeX comment text. Retained for backward comp.
defaults.put(USER_FILE_DIR_INDIVIDUAL, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER) + '-' + InetAddress.getLocalHost().getHostName()); // Valid setting name
} catch (UnknownHostException ex) {
LOGGER.info("Hostname not found.", ex);
defaults.put(USER_FILE_DIR_IND_LEGACY, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER));
defaults.put(USER_FILE_DIR_INDIVIDUAL, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER));
}
}
public void setLanguageDependentDefaultValues() {
// Entry editor tab 0:
defaults.put(CUSTOM_TAB_NAME + "_def0", Localization.lang("General"));
defaults.put(CUSTOM_TAB_FIELDS + "_def0", "crossref;keywords;file;doi;url;"
+ "comment;owner;timestamp");
// Entry editor tab 1:
defaults.put(CUSTOM_TAB_FIELDS + "_def1", "abstract");
defaults.put(CUSTOM_TAB_NAME + "_def1", Localization.lang("Abstract"));
// Entry editor tab 2: Review Field - used for research comments, etc.
defaults.put(CUSTOM_TAB_FIELDS + "_def2", "review");
defaults.put(CUSTOM_TAB_NAME + "_def2", Localization.lang("Review"));
}
public boolean putBracesAroundCapitals(String fieldName) {
return putBracesAroundCapitalsFields.contains(fieldName);
}
public void updateSpecialFieldHandling() {
putBracesAroundCapitalsFields.clear();
String fieldString = get(PUT_BRACES_AROUND_CAPITALS);
if (!fieldString.isEmpty()) {
String[] fields = fieldString.split(";");
for (String field : fields) {
putBracesAroundCapitalsFields.add(field.trim());
}
}
nonWrappableFields.clear();
fieldString = get(NON_WRAPPABLE_FIELDS);
if (!fieldString.isEmpty()) {
String[] fields = fieldString.split(";");
for (String field : fields) {
nonWrappableFields.add(field.trim());
}
}
}
public char getValueDelimiters(int index) {
return getValueDelimiters()[index];
}
private char[] getValueDelimiters() {
return JabRefPreferences.VALUE_DELIMITERS[getInt(VALUE_DELIMITERS2)];
}
/**
* Check whether a key is set (differently from null).
*
* @param key The key to check.
* @return true if the key is set, false otherwise.
*/
public boolean hasKey(String key) {
return prefs.get(key, null) != null;
}
public String get(String key) {
return prefs.get(key, (String) defaults.get(key));
}
public String get(String key, String def) {
return prefs.get(key, def);
}
public boolean getBoolean(String key) {
return prefs.getBoolean(key, getBooleanDefault(key));
}
public boolean getBoolean(String key, boolean def) {
return prefs.getBoolean(key, def);
}
private boolean getBooleanDefault(String key) {
return (Boolean) defaults.get(key);
}
public double getDouble(String key) {
return prefs.getDouble(key, getDoubleDefault(key));
}
private double getDoubleDefault(String key) {
return (Double) defaults.get(key);
}
public int getInt(String key) {
return prefs.getInt(key, getIntDefault(key));
}
public int getIntDefault(String key) {
return (Integer) defaults.get(key);
}
public byte[] getByteArray(String key) {
return prefs.getByteArray(key, getByteArrayDefault(key));
}
private byte[] getByteArrayDefault(String key) {
return (byte[]) defaults.get(key);
}
public void put(String key, String value) {
prefs.put(key, value);
}
public void putBoolean(String key, boolean value) {
prefs.putBoolean(key, value);
}
public void putDouble(String key, double value) {
prefs.putDouble(key, value);
}
public void putInt(String key, int value) {
prefs.putInt(key, value);
}
public void putByteArray(String key, byte[] value) {
prefs.putByteArray(key, value);
}
public void remove(String key) {
prefs.remove(key);
}
/**
* Puts a string array into the Preferences, by linking its elements with ';' into a single string. Escape
* characters make the process transparent even if strings contain ';'.
*/
public void putStringArray(String key, String[] value) {
if (value == null) {
remove(key);
return;
}
if (value.length > 0) {
StringBuilder linked = new StringBuilder();
for (int i = 0; i < value.length - 1; i++) {
linked.append(makeEscape(value[i]));
linked.append(';');
}
linked.append(makeEscape(value[value.length - 1]));
put(key, linked.toString());
} else {
put(key, "");
}
}
/**
* Returns a String[] containing the chosen columns.
*/
public String[] getStringArray(String key) {
String names = get(key);
if (names == null) {
return null;
}
StringReader rd = new StringReader(names);
Vector<String> arr = new Vector<String>();
String rs;
try {
while ((rs = getNextUnit(rd)) != null) {
arr.add(rs);
}
} catch (IOException ignored) {
}
String[] res = new String[arr.size()];
for (int i = 0; i < res.length; i++) {
res[i] = arr.elementAt(i);
}
return res;
}
/**
* Looks up a color definition in preferences, and returns the Color object.
*
* @param key The key for this setting.
* @return The color corresponding to the setting.
*/
public Color getColor(String key) {
String value = get(key);
int[] rgb = getRgb(value);
return new Color(rgb[0], rgb[1], rgb[2]);
}
public Color getDefaultColor(String key) {
String value = (String) defaults.get(key);
int[] rgb = getRgb(value);
return new Color(rgb[0], rgb[1], rgb[2]);
}
/**
* Set the default value for a key. This is useful for plugins that need to add default values for the prefs keys
* they use.
*
* @param key The preferences key.
* @param value The default value.
*/
public void putDefaultValue(String key, Object value) {
defaults.put(key, value);
}
/**
* Stores a color in preferences.
*
* @param key The key for this setting.
* @param color The Color to store.
*/
public void putColor(String key, Color color) {
String rgb = String.valueOf(color.getRed()) + ':' + String.valueOf(color.getGreen()) + ':' + String.valueOf(color.getBlue());
put(key, rgb);
}
/**
* Looks up a color definition in preferences, and returns an array containing the RGB values.
*
* @param value The key for this setting.
* @return The RGB values corresponding to this color setting.
*/
private int[] getRgb(String value) {
String[] elements = value.split(":");
int[] values = new int[3];
values[0] = Integer.parseInt(elements[0]);
values[1] = Integer.parseInt(elements[1]);
values[2] = Integer.parseInt(elements[2]);
return values;
}
/**
* Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences.
*/
public KeyStroke getKey(String bindName) {
String s = keyBinds.get(bindName);
// If the current key bindings don't contain the one asked for,
// we fall back on the default. This should only happen when a
// user has his own set in Preferences, and has upgraded to a
// new version where new bindings have been introduced.
if (s == null) {
s = defaultKeyBinds.get(bindName);
if (s == null) {
// there isn't even a default value
// Output error
LOGGER.info("Could not get key binding for \"" + bindName + '"');
// fall back to a default value
s = "Not associated";
}
// So, if there is no configured key binding, we add the fallback value to the current
// hashmap, so this doesn't happen again, and so this binding
// will appear in the KeyBindingsDialog.
keyBinds.put(bindName, s);
}
if (OS.OS_X) {
return getKeyForMac(KeyStroke.getKeyStroke(s));
} else {
return KeyStroke.getKeyStroke(s);
}
}
/**
* Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences, but adapted for Mac
* users, with the Command key preferred instead of Control.
* TODO: Move to OS.java? Or replace with portable Java key codes, i.e. KeyEvent
*/
private KeyStroke getKeyForMac(KeyStroke ks) {
if (ks == null) {
return null;
}
int keyCode = ks.getKeyCode();
if ((ks.getModifiers() & InputEvent.CTRL_MASK) == 0) {
return ks;
} else {
int modifiers = 0;
if ((ks.getModifiers() & InputEvent.SHIFT_MASK) != 0) {
modifiers = modifiers | InputEvent.SHIFT_MASK;
}
if ((ks.getModifiers() & InputEvent.ALT_MASK) != 0) {
modifiers = modifiers | InputEvent.ALT_MASK;
}
if (SHORTCUT_MASK == -1) {
try {
SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
} catch (Throwable ignored) {
}
}
return KeyStroke.getKeyStroke(keyCode, SHORTCUT_MASK + modifiers);
}
}
/**
* Returns the HashMap containing all key bindings.
*/
public HashMap<String, String> getKeyBindings() {
return keyBinds.getKeyBindings();
}
/**
* Returns the HashMap containing default key bindings.
*/
public HashMap<String, String> getDefaultKeys() {
return defaultKeyBinds.getKeyBindings();
}
/**
* Clear all preferences.
*
* @throws BackingStoreException
*/
public void clear() throws BackingStoreException {
prefs.clear();
}
public void clear(String key) {
prefs.remove(key);
}
/**
* Calling this method will write all preferences into the preference store.
*/
public void flush() {
if (getBoolean(MEMORY_STICK_MODE)) {
try {
exportPreferences("jabref.xml");
} catch (IOException e) {
LOGGER.info("Could not save preferences for memory stick mode: " + e.getLocalizedMessage(), e);
}
}
try {
prefs.flush();
} catch (BackingStoreException ex) {
ex.printStackTrace();
}
}
/**
* Stores new key bindings into Preferences, provided they actually differ from the old ones.
*/
public void setNewKeyBindings(HashMap<String, String> newBindings) {
if (!newBindings.equals(keyBinds)) {
// This confirms that the bindings have actually changed.
String[] bindNames = new String[newBindings.size()];
String[] bindings = new String[newBindings.size()];
int index = 0;
for (String nm : newBindings.keySet()) {
String bnd = newBindings.get(nm);
bindNames[index] = nm;
bindings[index] = bnd;
index++;
}
putStringArray("bindNames", bindNames);
putStringArray("bindings", bindings);
keyBinds.overwriteBindings(newBindings);
}
}
/**
* Fetches key patterns from preferences.
* The implementation doesn't cache the results
*
* @return LabelPattern containing all keys. Returned LabelPattern has no parent
*/
public GlobalLabelPattern getKeyPattern() {
JabRefPreferences.keyPattern = new GlobalLabelPattern();
Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class);
try {
String[] keys = pre.keys();
if (keys.length > 0) {
for (String key : keys) {
JabRefPreferences.keyPattern.addLabelPattern(key, pre.get(key, null));
}
}
} catch (BackingStoreException ex) {
LOGGER.info("BackingStoreException in JabRefPreferences.getKeyPattern", ex);
}
return JabRefPreferences.keyPattern;
}
/**
* Adds the given key pattern to the preferences
*
* @param pattern the pattern to store
*/
public void putKeyPattern(GlobalLabelPattern pattern) {
JabRefPreferences.keyPattern = pattern;
// Store overridden definitions to Preferences.
Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class);
try {
pre.clear(); // We remove all old entries.
} catch (BackingStoreException ex) {
LOGGER.info("BackingStoreException in JabRefPreferences.putKeyPattern", ex);
}
Enumeration<String> allKeys = pattern.getAllKeys();
while (allKeys.hasMoreElements()) {
String key = allKeys.nextElement();
if (!pattern.isDefaultValue(key)) {
ArrayList<String> value = pattern.getValue(key);
// no default value
// the first entry in the array is the full pattern
// see net.sf.jabref.logic.labelPattern.LabelPatternUtil.split(String)
pre.put(key, value.get(0));
}
}
}
private void restoreKeyBindings() {
// Define default keybindings.
defaultKeyBinds = new KeyBinds();
// First read the bindings, and their names.
String[] bindNames = getStringArray("bindNames");
String[] bindings = getStringArray("bindings");
// Then set up the key bindings HashMap.
if (bindNames == null || bindings == null
|| bindNames.length != bindings.length) {
// Nothing defined in Preferences, or something is wrong.
keyBinds = new KeyBinds();
return;
}
for (int i = 0; i < bindNames.length; i++) {
keyBinds.put(bindNames[i], bindings[i]);
}
}
private String getNextUnit(Reader data) throws IOException {
// character last read
// -1 if end of stream
// initialization necessary, because of Java compiler
int c = -1;
// last character was escape symbol
boolean escape = false;
// true if a ";" is found
boolean done = false;
StringBuilder res = new StringBuilder();
while (!done && (c = data.read()) != -1) {
if (c == '\\') {
if (!escape) {
escape = true;
} else {
escape = false;
res.append('\\');
}
} else {
if (c == ';') {
if (!escape) {
done = true;
} else {
res.append(';');
}
} else {
res.append((char) c);
}
escape = false;
}
}
if (res.length() > 0) {
return res.toString();
} else if (c == -1) {
// end of stream
return null;
} else {
return "";
}
}
private String makeEscape(String s) {
StringBuilder sb = new StringBuilder();
int c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (c == '\\' || c == ';') {
sb.append('\\');
}
sb.append((char) c);
}
return sb.toString();
}
/**
* Stores all information about the entry type in preferences, with the tag given by number.
*/
public void storeCustomEntryType(CustomEntryType tp, int number) {
String nr = "" + number;
put(JabRefPreferences.CUSTOM_TYPE_NAME + nr, tp.getName());
put(JabRefPreferences.CUSTOM_TYPE_REQ + nr, tp.getRequiredFieldsString());
putStringArray(JabRefPreferences.CUSTOM_TYPE_OPT + nr, tp.getOptionalFields().toArray(new String[0]));
putStringArray(JabRefPreferences.CUSTOM_TYPE_PRIOPT + nr, tp.getPrimaryOptionalFields().toArray(new String[0]));
}
/**
* Retrieves all information about the entry type in preferences, with the tag given by number.
*/
public CustomEntryType getCustomEntryType(int number) {
String nr = "" + number;
String name = get(JabRefPreferences.CUSTOM_TYPE_NAME + nr);
String[] req = getStringArray(JabRefPreferences.CUSTOM_TYPE_REQ + nr);
String[] opt = getStringArray(JabRefPreferences.CUSTOM_TYPE_OPT + nr);
String[] priOpt = getStringArray(JabRefPreferences.CUSTOM_TYPE_PRIOPT + nr);
if (name == null) {
return null;
}
if (priOpt == null) {
return new CustomEntryType(StringUtil.capitalizeFirst(name), req, opt);
}
String[] secOpt = StringUtil.getRemainder(opt, priOpt);
return new CustomEntryType(StringUtil.capitalizeFirst(name), req, priOpt, secOpt);
}
public List<ExternalFileType> getDefaultExternalFileTypes() {
List<ExternalFileType> list = new ArrayList<ExternalFileType>();
list.add(new ExternalFileType("PDF", "pdf", "application/pdf", "evince", "pdfSmall", IconTheme.getImage("pdfSmall")));
list.add(new ExternalFileType("PostScript", "ps", "application/postscript", "evince", "psSmall", IconTheme.getImage("psSmall")));
list.add(new ExternalFileType("Word", "doc", "application/msword", "oowriter", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("Word 2007+", "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "oowriter", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("OpenDocument text", "odt", "application/vnd.oasis.opendocument.text", "oowriter", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("Excel", "xls", "application/excel", "oocalc", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("Excel 2007+", "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "oocalc", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("OpenDocument spreadsheet", "ods", "application/vnd.oasis.opendocument.spreadsheet", "oocalc", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("PowerPoint", "ppt", "application/vnd.ms-powerpoint", "ooimpress", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("PowerPoint 2007+", "pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "ooimpress", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("OpenDocument presentation", "odp", "application/vnd.oasis.opendocument.presentation", "ooimpress", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("Rich Text Format", "rtf", "application/rtf", "oowriter", "openoffice", IconTheme.getImage("openoffice")));
list.add(new ExternalFileType("PNG image", "png", "image/png", "gimp", "picture", IconTheme.getImage("picture")));
list.add(new ExternalFileType("GIF image", "gif", "image/gif", "gimp", "picture", IconTheme.getImage("picture")));
list.add(new ExternalFileType("JPG image", "jpg", "image/jpeg", "gimp", "picture", IconTheme.getImage("picture")));
list.add(new ExternalFileType("Djvu", "djvu", "", "evince", "psSmall", IconTheme.getImage("psSmall")));
list.add(new ExternalFileType("Text", "txt", "text/plain", "emacs", "emacs", IconTheme.getImage("emacs")));
list.add(new ExternalFileType("LaTeX", "tex", "application/x-latex", "emacs", "emacs", IconTheme.getImage("emacs")));
list.add(new ExternalFileType("CHM", "chm", "application/mshelp", "gnochm", "www", IconTheme.getImage("www")));
list.add(new ExternalFileType("TIFF image", "tiff", "image/tiff", "gimp", "picture", IconTheme.getImage("picture")));
list.add(new ExternalFileType("URL", "html", "text/html", "firefox", "www", IconTheme.getImage("www")));
list.add(new ExternalFileType("MHT", "mht", "multipart/related", "firefox", "www", IconTheme.getImage("www")));
list.add(new ExternalFileType("ePUB", "epub", "application/epub+zip", "firefox", "www", IconTheme.getImage("www")));
// On all OSes there is a generic application available to handle file opening,
// so we don't need the default application settings anymore:
for (ExternalFileType type : list) {
type.setOpenWith("");
}
return list;
}
public ExternalFileType[] getExternalFileTypeSelection() {
return externalFileTypes.toArray(new ExternalFileType[externalFileTypes.size()]);
}
/**
* Look up the external file type registered with this name, if any.
*
* @param name The file type name.
* @return The ExternalFileType registered, or null if none.
*/
public ExternalFileType getExternalFileTypeByName(String name) {
for (ExternalFileType type : externalFileTypes) {
if (type.getName().equals(name)) {
return type;
}
}
// Return an instance that signifies an unknown file type:
return new UnknownExternalFileType(name);
}
/**
* Look up the external file type registered for this extension, if any.
*
* @param extension The file extension.
* @return The ExternalFileType registered, or null if none.
*/
public ExternalFileType getExternalFileTypeByExt(String extension) {
for (ExternalFileType type : externalFileTypes) {
if (type.getExtension() != null && type.getExtension().equalsIgnoreCase(extension)) {
return type;
}
}
return null;
}
/**
* Look up the external file type registered for this filename, if any.
*
* @param filename The name of the file whose type to look up.
* @return The ExternalFileType registered, or null if none.
*/
public ExternalFileType getExternalFileTypeForName(String filename) {
int longestFound = -1;
ExternalFileType foundType = null;
for (ExternalFileType type : externalFileTypes) {
if (type.getExtension() != null && filename.toLowerCase().
endsWith(type.getExtension().toLowerCase())) {
if (type.getExtension().length() > longestFound) {
longestFound = type.getExtension().length();
foundType = type;
}
}
}
return foundType;
}
/**
* Look up the external file type registered for this MIME type, if any.
*
* @param mimeType The MIME type.
* @return The ExternalFileType registered, or null if none. For the mime type "text/html", a valid file type is
* guaranteed to be returned.
*/
public ExternalFileType getExternalFileTypeByMimeType(String mimeType) {
for (ExternalFileType type : externalFileTypes) {
if (type.getMimeType() != null && type.getMimeType().equals(mimeType)) {
return type;
}
}
if (mimeType.equals("text/html")) {
return HTML_FALLBACK_TYPE;
} else {
return null;
}
}
/**
* Reset the List of external file types after user customization.
*
* @param types The new List of external file types. This is the complete list, not just new entries.
*/
public void setExternalFileTypes(List<ExternalFileType> types) {
// First find a list of the default types:
List<ExternalFileType> defTypes = getDefaultExternalFileTypes();
// Make a list of types that are unchanged:
List<ExternalFileType> unchanged = new ArrayList<ExternalFileType>();
externalFileTypes.clear();
for (ExternalFileType type : types) {
externalFileTypes.add(type);
// See if we can find a type with matching name in the default type list:
ExternalFileType found = null;
for (ExternalFileType defType : defTypes) {
if (defType.getName().equals(type.getName())) {
found = defType;
break;
}
}
if (found != null) {
// Found it! Check if it is an exact match, or if it has been customized:
if (found.equals(type)) {
unchanged.add(type);
} else {
// It was modified. Remove its entry from the defaults list, since
// the type hasn't been removed:
defTypes.remove(found);
}
}
}
// Go through unchanged types. Remove them from the ones that should be stored,
// and from the list of defaults, since we don't need to mention these in prefs:
for (ExternalFileType type : unchanged) {
defTypes.remove(type);
types.remove(type);
}
// Now set up the array to write to prefs, containing all new types, all modified
// types, and a flag denoting each default type that has been removed:
String[][] array = new String[types.size() + defTypes.size()][];
int i = 0;
for (ExternalFileType type : types) {
array[i] = type.getStringArrayRepresentation();
i++;
}
for (ExternalFileType type : defTypes) {
array[i] = new String[] {type.getName(), JabRefPreferences.FILE_TYPE_REMOVED_FLAG};
i++;
}
//System.out.println("Encoded: '"+Util.encodeStringArray(array)+"'");
put("externalFileTypes", StringUtil.encodeStringArray(array));
}
/**
* Set up the list of external file types, either from default values, or from values recorded in Preferences.
*/
public void updateExternalFileTypes() {
// First get a list of the default file types as a starting point:
List<ExternalFileType> types = getDefaultExternalFileTypes();
// If no changes have been stored, simply use the defaults:
if (prefs.get("externalFileTypes", null) == null) {
externalFileTypes.clear();
externalFileTypes.addAll(types);
return;
}
// Read the prefs information for file types:
String[][] vals = StringUtil.decodeStringDoubleArray(prefs.get("externalFileTypes", ""));
for (String[] val : vals) {
if (val.length == 2 && val[1].equals(JabRefPreferences.FILE_TYPE_REMOVED_FLAG)) {
// This entry indicates that a default entry type should be removed:
ExternalFileType toRemove = null;
for (ExternalFileType type : types) {
if (type.getName().equals(val[0])) {
toRemove = type;
break;
}
}
// If we found it, remove it from the type list:
if (toRemove != null) {
types.remove(toRemove);
}
} else {
// A new or modified entry type. Construct it from the string array:
ExternalFileType type = new ExternalFileType(val);
// Check if there is a default type with the same name. If so, this is a
// modification of that type, so remove the default one:
ExternalFileType toRemove = null;
for (ExternalFileType defType : types) {
if (type.getName().equals(defType.getName())) {
toRemove = defType;
break;
}
}
// If we found it, remove it from the type list:
if (toRemove != null) {
types.remove(toRemove);
}
// Then add the new one:
types.add(type);
}
}
// Finally, build the list of types based on the modified defaults list:
for (ExternalFileType type : types) {
externalFileTypes.add(type);
}
}
/**
* Removes all information about custom entry types with tags of
*
* @param number or higher.
*/
public void purgeCustomEntryTypes(int number) {
purgeSeries(JabRefPreferences.CUSTOM_TYPE_NAME, number);
purgeSeries(JabRefPreferences.CUSTOM_TYPE_REQ, number);
purgeSeries(JabRefPreferences.CUSTOM_TYPE_OPT, number);
purgeSeries(JabRefPreferences.CUSTOM_TYPE_PRIOPT, number);
}
/**
* Removes all entries keyed by prefix+number, where number is equal to or higher than the given number.
*
* @param number or higher.
*/
public void purgeSeries(String prefix, int number) {
while (get(prefix + number) != null) {
remove(prefix + number);
number++;
}
}
public EntryEditorTabList getEntryEditorTabList() {
if (tabList == null) {
updateEntryEditorTabList();
}
return tabList;
}
public void updateEntryEditorTabList() {
tabList = new EntryEditorTabList();
}
/**
* Exports Preferences to an XML file.
*
* @param filename String File to export to
*/
public void exportPreferences(String filename) throws IOException {
File f = new File(filename);
OutputStream os = new FileOutputStream(f);
try {
prefs.exportSubtree(os);
} catch (BackingStoreException ex) {
throw new IOException(ex);
} finally {
if (os != null) {
os.close();
}
}
}
/**
* Imports Preferences from an XML file.
*
* @param filename String File to import from
*/
public void importPreferences(String filename) throws IOException {
File f = new File(filename);
InputStream is = new FileInputStream(f);
try {
Preferences.importPreferences(is);
} catch (InvalidPreferencesFormatException ex) {
throw new IOException(ex);
}
}
/**
* Determines whether the given field should be written without any sort of wrapping.
*
* @param fieldName The field name.
* @return true if the field should not be wrapped.
*/
public boolean isNonWrappableField(String fieldName) {
return nonWrappableFields.contains(fieldName);
}
/**
* ONLY FOR TESTING!
*
* Do not use in production code. Otherwise the singleton pattern is broken and preferences might get lost.
* @param prefs
*/
void overwritePreferences(JabRefPreferences prefs) {
singleton = prefs;
}
} |
package no.steria.quizzical;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class QuizServlet extends HttpServlet {
private Response quizResponse;
private MongoQuizDao mongoQuizDao;
private MongoResponseDao mongoResponseDao;
private InputCleaner cleaner;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(req.getReader().readLine());
int quizId=0;
String name="", email="";
HashMap<String,Integer> answersToDB = new HashMap<String,Integer>();
Iterator<Entry<String,JsonNode>> allEntries = rootNode.getFields();
while(allEntries.hasNext()){
Entry<String, JsonNode> entry = allEntries.next();
if(entry.getKey().equals("answers")){
Iterator<Entry<String,JsonNode>> answerEntries = entry.getValue().getFields();
while(answerEntries.hasNext()){
Entry<String,JsonNode> answer = answerEntries.next();
answersToDB.put(answer.getKey(), answer.getValue().asInt());
}
}else if(entry.getKey().equals("quizId")){
quizId = Integer.parseInt(entry.getValue().asText());
}else if(entry.getKey().equals("name")){
name = cleaner.clean(entry.getValue().asText());
}else if(entry.getKey().equals("email")){
email = cleaner.clean(entry.getValue().asText());
}
}
quizResponse = new Response(quizId, name, email, answersToDB);
quizResponse.calculateScore(mongoQuizDao.getQuiz(quizId));
mongoResponseDao.setResponse(quizResponse);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/json");
ObjectMapper mapper = new ObjectMapper();
PrintWriter writer = resp.getWriter();
int mode = Integer.parseInt(req.getParameter("mode"));
if(mode == 1){
retrieveQuizByQuizId(req, mapper, writer);
}
}
private void retrieveQuizByQuizId(HttpServletRequest req,
ObjectMapper mapper, PrintWriter writer) throws IOException,
JsonGenerationException, JsonMappingException {
int quizId = Integer.parseInt(req.getParameter("quizId"));
Quiz quiz = null;
quiz = mongoQuizDao.getQuiz(quizId);
Iterator<Question> questions = quiz.getQuestions().iterator();
while(questions.hasNext()){
questions.next().setAnswer(-1);
}
if(!quiz.getActive()){
throw new IllegalArgumentException();
}
mapper.writeValue(writer, quiz);
}
public void setQuizDao(MongoQuizDao quizDao) {
this.mongoQuizDao = quizDao;
}
@Override
public void init() throws ServletException {
super.init();
mongoQuizDao = new MongoQuizDao();
mongoResponseDao = new MongoResponseDao();
}
} |
package org.apache.mesos.hdfs;
import com.google.inject.Inject;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mesos.hdfs.config.SchedulerConf;
import org.apache.mesos.hdfs.state.ClusterState;
import org.apache.mesos.hdfs.state.State;
import org.apache.mesos.hdfs.util.HDFSConstants;
import org.apache.mesos.MesosNativeLibrary;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos.*;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.state.ZooKeeperState;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
public class Scheduler implements org.apache.mesos.Scheduler, Runnable {
public static final Log log = LogFactory.getLog(Scheduler.class);
private final SchedulerConf conf;
private final String localhost;
private Map<OfferID, Offer> pendingOffers = new ConcurrentHashMap<>();
private boolean initializingCluster = false;
private Set<TaskID> stagingTasks = new HashSet<>();
@Inject
public Scheduler(SchedulerConf conf) {
this.conf = conf;
initClusterState();
try {
localhost = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
private void initClusterState() {
MesosNativeLibrary.load(conf.getNativeLibrary());
ZooKeeperState zkState = new ZooKeeperState(conf.getStateZkServers(),
conf.getStateZkTimeout(), TimeUnit.MILLISECONDS, "/hdfs-mesos/" + conf.getClusterName());
State state = new State(zkState);
ClusterState clusterState = ClusterState.getInstance();
clusterState.init(state);
}
public SchedulerConf getConf() {
return conf;
}
@Override
public void disconnected(SchedulerDriver driver) {
log.info("Scheduler driver disconnected");
}
@Override
public void error(SchedulerDriver driver, String message) {
log.error("Scheduler driver error: " + message);
}
@Override
public void executorLost(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID,
int status) {
log.info("Executor lost: executorId=" + executorID.getValue() + " slaveId="
+ slaveID.getValue() + " status=" + status);
}
@Override
public void frameworkMessage(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID,
byte[] data) {
log.info("Framework message: executorId=" + executorID.getValue() + " slaveId="
+ slaveID.getValue() + " data='" + Arrays.toString(data) + "'");
}
@Override
public void offerRescinded(SchedulerDriver driver, OfferID offerId) {
log.info("Offer rescinded: offerId=" + offerId.getValue());
}
@Override
public void registered(SchedulerDriver driver, FrameworkID frameworkId, MasterInfo masterInfo) {
try {
ClusterState clusterState = ClusterState.getInstance();
clusterState.getState().setFrameworkId(frameworkId);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
log.info("Registered framework frameworkId=" + frameworkId.getValue());
}
@Override
public void reregistered(SchedulerDriver driver, MasterInfo masterInfo) {
log.info("Reregistered framework.");
}
private void launchNode(SchedulerDriver driver, Offer offer,
String nodeName, List<String> taskNames, String executorName) {
ClusterState clusterState = ClusterState.getInstance();
log.info(String.format("Launching node of type %s with tasks %s", nodeName,
taskNames.toString()));
String taskIdName = String.format("%s.%s.%d", nodeName, executorName,
System.currentTimeMillis());
ExecutorInfo executorInfo = createExecutor(taskIdName, nodeName, executorName);
List<TaskInfo> tasks = new ArrayList<>();
for (String taskName : taskNames) {
List<Resource> taskResources = getTaskResources(taskName);
TaskID taskId = TaskID.newBuilder()
.setValue(String.format("task.%s.%s", taskName, taskIdName))
.build();
TaskInfo task = TaskInfo.newBuilder()
.setExecutor(executorInfo)
.setName(taskName)
.setTaskId(taskId)
.setSlaveId(offer.getSlaveId())
.addAllResources(taskResources)
.setData(ByteString.copyFromUtf8(
String.format("bin/hdfs-mesos-%s", taskName)))
.build();
tasks.add(task);
stagingTasks.add(taskId);
clusterState.addTask(taskId, offer.getHostname(), offer.getSlaveId().getValue());
}
driver.launchTasks(Arrays.asList(offer.getId()), tasks);
}
private ExecutorInfo createExecutor(String taskIdName, String nodeName, String executorName) {
int confServerPort = conf.getConfigServerPort();
List<Resource> resources = getExecutorResources();
ExecutorInfo executorInfo = ExecutorInfo.newBuilder()
.setName(nodeName + " executor")
.setExecutorId(ExecutorID.newBuilder().setValue("executor." + taskIdName).build())
.addAllResources(resources)
.setCommand(CommandInfo.newBuilder()
.addAllUris(Arrays.asList(
CommandInfo.URI.newBuilder().setValue(
conf.getExecUri())
.build(),
CommandInfo.URI.newBuilder().setValue(
String.format("http://%s:%d/hdfs-site.xml", localhost, confServerPort))
.build()))
.setEnvironment(Environment.newBuilder()
.addAllVariables(Arrays.asList(
Environment.Variable.newBuilder()
.setName("HADOOP_OPTS")
.setValue(conf.getJvmOpts()).build(),
Environment.Variable.newBuilder()
.setName("HADOOP_HEAPSIZE")
.setValue(String.format("%d", conf.getHadoopHeapSize())).build(),
Environment.Variable.newBuilder()
.setName("HADOOP_NAMENODE_OPTS")
.setValue("-Xmx" + conf.getNameNodeHeapSize() + "m").build(),
Environment.Variable.newBuilder()
.setName("HADOOP_DATANODE_OPTS")
.setValue("-Xmx" + conf.getDataNodeHeapSize() + "m").build(),
Environment.Variable.newBuilder()
.setName("EXECUTOR_OPTS")
.setValue("-Xmx" + conf.getExecutorHeap() + "m").build())))
.setValue(
"env ; cd hdfs-mesos-* && exec java $HADOOP_OPTS $EXECUTOR_OPTS " + |
package org.apache.mesos.hdfs;
import com.google.inject.Inject;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mesos.hdfs.config.SchedulerConf;
import org.apache.mesos.hdfs.state.ClusterState;
import org.apache.mesos.hdfs.state.State;
import org.apache.mesos.MesosNativeLibrary;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos.*;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.state.ZooKeeperState;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
public class Scheduler implements org.apache.mesos.Scheduler, Runnable {
private static final String NAMENODE_INIT_MESSAGE = "i";
private static final String NAMENODE_BOOTSTRAP_MESSAGE = "b";
private static final String NAME_NODE_ID = "namenode";
private static final String JOURNAL_NODE_ID = "journalnode";
private static final String DATA_NODE_ID = "datanode";
private static final String ZKFC_NODE_ID = "zkfc";
private static final String NODE_EXECUTOR_ID = "NodeExecutor";
private static final String NAME_NODE_EXECUTOR_ID = "NameNodeExecutor";
private static final String NAME_NODE_TASK_STR = NAME_NODE_ID + "." + NAME_NODE_ID + "."
+ NAME_NODE_EXECUTOR_ID;
private static final Integer TOTAL_NAME_NODES = 2;
public static final Log log = LogFactory.getLog(Scheduler.class);
private final SchedulerConf conf;
private final String localhost;
private Map<OfferID, Offer> pendingOffers = new ConcurrentHashMap<>();
private boolean initializingCluster = false;
private Set<TaskID> stagingTasks = new HashSet<>();
//TODO(elingg) simplify number of variables used including variables related to NameNodes
private int nameNodesRunning = 0;
private int journalNodesRunning = 0;
@Inject
public Scheduler(SchedulerConf conf) {
this.conf = conf;
initClusterState();
try {
localhost = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
private void initClusterState() {
MesosNativeLibrary.load(conf.getNativeLibrary());
ZooKeeperState zkState = new ZooKeeperState(conf.getStateZkServers(),
conf.getStateZkTimeout(), TimeUnit.MILLISECONDS, "/hdfs-mesos/" + conf.getClusterName());
State state = new State(zkState);
ClusterState clusterState = ClusterState.getInstance();
clusterState.init(state);
}
public SchedulerConf getConf() {
return conf;
}
@Override
public void disconnected(SchedulerDriver driver) {
log.info("Scheduler driver disconnected");
}
@Override
public void error(SchedulerDriver driver, String message) {
log.error("Scheduler driver error: " + message);
}
@Override
public void executorLost(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID,
int status) {
log.info("Executor lost: executorId=" + executorID.getValue() + " slaveId="
+ slaveID.getValue() + " status=" + status);
}
@Override
public void frameworkMessage(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID,
byte[] data) {
log.info("Framework message: executorId=" + executorID.getValue() + " slaveId="
+ slaveID.getValue() + " data='" + Arrays.toString(data) + "'");
}
@Override
public void offerRescinded(SchedulerDriver driver, OfferID offerId) {
log.info("Offer rescinded: offerId=" + offerId.getValue());
}
@Override
public void registered(SchedulerDriver driver, FrameworkID frameworkId, MasterInfo masterInfo) {
try {
ClusterState clusterState = ClusterState.getInstance();
clusterState.getState().setFrameworkId(frameworkId);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
log.info("Registered framework frameworkId=" + frameworkId.getValue());
reregistered(driver, masterInfo);
}
@Override
public void reregistered(SchedulerDriver driver, MasterInfo masterInfo) {
log.info("Reregistered framework.");
}
private void launchNode(SchedulerDriver driver, Offer offer,
String nodeName, List<String> taskNames, String executorName) {
ClusterState clusterState = ClusterState.getInstance();
log.info(String.format("Launching node of type %s with tasks %s", nodeName,
taskNames.toString()));
int confServerPort = conf.getConfigServerPort();
List<Resource> resources = getExecutorResources();
String taskIdName = String.format("%s.%s.%d", nodeName, executorName,
System.currentTimeMillis());
ExecutorInfo executorInfo = ExecutorInfo.newBuilder()
.setName(nodeName + " executor")
.setExecutorId(ExecutorID.newBuilder().setValue("executor." + taskIdName).build())
.addAllResources(resources)
.setCommand(CommandInfo.newBuilder()
.addAllUris(Arrays.asList(
CommandInfo.URI.newBuilder().setValue(conf.getExecUri())
.build(),
CommandInfo.URI.newBuilder().setValue(
String.format("http://%s:%d/hdfs-site.xml", localhost, confServerPort))
.build()))
.setEnvironment(Environment.newBuilder()
.addAllVariables(Arrays.asList(
Environment.Variable.newBuilder()
.setName("HADOOP_OPTS")
.setValue(conf.getJvmOpts()).build(),
Environment.Variable.newBuilder()
.setName("HADOOP_HEAPSIZE")
.setValue(String.format("%d", conf.getHadoopHeapSize())).build(),
Environment.Variable.newBuilder()
.setName("HADOOP_NAMENODE_OPTS")
.setValue("-Xmx" + conf.getNameNodeHeapSize() + "m").build(),
Environment.Variable.newBuilder()
.setName("HADOOP_DATANODE_OPTS")
.setValue("-Xmx" + conf.getDataNodeHeapSize() + "m").build(),
Environment.Variable.newBuilder()
.setName("EXECUTOR_OPTS")
.setValue("-Xmx" + conf.getExecutorHeap() + "m").build())))
.setValue("env ; cd hadoop-2.* && exec java $HADOOP_OPTS $EXECUTOR_OPTS " + |
package org.commcare.suite.model;
import org.commcare.cases.entity.Entity;
import org.commcare.cases.entity.NodeEntityFactory;
import org.commcare.util.CollectionUtils;
import org.commcare.util.DetailFieldPrintInfo;
import org.commcare.cases.entity.EntityUtil;
import org.commcare.util.GridCoordinate;
import org.commcare.util.GridStyle;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.util.ArrayUtilities;
import org.javarosa.core.util.OrderedHashtable;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.ExtWrapMap;
import org.javarosa.core.util.externalizable.ExtWrapNullable;
import org.javarosa.core.util.externalizable.ExtWrapTagged;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.model.xform.XPathReference;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.FunctionUtils;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.parser.XPathSyntaxException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
/**
* A Detail model defines the structure in which
* the details about something should be displayed
* to users (generally cases or referrals).
*
* Detail models maintain a set of Text objects
* which provide a template for how details about
* objects should be displayed, along with a model
* which defines the context of what data should be
* obtained to fill in those templates.
*
* @author ctsims
*/
public class Detail implements Externalizable {
public static final String PRINT_TEMPLATE_PROVIDED_VIA_GLOBAL_SETTING = "provided-globally";
// id will be null if this is a child detail / tab
private String id;
private TreeReference nodeset;
private DisplayUnit title;
/**
* Optional and only relevant if this detail has child details. In that
* case, form may be 'image' or omitted.
*/
private String titleForm;
private Detail[] details;
private DetailField[] fields;
private Callout callout;
private OrderedHashtable<String, String> variables;
private OrderedHashtable<String, XPathExpression> variablesCompiled;
private Vector<Action> actions;
// Force the activity that is showing this detail to show itself in landscape view only
private boolean forceLandscapeView;
private XPathExpression focusFunction;
// A button to print this detail should be provided
private boolean printEnabled;
private String printTemplatePath;
private XPathExpression parsedRelevancyExpression;
// REGION -- These fields are only used if this detail is a case tile
// Allows for the possibility of case tiles being displayed in a grid
private int numEntitiesToDisplayPerRow;
// Indicates that the height of a single cell in the tile's grid layout should be treated as
// equal to its width, rather than being computed independently
private boolean useUniformUnitsInCaseTile;
// ENDREGION
/**
* Serialization Only
*/
public Detail() {
}
public Detail(String id, DisplayUnit title, String nodeset, Vector<Detail> detailsVector,
Vector<DetailField> fieldsVector, OrderedHashtable<String, String> variables,
Vector<Action> actions, Callout callout, String fitAcross,
String uniformUnitsString, String forceLandscape, String focusFunction,
String printPathProvided, String relevancy) {
if (detailsVector.size() > 0 && fieldsVector.size() > 0) {
throw new IllegalArgumentException("A detail may contain either sub-details or fields, but not both.");
}
this.id = id;
this.title = title;
if (nodeset != null) {
this.nodeset = XPathReference.getPathExpr(nodeset).getReference();
}
this.details = ArrayUtilities.copyIntoArray(detailsVector, new Detail[detailsVector.size()]);
this.fields = ArrayUtilities.copyIntoArray(fieldsVector, new DetailField[fieldsVector.size()]);
this.variables = variables;
this.actions = actions;
this.callout = callout;
this.useUniformUnitsInCaseTile = "true".equals(uniformUnitsString);
this.forceLandscapeView = "true".equals(forceLandscape);
this.printEnabled = templatePathValid(printPathProvided);
if (focusFunction != null) {
try {
this.focusFunction = XPathParseTool.parseXPath(focusFunction);
} catch (XPathSyntaxException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
if (fitAcross != null) {
try {
this.numEntitiesToDisplayPerRow = Integer.parseInt(fitAcross);
} catch (NumberFormatException e) {
numEntitiesToDisplayPerRow = 1;
}
} else {
numEntitiesToDisplayPerRow = 1;
}
if (relevancy != null && !"".equals(relevancy)) {
try {
this.parsedRelevancyExpression = XPathParseTool.parseXPath(relevancy);
} catch (XPathSyntaxException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
/**
* @return The id of this detail template
*/
public String getId() {
return id;
}
/**
* @return A title to be displayed to users regarding
* the type of content being described.
*/
public DisplayUnit getTitle() {
return title;
}
/**
* @return A reference to a set of sub-elements of this detail. If provided,
* the detail will display fields for each element of this nodeset.
*/
public TreeReference getNodeset() {
return nodeset;
}
/**
* @return Any child details of this detail.
*/
public Detail[] getDetails() {
return details;
}
/**
* Given a detail, return an array of details that will contain either
* - all child details
* - a single-element array containing the given detail, if it has no children
*/
public Detail[] getFlattenedDetails() {
if (this.isCompound()) {
return this.getDetails();
}
return new Detail[]{this};
}
/**
* @return Any fields belonging to this detail.
*/
public DetailField[] getFields() {
return fields;
}
/**
* @return True iff this detail has child details.
*/
public boolean isCompound() {
return details.length > 0;
}
/**
* Whether this detail is expected to be so huge in scope that
* the platform should limit its strategy for loading it to be asynchronous
* and cached on special keys.
*/
public boolean useAsyncStrategy() {
for (DetailField f : getFields()) {
if (f.getSortOrder() == DetailField.SORT_ORDER_CACHABLE) {
return true;
}
}
return false;
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
id = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
title = (DisplayUnit)ExtUtil.read(in, DisplayUnit.class, pf);
titleForm = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
nodeset = (TreeReference)ExtUtil.read(in, new ExtWrapNullable(TreeReference.class), pf);
Vector<Detail> theDetails = (Vector<Detail>)ExtUtil.read(in, new ExtWrapList(Detail.class), pf);
details = new Detail[theDetails.size()];
ArrayUtilities.copyIntoArray(theDetails, details);
Vector<DetailField> theFields = (Vector<DetailField>)ExtUtil.read(in, new ExtWrapList(DetailField.class), pf);
fields = new DetailField[theFields.size()];
ArrayUtilities.copyIntoArray(theFields, fields);
variables = (OrderedHashtable<String, String>)ExtUtil.read(in, new ExtWrapMap(String.class, String.class, ExtWrapMap.TYPE_ORDERED), pf);
actions = (Vector<Action>)ExtUtil.read(in, new ExtWrapList(Action.class), pf);
callout = (Callout)ExtUtil.read(in, new ExtWrapNullable(Callout.class), pf);
forceLandscapeView = ExtUtil.readBool(in);
focusFunction = (XPathExpression)ExtUtil.read(in, new ExtWrapNullable(new ExtWrapTagged()), pf);
numEntitiesToDisplayPerRow = (int)ExtUtil.readNumeric(in);
useUniformUnitsInCaseTile = ExtUtil.readBool(in);
parsedRelevancyExpression = (XPathExpression)ExtUtil.read(in, new ExtWrapNullable(new ExtWrapTagged()), pf);
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.write(out, new ExtWrapNullable(id));
ExtUtil.write(out, title);
ExtUtil.write(out, new ExtWrapNullable(titleForm));
ExtUtil.write(out, new ExtWrapNullable(nodeset));
ExtUtil.write(out, new ExtWrapList(ArrayUtilities.toVector(details)));
ExtUtil.write(out, new ExtWrapList(ArrayUtilities.toVector(fields)));
ExtUtil.write(out, new ExtWrapMap(variables));
ExtUtil.write(out, new ExtWrapList(actions));
ExtUtil.write(out, new ExtWrapNullable(callout));
ExtUtil.writeBool(out, forceLandscapeView);
ExtUtil.write(out, new ExtWrapNullable(focusFunction == null ? null : new ExtWrapTagged(focusFunction)));
ExtUtil.writeNumeric(out, numEntitiesToDisplayPerRow);
ExtUtil.writeBool(out, useUniformUnitsInCaseTile);
ExtUtil.write(out, new ExtWrapNullable(
parsedRelevancyExpression == null ? null : new ExtWrapTagged(parsedRelevancyExpression)));
}
public OrderedHashtable<String, XPathExpression> getVariableDeclarations() {
if (variablesCompiled == null) {
variablesCompiled = new OrderedHashtable<>();
for (Enumeration en = variables.keys(); en.hasMoreElements(); ) {
String key = (String)en.nextElement();
//TODO: This is stupid, parse this stuff at XML Parse time.
try {
variablesCompiled.put(key, XPathParseTool.parseXPath(variables.get(key)));
} catch (XPathSyntaxException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
return variablesCompiled;
}
/**
* Retrieve the custom/callback action used in this detail in
* the event that there are no matches.
*
* @return An Action model definition if one is defined for this detail.
* Null if there is no associated action.
*/
public Vector<Action> getCustomActions(EvaluationContext evaluationContext) {
Vector<Action> relevantActions = new Vector<>();
for (Action action : actions) {
if (action.isRelevant(evaluationContext)) {
relevantActions.addElement(action);
}
}
return relevantActions;
}
/**
* @return The indices of which fields should be used for sorting and their order
*/
public int[] getOrderedFieldIndicesForSorting() {
Vector<Integer> indices = new Vector<>();
Vector<Integer> cacheAndIndexedIndices = new Vector<>();
outer:
for (int i = 0; i < fields.length; ++i) {
int order = fields[i].getSortOrder();
if (order == -2) {
cacheAndIndexedIndices.addElement(i);
}
if (order < 1) {
continue;
}
for (int j = 0; j < indices.size(); ++j) {
if (order < fields[indices.elementAt(j)].getSortOrder()) {
indices.insertElementAt(i, j);
continue outer;
}
}
//otherwise it's larger than all of the other fields.
indices.addElement(i);
continue;
}
return CollectionUtils.mergeIntegerVectorsInArray(indices, cacheAndIndexedIndices);
}
//These are just helpers around the old structure. Shouldn't really be
//used if avoidable
/**
* Obsoleted - Don't use
*/
public String[] getTemplateSizeHints() {
return new Map<String[]>(new String[fields.length]) {
@Override
protected void map(DetailField f, String[] a, int i) {
a[i] = f.getTemplateWidthHint();
}
}.go();
}
/**
* Obsoleted - Don't use
*/
public String[] getHeaderForms() {
return new Map<String[]>(new String[fields.length]) {
@Override
protected void map(DetailField f, String[] a, int i) {
a[i] = f.getHeaderForm();
}
}.go();
}
/**
* Obsoleted - Don't use
*/
public String[] getTemplateForms() {
return new Map<String[]>(new String[fields.length]) {
@Override
protected void map(DetailField f, String[] a, int i) {
a[i] = f.getTemplateForm();
}
}.go();
}
public boolean usesEntityTileView() {
boolean usingEntityTile = false;
for (DetailField currentField : fields) {
if (currentField.getGridX() >= 0 && currentField.getGridY() >= 0 &&
currentField.getGridWidth() >= 0 && currentField.getGridHeight() > 0) {
usingEntityTile = true;
}
}
return usingEntityTile;
}
public boolean shouldBeLaidOutInGrid() {
return numEntitiesToDisplayPerRow > 1 && usesEntityTileView();
}
public int getNumEntitiesToDisplayPerRow() {
return numEntitiesToDisplayPerRow;
}
public boolean useUniformUnitsInCaseTile() {
return useUniformUnitsInCaseTile;
}
public boolean forcesLandscape() {
return forceLandscapeView;
}
public GridCoordinate[] getGridCoordinates() {
GridCoordinate[] mGC = new GridCoordinate[fields.length];
for (int i = 0; i < fields.length; i++) {
DetailField currentField = fields[i];
mGC[i] = new GridCoordinate(currentField.getGridX(), currentField.getGridY(),
currentField.getGridWidth(), currentField.getGridHeight());
}
return mGC;
}
public GridStyle[] getGridStyles() {
GridStyle[] mGC = new GridStyle[fields.length];
for (int i = 0; i < fields.length; i++) {
DetailField currentField = fields[i];
mGC[i] = new GridStyle(currentField.getFontSize(), currentField.getHorizontalAlign(),
currentField.getVerticalAlign(), currentField.getCssId());
}
return mGC;
}
public Callout getCallout() {
return callout;
}
public boolean hasSortField() {
for (DetailField f : getFields()) {
if (f.getSortOrder() > 0) {
return true;
}
}
return false;
}
private abstract class Map<E> {
private final E a;
private Map(E a) {
this.a = a;
}
protected abstract void map(DetailField f, E a, int i);
public E go() {
for (int i = 0; i < fields.length; ++i) {
map(fields[i], a, i);
}
return a;
}
}
/**
* Given an evaluation context which a qualified nodeset, will populate that EC with the
* evaluated variable values associated with this detail.
*
* @param ec The Evaluation Context to be used to evaluate the variable expressions and which
* will be populated by their result. Will be modified in place.
*/
public void populateEvaluationContextVariables(EvaluationContext ec) {
Hashtable<String, XPathExpression> variables = getVariableDeclarations();
//These are actually in an ordered hashtable, so we can't just get the keyset, since it's
//in a 1.3 hashtable equivalent
for (Enumeration en = variables.keys(); en.hasMoreElements(); ) {
String key = (String)en.nextElement();
ec.setVariable(key, FunctionUtils.unpack(variables.get(key).eval(ec)));
}
}
public boolean evaluateFocusFunction(EvaluationContext ec) {
if (focusFunction == null) {
return false;
}
Object value = FunctionUtils.unpack(focusFunction.eval(ec));
return FunctionUtils.toBoolean(value);
}
public XPathExpression getFocusFunction() {
return focusFunction;
}
private boolean templatePathValid(String templatePathProvided) {
if (PRINT_TEMPLATE_PROVIDED_VIA_GLOBAL_SETTING.equals(templatePathProvided)) {
return true;
} else if (templatePathProvided != null) {
try {
ReferenceManager.instance().DeriveReference(templatePathProvided).getLocalURI();
this.printTemplatePath = templatePathProvided;
return true;
} catch (InvalidReferenceException e) {
System.out.println("Invalid print template path provided for detail with id " + this.id);
}
}
return false;
}
public boolean isPrintEnabled() {
return this.printEnabled;
}
public String getPrintTemplatePath() {
return this.printTemplatePath;
}
public HashMap<String, DetailFieldPrintInfo> getKeyValueMapForPrint(TreeReference selectedEntityRef,
EvaluationContext baseContext) {
HashMap<String, DetailFieldPrintInfo> mapping = new HashMap<>();
populateMappingWithDetailFields(mapping, selectedEntityRef, baseContext, null);
return mapping;
}
private void populateMappingWithDetailFields(HashMap<String, DetailFieldPrintInfo> mapping,
TreeReference selectedEntityRef,
EvaluationContext baseContext,
Detail parentDetail) {
if (isCompound()) {
for (Detail childDetail : details) {
childDetail.populateMappingWithDetailFields(mapping, selectedEntityRef, baseContext, this);
}
} else {
Entity entityForDetail =
getCorrespondingEntity(selectedEntityRef, parentDetail, baseContext);
for (int i = 0; i < fields.length; i++) {
if (entityForDetail.isValidField(i)) {
mapping.put(
fields[i].getPrintIdentifierRobust(),
new DetailFieldPrintInfo(fields[i], entityForDetail, i));
}
}
}
}
private Entity getCorrespondingEntity(TreeReference selectedEntityRef, Detail parentDetail,
EvaluationContext baseContext) {
EvaluationContext entityFactoryContext =
EntityUtil.getEntityFactoryContext(selectedEntityRef, parentDetail != null,
parentDetail, baseContext);
NodeEntityFactory factory = new NodeEntityFactory(this, entityFactoryContext);
return factory.getEntity(selectedEntityRef);
}
public Detail[] getDisplayableChildDetails(EvaluationContext ec) {
Vector<Detail> displayableDetails = new Vector<>();
for (Detail d : this.details) {
if (d.isRelevant(ec)) {
displayableDetails.add(d);
}
}
return ArrayUtilities.copyIntoArray(displayableDetails, new Detail[displayableDetails.size()]);
}
/**
* NOTE that this method should only be used/considered in the context of a sub-detail (i.e. a tab)
*
* @param context The context in which to evaluate the relevancy condition
* @return true iff the detail should be displayed as a tab
* @throws XPathSyntaxException
*/
private boolean isRelevant(EvaluationContext context) {
if (parsedRelevancyExpression == null) {
return true;
}
return FunctionUtils.toBoolean(parsedRelevancyExpression.eval(context));
}
} |
package org.concord.energy3d.model;
import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.concord.energy3d.scene.Scene;
import org.concord.energy3d.scene.Scene.TextureMode;
import org.concord.energy3d.shapes.Heliodon;
import org.concord.energy3d.util.SelectUtil;
import com.ardor3d.bounding.BoundingBox;
import com.ardor3d.bounding.BoundingSphere;
import com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils;
import com.ardor3d.extension.model.collada.jdom.ColladaImporter;
import com.ardor3d.extension.model.collada.jdom.ColladaMaterialUtils;
import com.ardor3d.extension.model.collada.jdom.data.ColladaStorage;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.BlendState.TestFunction;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.Spatial;
import com.ardor3d.scenegraph.extension.BillboardNode;
import com.ardor3d.scenegraph.extension.BillboardNode.BillboardAlignment;
import com.ardor3d.scenegraph.hint.CullHint;
import com.ardor3d.scenegraph.shape.Cylinder;
import com.ardor3d.scenegraph.shape.Quad;
import com.ardor3d.scenegraph.shape.Sphere;
import com.ardor3d.util.resource.ResourceLocatorTool;
import com.ardor3d.util.resource.ResourceSource;
public class Tree extends HousePart {
private static final long serialVersionUID = 1L;
private static Spatial treeModel;
private static boolean isBillboard = true;
private transient Spatial model;
private transient BillboardNode billboard;
private transient Node collisionRoot;
private transient Sphere sphere;
public static void loadModel() {
new Thread() {
@Override
public void run() {
System.out.print("Loading tree model...");
Thread.yield();
if (isBillboard) {
} else {
final ResourceSource source = ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_MODEL, "tree3.dae");
final ColladaImporter colladaImporter = new ColladaImporter();
Logger.getLogger(ColladaAnimUtils.class.getName()).setLevel(Level.SEVERE);
Logger.getLogger(ColladaMaterialUtils.class.getName()).setLevel(Level.SEVERE);
ColladaStorage storage;
try {
storage = colladaImporter.load(source);
treeModel = storage.getScene();
} catch (final IOException e) {
e.printStackTrace();
}
}
System.out.println("done");
}
}.start();
}
public Tree() {
super(1, 1, 1);
init();
}
@Override
protected void init() {
super.init();
relativeToHorizontal = true;
if (!isBillboard) {
model = treeModel.makeCopy(true);
root.attachChild(model);
} else {
final double scale = 1 / (Scene.getInstance().getAnnotationScale() / 0.2);
mesh = new Quad("Tree Quad", 30 * scale, 30 * scale);
// mesh.setModelBound(null);
mesh.setModelBound(new BoundingBox());
mesh.updateModelBound();
mesh.setRotation(new Matrix3().fromAngles(Math.PI / 2, 0, 0));
mesh.setTranslation(0, 0, 15 * scale);
final BlendState bs = new BlendState();
bs.setEnabled(true);
bs.setBlendEnabled(false);
bs.setTestEnabled(true);
bs.setTestFunction(TestFunction.GreaterThan);
bs.setReference(0.7f);
mesh.setRenderState(bs);
mesh.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
billboard = new BillboardNode("Billboard");
billboard.setAlignment(BillboardAlignment.AxialZ);
billboard.attachChild(mesh);
root.attachChild(billboard);
sphere = new Sphere("Tree Sphere", 10, 10, 14 * scale);
sphere.setScale(1, 1, 0.7);
sphere.setTranslation(0, 0, 19 * scale);
sphere.setModelBound(new BoundingSphere());
sphere.updateModelBound();
final Cylinder cylinder = new Cylinder("Tree Cylinder", 10, 10, 1 * scale, 20 * scale);
cylinder.setTranslation(0, 0, 10 * scale);
cylinder.setModelBound(new BoundingBox());
cylinder.updateModelBound();
collisionRoot = new Node("Tree Collision Root");
collisionRoot.attachChild(sphere);
collisionRoot.attachChild(cylinder);
if (points.size() > 0)
collisionRoot.setTranslation(getAbsPoint(0));
collisionRoot.updateWorldBound(true);
collisionRoot.getSceneHints().setCullHint(CullHint.Always);
root.attachChild(collisionRoot);
sphere.setUserData(new UserData(this));
cylinder.setUserData(new UserData(this, 0, true));
}
updateTextureAndColor();
}
@Override
public void setPreviewPoint(final int x, final int y) {
final int index = 0;
final PickedHousePart pick = SelectUtil.pickPart(x, y, new Class<?>[] { Foundation.class, null });
if (pick != null) {
final Vector3 p = pick.getPoint();
snapToGrid(p, getAbsPoint(index), getGridSize());
points.get(index).set(toRelative(p));
}
draw();
setEditPointsVisible(true);
}
@Override
public double getGridSize() {
return 5.0;
}
@Override
protected boolean mustHaveContainer() {
return false;
}
@Override
public boolean isPrintable() {
return false;
}
@Override
public boolean isDrawable() {
return true;
}
@Override
protected void drawMesh() {
if (isBillboard) {
billboard.setTranslation(getAbsPoint(0));
collisionRoot.setTranslation(getAbsPoint(0));
} else
model.setTranslation(getAbsPoint(0));
}
@Override
protected String getTextureFileName() {
if (isShedded())
return "tree_shedded.png";
else
return "tree.png";
}
private boolean isShedded() {
final int month = Heliodon.getInstance().getCalander().get(Calendar.MONTH);
return month > 10 || month < 4;
}
@Override
public void updateTextureAndColor() {
if (isBillboard)
updateTextureAndColor(mesh, Scene.getInstance().getWallColor(), TextureMode.Full);
}
public Node getCollisionRoot() {
sphere.removeFromParent();
if (!isShedded())
collisionRoot.attachChild(sphere);
collisionRoot.updateWorldBound(true);
return collisionRoot;
}
} |
package biz.playr;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class StartPlayrServiceAtBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("biz.playr.StartPlayrServiceAtBootReceiver", "overide onReceive");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, biz.playr.PlayrService.class);
context.startService(serviceIntent);
Log.i("biz.playr.StartPlayrServiceAtBootReceiver", "onReceive: started PlayrService");
}
}
} |
package org.dita.dost.chunk;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.module.AbstractPipelineModuleImpl;
import org.dita.dost.pipeline.AbstractPipelineInput;
import org.dita.dost.pipeline.AbstractPipelineOutput;
public class ChunkModule extends AbstractPipelineModuleImpl {
public enum Action {
COMBINE("combine"),
SPLIT("split");
public final String name;
Action(final String name) {
this.name = name;
}
}
@Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException {
}
} |
package com.heavyplayer.tooltip;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.os.Build;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Tooltip extends ViewGroup {
// TODO: Most of these could/should be settable.
private static final int TEXT_SIZE_SP = 15;
private static final int ARROW_SIDE_SIZE_DP = 10;
private static final int ROUNDED_CORNERS_RADII_DP = 4;
private static final int PADDING_VERTICAL_DP = 7;
private static final int PADDING_HORIZONTAL_DP = 14;
private final UpdateWindowListener UPDATE_WINDOW_LISTENER = new UpdateWindowListener();
private Activity mActivity;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mWindowLayoutParams;
private LayoutInflater mLayoutInflater;
private boolean mVisible;
private Rect mTarget;
private View mTargetView;
private Integer mTargetX, mTargetY;
private android.view.Menu mMenu;
private com.actionbarsherlock.view.Menu mMenuSherlock;
private int mMenuItemId;
private int mGravity = Gravity.TOP;
private Point mDisplaySize = new Point();
private Point mWindowPosition = new Point();
private ArrowView mArrowView;
private BalloonView mBalloonView;
private int mColor = Color.WHITE;
private CharSequence mText;
private int mTextColor = Color.BLACK;
private OnShowListener mOnShowListener;
private OnClickListener mOnClickListener;
private OnDismissListener mOnDismissListener;
public Tooltip(Activity activity) {
super(activity);
mActivity = activity;
mWindowManager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE);
mLayoutInflater = (LayoutInflater)activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
public void show() {
// Make sure there are no views (in case show() is called twice).
removeAllViews();
// Create and add inner views.
mArrowView = new ArrowView(mActivity);
addView(mArrowView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mBalloonView = new BalloonView(mActivity);
addView(mBalloonView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
// TODO: Configure the views here instead of having the values read from super (this).
setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOnClickListener != null)
mOnClickListener.onClick(Tooltip.this);
else
dismiss();
}
});
locateTarget(new OnTargetExtractedListener() {
@Override
public void onTargetExtracted(boolean immediate, boolean visible, boolean changed) {
calculateGravity();
calculateWindowPosition();
mWindowLayoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
mWindowPosition.x,
mWindowPosition.y,
WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
mWindowLayoutParams.windowAnimations = R.style.TooltipAnimation;
mWindowLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
mWindowManager.addView(Tooltip.this, mWindowLayoutParams);
if(visible) {
mVisible = true;
} else {
setVisibility(View.GONE);
mVisible = false;
}
if(mTargetView != null)
mTargetView.getViewTreeObserver().addOnPreDrawListener(UPDATE_WINDOW_LISTENER);
if(mOnShowListener != null)
mOnShowListener.onShow(Tooltip.this);
}
});
}
public void dismiss() {
if(mTargetView != null)
mTargetView.getViewTreeObserver().removeOnPreDrawListener(UPDATE_WINDOW_LISTENER);
mWindowLayoutParams.windowAnimations = R.style.TooltipAnimation;
mWindowManager.updateViewLayout(this, mWindowLayoutParams);
mWindowManager.removeView(this);
if(mOnDismissListener != null)
mOnDismissListener.onDismiss(this);
}
private void updateWindow() {
locateTarget(new OnTargetExtractedListener() {
@Override
public void onTargetExtracted(boolean immediate, boolean visible, boolean changed) {
if(changed) {
calculateWindowPosition();
if(mVisible && !visible) {
mWindowLayoutParams.windowAnimations = R.style.TooltipAnimation;
setVisibility(View.GONE);
mVisible = false;
}
else if(!mVisible && visible) {
// Don't use the WindowManager's animation since it doesn't onLayout() until it ends.
Animation inAnim = AnimationUtils.loadAnimation(mActivity, android.R.anim.fade_in);
mArrowView.startAnimation(inAnim);
mBalloonView.startAnimation(inAnim);
mWindowLayoutParams.windowAnimations = 0;
setVisibility(View.VISIBLE);
mVisible = true;
}
mWindowLayoutParams.x = mWindowPosition.x;
mWindowLayoutParams.y = mWindowPosition.y;
mWindowManager.updateViewLayout(Tooltip.this, mWindowLayoutParams);
}
}
});
}
/**
* Set the view which is targeted by this tooltip.
*/
public void setTarget(View targetView) {
mTargetView = targetView;
}
/**
* Set the coordinates which are targeted by this tooltip.
*
* @param targetX the X center coordinate
* @param targetY the Y center coordinate
*/
public void setTarget(int targetX, int targetY) {
mTargetX = targetX;
mTargetY = targetY;
}
/**
* Set the menu item targeted by this tooltip.
*
* Only visible Action Bar menu items are supported. When used with collapsed
* menu items, or the old bottom menus, the behaviour is undefined.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setTarget(android.view.Menu menu, int menuItemId) {
android.view.MenuItem item = menu.findItem(menuItemId);
View actionView = item.getActionView();
if(actionView != null) {
setTarget(actionView);
}
else {
mMenu = menu;
mMenuItemId = menuItemId;
}
}
/**
* Set the menu item targeted by this tooltip.
*
* Only visible Action Bar menu items are supported. When used with collapsed
* menu items, or the old bottom menus, the behaviour is undefined.
*/
public void setTarget(com.actionbarsherlock.view.Menu menu, int menuItemId) {
com.actionbarsherlock.view.MenuItem item = menu.findItem(menuItemId);
View actionView = item.getActionView();
if(actionView != null) {
setTarget(actionView);
}
else {
mMenuSherlock = menu;
mMenuItemId = menuItemId;
}
}
/**
* Set the tooltip's color.
*/
public void setColor(int color) {
mColor = color;
}
/**
* Set the text that appears in the tooltip.
*/
public void setText(CharSequence text) {
mText = text;
}
/**
* Set the tooltip's text color.
*/
public void setTextColor(int textColor) {
mTextColor = textColor;
}
/**
* Set the listener to be invoked when the tooltip is shown.
*/
public void setOnShowListener(OnShowListener listener) {
mOnShowListener = listener;
}
/**
* Set the listener to be invoked when the tooltip is shown. By default, when a tooltip is tapped, it's dismissed.
*/
public void setOnClickListener(OnClickListener listener) {
mOnClickListener = listener;
}
/**
* Set the listener to be invoked when the tooltip is dismissed.
*/
public void setOnDismissListener(OnDismissListener listener) {
mOnDismissListener = listener;
}
@SuppressLint("NewApi")
private void locateTarget(final OnTargetExtractedListener onTargetExtractedListener) {
final Rect previousTarget = mTarget;
if(mTargetX != null && mTargetY != null) {
mTarget = new Rect(mTargetX, mTargetY, mTargetX, mTargetY);
if(onTargetExtractedListener != null) {
calculateDisplaySize();
onTargetExtractedListener.onTargetExtracted(
true,
((mTarget.right >= 0 || mTarget.left <= mDisplaySize.x) && (mTarget.top >= 0 || mTarget.bottom <= mDisplaySize.y)),
!mTarget.equals(previousTarget)
);
}
}
else if(mTargetView != null) {
locateTargetByView(mTargetView);
if(onTargetExtractedListener != null) {
Rect rect = new Rect();
onTargetExtractedListener.onTargetExtracted(
true,
mTargetView.getLocalVisibleRect(rect) && mTargetView.isShown(),
!mTarget.equals(previousTarget)
);
}
}
else if(mMenu != null) {
final android.view.MenuItem item = mMenu.findItem(mMenuItemId);
if(item != null) {
final ViewGroup actionView = getActionView(item.getIcon());
if(actionView != null) {
item.setActionView(actionView);
actionView.post(new Runnable() {
@Override
public void run() {
locateTargetByView(actionView);
if(onTargetExtractedListener != null)
onTargetExtractedListener.onTargetExtracted(
false,
actionView.getLocalVisibleRect(new Rect()) && actionView.isShown(),
!mTarget.equals(previousTarget)
);
item.setActionView(null);
}
});
}
}
}
else if(mMenuSherlock != null) {
final com.actionbarsherlock.view.MenuItem item = mMenuSherlock.findItem(mMenuItemId);
if(item != null) {
final ViewGroup actionView = getActionView(item.getIcon());
item.setActionView(actionView);
if(actionView != null) {
actionView.post(new Runnable() {
@Override
public void run() {
locateTargetByView(actionView);
if(onTargetExtractedListener != null)
onTargetExtractedListener.onTargetExtracted(
false,
actionView.getLocalVisibleRect(new Rect()) && actionView.isShown(),
!mTarget.equals(previousTarget)
);
item.setActionView(null);
}
});
}
}
}
else if(onTargetExtractedListener != null) {
onTargetExtractedListener.onTargetExtracted(true, false, previousTarget != null);
}
}
private ViewGroup getActionView(Drawable icon) {
ViewGroup actionView = (ViewGroup)mLayoutInflater.inflate(R.layout.ab_placeholder_item, new LinearLayout(mActivity), false);
if(actionView != null) {
ImageView iconView = (ImageView)actionView.getChildAt(0);
if(iconView != null)
iconView.setImageDrawable(icon);
}
return actionView;
}
private void calculateGravity() {
if(mTarget == null)
throw new IllegalStateException("You must set some target.");
calculateDisplaySize();
// Multiply each space by the opposite action to uniform the scale.
int leftSpace = mTarget.left * mDisplaySize.y;
int topSpace = mTarget.top * mDisplaySize.x;
int rightSpace = (mDisplaySize.x - mTarget.right) * mDisplaySize.y;
int bottomSpace = (mDisplaySize.y - mTarget.bottom) * mDisplaySize.x;
int mostSpacious = Math.max(leftSpace, Math.max(topSpace, Math.max(rightSpace, bottomSpace)));
// Prefer TOP or BOTTOM by allowing them to be up to 30% smaller.
if(topSpace == mostSpacious || (bottomSpace != mostSpacious && topSpace > 0.7 * mostSpacious))
mGravity = Gravity.TOP;
else if(bottomSpace == mostSpacious || (topSpace != mostSpacious && bottomSpace > 0.7 * mostSpacious))
mGravity = Gravity.BOTTOM;
else if(leftSpace == mostSpacious)
mGravity = Gravity.LEFT;
else if(rightSpace == mostSpacious)
mGravity = Gravity.RIGHT;
}
private void calculateWindowPosition() {
calculateDisplaySize();
ensureChildrenMeasured();
int arrowWidth = mArrowView.getMeasuredWidth();
int arrowHeight = mArrowView.getMeasuredHeight();
int balloonWidth = mBalloonView.getMeasuredWidth();
int balloonHeight = mBalloonView.getMeasuredHeight();
int targetCenterX = getTargetVisibleCenterX();
int targetCenterY = getTargetVisibleCenterY();
int targetWidth = getTargetVisibleWidth();
int targetHeight = getTargetVisibleHeight();
// Set common properties.
switch(mGravity) {
case Gravity.TOP:
case Gravity.BOTTOM:
mWindowPosition.x = targetCenterX - balloonWidth / 2;
break;
case Gravity.LEFT:
case Gravity.RIGHT:
mWindowPosition.y = targetCenterY - balloonHeight / 2;
break;
}
// Set individual properties.
switch(mGravity) {
case Gravity.TOP:
mWindowPosition.y = mTarget.top - balloonHeight - Math.min(arrowHeight / 2, targetHeight / 2);
break;
case Gravity.BOTTOM:
mWindowPosition.y = mTarget.bottom - Math.min(arrowHeight / 2, targetHeight / 2);
break;
case Gravity.LEFT:
mWindowPosition.x = mTarget.left - balloonWidth - Math.min(arrowWidth / 2, targetWidth / 2);
break;
case Gravity.RIGHT:
mWindowPosition.x = mTarget.right - Math.min(arrowWidth / 2, targetWidth / 2);
break;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
ensureChildrenMeasured();
int arrowWidth = mArrowView.getMeasuredWidth();
int arrowHeight = mArrowView.getMeasuredHeight();
int balloonWidth = mBalloonView.getMeasuredWidth();
int balloonHeight = mBalloonView.getMeasuredHeight();
switch(mGravity) {
case Gravity.TOP:
case Gravity.BOTTOM:
setMeasuredDimension(balloonWidth, arrowHeight + balloonHeight);
break;
case Gravity.LEFT:
case Gravity.RIGHT:
setMeasuredDimension(arrowWidth + balloonWidth, balloonHeight);
break;
default:
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
break;
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
calculateDisplaySize();
int width = right - left;
int height = bottom - top;
ensureChildrenMeasured();
int arrowWidth = mArrowView.getMeasuredWidth();
int arrowHeight = mArrowView.getMeasuredHeight();
int balloonWidth = mBalloonView.getMeasuredWidth();
int balloonHeight = mBalloonView.getMeasuredHeight();
// Set the positions.
int arrowLeft = trim(0, mWindowPosition.x + width - mDisplaySize.x, mWindowPosition.x);
int arrowTop = trim(0, mWindowPosition.y + height - mDisplaySize.y, mWindowPosition.y);
int balloonLeft = arrowLeft;
int balloonTop = arrowTop;
// Position arrow and balloon with respect to each other.
switch(mGravity) {
case Gravity.TOP:
arrowLeft += width / 2 - arrowWidth / 2;
arrowTop += balloonHeight;
break;
case Gravity.BOTTOM:
arrowLeft += width / 2 - arrowWidth / 2;
balloonTop += arrowHeight;
break;
case Gravity.LEFT:
arrowLeft += balloonWidth;
arrowTop += height / 2 - arrowHeight / 2;
break;
case Gravity.RIGHT:
arrowTop += height / 2 - arrowHeight / 2;
balloonLeft += arrowWidth;
break;
}
// Don't let the balloon be out of the screen when there's no need.
switch(mGravity) {
case Gravity.TOP:
case Gravity.BOTTOM:
if(balloonLeft < 0)
balloonLeft = Math.min(0, balloonLeft + (balloonWidth / 2 - arrowWidth + getRoundedCornersRadii()));
else if(mWindowPosition.x > mDisplaySize.x - balloonWidth)
balloonLeft = Math.max(0, (mWindowPosition.x - (balloonWidth / 2 - arrowWidth + getRoundedCornersRadii())) - (mDisplaySize.x - balloonWidth));
break;
case Gravity.LEFT:
case Gravity.RIGHT:
if(balloonTop < 0)
balloonTop = Math.min(0, balloonTop + (balloonHeight / 2 - arrowHeight + getRoundedCornersRadii()));
else if(mWindowPosition.y > mDisplaySize.y - balloonHeight)
balloonTop = Math.max(0, (mWindowPosition.y - (balloonHeight / 2 - arrowHeight + getRoundedCornersRadii())) - (mDisplaySize.y - balloonHeight));
break;
}
// Lay out the views.
mArrowView.layout(arrowLeft, arrowTop, arrowLeft + arrowWidth, arrowTop + arrowHeight);
mBalloonView.layout(balloonLeft, balloonTop, balloonLeft + balloonWidth, balloonTop + balloonHeight);
}
private void ensureChildrenMeasured() {
int arrowWidth = mArrowView.getMeasuredWidth();
int arrowHeight = mArrowView.getMeasuredHeight();
if(arrowWidth == 0 || arrowHeight == 0) {
int arrowWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mDisplaySize.x, MeasureSpec.AT_MOST);
int arrowHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mDisplaySize.y, MeasureSpec.AT_MOST);
measureChild(mArrowView, arrowWidthMeasureSpec, arrowHeightMeasureSpec);
}
int balloonWidth = mBalloonView.getMeasuredWidth();
int balloonHeight = mBalloonView.getMeasuredHeight();
if(balloonWidth == 0 || balloonHeight == 0) {
int balloonWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mDisplaySize.x - arrowWidth, MeasureSpec.AT_MOST);
int balloonHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mDisplaySize.y - arrowHeight, MeasureSpec.AT_MOST);
measureChild(mBalloonView, balloonWidthMeasureSpec, balloonHeightMeasureSpec);
}
}
// TODO: Cache these values.
private int getArrowSideSize() {
int px = dpToPx(ARROW_SIDE_SIZE_DP);
return (px & 1) == 0 ? px : px -1; // Ensure it's even.
}
private int getRoundedCornersRadii() {
return dpToPx(ROUNDED_CORNERS_RADII_DP);
}
private int getPaddingVertical() {
return dpToPx(PADDING_VERTICAL_DP);
}
private int getPaddingHorizontal() {
return dpToPx(PADDING_HORIZONTAL_DP);
}
private int getTargetVisibleCenterX() {
return (trim(mTarget.right, 0, mDisplaySize.x) + trim(mTarget.left, 0, mDisplaySize.x)) >> 1;
}
private int getTargetVisibleCenterY() {
return (trim(mTarget.bottom, 0, mDisplaySize.y) + trim(mTarget.top, 0, mDisplaySize.y)) >> 1;
}
private int getTargetVisibleWidth() {
return trim(mTarget.right, 0, mDisplaySize.x) - trim(mTarget.left, 0, mDisplaySize.x);
}
private int getTargetVisibleHeight() {
return trim(mTarget.bottom, 0, mDisplaySize.y) - trim(mTarget.top, 0, mDisplaySize.y);
}
private int dpToPx(int dpValue) {
return (int)TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dpValue, mActivity.getResources().getDisplayMetrics());
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void calculateDisplaySize() {
View decorView = mActivity.getWindow().getDecorView();
int[] position = new int[2];
decorView.getLocationOnScreen(position);
mDisplaySize.x = decorView.getWidth() - position[0];
mDisplaySize.y = decorView.getHeight() - position[1];
}
private void locateTargetByView(View view) {
int[] position = new int[2];
view.getLocationInWindow(position);
mTarget = new Rect();
mTarget.left = position[0];
mTarget.top = position[1];
mTarget.right = mTarget.left + view.getWidth();
mTarget.bottom = mTarget.top + view.getHeight();
}
private int trim(int val, int min, int max) {
return Math.max(min, Math.min(max, val));
}
public interface OnShowListener {
public void onShow(Tooltip tooltip);
}
public interface OnClickListener {
public void onClick(Tooltip tooltip);
}
public interface OnDismissListener {
public void onDismiss(Tooltip tooltip);
}
private class BalloonView extends TextView {
private BalloonView(Context context) {
super(context);
setText(mText);
setTextColor(mTextColor);
setTextSize(TypedValue.COMPLEX_UNIT_SP, TEXT_SIZE_SP);
setTypeface(null, Typeface.BOLD);
setSingleLine(false);
setGravity(Gravity.CENTER);
setPadding(getPaddingHorizontal(), getPaddingVertical(), getPaddingHorizontal(), getPaddingVertical());
setBackground(new ShapeDrawable(new ColoredRoundRectShape(getRoundedCornersRadii())));
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void setBackground(Drawable background) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
super.setBackground(background);
else
super.setBackgroundDrawable(background);
}
private class ColoredRoundRectShape extends RoundRectShape {
private Paint mPaint;
private ColoredRoundRectShape(float radii) {
super(new float[]{radii, radii, radii, radii, radii, radii, radii, radii}, null, null);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(mColor);
}
@Override
public void draw(Canvas canvas, Paint paint) {
super.draw(canvas, mPaint);
}
}
}
private class ArrowView extends View {
private Paint mPaint;
private Path mPath;
public ArrowView(Context context) {
super(context);
}
private void ensurePaint() {
if(mPaint == null) {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
mPaint.setColor(mColor);
}
}
private void ensurePath() {
if(mPath == null) {
mPath = new Path();
mPath.setFillType(Path.FillType.EVEN_ODD);
int otherSideSize = getOtherSideSize();
mPath.moveTo(0, 0);
mPath.lineTo(otherSideSize / 2, getArrowSideSize());
mPath.lineTo(otherSideSize, 0);
mPath.close();
}
}
private int getOtherSideSize() {
return getArrowSideSize() * 2;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
switch(mGravity) {
case Gravity.TOP:
case Gravity.BOTTOM:
setMeasuredDimension(getOtherSideSize(), getArrowSideSize());
break;
case Gravity.LEFT:
case Gravity.RIGHT:
setMeasuredDimension(getArrowSideSize(), getOtherSideSize());
break;
default:
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
break;
}
}
@Override
protected void onDraw(Canvas canvas) {
ensurePaint();
ensurePath();
int count = canvas.save();
switch(mGravity) {
case Gravity.BOTTOM:
canvas.rotate(180, getOtherSideSize() / 2, getArrowSideSize() / 2);
break;
case Gravity.LEFT:
canvas.rotate(-90, getOtherSideSize() / 2, getOtherSideSize() / 2);
break;
case Gravity.RIGHT:
canvas.rotate(90, getArrowSideSize() / 2, getArrowSideSize() / 2);
break;
default:
break;
}
canvas.drawPath(mPath, mPaint);
canvas.restoreToCount(count);
}
}
private interface OnTargetExtractedListener {
/**
* @param immediate true if we were able to extract the target location immediately, false if not
* @param visible true if the target is currently visible on screen, false if not
* @param changed true if the target changed its location, false if not
*/
void onTargetExtracted(boolean immediate, boolean visible, boolean changed);
}
private class UpdateWindowListener implements ViewTreeObserver.OnPreDrawListener {
@Override
public boolean onPreDraw() {
updateWindow();
return true;
}
}
} |
package cltestgrid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
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.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.EntityNotFoundException;
@SuppressWarnings("serial")
public class GetBlob extends HttpServlet {
private static final Logger log = Logger.getLogger(Upload.class.getName());
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException
{
try {
final String key = req.getParameter("key");
BlobKey blobKey;
// the key may be specified in one of two forms:
if (key.length() > 19) {
// Very long string (162 characters) are real blobstore BlobKeys;
// the URLs with such long keys are very nasty.
blobKey = new BlobKey(key);
} else {
// Indirectly, via intermediate short key,
// which is ID of a datastore Entity, storing
// the original BlobKey;
// that way we allow prettier URLs.
Key datastoreKey = KeyFactory.createKey("ShortKey", Long.valueOf(key));
try {
Entity shortKeyEntity = datastore.get(datastoreKey);
blobKey = (BlobKey)shortKeyEntity.getProperty("blobKey");
} catch (EntityNotFoundException e) {
throw new NotFoundException("Unknown key is specified: " + key);
}
}
blobstoreService.serve(blobKey, resp);
} catch (NotFoundException e) {
log.log(Level.SEVERE, "Log not found, returning status 404", e);
resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
}
}
}
class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
} |
package org.jscep.response;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
import java.util.Collections;
import java.util.EnumSet;
/**
* This class represents a set of capabilities for a particular
* SCEP server.
*
* @author David Grant
*/
public class Capabilities {
private EnumSet<Capability> capabilities;
/**
* Constructs a new instance of this class with the specified
* capabilities.
*
* @param capabilities the capabilities.
*/
public Capabilities(Capability... capabilities) {
this.capabilities = EnumSet.noneOf(Capability.class);
Collections.addAll(this.capabilities, capabilities);
}
/**
* Add the provided capability to this capabilities set.
*
* @param capability the capability to add.
*/
public void add(Capability capability) {
capabilities.add(capability);
}
/**
* Returns <code>true</code> if the server supports the provided
* Capability, <code>false</code> otherwise.
*
* @param capability the capability to test for.
* @return <code>true</code> if the server supports the provided
* Capability, <code>false</code> otherwise.
*/
public boolean contains(Capability capability) {
return capabilities.contains(capability);
}
/**
* Returns <tt>true</tt> if POST is supported, <tt>false</tt> otherwise.
*
* @return <tt>true</tt> if POST is supported, <tt>false</tt> otherwise.
*/
public boolean isPostSupported() {
return capabilities.contains(Capability.POST_PKI_OPERATION);
}
/**
* Returns <tt>true</tt> if retrieval of the next CA is supported, <tt>false</tt> otherwise.
*
* @return <tt>true</tt> if retrieval of the next CA is supported, <tt>false</tt> otherwise.
*/
public boolean isRolloverSupported() {
return capabilities.contains(Capability.GET_NEXT_CA_CERT);
}
/**
* Returns <tt>true</tt> if certificate renewal is supported, <tt>false</tt> otherwise.
*
* @return <tt>true</tt> if certificate renewal is supported, <tt>false</tt> otherwise.
*/
public boolean isRenewalSupported() {
return capabilities.contains(Capability.RENEWAL);
}
/**
* Returns the strongest cipher algorithm supported by the server and client.
* <p/>
* The algorithms are ordered thus:
* <ol>
* <li>DESede ("Triple DES")</li>
* <li>DES</li>
* </ol>
*
* @return the strongest cipher algorithm supported by the server and client.
*/
public String getStrongestCipher() {
final String cipher;
if (cipherExists("DESede") && capabilities.contains(Capability.TRIPLE_DES)) {
cipher = "DESede";
} else {
cipher = "DES";
}
return cipher;
}
private boolean cipherExists(String algorithm) {
return algorithmExists("Cipher", algorithm);
}
private boolean algorithmExists(String serviceType, String algorithm) {
for (Provider provider : Security.getProviders()) {
for (Service service : provider.getServices()) {
if (service.getType().equals(serviceType)) {
if (service.getAlgorithm().equals(algorithm)) {
return true;
}
}
}
}
return false;
}
/**
* Returns the strongest message digest algorithm supported by the server and client.
* <p/>
* The algorithms are ordered thus:
* <ol>
* <li>SHA-512</li>
* <li>SHA-256</li>
* <li>SHA-1</li>
* <li>MD5</li>
* </ol>
*
* @return the strongest message digest algorithm supported by the server and client.
*/
public String getStrongestMessageDigest() {
final String digest;
if (digestExists("SHA-512") && capabilities.contains(Capability.SHA_512)) {
digest = "SHA-512";
} else if (digestExists("SHA-256") && capabilities.contains(Capability.SHA_256)) {
digest = "SHA-256";
} else if (digestExists("SHA-1") && capabilities.contains(Capability.SHA_1)) {
digest = "SHA-1";
} else {
digest = "MD5";
}
return digest;
}
private boolean digestExists(String digest) {
return algorithmExists("MessageDigest", digest);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return capabilities.toString();
}
} |
package org.jtrfp.trcl.beh;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.obj.WorldObject;
public class FacingObject extends Behavior {
private WorldObject target;
private final double [] work = new double[3];
private final double [] perp = new double[3];
private final double [] UP = new double[]{0,1,0};
@Override
public void _tick(long tickTimeMillis){
if(target!=null){
final WorldObject parent = getParent();
final double [] tPos = target.getPosition();
final double [] pPos = parent.getPosition();
Vect3D.subtract(tPos, pPos, work);
parent.setHeading(new Vector3D(Vect3D.normalize(work,work)));
Vect3D.cross(work, UP, perp);
Vect3D.cross(perp, work, perp);
parent.setTop(new Vector3D(UP));
}//end if(!null)
}//end _tick(...)
/**
* @return the target
*/
public WorldObject getTarget() {
return target;
}
/**
* @param target the target to set
*/
public FacingObject setTarget(WorldObject target) {
this.target = target;
return this;
}
}//end FacingObject |
package org.kohsuke.github;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang.StringUtils;
import javax.xml.bind.DatatypeConverter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.*;
import static java.util.Arrays.asList;
/**
* A repository on GitHub.
*
* @author Kohsuke Kawaguchi
*/
@SuppressWarnings({"UnusedDeclaration"})
@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD",
"NP_UNWRITTEN_FIELD"}, justification = "JSON API")
public class GHRepository extends GHObject {
/*package almost final*/ GitHub root;
private String description, homepage, name, full_name;
private String html_url; // this is the UI
private String git_url, ssh_url, clone_url, svn_url, mirror_url;
private GHUser owner; // not fully populated. beware.
private boolean has_issues, has_wiki, fork, has_downloads;
@JsonProperty("private")
private boolean _private;
private int watchers,forks,open_issues,size,network_count,subscribers_count;
private String pushed_at;
private Map<Integer,GHMilestone> milestones = new HashMap<Integer, GHMilestone>();
private String default_branch,language;
private Map<String,GHCommit> commits = new HashMap<String, GHCommit>();
private GHRepoPermission permissions;
private GHRepository source, parent;
public GHDeploymentBuilder createDeployment(String ref) {
return new GHDeploymentBuilder(this,ref);
}
public PagedIterable<GHDeploymentStatus> getDeploymentStatuses(final int id) {
return new PagedIterable<GHDeploymentStatus>() {
public PagedIterator<GHDeploymentStatus> _iterator(int pageSize) {
return new PagedIterator<GHDeploymentStatus>(root.retrieve().asIterator(getApiTailUrl("deployments")+"/"+id+"/statuses", GHDeploymentStatus[].class, pageSize)) {
@Override
protected void wrapUp(GHDeploymentStatus[] page) {
for (GHDeploymentStatus c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public PagedIterable<GHDeployment> listDeployments(String sha,String ref,String task,String environment){
List<String> params = Arrays.asList(getParam("sha", sha), getParam("ref", ref), getParam("task", task), getParam("environment", environment));
final String deploymentsUrl = getApiTailUrl("deployments") + "?"+ join(params,"&");
return new PagedIterable<GHDeployment>() {
public PagedIterator<GHDeployment> _iterator(int pageSize) {
return new PagedIterator<GHDeployment>(root.retrieve().asIterator(deploymentsUrl, GHDeployment[].class, pageSize)) {
@Override
protected void wrapUp(GHDeployment[] page) {
for (GHDeployment c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
private String join(List<String> params, String joinStr) {
StringBuilder output = new StringBuilder();
for(String param: params){
if(param != null){
output.append(param+joinStr);
}
}
return output.toString();
}
private String getParam(String name, String value) {
return StringUtils.trimToNull(value)== null? null: name+"="+value;
}
public GHDeploymentStatusBuilder createDeployStatus(int deploymentId, GHDeploymentState ghDeploymentState) {
return new GHDeploymentStatusBuilder(this,deploymentId,ghDeploymentState);
}
private static class GHRepoPermission {
boolean pull,push,admin;
}
public String getDescription() {
return description;
}
public String getHomepage() {
return homepage;
}
/**
* Gets the git:// URL to this repository, such as "git://github.com/kohsuke/jenkins.git"
* This URL is read-only.
*/
public String getGitTransportUrl() {
return git_url;
}
public String gitHttpTransportUrl() {
return clone_url;
}
public String getSvnUrl() {
return svn_url;
}
public String getMirrorUrl() {
return mirror_url;
}
/**
* Gets the SSH URL to access this repository, such as git@github.com:rails/rails.git
*/
public String getSshUrl() {
return ssh_url;
}
public URL getHtmlUrl() {
return GitHub.parseURL(html_url);
}
public String getName() {
return name;
}
public String getFullName() {
return full_name;
}
public boolean hasPullAccess() {
return permissions!=null && permissions.pull;
}
public boolean hasPushAccess() {
return permissions!=null && permissions.push;
}
public boolean hasAdminAccess() {
return permissions!=null && permissions.admin;
}
/**
* Gets the primary programming language.
*/
public String getLanguage() {
return language;
}
public GHUser getOwner() throws IOException {
return root.getUser(owner.login); // because 'owner' isn't fully populated
}
public GHIssue getIssue(int id) throws IOException {
return root.retrieve().to(getApiTailUrl("issues/" + id), GHIssue.class).wrap(this);
}
public GHIssueBuilder createIssue(String title) {
return new GHIssueBuilder(this,title);
}
public List<GHIssue> getIssues(GHIssueState state) throws IOException {
return listIssues(state).asList();
}
public List<GHIssue> getIssues(GHIssueState state, GHMilestone milestone) throws IOException {
return Arrays.asList(GHIssue.wrap(root.retrieve()
.with("state", state)
.with("milestone", milestone == null ? "none" : "" + milestone.getNumber())
.to(getApiTailUrl("issues"),
GHIssue[].class), this));
}
/**
* Lists up all the issues in this repository.
*/
public PagedIterable<GHIssue> listIssues(final GHIssueState state) {
return new PagedIterable<GHIssue>() {
public PagedIterator<GHIssue> _iterator(int pageSize) {
return new PagedIterator<GHIssue>(root.retrieve().with("state",state).asIterator(getApiTailUrl("issues"), GHIssue[].class, pageSize)) {
@Override
protected void wrapUp(GHIssue[] page) {
for (GHIssue c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public GHReleaseBuilder createRelease(String tag) {
return new GHReleaseBuilder(this,tag);
}
/**
* Creates a named ref, such as tag, branch, etc.
*
* @param name
* The name of the fully qualified reference (ie: refs/heads/master).
* If it doesn't start with 'refs' and have at least two slashes, it will be rejected.
* @param sha
* The SHA1 value to set this reference to
*/
public GHRef createRef(String name, String sha) throws IOException {
return new Requester(root)
.with("ref", name).with("sha", sha).method("POST").to(getApiTailUrl("git/refs"), GHRef.class).wrap(root);
}
/**
* @deprecated
* use {@link #listReleases()}
*/
public List<GHRelease> getReleases() throws IOException {
return listReleases().asList();
}
public PagedIterable<GHRelease> listReleases() throws IOException {
return new PagedIterable<GHRelease>() {
public PagedIterator<GHRelease> _iterator(int pageSize) {
return new PagedIterator<GHRelease>(root.retrieve().asIterator(getApiTailUrl("releases"), GHRelease[].class, pageSize)) {
@Override
protected void wrapUp(GHRelease[] page) {
for (GHRelease c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public PagedIterable<GHTag> listTags() throws IOException {
return new PagedIterable<GHTag>() {
public PagedIterator<GHTag> _iterator(int pageSize) {
return new PagedIterator<GHTag>(root.retrieve().asIterator(getApiTailUrl("tags"), GHTag[].class, pageSize)) {
@Override
protected void wrapUp(GHTag[] page) {
for (GHTag c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
/**
* List languages for the specified repository.
* The value on the right of a language is the number of bytes of code written in that language.
* {
"C": 78769,
"Python": 7769
}
*/
public Map<String,Long> listLanguages() throws IOException {
return root.retrieve().to(getApiTailUrl("languages"), HashMap.class);
}
public String getOwnerName() {
return owner.login;
}
public boolean hasIssues() {
return has_issues;
}
public boolean hasWiki() {
return has_wiki;
}
public boolean isFork() {
return fork;
}
/**
* Returns the number of all forks of this repository.
* This not only counts direct forks, but also forks of forks, and so on.
*/
public int getForks() {
return forks;
}
public boolean isPrivate() {
return _private;
}
public boolean hasDownloads() {
return has_downloads;
}
public int getWatchers() {
return watchers;
}
public int getOpenIssueCount() {
return open_issues;
}
public int getNetworkCount() {
return network_count;
}
public int getSubscribersCount() {
return subscribers_count;
}
/**
*
* @return
* null if the repository was never pushed at.
*/
public Date getPushedAt() {
return GitHub.parseDate(pushed_at);
}
/**
* Returns the primary branch you'll configure in the "Admin > Options" config page.
*
* @return
* This field is null until the user explicitly configures the master branch.
*/
public String getDefaultBranch() {
return default_branch;
}
/**
* @deprecated
* Renamed to {@link #getDefaultBranch()}
*/
public String getMasterBranch() {
return default_branch;
}
public int getSize() {
return size;
}
/**
* Gets the collaborators on this repository.
* This set always appear to include the owner.
*/
@WithBridgeMethods(Set.class)
public GHPersonSet<GHUser> getCollaborators() throws IOException {
return new GHPersonSet<GHUser>(listCollaborators().asList());
}
/**
* Lists up the collaborators on this repository.
*
* @return Users
* @throws IOException
*/
public PagedIterable<GHUser> listCollaborators() throws IOException {
return new PagedIterable<GHUser>() {
public PagedIterator<GHUser> _iterator(int pageSize) {
return new PagedIterator<GHUser>(root.retrieve().asIterator(getApiTailUrl("collaborators"), GHUser[].class, pageSize)) {
@Override
protected void wrapUp(GHUser[] users) {
for (GHUser user : users) {
user.wrapUp(root);
}
}
};
}
};
}
/**
* Gets the names of the collaborators on this repository.
* This method deviates from the principle of this library but it works a lot faster than {@link #getCollaborators()}.
*/
public Set<String> getCollaboratorNames() throws IOException {
Set<String> r = new HashSet<String>();
for (GHUser u : GHUser.wrap(root.retrieve().to(getApiTailUrl("collaborators"), GHUser[].class),root))
r.add(u.login);
return r;
}
/**
* If this repository belongs to an organization, return a set of teams.
*/
public Set<GHTeam> getTeams() throws IOException {
return Collections.unmodifiableSet(new HashSet<GHTeam>(Arrays.asList(GHTeam.wrapUp(root.retrieve().to(getApiTailUrl("teams"), GHTeam[].class), root.getOrganization(owner.login)))));
}
public void addCollaborators(GHUser... users) throws IOException {
addCollaborators(asList(users));
}
public void addCollaborators(Collection<GHUser> users) throws IOException {
modifyCollaborators(users, "PUT");
}
public void removeCollaborators(GHUser... users) throws IOException {
removeCollaborators(asList(users));
}
public void removeCollaborators(Collection<GHUser> users) throws IOException {
modifyCollaborators(users, "DELETE");
}
private void modifyCollaborators(Collection<GHUser> users, String method) throws IOException {
verifyMine();
for (GHUser user : users) {
new Requester(root).method(method).to(getApiTailUrl("collaborators/" + user.getLogin()));
}
}
public void setEmailServiceHook(String address) throws IOException {
Map<String, String> config = new HashMap<String, String>();
config.put("address", address);
new Requester(root).method("POST").with("name", "email").with("config", config).with("active", true)
.to(getApiTailUrl("hooks"));
}
private void edit(String key, String value) throws IOException {
Requester requester = new Requester(root);
if (!key.equals("name"))
requester.with("name", name); // even when we don't change the name, we need to send it in
requester.with(key, value).method("PATCH").to(getApiTailUrl(""));
}
/**
* Enables or disables the issue tracker for this repository.
*/
public void enableIssueTracker(boolean v) throws IOException {
edit("has_issues", String.valueOf(v));
}
/**
* Enables or disables Wiki for this repository.
*/
public void enableWiki(boolean v) throws IOException {
edit("has_wiki", String.valueOf(v));
}
public void enableDownloads(boolean v) throws IOException {
edit("has_downloads",String.valueOf(v));
}
/**
* Rename this repository.
*/
public void renameTo(String name) throws IOException {
edit("name",name);
}
public void setDescription(String value) throws IOException {
edit("description",value);
}
public void setHomepage(String value) throws IOException {
edit("homepage",value);
}
public void setDefaultBranch(String value) throws IOException {
edit("default_branch", value);
}
/**
* Deletes this repository.
*/
public void delete() throws IOException {
try {
new Requester(root).method("DELETE").to(getApiTailUrl(""));
} catch (FileNotFoundException x) {
throw (FileNotFoundException) new FileNotFoundException("Failed to delete " + owner.login + "/" + name + "; might not exist, or you might need the delete_repo scope in your token: http://stackoverflow.com/a/19327004/12916").initCause(x);
}
}
/**
* Sort orders for listing forks
*/
public enum ForkSort { NEWEST, OLDEST, STARGAZERS }
/**
* Lists all the direct forks of this repository, sorted by
* github api default, currently {@link ForkSort#NEWEST ForkSort.NEWEST}.
*/
public PagedIterable<GHRepository> listForks() {
return listForks(null);
}
/**
* Lists all the direct forks of this repository, sorted by the given sort order.
* @param sort the sort order. If null, defaults to github api default,
* currently {@link ForkSort#NEWEST ForkSort.NEWEST}.
*/
public PagedIterable<GHRepository> listForks(final ForkSort sort) {
return new PagedIterable<GHRepository>() {
public PagedIterator<GHRepository> _iterator(int pageSize) {
return new PagedIterator<GHRepository>(root.retrieve().with("sort",sort).asIterator(getApiTailUrl("forks"), GHRepository[].class, pageSize)) {
@Override
protected void wrapUp(GHRepository[] page) {
for (GHRepository c : page) {
c.wrap(root);
}
}
};
}
};
}
/**
* Forks this repository as your repository.
*
* @return
* Newly forked repository that belong to you.
*/
public GHRepository fork() throws IOException {
return new Requester(root).method("POST").to(getApiTailUrl("forks"), GHRepository.class).wrap(root);
}
/**
* Forks this repository into an organization.
*
* @return
* Newly forked repository that belong to you.
*/
public GHRepository forkTo(GHOrganization org) throws IOException {
new Requester(root).to(getApiTailUrl("forks?org="+org.getLogin()));
// this API is asynchronous. we need to wait for a bit
for (int i=0; i<10; i++) {
GHRepository r = org.getRepository(name);
if (r!=null) return r;
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw (IOException)new InterruptedIOException().initCause(e);
}
}
throw new IOException(this+" was forked into "+org.getLogin()+" but can't find the new repository");
}
/**
* Retrieves a specified pull request.
*/
public GHPullRequest getPullRequest(int i) throws IOException {
return root.retrieve().to(getApiTailUrl("pulls/" + i), GHPullRequest.class).wrapUp(this);
}
/**
* Retrieves all the pull requests of a particular state.
*
* @see #listPullRequests(GHIssueState)
*/
public List<GHPullRequest> getPullRequests(GHIssueState state) throws IOException {
return queryPullRequests().state(state).list().asList();
}
/**
* Retrieves all the pull requests of a particular state.
*
* @deprecated
* Use {@link #queryPullRequests()}
*/
public PagedIterable<GHPullRequest> listPullRequests(GHIssueState state) {
return queryPullRequests().state(state).list();
}
/**
* Retrieves pull requests.
*/
public GHPullRequestQueryBuilder queryPullRequests() {
return new GHPullRequestQueryBuilder(this);
}
/**
* Creates a new pull request.
*
* @param title
* Required. The title of the pull request.
* @param head
* Required. The name of the branch where your changes are implemented.
* For cross-repository pull requests in the same network,
* namespace head with a user like this: username:branch.
* @param base
* Required. The name of the branch you want your changes pulled into.
* This should be an existing branch on the current repository.
* @param body
* The contents of the pull request. This is the markdown description
* of a pull request.
*/
public GHPullRequest createPullRequest(String title, String head, String base, String body) throws IOException {
return new Requester(root).with("title",title)
.with("head",head)
.with("base",base)
.with("body",body).to(getApiTailUrl("pulls"),GHPullRequest.class).wrapUp(this);
}
/**
* Retrieves the currently configured hooks.
*/
public List<GHHook> getHooks() throws IOException {
return GHHooks.repoContext(this, owner).getHooks();
}
public GHHook getHook(int id) throws IOException {
return GHHooks.repoContext(this, owner).getHook(id);
}
/**
* Gets a comparison between 2 points in the repository. This would be similar
* to calling <tt>git log id1...id2</tt> against a local repository.
* @param id1 an identifier for the first point to compare from, this can be a sha1 ID (for a commit, tag etc) or a direct tag name
* @param id2 an identifier for the second point to compare to. Can be the same as the first point.
* @return the comparison output
* @throws IOException on failure communicating with GitHub
*/
public GHCompare getCompare(String id1, String id2) throws IOException {
GHCompare compare = root.retrieve().to(getApiTailUrl(String.format("compare/%s...%s", id1, id2)), GHCompare.class);
return compare.wrap(this);
}
public GHCompare getCompare(GHCommit id1, GHCommit id2) throws IOException {
return getCompare(id1.getSHA1(), id2.getSHA1());
}
public GHCompare getCompare(GHBranch id1, GHBranch id2) throws IOException {
GHRepository owner1 = id1.getOwner();
GHRepository owner2 = id2.getOwner();
// If the owner of the branches is different, we have a cross-fork compare.
if (owner1!=null && owner2!=null) {
String ownerName1 = owner1.getOwnerName();
String ownerName2 = owner2.getOwnerName();
if (!StringUtils.equals(ownerName1, ownerName2)) {
String qualifiedName1 = String.format("%s:%s", ownerName1, id1.getName());
String qualifiedName2 = String.format("%s:%s", ownerName2, id2.getName());
return getCompare(qualifiedName1, qualifiedName2);
}
}
return getCompare(id1.getName(), id2.getName());
}
/**
* Retrieves all refs for the github repository.
* @return an array of GHRef elements coresponding with the refs in the remote repository.
* @throws IOException on failure communicating with GitHub
*/
public GHRef[] getRefs() throws IOException {
return GHRef.wrap(root.retrieve().to(String.format("/repos/%s/%s/git/refs", owner.login, name), GHRef[].class), root);
}
/**
* Retrieves all refs of the given type for the current GitHub repository.
* @param refType the type of reg to search for e.g. <tt>tags</tt> or <tt>commits</tt>
* @return an array of all refs matching the request type
* @throws IOException on failure communicating with GitHub, potentially due to an invalid ref type being requested
*/
public GHRef[] getRefs(String refType) throws IOException {
return GHRef.wrap(root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", owner.login, name, refType), GHRef[].class),root);
}
/**
* Retrive a ref of the given type for the current GitHub repository.
*
* @param refName
* eg: heads/branch
* @return refs matching the request type
* @throws IOException
* on failure communicating with GitHub, potentially due to an
* invalid ref type being requested
*/
public GHRef getRef(String refName) throws IOException {
return root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", owner.login, name, refName), GHRef.class).wrap(root);
}
/**
* Retrive a tree of the given type for the current GitHub repository.
*
* @param sha - sha number or branch name ex: "master"
* @return refs matching the request type
* @throws IOException
* on failure communicating with GitHub, potentially due to an
* invalid tree type being requested
*/
public GHTree getTree(String sha) throws IOException {
String url = String.format("/repos/%s/%s/git/trees/%s", owner.login, name, sha);
return root.retrieve().to(url, GHTree.class).wrap(root);
}
public GHTree getTreeRecursive(String sha, int recursive) throws IOException {
String url = String.format("/repos/%s/%s/git/trees/%s?recursive=%d", owner.login, name, sha, recursive);
return root.retrieve().to(url, GHTree.class).wrap(root);
}
/**
* Gets a commit object in this repository.
*/
public GHCommit getCommit(String sha1) throws IOException {
GHCommit c = commits.get(sha1);
if (c==null) {
c = root.retrieve().to(String.format("/repos/%s/%s/commits/%s", owner.login, name, sha1), GHCommit.class).wrapUp(this);
commits.put(sha1,c);
}
return c;
}
/**
* Lists all the commits.
*/
public PagedIterable<GHCommit> listCommits() {
return new PagedIterable<GHCommit>() {
public PagedIterator<GHCommit> _iterator(int pageSize) {
return new PagedIterator<GHCommit>(root.retrieve().asIterator(String.format("/repos/%s/%s/commits", owner.login, name), GHCommit[].class, pageSize)) {
protected void wrapUp(GHCommit[] page) {
for (GHCommit c : page)
c.wrapUp(GHRepository.this);
}
};
}
};
}
/**
* Search commits by specifying filters through a builder pattern.
*/
public GHCommitQueryBuilder queryCommits() {
return new GHCommitQueryBuilder(this);
}
/**
* Lists up all the commit comments in this repository.
*/
public PagedIterable<GHCommitComment> listCommitComments() {
return new PagedIterable<GHCommitComment>() {
public PagedIterator<GHCommitComment> _iterator(int pageSize) {
return new PagedIterator<GHCommitComment>(root.retrieve().asIterator(String.format("/repos/%s/%s/comments", owner.login, name), GHCommitComment[].class, pageSize)) {
@Override
protected void wrapUp(GHCommitComment[] page) {
for (GHCommitComment c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
/**
* Lists all the commit statues attached to the given commit, newer ones first.
*/
public PagedIterable<GHCommitStatus> listCommitStatuses(final String sha1) throws IOException {
return new PagedIterable<GHCommitStatus>() {
public PagedIterator<GHCommitStatus> _iterator(int pageSize) {
return new PagedIterator<GHCommitStatus>(root.retrieve().asIterator(String.format("/repos/%s/%s/statuses/%s", owner.login, name, sha1), GHCommitStatus[].class, pageSize)) {
@Override
protected void wrapUp(GHCommitStatus[] page) {
for (GHCommitStatus c : page)
c.wrapUp(root);
}
};
}
};
}
/**
* Gets the last status of this commit, which is what gets shown in the UI.
*/
public GHCommitStatus getLastCommitStatus(String sha1) throws IOException {
List<GHCommitStatus> v = listCommitStatuses(sha1).asList();
return v.isEmpty() ? null : v.get(0);
}
/**
* Creates a commit status
*
* @param targetUrl
* Optional parameter that points to the URL that has more details.
* @param description
* Optional short description.
* @param context
* Optinal commit status context.
*/
public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description, String context) throws IOException {
return new Requester(root)
.with("state", state)
.with("target_url", targetUrl)
.with("description", description)
.with("context", context)
.to(String.format("/repos/%s/%s/statuses/%s",owner.login,this.name,sha1),GHCommitStatus.class).wrapUp(root);
}
/**
* @see #createCommitStatus(String, GHCommitState,String,String,String)
*/
public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description) throws IOException {
return createCommitStatus(sha1, state, targetUrl, description, null);
}
/**
* Lists repository events.
*/
public PagedIterable<GHEventInfo> listEvents() throws IOException {
return new PagedIterable<GHEventInfo>() {
public PagedIterator<GHEventInfo> _iterator(int pageSize) {
return new PagedIterator<GHEventInfo>(root.retrieve().asIterator(String.format("/repos/%s/%s/events", owner.login, name), GHEventInfo[].class, pageSize)) {
@Override
protected void wrapUp(GHEventInfo[] page) {
for (GHEventInfo c : page)
c.wrapUp(root);
}
};
}
};
}
public PagedIterable<GHLabel> listLabels() throws IOException {
return new PagedIterable<GHLabel>() {
public PagedIterator<GHLabel> _iterator(int pageSize) {
return new PagedIterator<GHLabel>(root.retrieve().asIterator(getApiTailUrl("labels"), GHLabel[].class, pageSize)) {
@Override
protected void wrapUp(GHLabel[] page) {
for (GHLabel c : page)
c.wrapUp(GHRepository.this);
}
};
}
};
}
public GHLabel getLabel(String name) throws IOException {
return root.retrieve().to(getApiTailUrl("labels/"+name), GHLabel.class).wrapUp(this);
}
public GHLabel createLabel(String name, String color) throws IOException {
return root.retrieve().method("POST")
.with("name",name)
.with("color", color)
.to(getApiTailUrl("labels"), GHLabel.class).wrapUp(this);
}
public PagedIterable<GHUser> listSubscribers() {
return listUsers("subscribers");
}
/**
* Lists all the users who have starred this repo.
*/
public PagedIterable<GHUser> listStargazers() {
return listUsers("stargazers");
}
private PagedIterable<GHUser> listUsers(final String suffix) {
return new PagedIterable<GHUser>() {
public PagedIterator<GHUser> _iterator(int pageSize) {
return new PagedIterator<GHUser>(root.retrieve().asIterator(getApiTailUrl(suffix), GHUser[].class, pageSize)) {
protected void wrapUp(GHUser[] page) {
for (GHUser c : page)
c.wrapUp(root);
}
};
}
};
}
public GHHook createHook(String name, Map<String,String> config, Collection<GHEvent> events, boolean active) throws IOException {
return GHHooks.repoContext(this, owner).createHook(name, config, events, active);
}
public GHHook createWebHook(URL url, Collection<GHEvent> events) throws IOException {
return createHook("web",Collections.singletonMap("url",url.toExternalForm()),events,true);
}
public GHHook createWebHook(URL url) throws IOException {
return createWebHook(url,null);
}
// this is no different from getPullRequests(OPEN)
// /**
// * Retrieves all the pull requests.
// */
// public List<GHPullRequest> getPullRequests() throws IOException {
// return root.retrieveWithAuth("/pulls/"+owner+'/'+name,JsonPullRequests.class).wrap(root);
private void verifyMine() throws IOException {
if (!root.login.equals(owner.login))
throw new IOException("Operation not applicable to a repository owned by someone else: "+owner.login);
}
/**
* Returns a set that represents the post-commit hook URLs.
* The returned set is live, and changes made to them are reflected to GitHub.
*
* @deprecated
* Use {@link #getHooks()} and {@link #createHook(String, Map, Collection, boolean)}
*/
@SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS",
justification = "It causes a performance degradation, but we have already exposed it to the API")
public Set<URL> getPostCommitHooks() {
return postCommitHooks;
}
/**
* Live set view of the post-commit hook.
*/
@SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS",
justification = "It causes a performance degradation, but we have already exposed it to the API")
private final Set<URL> postCommitHooks = new AbstractSet<URL>() {
private List<URL> getPostCommitHooks() {
try {
List<URL> r = new ArrayList<URL>();
for (GHHook h : getHooks()) {
if (h.getName().equals("web")) {
r.add(new URL(h.getConfig().get("url")));
}
}
return r;
} catch (IOException e) {
throw new GHException("Failed to retrieve post-commit hooks",e);
}
}
@Override
public Iterator<URL> iterator() {
return getPostCommitHooks().iterator();
}
@Override
public int size() {
return getPostCommitHooks().size();
}
@Override
public boolean add(URL url) {
try {
createWebHook(url);
return true;
} catch (IOException e) {
throw new GHException("Failed to update post-commit hooks",e);
}
}
@Override
public boolean remove(Object url) {
try {
String _url = ((URL)url).toExternalForm();
for (GHHook h : getHooks()) {
if (h.getName().equals("web") && h.getConfig().get("url").equals(_url)) {
h.delete();
return true;
}
}
return false;
} catch (IOException e) {
throw new GHException("Failed to update post-commit hooks",e);
}
}
};
/*package*/ GHRepository wrap(GitHub root) {
this.root = root;
return this;
}
/**
* Gets branches by {@linkplain GHBranch#getName() their names}.
*/
public Map<String,GHBranch> getBranches() throws IOException {
Map<String,GHBranch> r = new TreeMap<String,GHBranch>();
for (GHBranch p : root.retrieve().to(getApiTailUrl("branches"), GHBranch[].class)) {
p.wrap(this);
r.put(p.getName(),p);
}
return r;
}
/**
* @deprecated
* Use {@link #listMilestones(GHIssueState)}
*/
public Map<Integer, GHMilestone> getMilestones() throws IOException {
Map<Integer,GHMilestone> milestones = new TreeMap<Integer, GHMilestone>();
for (GHMilestone m : listMilestones(GHIssueState.OPEN)) {
milestones.put(m.getNumber(), m);
}
return milestones;
}
/**
* Lists up all the milestones in this repository.
*/
public PagedIterable<GHMilestone> listMilestones(final GHIssueState state) {
return new PagedIterable<GHMilestone>() {
public PagedIterator<GHMilestone> _iterator(int pageSize) {
return new PagedIterator<GHMilestone>(root.retrieve().with("state",state).asIterator(getApiTailUrl("milestones"), GHMilestone[].class, pageSize)) {
@Override
protected void wrapUp(GHMilestone[] page) {
for (GHMilestone c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public GHMilestone getMilestone(int number) throws IOException {
GHMilestone m = milestones.get(number);
if (m == null) {
m = root.retrieve().to(getApiTailUrl("milestones/" + number), GHMilestone.class);
m.owner = this;
m.root = root;
milestones.put(m.getNumber(), m);
}
return m;
}
public GHContent getFileContent(String path) throws IOException {
return getFileContent(path, null);
}
public GHContent getFileContent(String path, String ref) throws IOException {
Requester requester = root.retrieve();
String target = getApiTailUrl("contents/" + path);
return requester.with("ref",ref).to(target, GHContent.class).wrap(this);
}
public List<GHContent> getDirectoryContent(String path) throws IOException {
return getDirectoryContent(path, null);
}
public List<GHContent> getDirectoryContent(String path, String ref) throws IOException {
Requester requester = root.retrieve();
while (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
String target = getApiTailUrl("contents/" + path);
GHContent[] files = requester.with("ref",ref).to(target, GHContent[].class);
GHContent.wrap(files, this);
return Arrays.asList(files);
}
public GHContent getReadme() throws IOException {
Requester requester = root.retrieve();
return requester.to(getApiTailUrl("readme"), GHContent.class).wrap(this);
}
public GHContentUpdateResponse createContent(String content, String commitMessage, String path) throws IOException {
return createContent(content, commitMessage, path, null);
}
public GHContentUpdateResponse createContent(String content, String commitMessage, String path, String branch) throws IOException {
final byte[] payload;
try {
payload = content.getBytes("UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new IOException("UTF-8 encoding is not supported", ex);
}
return createContent(payload, commitMessage, path, branch);
}
public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path) throws IOException {
return createContent(contentBytes, commitMessage, path, null);
}
public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path, String branch) throws IOException {
Requester requester = new Requester(root)
.with("path", path)
.with("message", commitMessage)
.with("content", DatatypeConverter.printBase64Binary(contentBytes))
.method("PUT");
if (branch != null) {
requester.with("branch", branch);
}
GHContentUpdateResponse response = requester.to(getApiTailUrl("contents/" + path), GHContentUpdateResponse.class);
response.getContent().wrap(this);
response.getCommit().wrapUp(this);
return response;
}
public GHMilestone createMilestone(String title, String description) throws IOException {
return new Requester(root)
.with("title", title).with("description", description).method("POST").to(getApiTailUrl("milestones"), GHMilestone.class).wrap(this);
}
public GHDeployKey addDeployKey(String title,String key) throws IOException {
return new Requester(root)
.with("title", title).with("key", key).method("POST").to(getApiTailUrl("keys"), GHDeployKey.class).wrap(this);
}
public List<GHDeployKey> getDeployKeys() throws IOException{
List<GHDeployKey> list = new ArrayList<GHDeployKey>(Arrays.asList(
root.retrieve().to(getApiTailUrl("keys"), GHDeployKey[].class)));
for (GHDeployKey h : list)
h.wrap(this);
return list;
}
/**
* Forked repositories have a 'source' attribute that specifies the ultimate source of the forking chain.
*
* @return
* {@link GHRepository} that points to the root repository where this repository is forked
* (indirectly or directly) from. Otherwise null.
* @see #getParent()
*/
public GHRepository getSource() throws IOException {
if (source == null) return null;
if (source.root == null)
source = root.getRepository(source.getFullName());
return source;
}
/**
* Forked repositories have a 'parent' attribute that specifies the repository this repository
* is directly forked from. If we keep traversing {@link #getParent()} until it returns null, that
* is {@link #getSource()}.
*
* @return
* {@link GHRepository} that points to the repository where this repository is forked
* directly from. Otherwise null.
* @see #getSource()
*/
public GHRepository getParent() throws IOException {
if (parent == null) return null;
if (parent.root == null)
parent = root.getRepository(parent.getFullName());
return parent;
}
/**
* Subscribes to this repository to get notifications.
*/
public GHSubscription subscribe(boolean subscribed, boolean ignored) throws IOException {
return new Requester(root)
.with("subscribed", subscribed)
.with("ignored", ignored)
.method("PUT").to(getApiTailUrl("subscription"), GHSubscription.class).wrapUp(this);
}
/**
* Returns the current subscription.
*
* @return null if no subscription exists.
*/
public GHSubscription getSubscription() throws IOException {
try {
return root.retrieve().to(getApiTailUrl("subscription"), GHSubscription.class).wrapUp(this);
} catch (FileNotFoundException e) {
return null;
}
}
public PagedIterable<Contributor> listContributors() throws IOException {
return new PagedIterable<Contributor>() {
public PagedIterator<Contributor> _iterator(int pageSize) {
return new PagedIterator<Contributor>(root.retrieve().asIterator(getApiTailUrl("contributors"), Contributor[].class, pageSize)) {
@Override
protected void wrapUp(Contributor[] page) {
for (Contributor c : page)
c.wrapUp(root);
}
};
}
};
}
public static class Contributor extends GHUser {
private int contributions;
public int getContributions() {
return contributions;
}
@Override
public int hashCode() {
// We ignore contributions in the calculation
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
// We ignore contributions in the calculation
return super.equals(obj);
}
}
/**
* Render a Markdown document.
*
* In {@linkplain MarkdownMode#GFM GFM mode}, issue numbers and user mentions
* are linked accordingly.
*
* @see GitHub#renderMarkdown(String)
*/
public Reader renderMarkdown(String text, MarkdownMode mode) throws IOException {
return new InputStreamReader(
new Requester(root)
.with("text", text)
.with("mode",mode==null?null:mode.toString())
.with("context", getFullName())
.asStream("/markdown"),
"UTF-8");
}
/**
* List all the notifications in a repository for the current user.
*/
public GHNotificationStream listNotifications() {
return new GHNotificationStream(root,getApiTailUrl("/notifications"));
}
@Override
public String toString() {
return "Repository:"+owner.login+":"+name;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof GHRepository) {
GHRepository that = (GHRepository) obj;
return this.owner.login.equals(that.owner.login)
&& this.name.equals(that.name);
}
return false;
}
String getApiTailUrl(String tail) {
if (tail.length()>0 && !tail.startsWith("/")) tail='/'+tail;
return "/repos/" + owner.login + "/" + name +tail;
}
} |
package cn.updev.Database;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
/** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal();
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;
/** Log4j */
private static Logger logger = Logger.getLogger(HibernateSessionFactory.class);
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the SessionFactory if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
logger.error("SessionFactory!");
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* Default constructor.
*/
private HibernateSessionFactory() {
}
} |
package org.lantern.state;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.codehaus.jackson.map.annotate.JsonView;
import org.lantern.GeoData;
import org.lantern.LanternUtils;
import org.lantern.monitoring.Counter;
import org.lantern.monitoring.Stats;
import org.lantern.monitoring.Stats.Counters;
import org.lantern.monitoring.Stats.Gauges;
import org.lantern.monitoring.Stats.Members;
import org.lantern.state.Model.Persistent;
import org.lantern.state.Model.Run;
/**
* Tracks statistics for this instance of Lantern.
*/
public class InstanceStats {
private Counter allBytes = Counter.averageOverOneSecond();
private Counter requestsGiven = Counter.averageOverOneSecond();
private Counter bytesGiven = Counter.averageOverOneSecond();
private Counter requestsGotten = Counter.averageOverOneSecond();
private Counter bytesGotten = Counter.averageOverOneSecond();
private Counter directBytes = Counter.averageOverOneSecond();
private AtomicBoolean usingUPnP = new AtomicBoolean(false);
private AtomicBoolean usingNATPMP = new AtomicBoolean(false);
private final Set<InetAddress> distinctProxiedClientAddresses = new HashSet<InetAddress>();
private final Map<String, Long> bytesGivenPerCountry = new HashMap<String, Long>();
@JsonView({ Run.class, Persistent.class })
public Counter getAllBytes() {
return allBytes;
}
public void setAllBytes(Counter allBytes) {
this.allBytes = allBytes;
}
public void addAllBytes(long bytes) {
allBytes.add(bytes);
}
@JsonView({ Run.class, Persistent.class })
public Counter getRequestsGiven() {
return requestsGiven;
}
public void setRequestsGiven(Counter requestsGiven) {
this.requestsGiven = requestsGiven;
}
public void addRequestGiven() {
requestsGiven.add(1);
}
@JsonView({ Run.class, Persistent.class })
public Counter getBytesGiven() {
return bytesGiven;
}
public void setBytesGiven(Counter bytesGiven) {
this.bytesGiven = bytesGiven;
}
synchronized public void addBytesGivenForLocation(GeoData geoData,
long bytes) {
bytesGiven.add(bytes);
if (geoData != null) {
String countryCode = geoData.getCountrycode();
Long originalBytes = bytesGivenPerCountry.get(countryCode);
if (originalBytes == null) {
originalBytes = 0l;
}
bytesGivenPerCountry.put(countryCode, originalBytes + bytes);
}
}
@JsonView({ Run.class, Persistent.class })
public Counter getRequestsGotten() {
return requestsGotten;
}
public void setRequestsGotten(Counter requestsGotten) {
this.requestsGotten = requestsGotten;
}
public void incrementRequestGotten() {
requestsGotten.add(1);
}
@JsonView({ Run.class, Persistent.class })
public Counter getBytesGotten() {
return bytesGotten;
}
public void setBytesGotten(Counter bytesGotten) {
this.bytesGotten = bytesGotten;
}
public void addBytesGotten(long bytes) {
bytesGotten.add(bytes);
}
@JsonView({ Run.class, Persistent.class })
public Counter getDirectBytes() {
return directBytes;
}
public void setDirectBytes(Counter directBytes) {
this.directBytes = directBytes;
}
public void addDirectBytes(long bytes) {
directBytes.add(bytes);
}
@JsonView({ Run.class })
public boolean getUsingUPnP() {
return usingUPnP.get();
}
public void setUsingUPnP(boolean usingUPnP) {
this.usingUPnP.set(usingUPnP);
}
@JsonView({ Run.class })
public boolean getUsingNATPMP() {
return usingNATPMP.get();
}
public void setUsingNATPMP(boolean usingNATPMP) {
this.usingNATPMP.set(usingNATPMP);
}
synchronized public void addProxiedClientAddress(InetAddress address) {
distinctProxiedClientAddresses.add(address);
}
@JsonView({ Run.class })
public long getDistinctPeers() {
return distinctProxiedClientAddresses.size();
}
public Stats toInstanceStats() {
Stats stats = new Stats();
long requestsGiven = this.requestsGiven.captureDelta();
long bytesGiven = this.bytesGiven.captureDelta();
stats.setIncrement(Counters.requestsGiven, requestsGiven);
stats.setIncrement(Counters.bytesGiven, bytesGiven);
if (LanternUtils.isFallbackProxy()) {
stats.setIncrement(Counters.requestsGivenByFallback,
requestsGiven);
stats.setIncrement(Counters.bytesGivenByFallback, bytesGiven);
} else {
stats.setIncrement(Counters.requestsGivenByPeer, requestsGiven);
stats.setIncrement(Counters.bytesGivenByPeer, bytesGiven);
}
stats.setIncrement(Counters.requestsGotten,
requestsGotten.captureDelta());
stats.setIncrement(Counters.bytesGotten, bytesGotten.captureDelta());
stats.setIncrement(Counters.directBytes, directBytes.captureDelta());
synchronized (bytesGivenPerCountry) {
for (Map.Entry<String, Long> entry : bytesGivenPerCountry
.entrySet()) {
stats.setIncrement(Counters.bytesGiven,
entry.getKey().toLowerCase(),
entry.getValue());
if (LanternUtils.isFallbackProxy()) {
stats.setIncrement(Counters.bytesGivenByFallback,
entry.getKey().toLowerCase(),
entry.getValue());
}
}
bytesGivenPerCountry.clear();
}
stats.setGauge(Gauges.usingUPnP, usingUPnP.get() ? 1 : 0);
stats.setGauge(Gauges.usingNATPMP, usingNATPMP.get() ? 1 : 0);
stats.setGauge(Gauges.bpsGiven, this.bytesGiven.getRate());
if (LanternUtils.isFallbackProxy()) {
stats.setGauge(Gauges.bpsGivenByFallback,
this.bytesGiven.getRate());
} else {
stats.setGauge(Gauges.bpsGivenByPeer, this.bytesGiven.getRate());
}
stats.setGauge(Gauges.bpsGotten, bytesGotten.getRate());
stats.setGauge(Gauges.distinctPeers, getDistinctPeers());
return stats;
}
public Stats toUserStats(
String userGuid,
boolean giving,
boolean getting) {
Stats stats = new Stats();
stats.setGauge(Gauges.userOnline, 1);
if (giving) {
stats.setGauge(Gauges.userOnlineGiving, 1);
}
if (getting) {
stats.setGauge(Gauges.userOnlineGetting, 1);
}
stats.setMember(Members.userOnlineEver, userGuid);
return stats;
}
} |
package com.CS2103.TextBuddy_v2;
import java.text.SimpleDateFormat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.io.*;
import java.util.StringTokenizer;
public class TextBuddyPlusPlus {
private static final String APP_COMMAND = "TextBuddy";
private static final String MSG_WELCOME = "Welcome to TextBuddy. %s is ready for use\n";
private static final String COMMAND = "command: ";
private static final String MSG_LIST_EMPTY = "%s is empty\n";
private static final String MSG_PRINT_LIST = "%d. %s\n";
private static final String MSG_ADDED_ELEMENT = "added to %s: \"%s\"\n";
private static final String MSG_DELETE_ELEMENT = "delete from %s: \"%s\"\n";
private static final String MSG_CLEAR_LIST = "all content deleted from %s\n";
private static final String MSG_ERROR_SAVING = "Error encountered when saving %s\n";
private static final String MSG_ERROR_READING = "Error encountered when reading %s\n";
private static final String MSG_INVALID_COMMAND = "Invalid command!\n";
private static final String MSG_INVALID_ELEID = "Invalid element ID\n";
private static final String MSG_SEARCH_FAIL = "\'%s\': keyword could not be found.\n";
private static final String MSG_SEARCH_INVALID = "Search Invalid!";
private static final String MSG_SORT_SUCCESS = "Successfully Sorted! \"%s\"";
// Points to current directory
private static final String CURRENT_DIRECTORY = System.getProperty("user.dir") + "/";
private static final String TXT_EXTENSION = ".txt";
// Booleans used when saving file
private static final boolean FILE_SAVE_SUCCESSFUL = true;
private static final boolean FILE_SAVE_UNSUCCESSFUL = false;
// Enumerated types of command
enum COMMAND_TYPE {
DISPLAY, ADD, DELETE, CLEAR, SORT, SEARCH, INVALID, EXIT
};
private static final ArrayList<String> list = new ArrayList<String>();
private static final BufferedReader buffered_reader = new BufferedReader(new InputStreamReader(System.in));
private static String file_name;
/**
* Initialize TextBuddy
* Usage: java TextBuddy <file_name>
* @param args Input parameters to execute TextBuddy.
* @throws IOException
*/
public static void main(String[] args) throws IOException {
TextBuddyPlusPlus textbuddypp = new TextBuddyPlusPlus();
textbuddypp.TextBuddy(args);
textbuddypp.processUserCommands();
}
public static void TextBuddy(String[] args) throws ArrayIndexOutOfBoundsException {
/* Check for filename in program input parameter
* If COMMAND equals to "TextBuddy", program is valid.
* Else, program will exit because of invalid command.
*/
if (args.length > 0) {
if(!args[0].equals(APP_COMMAND)){
print(MSG_INVALID_COMMAND);
System.exit(0);
} else {
file_name = args[1];
checkIfFileExists();
print(String.format(MSG_WELCOME, CURRENT_DIRECTORY + file_name));
}
} else if (args.length == 0 || args.length < 2) {
print(MSG_INVALID_COMMAND);
System.exit(0);
} else {
file_name = getDateTime().concat(TXT_EXTENSION);
}
}
/**
* Gets the current date and time.
*
* @return The current date and time in "dd-MMM-HH-mm" format.
*/
private static String getDateTime() {
SimpleDateFormat dt_format = new SimpleDateFormat("dd-MMM-HH-mm");
return (dt_format.format(new Date()));
}
/**
* Check if file exists
* If file exists, read the file contents.
* todo: Else create a new file
*/
private static void checkIfFileExists() {
try {
File file = new File(file_name);
if (!file.exists()) {
createFileIfNotExist(file);
} else {
/* Read in the file contents
* add it to the list
*/
String _line;
BufferedReader br = new BufferedReader(new FileReader(file_name));
while ((_line = br.readLine()) != null) {
list.add(_line);
}
br.close();
}
} catch (Exception ex) {
list.clear(); // Clear all data
print(String.format(MSG_ERROR_READING, file_name));
}
}
/**
* createFileIfNotExist:
*
* @param n_file Receive File to be processed
* @throws IOException
*/
private static void createFileIfNotExist(File n_file) throws IOException {
n_file.createNewFile();
}
/**
* processUserCommands:
* Read commands from each line and execute the commands accordingly
* DISPLAY: displays all lines in the file
* ADD: adds a line to the file
* DELETE: delete a line from the file
* CLEAR: clear the entire file
* EXIT: exit the program
* INVALID COMMAND: anything that doesn't resemble the commands above
*
* @throws IOException
*/
public static void processUserCommands() throws IOException {
String print_out = "";
while(true) {
print(COMMAND);
try {
/* Split the commands into two arguments.
* cmd[0] represents COMMAND argument
* cmd[1] represents the argument to be parsed into
*/
String[] cmd = buffered_reader.readLine().trim().split(" ", 2);
COMMAND_TYPE cmd_type = determineCommandType(cmd[0]);
switch (cmd_type) {
case DISPLAY :
print_out = displayFile();
break;
case ADD :
print_out = addElement(cmd[1]);
break;
case DELETE :
print_out = deleteElement(cmd[1]);
break;
case CLEAR :
print_out = clearList();
break;
case SORT :
print_out = sort();
break;
case SEARCH :
print_out = search(cmd[1]);
break;
case EXIT :
System.exit(0);
break;
default :
print(MSG_INVALID_COMMAND);
break;
}
} catch (Exception ex) {
print_out = MSG_INVALID_COMMAND;
}
print(print_out);
}
}
public static String executeCommand(String cmd) throws IOException {
String textInput = removeCommandType(cmd);
// String cmd_type = getFirstCommand(cmd.toUpperCase());
COMMAND_TYPE cmd_type = determineCommandType(cmd);
switch (cmd_type) {
case DISPLAY :
return displayFile();
case ADD :
return addElement(textInput);
case DELETE :
return deleteElement(textInput);
case CLEAR :
return clearList();
case SORT :
return sort();
case SEARCH :
return search(textInput);
case EXIT :
System.exit(0);
default :
throw new Error(MSG_INVALID_COMMAND);
}
}
private static String getFirstCommand(String cmd_in) {
StringTokenizer cmd_token = new StringTokenizer(cmd_in);
return cmd_token.nextToken();
}
private static String removeCommandType(String cmd_in) {
return cmd_in.replace(getFirstCommand(cmd_in), "").trim();
}
/**
* This operation determines which of the supported command types the user
* wants to perform
*
* @param command_type_str is the first word of the user command
*/
private static COMMAND_TYPE determineCommandType(String command_type_str) {
if (command_type_str == null) {
throw new Error("Command type string cannot be null!");
}
if (command_type_str.equalsIgnoreCase("display") || command_type_str.equalsIgnoreCase("ls")) {
return COMMAND_TYPE.DISPLAY;
} else if (command_type_str.equalsIgnoreCase("add") || command_type_str.equalsIgnoreCase("+")) {
return COMMAND_TYPE.ADD;
} else if (command_type_str.equalsIgnoreCase("delete") || command_type_str.equalsIgnoreCase("rm") || command_type_str.equalsIgnoreCase("-")) {
return COMMAND_TYPE.DELETE;
} else if (command_type_str.equalsIgnoreCase("clear")) {
return COMMAND_TYPE.CLEAR;
} else if (command_type_str.equalsIgnoreCase("sort")) {
return COMMAND_TYPE.SORT;
} else if (command_type_str.equalsIgnoreCase("search")) {
return COMMAND_TYPE.SEARCH;
} else if (command_type_str.equalsIgnoreCase("exit") || command_type_str.equalsIgnoreCase("quit") || command_type_str.equalsIgnoreCase("q")) {
return COMMAND_TYPE.EXIT;
} else {
return COMMAND_TYPE.INVALID;
}
}
/**
* addElement:
* add line to an ArrayList<String>
*
* @param _element Input element to be added
* @return Success message when element added or error while saving
*/
private static String addElement(String _element) {
list.add(_element);
boolean isFileSaveSuccessful = saveFile();
if (isFileSaveSuccessful) {
return String.format(MSG_ADDED_ELEMENT, file_name, _element);
} else {
return String.format(MSG_ERROR_SAVING, file_name);
}
}
/**
* saveFile:
* Saves ArrayList<String> elements to file
*
* @return True or false while saving file -> Success or failure in saving
*/
private static boolean saveFile() {
try {
FileWriter file = new FileWriter(file_name);
String output = "";
for (String _line : list) {
output = output + _line + "\n";
}
file.write(output);
file.flush();
file.close();
} catch (IOException e) {
return FILE_SAVE_UNSUCCESSFUL;
}
return FILE_SAVE_SUCCESSFUL;
}
/**
* displayFile:
* Displays all lines found in the text file.
* If list is empty, return list empty message, otherwise, print out the entire list of text
* @return Entire data entries list
* @throws IOException
*/
private static String displayFile() throws IOException {
StringBuffer strbuffer = new StringBuffer();
if (list.isEmpty()) {
System.out.printf(MSG_LIST_EMPTY, file_name);
} else {
for (int i = 0; i < list.size(); i++) {
strbuffer.append(String.format(MSG_PRINT_LIST, (i + 1), list.get(i)));
}
}
return strbuffer.toString();
}
/**
* deleteElement:
* deletes a single index line from the file
* @param param Input element to be deleted
* @return Delete successful and saved or error deleting and saving
*/
private static String deleteElement(String param) {
int id;
int _index;
// Parse the element ID
try {
id = parseID(param);
} catch (Exception e) {
return String.format(MSG_INVALID_COMMAND);
}
// Check if ID is valid
if (id > 0 && list.size() >= id) {
_index = id - 1; // 0 based indexing list
String element = list.get(_index);
list.remove(_index);
boolean isFileSaveSuccessful = saveFile();
if (isFileSaveSuccessful) {
return String.format(MSG_DELETE_ELEMENT, file_name, element);
} else {
return String.format(MSG_ERROR_SAVING, file_name);
}
} else if (list.isEmpty()) {
return String.format(MSG_LIST_EMPTY, file_name);
} else {
return String.format(MSG_INVALID_ELEID);
}
}
/**
* clearList:
* clears the data entries of the entire file
* @return File cleared successfully or error saving
* @throws IOException
*/
private static String clearList() throws IOException {
list.clear();
boolean isFileSaveSuccessful = saveFile();
if (isFileSaveSuccessful) {
return String.format(MSG_CLEAR_LIST, file_name);
} else {
return String.format(MSG_ERROR_SAVING, file_name);
}
}
/**
* Parse the parameter string into integer preparing for element deletion.
*
* @param param User entered parameter
* @return Element ID as entered by user if valid
* @throws Exception When invalid element ID entered
*/
private static int parseID(String param) throws Exception {
try {
return Integer.parseInt(param.split(" ", 2)[0]);
} catch (Exception e) {
throw e;
}
}
private static void print(String output) {
System.out.print(output);
}
/**
* Method to find lines with a particular keyword
*
* @param param Keyword to be searched for
*/
public static String search(String param) {
String str_result = "";
int count = 1;
if (param == null || param.trim().length() == 0) {
return MSG_SEARCH_INVALID;
}
for (String item : list) {
if (item.contains(param)) {
str_result += count + ". " + item + "\n";
count++;
}
}
if (str_result.length() == 0) {
return String.format(MSG_SEARCH_FAIL, param);
} else { return str_result; }
}
public static String sort() {
return null;
}
} |
package org.lightmare.deploy.fs;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.RestContainer;
import org.lightmare.config.Configuration;
import org.lightmare.jpa.datasource.FileParsers;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
import org.lightmare.utils.fs.WatchUtils;
/**
* Deployment manager, {@link Watcher#deployFile(URL)},
* {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and
* {@link File} modification event handler for deployments if java version is
* 1.7 or above
*
* @author levan
* @since 0.0.45-SNAPSHOT
*/
public class Watcher implements Runnable {
private static final String DEPLOY_THREAD_NAME = "watch_thread";
private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5;
private static final long SLEEP_TIME = 5500L;
private static final ExecutorService DEPLOY_POOL = Executors
.newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME,
DEPLOY_POOL_PRIORITY));
private Set<DeploymentDirectory> deployments;
private Set<String> dataSources;
private static final Logger LOG = Logger.getLogger(Watcher.class);
/**
* Defines file types for watch service
*
* @author Levan
* @since 0.0.45-SNAPSHOT
*/
private static enum WatchFileType {
DATA_SOURCE, DEPLOYMENT, NONE;
}
/**
* To filter only deployed sub files from directory
*
* @author levan
* @since 0.0.45-SNAPSHOT
*/
private static class DeployFiletr implements FileFilter {
@Override
public boolean accept(File file) {
boolean accept;
try {
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
accept = MetaContainer.chackDeployment(url);
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
}
return accept;
}
}
private Watcher() {
deployments = getDeployDirectories();
dataSources = getDataSourcePaths();
}
/**
* Clears and gets file {@link URL} by file name
*
* @param fileName
* @return {@link URL}
* @throws IOException
*/
private static URL getAppropriateURL(String fileName) throws IOException {
File file = new File(fileName);
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
return url;
}
/**
* Gets {@link Set} of {@link DeploymentDirectory} instances from
* configuration
*
* @return {@link Set}<code><DeploymentDirectory></code>
*/
private static Set<DeploymentDirectory> getDeployDirectories() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (config.isWatchStatus()
&& CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
return deploymetDirss;
}
/**
* Gets {@link Set} of data source paths from configuration
*
* @return {@link Set}<code><String></code>
*/
private static Set<String> getDataSourcePaths() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (config.isWatchStatus() && CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
return paths;
}
/**
* Checks and gets appropriated {@link WatchFileType} by passed file name
*
* @param fileName
* @return {@link WatchFileType}
*/
private static WatchFileType checkType(String fileName) {
WatchFileType type;
File file = new File(fileName);
String path = file.getPath();
String filePath = WatchUtils.clearPath(path);
path = file.getParent();
String parentPath = WatchUtils.clearPath(path);
Set<DeploymentDirectory> apps = getDeployDirectories();
Set<String> dss = getDataSourcePaths();
if (CollectionUtils.valid(apps)) {
String deploymantPath;
Iterator<DeploymentDirectory> iterator = apps.iterator();
boolean notDeployment = Boolean.TRUE;
DeploymentDirectory deployment;
while (iterator.hasNext() && notDeployment) {
deployment = iterator.next();
deploymantPath = deployment.getPath();
notDeployment = ObjectUtils.notEquals(deploymantPath,
parentPath);
}
if (notDeployment) {
type = WatchFileType.NONE;
} else {
type = WatchFileType.DEPLOYMENT;
}
} else if (CollectionUtils.valid(dss) && dss.contains(filePath)) {
type = WatchFileType.DATA_SOURCE;
} else {
type = WatchFileType.NONE;
}
return type;
}
private static void fillFileList(File[] files, List<File> list) {
if (CollectionUtils.valid(files)) {
for (File file : files) {
list.add(file);
}
}
}
/**
* Lists all deployed {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDeployments() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
File[] files;
List<File> list = new ArrayList<File>();
if (CollectionUtils.valid(deploymetDirss)) {
String path;
DeployFiletr filter = new DeployFiletr();
for (DeploymentDirectory deployment : deploymetDirss) {
path = deployment.getPath();
files = new File(path).listFiles(filter);
fillFileList(files, list);
}
}
return list;
}
/**
* Lists all data source {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDataSources() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
File file;
List<File> list = new ArrayList<File>();
if (CollectionUtils.valid(paths)) {
for (String path : paths) {
file = new File(path);
list.add(file);
}
}
return list;
}
/**
* Deploys application or data source file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void deployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
FileParsers fileParsers = new FileParsers();
fileParsers.parseStandaloneXml(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
deployFile(url);
}
}
/**
* Deploys application or data source file by passed {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void deployFile(URL url) throws IOException {
URL[] archives = { url };
MetaContainer.getCreator().scanForBeans(archives);
}
/**
* Removes from deployments application or data source file by passed
* {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void undeployFile(URL url) throws IOException {
boolean valid = MetaContainer.undeploy(url);
if (valid && RestContainer.hasRest()) {
RestProvider.reload();
}
}
/**
* Removes from deployments application or data source file by passed file
* name
*
* @param fileName
* @throws IOException
*/
public static void undeployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
Initializer.undeploy(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
undeployFile(url);
}
}
/**
* Removes from deployments and deploys again application or data source
* file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void redeployFile(String fileName) throws IOException {
undeployFile(fileName);
deployFile(fileName);
}
/**
* Handles file change event
*
* @param dir
* @param currentEvent
* @throws IOException
*/
private void handleEvent(Path dir, WatchEvent<Path> currentEvent)
throws IOException {
if (ObjectUtils.notNull(currentEvent)) {
Path prePath = currentEvent.context();
Path path = dir.resolve(prePath);
String fileName = path.toString();
int count = currentEvent.count();
Kind<?> kind = currentEvent.kind();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count);
redeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count);
undeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count);
redeployFile(fileName);
}
}
}
/**
* Runs file watch service
*
* @param watch
* @throws IOException
*/
private void runService(WatchService watch) throws IOException {
Path dir;
boolean toRun = true;
boolean valid;
while (toRun) {
try {
WatchKey key;
key = watch.take();
List<WatchEvent<?>> events = key.pollEvents();
WatchEvent<?> currentEvent = null;
WatchEvent<Path> typedCurrentEvent;
int times = 0;
dir = (Path) key.watchable();
for (WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (times == 0 || event.count() > currentEvent.count()) {
currentEvent = event;
}
times++;
valid = key.reset();
toRun = valid && key.isValid();
if (toRun) {
Thread.sleep(SLEEP_TIME);
typedCurrentEvent = ObjectUtils.cast(currentEvent);
handleEvent(dir, typedCurrentEvent);
}
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
private void registerPath(FileSystem fs, String path, WatchService watch)
throws IOException {
Path deployPath = fs.getPath(path);
deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW,
StandardWatchEventKinds.ENTRY_DELETE);
runService(watch);
}
private void registerPaths(File[] files, FileSystem fs, WatchService watch)
throws IOException {
String path;
for (File file : files) {
path = file.getPath();
registerPath(fs, path, watch);
}
}
private void registerPaths(Collection<DeploymentDirectory> deploymentDirss,
FileSystem fs, WatchService watch) throws IOException {
String path;
boolean scan;
File directory;
File[] files;
for (DeploymentDirectory deployment : deploymentDirss) {
path = deployment.getPath();
scan = deployment.isScan();
if (scan) {
directory = new File(path);
files = directory.listFiles();
if (CollectionUtils.valid(files)) {
registerPaths(files, fs, watch);
}
} else {
registerPath(fs, path, watch);
}
}
}
private void registerDsPaths(Collection<String> paths, FileSystem fs,
WatchService watch) throws IOException {
for (String path : paths) {
registerPath(fs, path, watch);
}
}
@Override
public void run() {
try {
FileSystem fs = FileSystems.getDefault();
WatchService watch = null;
try {
watch = fs.newWatchService();
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw ex;
}
if (CollectionUtils.valid(deployments)) {
registerPaths(deployments, fs, watch);
}
if (CollectionUtils.valid(dataSources)) {
registerDsPaths(dataSources, fs, watch);
}
} catch (IOException ex) {
LOG.fatal(ex.getMessage(), ex);
LOG.fatal("system going to shut down cause of hot deployment");
try {
ConnectionContainer.closeConnections();
} catch (IOException iex) {
LOG.fatal(iex.getMessage(), iex);
}
System.exit(-1);
} finally {
DEPLOY_POOL.shutdown();
}
}
/**
* Starts watch service for application and data source files
*/
public static void startWatch() {
Watcher watcher = new Watcher();
DEPLOY_POOL.submit(watcher);
}
} |
package com.android.email.activity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.OpenableColumns;
import android.text.TextWatcher;
import android.text.util.Rfc822Tokenizer;
import android.util.Config;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AutoCompleteTextView.Validator;
import com.android.email.Account;
import com.android.email.Email;
import com.android.email.EmailAddressAdapter;
import com.android.email.EmailAddressValidator;
import com.android.email.MessagingController;
import com.android.email.MessagingListener;
import com.android.email.Preferences;
import com.android.email.R;
import com.android.email.Utility;
import com.android.email.mail.Address;
import com.android.email.mail.Body;
import com.android.email.mail.Message;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Multipart;
import com.android.email.mail.Part;
import com.android.email.mail.Message.RecipientType;
import com.android.email.mail.internet.MimeBodyPart;
import com.android.email.mail.internet.MimeHeader;
import com.android.email.mail.internet.MimeMessage;
import com.android.email.mail.internet.MimeMultipart;
import com.android.email.mail.internet.MimeUtility;
import com.android.email.mail.internet.TextBody;
import com.android.email.mail.store.LocalStore;
import com.android.email.mail.store.LocalStore.LocalAttachmentBody;
public class MessageCompose extends Activity implements OnClickListener, OnFocusChangeListener {
private static final String ACTION_REPLY = "com.android.email.intent.action.REPLY";
private static final String ACTION_REPLY_ALL = "com.android.email.intent.action.REPLY_ALL";
private static final String ACTION_FORWARD = "com.android.email.intent.action.FORWARD";
private static final String ACTION_EDIT_DRAFT = "com.android.email.intent.action.EDIT_DRAFT";
private static final String EXTRA_ACCOUNT = "account";
private static final String EXTRA_FOLDER = "folder";
private static final String EXTRA_MESSAGE = "message";
private static final String STATE_KEY_ATTACHMENTS =
"com.android.email.activity.MessageCompose.attachments";
private static final String STATE_KEY_CC_SHOWN =
"com.android.email.activity.MessageCompose.ccShown";
private static final String STATE_KEY_BCC_SHOWN =
"com.android.email.activity.MessageCompose.bccShown";
private static final String STATE_KEY_QUOTED_TEXT_SHOWN =
"com.android.email.activity.MessageCompose.quotedTextShown";
private static final String STATE_KEY_SOURCE_MESSAGE_PROCED =
"com.android.email.activity.MessageCompose.stateKeySourceMessageProced";
private static final String STATE_KEY_DRAFT_UID =
"com.android.email.activity.MessageCompose.draftUid";
private static final int MSG_PROGRESS_ON = 1;
private static final int MSG_PROGRESS_OFF = 2;
private static final int MSG_UPDATE_TITLE = 3;
private static final int MSG_SKIPPED_ATTACHMENTS = 4;
private static final int MSG_SAVED_DRAFT = 5;
private static final int MSG_DISCARDED_DRAFT = 6;
private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1;
private Account mAccount;
private String mFolder;
private String mSourceMessageUid;
private Message mSourceMessage;
/**
* Indicates that the source message has been processed at least once and should not
* be processed on any subsequent loads. This protects us from adding attachments that
* have already been added from the restore of the view state.
*/
private boolean mSourceMessageProcessed = false;
private MultiAutoCompleteTextView mToView;
private MultiAutoCompleteTextView mCcView;
private MultiAutoCompleteTextView mBccView;
private EditText mSubjectView;
private EditText mMessageContentView;
private Button mSendButton;
private Button mDiscardButton;
private Button mSaveButton;
private LinearLayout mAttachments;
private View mQuotedTextBar;
private ImageButton mQuotedTextDelete;
private WebView mQuotedText;
private boolean mDraftNeedsSaving = false;
/**
* The draft uid of this message. This is used when saving drafts so that the same draft is
* overwritten instead of being created anew. This property is null until the first save.
*/
private String mDraftUid;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_PROGRESS_ON:
setProgressBarIndeterminateVisibility(true);
break;
case MSG_PROGRESS_OFF:
setProgressBarIndeterminateVisibility(false);
break;
case MSG_UPDATE_TITLE:
updateTitle();
break;
case MSG_SKIPPED_ATTACHMENTS:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_compose_attachments_skipped_toast),
Toast.LENGTH_LONG).show();
break;
case MSG_SAVED_DRAFT:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_saved_toast),
Toast.LENGTH_LONG).show();
break;
case MSG_DISCARDED_DRAFT:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_discarded_toast),
Toast.LENGTH_LONG).show();
break;
default:
super.handleMessage(msg);
break;
}
}
};
private Listener mListener = new Listener();
private EmailAddressAdapter mAddressAdapter;
private Validator mAddressValidator;
class Attachment implements Serializable {
public String name;
public String contentType;
public long size;
public Uri uri;
}
/**
* Compose a new message using the given account. If account is null the default account
* will be used.
* @param context
* @param account
*/
public static void actionCompose(Context context, Account account) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_ACCOUNT, account);
context.startActivity(i);
}
/**
* Compose a new message as a reply to the given message. If replyAll is true the function
* is reply all instead of simply reply.
* @param context
* @param account
* @param message
* @param replyAll
*/
public static void actionReply(
Context context,
Account account,
Message message,
boolean replyAll) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_ACCOUNT, account);
i.putExtra(EXTRA_FOLDER, message.getFolder().getName());
i.putExtra(EXTRA_MESSAGE, message.getUid());
if (replyAll) {
i.setAction(ACTION_REPLY_ALL);
}
else {
i.setAction(ACTION_REPLY);
}
context.startActivity(i);
}
/**
* Compose a new message as a forward of the given message.
* @param context
* @param account
* @param message
*/
public static void actionForward(Context context, Account account, Message message) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_ACCOUNT, account);
i.putExtra(EXTRA_FOLDER, message.getFolder().getName());
i.putExtra(EXTRA_MESSAGE, message.getUid());
i.setAction(ACTION_FORWARD);
context.startActivity(i);
}
/**
* Continue composition of the given message. This action modifies the way this Activity
* handles certain actions.
* Save will attempt to replace the message in the given folder with the updated version.
* Discard will delete the message from the given folder.
* @param context
* @param account
* @param folder
* @param message
*/
public static void actionEditDraft(Context context, Account account, Message message) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_ACCOUNT, account);
i.putExtra(EXTRA_FOLDER, message.getFolder().getName());
i.putExtra(EXTRA_MESSAGE, message.getUid());
i.setAction(ACTION_EDIT_DRAFT);
context.startActivity(i);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.message_compose);
mAddressAdapter = new EmailAddressAdapter(this);
mAddressValidator = new EmailAddressValidator();
mToView = (MultiAutoCompleteTextView)findViewById(R.id.to);
mCcView = (MultiAutoCompleteTextView)findViewById(R.id.cc);
mBccView = (MultiAutoCompleteTextView)findViewById(R.id.bcc);
mSubjectView = (EditText)findViewById(R.id.subject);
mMessageContentView = (EditText)findViewById(R.id.message_content);
mAttachments = (LinearLayout)findViewById(R.id.attachments);
mQuotedTextBar = findViewById(R.id.quoted_text_bar);
mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete);
mQuotedText = (WebView)findViewById(R.id.quoted_text);
TextWatcher watcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start,
int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int count) {
mDraftNeedsSaving = true;
}
public void afterTextChanged(android.text.Editable s) { }
};
mToView.addTextChangedListener(watcher);
mCcView.addTextChangedListener(watcher);
mBccView.addTextChangedListener(watcher);
mSubjectView.addTextChangedListener(watcher);
mMessageContentView.addTextChangedListener(watcher);
/*
* We set this to invisible by default. Other methods will turn it back on if it's
* needed.
*/
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mQuotedTextDelete.setOnClickListener(this);
mToView.setAdapter(mAddressAdapter);
mToView.setTokenizer(new Rfc822Tokenizer());
mToView.setValidator(mAddressValidator);
mCcView.setAdapter(mAddressAdapter);
mCcView.setTokenizer(new Rfc822Tokenizer());
mCcView.setValidator(mAddressValidator);
mBccView.setAdapter(mAddressAdapter);
mBccView.setTokenizer(new Rfc822Tokenizer());
mBccView.setValidator(mAddressValidator);
mSubjectView.setOnFocusChangeListener(this);
if (savedInstanceState != null) {
/*
* This data gets used in onCreate, so grab it here instead of onRestoreIntstanceState
*/
mSourceMessageProcessed =
savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false);
}
Intent intent = getIntent();
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) {
/*
* Someone has clicked a mailto: link. The address is in the URI.
*/
mAccount = Preferences.getPreferences(this).getDefaultAccount();
if (mAccount == null) {
/*
* There are no accounts set up. This should not have happened. Prompt the
* user to set up an account as an acceptable bailout.
*/
startActivity(new Intent(this, Accounts.class));
mDraftNeedsSaving = false;
finish();
return;
}
if (intent.getData() != null) {
Uri uri = intent.getData();
try {
if (uri.getScheme().equalsIgnoreCase("mailto")) {
Address[] addresses = Address.parse(uri.getSchemeSpecificPart());
addAddresses(mToView, addresses);
}
}
catch (Exception e) {
/*
* If we can't extract any information from the URI it's okay. They can
* still compose a message.
*/
}
}
}
else if (Intent.ACTION_SEND.equals(action)) {
/*
* Someone is trying to compose an email with an attachment, probably Pictures.
* The Intent should contain an EXTRA_STREAM with the data to attach.
*/
mAccount = Preferences.getPreferences(this).getDefaultAccount();
if (mAccount == null) {
/*
* There are no accounts set up. This should not have happened. Prompt the
* user to set up an account as an acceptable bailout.
*/
startActivity(new Intent(this, Accounts.class));
mDraftNeedsSaving = false;
finish();
return;
}
String type = intent.getType();
Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (stream != null && type != null) {
if (MimeUtility.mimeTypeMatches(type, Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES)) {
addAttachment(stream);
}
}
}
else {
mAccount = (Account) intent.getSerializableExtra(EXTRA_ACCOUNT);
mFolder = (String) intent.getStringExtra(EXTRA_FOLDER);
mSourceMessageUid = (String) intent.getStringExtra(EXTRA_MESSAGE);
}
if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) ||
ACTION_FORWARD.equals(action) || ACTION_EDIT_DRAFT.equals(action)) {
/*
* If we need to load the message we add ourself as a message listener here
* so we can kick it off. Normally we add in onResume but we don't
* want to reload the message every time the activity is resumed.
* There is no harm in adding twice.
*/
MessagingController.getInstance(getApplication()).addListener(mListener);
MessagingController.getInstance(getApplication()).loadMessageForView(
mAccount,
mFolder,
mSourceMessageUid,
mListener);
}
addAddress(mBccView, new Address(mAccount.getAlwaysBcc(), ""));
updateTitle();
//change focus to message body.
mMessageContentView.requestFocus();
}
public void onResume() {
super.onResume();
MessagingController.getInstance(getApplication()).addListener(mListener);
}
public void onPause() {
super.onPause();
saveIfNeeded();
MessagingController.getInstance(getApplication()).removeListener(mListener);
}
/**
* The framework handles most of the fields, but we need to handle stuff that we
* dynamically show and hide:
* Attachment list,
* Cc field,
* Bcc field,
* Quoted text,
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveIfNeeded();
ArrayList<Uri> attachments = new ArrayList<Uri>();
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
View view = mAttachments.getChildAt(i);
Attachment attachment = (Attachment) view.getTag();
attachments.add(attachment.uri);
}
outState.putParcelableArrayList(STATE_KEY_ATTACHMENTS, attachments);
outState.putBoolean(STATE_KEY_CC_SHOWN, mCcView.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_BCC_SHOWN, mBccView.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_QUOTED_TEXT_SHOWN,
mQuotedTextBar.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed);
outState.putString(STATE_KEY_DRAFT_UID, mDraftUid);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
ArrayList<Parcelable> attachments = (ArrayList<Parcelable>)
savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS);
mAttachments.removeAllViews();
for (Parcelable p : attachments) {
Uri uri = (Uri) p;
addAttachment(uri);
}
mCcView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ?
View.VISIBLE : View.GONE);
mBccView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_BCC_SHOWN) ?
View.VISIBLE : View.GONE);
mQuotedTextBar.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ?
View.VISIBLE : View.GONE);
mQuotedText.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ?
View.VISIBLE : View.GONE);
mDraftUid = savedInstanceState.getString(STATE_KEY_DRAFT_UID);
mDraftNeedsSaving = false;
}
private void updateTitle() {
if (mSubjectView.getText().length() == 0) {
setTitle(R.string.compose_title);
} else {
setTitle(mSubjectView.getText().toString());
}
}
public void onFocusChange(View view, boolean focused) {
if (!focused) {
updateTitle();
}
}
private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) {
if (addresses == null) {
return;
}
for (Address address : addresses) {
addAddress(view, address);
}
}
private void addAddress(MultiAutoCompleteTextView view, Address address) {
view.append(address + ", ");
}
private Address[] getAddresses(MultiAutoCompleteTextView view) {
Address[] addresses = Address.parse(view.getText().toString().trim());
return addresses;
}
private MimeMessage createMessage() throws MessagingException {
MimeMessage message = new MimeMessage();
message.setSentDate(new Date());
Address from = new Address(mAccount.getEmail(), mAccount.getName());
message.setFrom(from);
message.setRecipients(RecipientType.TO, getAddresses(mToView));
message.setRecipients(RecipientType.CC, getAddresses(mCcView));
message.setRecipients(RecipientType.BCC, getAddresses(mBccView));
message.setSubject(mSubjectView.getText().toString());
// XXX TODO - not sure why this won't add header
// message.setHeader("X-User-Agent", getString(R.string.message_header_mua));
/*
* Build the Body that will contain the text of the message. We'll decide where to
* include it later.
*/
String text = mMessageContentView.getText().toString();
if (mQuotedTextBar.getVisibility() == View.VISIBLE) {
String action = getIntent().getAction();
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(mSourceMessage,
"text/plain");
if (part != null) {
quotedText = MimeUtility.getTextFromPart(part);
}
if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)) {
text += String.format(
getString(R.string.message_compose_reply_header_fmt),
Address.toString(mSourceMessage.getFrom()));
if (quotedText != null) {
text += quotedText.replaceAll("(?m)^", ">");
}
}
else if (ACTION_FORWARD.equals(action)) {
text += String.format(
getString(R.string.message_compose_fwd_header_fmt),
mSourceMessage.getSubject(),
Address.toString(mSourceMessage.getFrom()),
Address.toString(
mSourceMessage.getRecipients(RecipientType.TO)),
Address.toString(
mSourceMessage.getRecipients(RecipientType.CC)));
if (quotedText != null) {
text += quotedText;
}
}
}
text = appendSignature(text);
TextBody body = new TextBody(text);
if (mAttachments.getChildCount() > 0) {
/*
* The message has attachments that need to be included. First we add the part
* containing the text that will be sent and then we include each attachment.
*/
MimeMultipart mp;
mp = new MimeMultipart();
mp.addBodyPart(new MimeBodyPart(body, "text/plain"));
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
Attachment attachment = (Attachment) mAttachments.getChildAt(i).getTag();
MimeBodyPart bp = new MimeBodyPart(
new LocalStore.LocalAttachmentBody(attachment.uri, getApplication()));
bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n name=\"%s\"",
attachment.contentType,
attachment.name));
bp.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION,
String.format("attachment;\n filename=\"%s\"",
attachment.name));
mp.addBodyPart(bp);
}
message.setBody(mp);
}
else {
/*
* No attachments to include, just stick the text body in the message and call
* it good.
*/
message.setBody(body);
}
return message;
}
private String appendSignature (String text) {
String mSignature;
mSignature = mAccount.getSignature();
if (mSignature != null && ! mSignature.contentEquals("")){
text += "\n-- \n" + mAccount.getSignature();
}
return text;
}
private void sendOrSaveMessage(boolean save) {
/*
* Create the message from all the data the user has entered.
*/
MimeMessage message;
try {
message = createMessage();
}
catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Failed to create new message for send or save.", me);
throw new RuntimeException("Failed to create a new message for send or save.", me);
}
if (save) {
/*
* Save a draft
*/
if (mDraftUid != null) {
message.setUid(mDraftUid);
}
else if (ACTION_EDIT_DRAFT.equals(getIntent().getAction())) {
/*
* We're saving a previously saved draft, so update the new message's uid
* to the old message's uid.
*/
message.setUid(mSourceMessageUid);
}
MessagingController.getInstance(getApplication()).saveDraft(mAccount, message);
mDraftUid = message.getUid();
// Don't display the toast if the user is just changing the orientation
if ((getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
mHandler.sendEmptyMessage(MSG_SAVED_DRAFT);
}
}
else {
/*
* Send the message
* TODO Is it possible for us to be editing a draft with a null source message? Don't
* think so. Could probably remove below check.
*/
if (ACTION_EDIT_DRAFT.equals(getIntent().getAction())
&& mSourceMessageUid != null) {
/*
* We're sending a previously saved draft, so delete the old draft first.
*/
MessagingController.getInstance(getApplication()).deleteMessage(
mAccount,
mFolder,
mSourceMessage,
null);
}
MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null);
}
}
private void saveIfNeeded() {
if (!mDraftNeedsSaving) {
return;
}
mDraftNeedsSaving = false;
sendOrSaveMessage(true);
}
private void onSend() {
if (getAddresses(mToView).length == 0 &&
getAddresses(mCcView).length == 0 &&
getAddresses(mBccView).length == 0) {
mToView.setError(getString(R.string.message_compose_error_no_recipients));
Toast.makeText(this, getString(R.string.message_compose_error_no_recipients),
Toast.LENGTH_LONG).show();
return;
}
sendOrSaveMessage(false);
mDraftNeedsSaving = false;
finish();
}
private void onDiscard() {
if (mSourceMessageUid != null) {
if (ACTION_EDIT_DRAFT.equals(getIntent().getAction()) && mSourceMessageUid != null) {
MessagingController.getInstance(getApplication()).deleteMessage(
mAccount,
mFolder,
mSourceMessage,
null);
}
}
mHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT);
mDraftNeedsSaving = false;
finish();
}
private void onSave() {
saveIfNeeded();
finish();
}
private void onAddCcBcc() {
mCcView.setVisibility(View.VISIBLE);
mBccView.setVisibility(View.VISIBLE);
}
/**
* Kick off a picker for whatever kind of MIME types we'll accept and let Android take over.
*/
private void onAddAttachment() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES[0]);
startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT);
}
private void addAttachment(Uri uri) {
addAttachment(uri, -1, null);
}
private void addAttachment(Uri uri, int size, String name) {
ContentResolver contentResolver = getContentResolver();
String contentType = contentResolver.getType(uri);
if (contentType == null) {
contentType = "";
}
Attachment attachment = new Attachment();
attachment.name = name;
attachment.contentType = contentType;
attachment.size = size;
attachment.uri = uri;
if (attachment.size == -1 || attachment.name == null) {
Cursor metadataCursor = contentResolver.query(
uri,
new String[]{ OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE },
null,
null,
null);
if (metadataCursor != null) {
try {
if (metadataCursor.moveToFirst()) {
if (attachment.name == null) {
attachment.name = metadataCursor.getString(0);
}
if (attachment.size == -1) {
attachment.size = metadataCursor.getInt(1);
}
}
} finally {
metadataCursor.close();
}
}
}
if (attachment.name == null) {
attachment.name = uri.getLastPathSegment();
}
View view = getLayoutInflater().inflate(
R.layout.message_compose_attachment,
mAttachments,
false);
TextView nameView = (TextView)view.findViewById(R.id.attachment_name);
ImageButton delete = (ImageButton)view.findViewById(R.id.attachment_delete);
nameView.setText(attachment.name);
delete.setOnClickListener(this);
delete.setTag(view);
view.setTag(attachment);
mAttachments.addView(view);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
addAttachment(data.getData());
mDraftNeedsSaving = true;
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.attachment_delete:
/*
* The view is the delete button, and we have previously set the tag of
* the delete button to the view that owns it. We don't use parent because the
* view is very complex and could change in the future.
*/
mAttachments.removeView((View) view.getTag());
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_delete:
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mDraftNeedsSaving = true;
break;
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.send:
onSend();
break;
case R.id.save:
onSave();
break;
case R.id.discard:
onDiscard();
break;
case R.id.add_cc_bcc:
onAddCcBcc();
break;
case R.id.add_attachment:
onAddAttachment();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.message_compose_option, menu);
return true;
}
/**
* Returns true if all attachments were able to be attached, otherwise returns false.
*/
private boolean loadAttachments(Part part, int depth) throws MessagingException {
if (part.getBody() instanceof Multipart) {
Multipart mp = (Multipart) part.getBody();
boolean ret = true;
for (int i = 0, count = mp.getCount(); i < count; i++) {
if (!loadAttachments(mp.getBodyPart(i), depth + 1)) {
ret = false;
}
}
return ret;
} else {
String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
String name = MimeUtility.getHeaderParameter(contentType, "name");
if (name != null) {
Body body = part.getBody();
if (body != null && body instanceof LocalAttachmentBody) {
final Uri uri = ((LocalAttachmentBody) body).getContentUri();
mHandler.post(new Runnable() {
public void run() {
addAttachment(uri);
}
});
}
else {
return false;
}
}
return true;
}
}
/**
* Pull out the parts of the now loaded source message and apply them to the new message
* depending on the type of message being composed.
* @param message
*/
private void processSourceMessage(Message message) {
String action = getIntent().getAction();
if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)) {
try {
if (message.getSubject() != null &&
!message.getSubject().toLowerCase().startsWith("re:")) {
mSubjectView.setText("Re: " + message.getSubject());
}
else {
mSubjectView.setText(message.getSubject());
}
/*
* If a reply-to was included with the message use that, otherwise use the from
* or sender address.
*/
Address[] replyToAddresses;
if (message.getReplyTo().length > 0) {
addAddresses(mToView, replyToAddresses = message.getReplyTo());
}
else {
addAddresses(mToView, replyToAddresses = message.getFrom());
}
if (ACTION_REPLY_ALL.equals(action)) {
for (Address address : message.getRecipients(RecipientType.TO)) {
if (!address.getAddress().equalsIgnoreCase(mAccount.getEmail())) {
addAddress(mToView, address);
}
}
if (message.getRecipients(RecipientType.CC).length > 0) {
for (Address address : message.getRecipients(RecipientType.CC)) {
if (!Utility.arrayContains(replyToAddresses, address)) {
addAddress(mCcView, address);
}
}
mCcView.setVisibility(View.VISIBLE);
}
}
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
String text = MimeUtility.getTextFromPart(part);
if (text != null) {
mQuotedTextBar.setVisibility(View.VISIBLE);
mQuotedText.setVisibility(View.VISIBLE);
mQuotedText.loadDataWithBaseURL("email://", text, part.getMimeType(),
"utf-8", null);
}
}
}
catch (MessagingException me) {
/*
* This really should not happen at this point but if it does it's okay.
* The user can continue composing their message.
*/
}
}
else if (ACTION_FORWARD.equals(action)) {
try {
if (message.getSubject() != null &&
!message.getSubject().toLowerCase().startsWith("fwd:")) {
mSubjectView.setText("Fwd: " + message.getSubject());
}
else {
mSubjectView.setText(message.getSubject());
}
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
String text = MimeUtility.getTextFromPart(part);
if (text != null) {
mQuotedTextBar.setVisibility(View.VISIBLE);
mQuotedText.setVisibility(View.VISIBLE);
mQuotedText.loadDataWithBaseURL("email://", text, part.getMimeType(),
"utf-8", null);
}
}
if (!mSourceMessageProcessed) {
if (!loadAttachments(message, 0)) {
mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS);
}
}
}
catch (MessagingException me) {
/*
* This really should not happen at this point but if it does it's okay.
* The user can continue composing their message.
*/
}
}
else if (ACTION_EDIT_DRAFT.equals(action)) {
try {
mSubjectView.setText(message.getSubject());
addAddresses(mToView, message.getRecipients(RecipientType.TO));
if (message.getRecipients(RecipientType.CC).length > 0) {
addAddresses(mCcView, message.getRecipients(RecipientType.CC));
mCcView.setVisibility(View.VISIBLE);
}
if (message.getRecipients(RecipientType.BCC).length > 0) {
addAddresses(mBccView, message.getRecipients(RecipientType.BCC));
mBccView.setVisibility(View.VISIBLE);
}
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part != null) {
String text = MimeUtility.getTextFromPart(part);
mMessageContentView.setText(text);
}
if (!mSourceMessageProcessed) {
loadAttachments(message, 0);
}
}
catch (MessagingException me) {
// TODO
}
}
mSourceMessageProcessed = true;
mDraftNeedsSaving = false;
}
class Listener extends MessagingListener {
@Override
public void loadMessageForViewStarted(Account account, String folder, String uid) {
mHandler.sendEmptyMessage(MSG_PROGRESS_ON);
}
@Override
public void loadMessageForViewFinished(Account account, String folder, String uid,
Message message) {
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
}
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
final Message message) {
mSourceMessage = message;
runOnUiThread(new Runnable() {
public void run() {
processSourceMessage(message);
}
});
}
@Override
public void loadMessageForViewFailed(Account account, String folder, String uid,
final String message) {
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
// TODO show network error
}
@Override
public void messageUidChanged(
Account account,
String folder,
String oldUid,
String newUid) {
if (account.equals(mAccount)
&& (folder.equals(mFolder)
|| (mFolder == null
&& folder.equals(mAccount.getDraftsFolderName())))) {
if (oldUid.equals(mDraftUid)) {
mDraftUid = newUid;
}
if (oldUid.equals(mSourceMessageUid)) {
mSourceMessageUid = newUid;
}
if (mSourceMessage != null && (oldUid.equals(mSourceMessage.getUid()))) {
mSourceMessage.setUid(newUid);
}
}
}
}
} |
package org.lightmare.deploy.fs;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.lightmare.cache.MetaContainer;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.jpa.datasource.DataSourceInitializer;
import org.lightmare.jpa.datasource.FileParsers;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
import org.lightmare.utils.fs.WatchUtils;
/**
* Deployment manager, {@link Watcher#deployFile(URL)},
* {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and
* {@link File} modification event handler for deployments if java version is
* 1.7 or above
*
* @author levan
*
*/
public class Watcher implements Runnable {
private static final String DEPLOY_THREAD_NAME = "watch_thread";
private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5;
private static final long SLEEP_TIME = 5500L;
private static final ExecutorService DEPLOY_POOL = Executors
.newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME,
DEPLOY_POOL_PRIORITY));
private Set<String> deployments;
private Set<String> dataSources;
private static final Logger LOG = Logger.getLogger(Watcher.class);
private static enum WatchFileType {
DATA_SOURCE, DEPLOYMENT, NONE;
}
/**
* To filter only deployed sub files from directory
*
* @author levan
*
*/
private static class DeployFiletr implements FileFilter {
@Override
public boolean accept(File file) {
boolean accept;
try {
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
accept = MetaContainer.chackDeployment(url);
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
}
return accept;
}
}
private Watcher() {
deployments = MetaCreator.CONFIG.getDeploymentPath();
dataSources = MetaCreator.CONFIG.getDataSourcePath();
}
private static URL getAppropriateURL(String fileName) throws IOException {
File file = new File(fileName);
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
return url;
}
private static WatchFileType checkType(String fileName) {
WatchFileType type;
File file = new File(fileName);
String path = file.getParent();
Set<String> apps = MetaCreator.CONFIG.getDeploymentPath();
Set<String> dss = MetaCreator.CONFIG.getDataSourcePath();
if (ObjectUtils.available(apps) && apps.contains(path)) {
type = WatchFileType.DEPLOYMENT;
} else if (ObjectUtils.available(dss) && dss.contains(path)) {
type = WatchFileType.DATA_SOURCE;
} else {
type = WatchFileType.NONE;
}
return type;
}
private static void fillFileList(File[] files, List<File> list) {
if (ObjectUtils.available(files)) {
for (File file : files) {
list.add(file);
}
}
}
/**
* Lists all deployed {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDeployments() {
Set<String> paths = MetaCreator.CONFIG.getDeploymentPath();
File[] files;
List<File> list = new ArrayList<File>();
if (ObjectUtils.available(paths)) {
for (String path : paths) {
files = new File(path).listFiles(new DeployFiletr());
fillFileList(files, list);
}
}
return list;
}
/**
* Lists all data source {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDataSources() {
Set<String> paths = MetaCreator.CONFIG.getDataSourcePath();
File[] files;
List<File> list = new ArrayList<File>();
if (ObjectUtils.available(paths)) {
for (String path : paths) {
files = new File(path).listFiles(new DeployFiletr());
fillFileList(files, list);
}
}
return list;
}
public static void deployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
FileParsers fileParsers = new FileParsers();
fileParsers.parseStandaloneXml(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
deployFile(url);
}
}
public static void deployFile(URL url) throws IOException {
URL[] archives = { url };
MetaContainer.getCreator().scanForBeans(archives);
}
public static void undeployFile(URL url) throws IOException {
MetaContainer.undeploy(url);
MetaContainer.getCreator().clear();
}
public static void undeployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
DataSourceInitializer.undeploy(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
undeployFile(url);
}
}
public static void redeployFile(String fileName) throws IOException {
undeployFile(fileName);
deployFile(fileName);
}
private void handleEvent(Path dir, WatchEvent<Path> currentEvent)
throws IOException {
if (currentEvent == null) {
return;
}
Path prePath = currentEvent.context();
Path path = dir.resolve(prePath);
String fileName = path.toString();
int count = currentEvent.count();
Kind<?> kind = currentEvent.kind();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
LOG.info(String.format("Modify: %s, count: %s\n", fileName, count));
redeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
LOG.info(String.format("Delete: %s, count: %s\n", fileName, count));
undeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
LOG.info(String.format("Create: %s, count: %s\n", fileName, count));
redeployFile(fileName);
}
}
@SuppressWarnings("unchecked")
private void runService(WatchService watch) throws IOException {
Path dir;
boolean toRun = true;
boolean valid;
while (toRun) {
try {
WatchKey key;
key = watch.take();
List<WatchEvent<?>> events = key.pollEvents();
WatchEvent<?> currentEvent = null;
int times = 0;
dir = (Path) key.watchable();
for (WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (times == 0 || event.count() > currentEvent.count()) {
currentEvent = event;
}
times++;
valid = key.reset();
toRun = valid && key.isValid();
if (toRun) {
Thread.sleep(SLEEP_TIME);
handleEvent(dir, (WatchEvent<Path>) currentEvent);
}
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
private void registerPath(FileSystem fs, String path, WatchService watch)
throws IOException {
Path deployPath = fs.getPath(path);
deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW,
StandardWatchEventKinds.ENTRY_DELETE);
runService(watch);
}
private void registerPaths(Collection<String> paths, FileSystem fs,
WatchService watch) throws IOException {
for (String path : paths) {
registerPath(fs, path, watch);
}
}
@Override
public void run() {
try {
FileSystem fs = FileSystems.getDefault();
WatchService watch = null;
try {
watch = fs.newWatchService();
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw ex;
}
if (ObjectUtils.available(deployments)) {
registerPaths(deployments, fs, watch);
}
if (ObjectUtils.available(dataSources)) {
registerPaths(dataSources, fs, watch);
}
} catch (IOException ex) {
LOG.fatal(ex.getMessage(), ex);
LOG.fatal("system going to shut down cause of hot deployment");
MetaCreator.closeAllConnections();
System.exit(-1);
} finally {
DEPLOY_POOL.shutdown();
}
}
public static void startWatch() {
Watcher watcher = new Watcher();
DEPLOY_POOL.submit(watcher);
}
} |
package tlc2.tool.distributed;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import tlc2.TLCGlobals;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.tool.ModelChecker;
import tlc2.tool.TLCState;
import tlc2.tool.TLCTrace;
import tlc2.tool.WorkerException;
import tlc2.tool.distributed.fp.DynamicFPSetManager;
import tlc2.tool.distributed.fp.FPSetRMI;
import tlc2.tool.distributed.fp.IFPSetManager;
import tlc2.tool.distributed.fp.StaticFPSetManager;
import tlc2.tool.distributed.management.TLCServerMXWrapper;
import tlc2.tool.distributed.selector.BlockSelectorFactory;
import tlc2.tool.distributed.selector.IBlockSelector;
import tlc2.tool.fp.FPSet;
import tlc2.tool.management.TLCStandardMBean;
import tlc2.tool.queue.DiskStateQueue;
import tlc2.tool.queue.IStateQueue;
import tlc2.util.FP64;
import util.Assert;
import util.FileUtil;
import util.SimpleFilenameToStream;
import util.UniqueString;
@SuppressWarnings("serial")
public class TLCServer extends UnicastRemoteObject implements TLCServerRMI,
InternRMI {
/**
* the port # for tlc server
*/
public static int Port = Integer.getInteger(TLCServer.class.getName() + ".port", 10997);
/**
* show statistics every 1 minutes
*/
private static final int REPORT_INTERVAL = Integer.getInteger(TLCServer.class.getName() + ".report", 1 * 60 * 1000);
/**
* If the state/ dir should be cleaned up after a successful model run
*/
private static final boolean VETO_CLEANUP = Boolean.getBoolean(TLCServer.class.getName() + ".vetoCleanup");
/**
* Performance metric: distinct states per minute
*/
private long distinctStatesPerMinute;
/**
* Performance metric: states per minute
*/
private long statesPerMinute;
public final IFPSetManager fpSetManager;
public final IStateQueue stateQueue;
public final TLCTrace trace;
private final DistApp work;
private final String metadir;
private final String filename;
public FPSet fpSet;
private TLCState errState = null;
private boolean done = false;
private boolean keepCallStack = false;
private int thId = 0;
private final Map<TLCServerThread, TLCWorkerRMI> threadsToWorkers = new HashMap<TLCServerThread, TLCWorkerRMI>();
private final CyclicBarrier barrier;
private final IBlockSelector blockSelector;
static final int expectedWorkerCount = Integer.getInteger(TLCServer.class.getName() + ".expectedWorkerCount", 1);
private final CountDownLatch latch;
static final int expectedFPSetCount = Integer.getInteger(TLCServer.class.getName() + ".expectedFPSetCount", 0);
/**
* @param work
* @throws IOException
* @throws NotBoundException
*/
public TLCServer(TLCApp work) throws IOException, NotBoundException {
// LL modified error message on 7 April 2012
Assert.check(work != null, "TLC server found null work.");
this.metadir = work.getMetadir();
int end = this.metadir.length();
if (this.metadir.endsWith(FileUtil.separator))
end
int start = this.metadir.lastIndexOf(FileUtil.separator, end - 1);
this.filename = this.metadir.substring(start + 1, end);
this.work = work;
this.stateQueue = new DiskStateQueue(this.metadir);
this.trace = new TLCTrace(this.metadir, this.work.getFileName(),
this.work);
if (TLCGlobals.fpServers == null && expectedFPSetCount <= 0) {
this.fpSet = FPSet.getFPSet(work.getFPBits(), work.getFpMemSize());
this.fpSet.init(0, this.metadir, this.work.getFileName());
this.fpSetManager = new StaticFPSetManager((FPSetRMI) this.fpSet);
} else if (expectedFPSetCount > 0) {
this.fpSetManager = new DynamicFPSetManager(expectedFPSetCount);
} else {
this.fpSetManager = new StaticFPSetManager(TLCGlobals.fpServers);
}
barrier = new CyclicBarrier(expectedWorkerCount);
latch = new CountDownLatch(expectedFPSetCount);
blockSelector = BlockSelectorFactory.getBlockSelector(this);
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#getCheckDeadlock()
*/
public final Boolean getCheckDeadlock() {
return this.work.getCheckDeadlock();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#getPreprocess()
*/
public final Boolean getPreprocess() {
return this.work.getPreprocess();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#getFPSetManager()
*/
public final IFPSetManager getFPSetManager() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return this.fpSetManager;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#getIrredPolyForFP()
*/
public final long getIrredPolyForFP() {
return FP64.getIrredPoly();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.InternRMI#intern(java.lang.String)
*/
public final UniqueString intern(String str) {
// SZ 11.04.2009: changed access method
return UniqueString.uniqueStringOf(str);
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#registerWorker(tlc2.tool.distributed.TLCWorkerRMI)
*/
public synchronized final void registerWorker(TLCWorkerRMI worker
) throws IOException {
// Wake up potentially stuck TLCServerThreads (in
// tlc2.tool.queue.StateQueue.isAvail()) to avoid a deadlock.
// Obviously stuck TLCServerThreads will never be reported to
// users if resumeAllStuck() is not call by a new worker.
stateQueue.resumeAllStuck();
// create new server thread for given worker
final TLCServerThread thread = new TLCServerThread(this.thId++, worker, this, barrier, blockSelector);
threadsToWorkers.put(thread, worker);
if (TLCGlobals.fpServers == null && expectedFPSetCount <= 0) {
this.fpSet.addThread();
}
thread.start();
MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_REGISTERED, worker.getURI().toString());
}
public synchronized void registerFPSet(FPSetRMI fpSet, String hostname) throws RemoteException {
this.fpSetManager.register(fpSet, hostname);
latch.countDown();
}
/**
* An (idempotent) method to remove a (dead) TLCServerThread from the TLCServer.
*
* @see Map#remove(Object)
* @param thread
* @return
*/
public synchronized TLCWorkerRMI removeTLCServerThread(final TLCServerThread thread) {
final TLCWorkerRMI worker = threadsToWorkers.remove(thread);
if (worker != null) {
MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_DEREGISTERED, thread.getUri().toString());
}
return worker;
}
/**
* @param s
* @param keep
* @return
*/
public synchronized final boolean setErrState(TLCState s, boolean keep) {
if (this.done)
return false;
this.done = true;
this.errState = s;
this.keepCallStack = keep;
return true;
}
public final void setDone() {
this.done = true;
}
/**
* Creates a checkpoint for the currently running model run
* @throws IOException
* @throws InterruptedException
*/
public void checkpoint() throws IOException, InterruptedException {
if (this.stateQueue.suspendAll()) {
// Checkpoint:
MP.printMessage(EC.TLC_CHECKPOINT_START, "-- Checkpointing of run " + this.metadir
+ " compl");
// start checkpointing:
this.stateQueue.beginChkpt();
this.trace.beginChkpt();
if (this.fpSet == null) {
this.fpSetManager.checkpoint(this.filename);
} else {
this.fpSet.beginChkpt();
}
this.stateQueue.resumeAll();
UniqueString.internTbl.beginChkpt(this.metadir);
// commit:
this.stateQueue.commitChkpt();
this.trace.commitChkpt();
UniqueString.internTbl.commitChkpt(this.metadir);
if (this.fpSet != null) {
this.fpSet.commitChkpt();
}
MP.printMessage(EC.TLC_CHECKPOINT_END, "eted.");
}
}
/**
* Recovers a model run
* @throws IOException
* @throws InterruptedException
*/
public final void recover() throws IOException, InterruptedException {
this.trace.recover();
this.stateQueue.recover();
if (this.fpSet == null) {
this.fpSetManager.recover(this.filename);
} else {
this.fpSet.recover();
}
}
/**
* @throws Exception
*/
private final Set<Long> doInit() throws Exception {
final SortedSet<Long> set = new TreeSet<Long>();
TLCState curState = null;
try {
TLCState[] initStates = work.getInitStates();
for (int i = 0; i < initStates.length; i++) {
curState = initStates[i];
boolean inConstraints = work.isInModel(curState);
boolean seen = false;
if (inConstraints) {
long fp = curState.fingerPrint();
seen = !set.add(fp);
if (!seen) {
initStates[i].uid = trace.writeState(fp);
stateQueue.enqueue(initStates[i]);
}
}
if (!inConstraints || !seen) {
work.checkState(null, curState);
}
}
} catch (Exception e) {
this.errState = curState;
this.keepCallStack = true;
if (e instanceof WorkerException) {
this.errState = ((WorkerException) e).state2;
this.keepCallStack = ((WorkerException) e).keepCallStack;
}
this.done = true;
throw e;
}
return set;
}
/**
* @param cleanup
* @throws IOException
*/
public final void close(boolean cleanup) throws IOException {
this.trace.close();
if (this.fpSet == null) {
this.fpSetManager.close(cleanup);
} else {
this.fpSet.close();
}
if (cleanup && !VETO_CLEANUP) {
FileUtil.deleteDir(new File(this.metadir), true);
}
}
/**
* @param server
* @throws IOException
* @throws InterruptedException
* @throws NotBoundException
*/
public static void modelCheck(TLCServer server) throws IOException, InterruptedException, NotBoundException {
/*
* Before we initialize the server, we check if recovery is requested
*/
boolean recovered = false;
if (server.work.canRecover()) {
MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_START, server.metadir);
server.recover();
MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_END, new String[] { String.valueOf(server.fpSet.size()),
String.valueOf(server.stateQueue.size())});
recovered = true;
}
/*
* Start initializing the server by calculating the init state(s)
*/
Set<Long> initFPs = new TreeSet<Long>();
if (!recovered) {
// Initialize with the initial states:
try {
MP.printMessage(EC.TLC_COMPUTING_INIT);
initFPs = server.doInit();
MP.printMessage(EC.TLC_INIT_GENERATED1,
new String[] { String.valueOf(server.stateQueue.size()), "(s)" });
} catch (Throwable e) {
// Assert.printStack(e);
server.done = true;
// LL modified error message on 7 April 2012
MP.printError(EC.GENERAL, "initializing the server", e); // LL changed call 7 April 2012
if (server.errState != null) {
MP.printMessage(EC.TLC_INITIAL_STATE, "While working on the initial state: " + server.errState);
}
// We redo the work on the error state, recording the call
// stack.
server.work.setCallStack();
try {
initFPs = server.doInit();
} catch (Throwable e1) {
MP.printError(EC.GENERAL, "evaluating the nested" // LL changed call 7 April 2012
+ "\nexpressions at the following positions:\n"
+ server.work.printCallStack(), e);
}
}
}
if (server.done) {
// clean up before exit:
server.close(false);
return;
}
// Create the central naming authority that is used by _all_ nodes
String hostname = InetAddress.getLocalHost().getHostName();
Registry rg = LocateRegistry.createRegistry(Port);
rg.rebind("TLCServer", server);
MP.printMessage(EC.TLC_DISTRIBUTED_SERVER_RUNNING, hostname);
// First register TLCSERVER with RMI and only then wait for all FPSets
// to become registered. This only waits if we use distributed
// fingerprint set (FPSet) servers which have to partition the
// distributed hash table (fingerprint space) prior to starting model
// checking.
server.latch.await();
// Add the init state(s) to the local FPSet or distributed servers
for (Long fp : initFPs) {
server.fpSetManager.put(fp);
}
/*
* This marks the end of the master and FPSet server initialization.
* Model checking can start now.
*/
// Model checking results to be collected after model checking has finished
long oldNumOfGenStates = 0;
long oldFPSetSize = 0;
// Wait for completion, but print out progress report and checkpoint
// periodically.
synchronized (server) { //TODO convert to do/while to move initial wait into loop
server.wait(REPORT_INTERVAL);
}
while (true) {
if (TLCGlobals.doCheckPoint()) {
// Periodically create a checkpoint assuming it is activated
server.checkpoint();
}
synchronized (server) {
if (!server.done) {
final long numOfGenStates = server.getStatesComputed();
final long fpSetSize = server.fpSetManager.size();
// print progress showing states per minute metric (spm)
final double factor = REPORT_INTERVAL / 60000d;
server.statesPerMinute = (long) ((numOfGenStates - oldNumOfGenStates) / factor);
server.distinctStatesPerMinute = (long) ((fpSetSize - oldFPSetSize) / factor);
// print to system.out
MP.printMessage(EC.TLC_PROGRESS_STATS, new String[] { String.valueOf(server.trace.getLevelForReporting()),
String.valueOf(numOfGenStates), String.valueOf(fpSetSize),
String.valueOf(server.getNewStates()), String.valueOf(server.statesPerMinute), String.valueOf(server.distinctStatesPerMinute) });
// Make the TLCServer main thread sleep for one report interval
server.wait(REPORT_INTERVAL);
// keep current values as old values
oldFPSetSize = fpSetSize;
oldNumOfGenStates = numOfGenStates;
}
if (server.done) {
break;
}
}
}
/*
* From this point on forward, we expect model checking to be done. What
* is left open, is to collect results and clean up
*/
// Wait for all the server threads to die.
for (final Entry<TLCServerThread, TLCWorkerRMI> entry : server.threadsToWorkers.entrySet()) {
final TLCServerThread thread = entry.getKey();
thread.join();
// print worker stats
int sentStates = thread.getSentStates();
int receivedStates = thread.getReceivedStates();
URI name = thread.getUri();
MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_STATS,
new String[] { name.toString(), Integer.toString(sentStates), Integer.toString(receivedStates) });
final TLCWorkerRMI worker = entry.getValue();
try {
worker.exit();
} catch (NoSuchObjectException e) {
// worker might have been lost in the meantime
MP.printMessage(EC.GENERAL, "Ignoring attempt to exit dead worker");
}
}
server.statesPerMinute = 0;
server.distinctStatesPerMinute = 0;
// Postprocessing:
boolean success = (server.errState == null);
if (success && server.fpSet != null) {
// We get here because the checking has succeeded.
ModelChecker.reportSuccess(server.fpSet, server.fpSetManager.size());
} else if (success && server.fpSet == null) {
final long d = server.fpSetManager.size();
final double actualProb = server.fpSetManager.checkFPs();
ModelChecker.reportSuccess(d, actualProb, server.fpSetManager.getStatesSeen());
} else if (server.keepCallStack) {
// We redo the work on the error state, recording the call stack.
server.work.setCallStack();
try {
// server.doNext();
} catch (Exception e) {
MP.printMessage(EC.TLC_NESTED_EXPRESSION, "The error occurred when TLC was evaluating the nested"
+ "\nexpressions at the following positions:");
server.work.printCallStack();
}
}
server.printSummary(success);
// Close trace and (distributed) _FPSet_ servers!
server.close(success);
// dispose RMI leftovers
rg.unbind("TLCServer");
if (server.fpSet != null) {
server.fpSet.unexportObject(false);
}
UnicastRemoteObject.unexportObject(server, false);
MP.printMessage(EC.TLC_FINISHED);
MP.flush();
}
public long getStatesGeneratedPerMinute() {
return statesPerMinute;
}
public long getDistinctStatesGeneratedPerMinute() {
return distinctStatesPerMinute;
}
/**
* @return
*/
public synchronized long getNewStates() {
long res = stateQueue.size();
for (TLCServerThread thread : threadsToWorkers.keySet()) {
res += thread.getCurrentSize();
}
return res;
}
// use fingerprint server to determine how many states have been calculated
public long getStatesComputed() throws RemoteException {
return fpSetManager.getStatesSeen();
}
// query each worker for how many states computed (workers might disconnect)
// private long getStatesComputed() throws RemoteException {
// long res = 0L;
// for (int i = 0; i < workerCnt; i++) {
// res += workers[i].getStatesComputed();
// return res;
/**
* This allows the toolbox to easily display the last set
* of state space statistics by putting them in the same
* form as all other progress statistics.
*/
public final void printSummary(boolean success) throws IOException
{
long statesGenerated = this.getStatesComputed();
long distinctStates = this.fpSetManager.size();
long statesLeftInQueue = this.getNewStates();
int level = this.trace.getLevelForReporting();
if (TLCGlobals.tool) {
MP.printMessage(EC.TLC_PROGRESS_STATS, new String[] { String.valueOf(level),
String.valueOf(statesGenerated), String.valueOf(distinctStates),
String.valueOf(statesLeftInQueue), "0", "0" });
}
MP.printMessage(EC.TLC_STATS, new String[] { String.valueOf(statesGenerated),
String.valueOf(distinctStates), String.valueOf(statesLeftInQueue) });
if (success) {
MP.printMessage(EC.TLC_SEARCH_DEPTH, String.valueOf(level));
}
}
public static void main(String argv[]) {
MP.printMessage(EC.GENERAL, "TLC Server " + TLCGlobals.versionOfTLC);
TLCStandardMBean tlcServerMXWrapper = TLCStandardMBean.getNullTLCStandardMBean();
TLCServer server = null;
try {
final String fpServerProperty = System.getProperty("fp_servers");
if(fpServerProperty != null) {
String[] fpServers = fpServerProperty.split(",");
TLCGlobals.fpServers = fpServers;
}
TLCGlobals.setNumWorkers(0);
server = new TLCServer(TLCApp.create(argv));
tlcServerMXWrapper = new TLCServerMXWrapper(server);
if(server != null) {
Runtime.getRuntime().addShutdownHook(new Thread(new WorkerShutdownHook(server)));
modelCheck(server);
}
} catch (Throwable e) {
System.gc();
// Assert.printStack(e);
if (e instanceof StackOverflowError) {
MP.printError(EC.SYSTEM_STACK_OVERFLOW, e);
} else if (e instanceof OutOfMemoryError) {
MP.printError(EC.SYSTEM_OUT_OF_MEMORY, e);
} else {
MP.printError(EC.GENERAL, e);
}
if (server != null) {
try {
server.close(false);
} catch (Exception e1) {
e1.printStackTrace();
}
}
} finally {
tlcServerMXWrapper.unregister();
}
}
/**
* @return Number of currently registered workers
*/
public int getWorkerCount() {
return threadsToWorkers.size();
}
/**
* @return
*/
synchronized TLCServerThread[] getThreads() {
return threadsToWorkers.keySet().toArray(new TLCServerThread[threadsToWorkers.size()]);
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#isDone()
*/
public boolean isDone() throws RemoteException {
return done;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#getSpec()
*/
public String getSpecFileName() throws RemoteException {
return this.work.getFileName();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#getConfig()
*/
public String getConfigFileName() throws RemoteException {
return this.work.getConfigName();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.TLCServerRMI#getFile(java.lang.String)
*/
public byte[] getFile(final String file) throws RemoteException {
// sanitize file to only last part of the path
// to make sure to not load files outside of spec dir
String name = new File(file).getName();
// Resolve all
File f = new SimpleFilenameToStream().resolve(name);
return read(f);
}
private byte[] read(final File file) {
if (file.isDirectory())
throw new RuntimeException("Unsupported operation, file "
+ file.getAbsolutePath() + " is a directory");
if (file.length() > Integer.MAX_VALUE)
throw new RuntimeException("Unsupported operation, file "
+ file.getAbsolutePath() + " is too big");
Throwable pending = null;
FileInputStream in = null;
final byte buffer[] = new byte[(int) file.length()];
try {
in = new FileInputStream(file);
in.read(buffer);
} catch (Exception e) {
pending = new RuntimeException("Exception occured on reading file "
+ file.getAbsolutePath(), e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
if (pending == null) {
pending = new RuntimeException(
"Exception occured on closing file"
+ file.getAbsolutePath(), e);
}
}
}
if (pending != null) {
throw new RuntimeException(pending);
}
}
return buffer;
}
/**
* Tries to exit all connected workers
*/
private static class WorkerShutdownHook implements Runnable {
private final TLCServer server;
public WorkerShutdownHook(final TLCServer aServer) {
server = aServer;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
for (TLCWorkerRMI worker : server.threadsToWorkers.values()) {
try {
if(worker != null) {
worker.exit();
}
} catch (java.rmi.ConnectException e) {
// happens if worker has exited already
} catch (java.rmi.NoSuchObjectException e) {
// happens if worker has exited already
} catch (IOException e) {
//TODO handle more gracefully
e.printStackTrace();
}
}
}
}
} |
package org.lightmare.remote.rpc;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.IOException;
import org.lightmare.config.ConfigKeys;
import org.lightmare.config.Configuration;
import org.lightmare.remote.rcp.RcpHandler;
import org.lightmare.remote.rcp.decoders.RcpDecoder;
import org.lightmare.remote.rpc.decoders.RpcEncoder;
import org.lightmare.remote.rpc.wrappers.RpcWrapper;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
/**
* Client class to produce remote procedure call
*
* @author levan
* @since 0.0.21-SNAPSHOT
*/
public class RPCall {
private String host;
private int port;
private RcpHandler handler;
private static int timeout;
private static int workerPoolSize;
private static EventLoopGroup worker;
private static final int ZERO_TIMEOUT = 0;
protected static class ChannelInitializerImpl extends
ChannelInitializer<SocketChannel> {
private RcpHandler handler;
public ChannelInitializerImpl(RcpHandler handler){
this.handler = handler;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
RpcEncoder rpcEncoder = new RpcEncoder();
RcpDecoder rcpDecoder = new RcpDecoder();
ch.pipeline().addLast(rpcEncoder, rcpDecoder, handler);
}
}
public RPCall(String host, int port) {
this.host = host;
this.port = port;
}
public static void configure(Configuration config) {
if (worker == null) {
workerPoolSize = config.getIntValue(ConfigKeys.WORKER_POOL.key);
timeout = config.getIntValue(ConfigKeys.CONNECTION_TIMEOUT.key);
worker = new NioEventLoopGroup(workerPoolSize,
new ThreadFactoryUtil("netty-worker-thread",
(Thread.MAX_PRIORITY - 1)));
}
}
private Bootstrap getBootstrap() {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worker);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
if (timeout > ZERO_TIMEOUT) {
bootstrap.option(ChannelOption.SO_TIMEOUT, timeout);
}
handler = new RcpHandler();
bootstrap.handler(new ChannelInitializerImpl(handler));
return bootstrap;
}
public Object call(RpcWrapper wrapper) throws IOException {
Object value;
try {
Bootstrap bootstrap = getBootstrap();
try {
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
value = handler.getWrapper();
} finally {
worker.shutdownGracefully();
}
return value;
}
} |
// jTDS JDBC Driver for Microsoft SQL Server and Sybase
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package net.sourceforge.jtds.jdbc;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* jTDS implementation of the java.sql.Statement interface.<p>
* NB. As allowed by the JDBC standard and like most other drivers,
* this implementation only allows one open result set at a time.
* <p>
* Implementation notes:
* <p>
* I experimented with allowing multiple open result sets as supported
* by the origianal jTDS but rejected this approach for the following
* reasons:
* <ol>
* <li>It is more difficult to ensure that there are no memory leaks and that
* cursors are closed if multiple open sets are allowed.
* <li>The use of one result set allows cursor and non cursor result sets to
* be derived from exeuteQuery() or execute() and getResultSet() in the
* same way that other drivers do.
* </ol>
* In the event of an IO failure the setClosed() method forces this statement
* and associated result set to close preventing the propogation of errors.
* This class includes a finalize method which increases the chances of the
* statement being closed tidly in a pooled environment where the user has
* forgotten to explicitly close the statement before it goes out of scope.
*
* @see java.sql.Statement
* @see java.sql.Connection#createStatement
* @see java.sql.ResultSet
*
* @author Mike Hutchinson
* @version $Id: JtdsStatement.java,v 1.41 2005-05-13 18:46:19 ddkilzer Exp $
*/
public class JtdsStatement implements java.sql.Statement {
/*
* Constants used for backwards compatibility with JDK 1.3
*/
static final int RETURN_GENERATED_KEYS = 1;
static final int NO_GENERATED_KEYS = 2;
static final int CLOSE_CURRENT_RESULT = 1;
static final int KEEP_CURRENT_RESULT = 2;
static final int CLOSE_ALL_RESULTS = 3;
static final int BOOLEAN = 16;
static final int DATALINK = 70;
static final Integer SUCCESS_NO_INFO = new Integer(-2);
static final Integer EXECUTE_FAILED = new Integer(-3);
/** The connection owning this statement object. */
protected ConnectionJDBC2 connection;
/** The TDS object used for server access. */
protected TdsCore tds;
/** The read query timeout in seconds */
protected int queryTimeout;
/** The current <code>ResultSet</code>. */
protected JtdsResultSet currentResult;
/** The current update count. */
private int updateCount = -1;
/** The fetch direction for result sets. */
protected int fetchDirection = ResultSet.FETCH_FORWARD;
protected int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
protected int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
/** The fetch size (default 100, only used by cursor
* <code>ResultSet</code>s).
*/
protected int fetchSize = 100;
/** The cursor name to be used for positioned updates. */
protected String cursorName;
/** True if this statement is closed. */
protected boolean closed;
/** The maximum field size (not used at present). */
protected int maxFieldSize;
/** The maximum number of rows to return (not used at present). */
protected int maxRows;
/** True if SQL statements should be preprocessed. */
protected boolean escapeProcessing = true;
/** SQL Diagnostic exceptions and warnings. */
protected final SQLDiagnostic messages;
/** Batched SQL Statement array. */
protected ArrayList batchValues;
/** Dummy result set for getGeneratedKeys. */
protected JtdsResultSet genKeyResultSet;
/**
* List of queued results (update counts, possibly followed by a
* <code>ResultSet</code>).
*/
protected final LinkedList resultQueue = new LinkedList();
/** List of open result sets. */
protected ArrayList openResultSets;
/**
* Construct a new Statement object.
*
* @param connection The parent connection.
* @param resultSetType The result set type for example TYPE_FORWARD_ONLY.
* @param resultSetConcurrency The concurrency for example CONCUR_READ_ONLY.
*/
JtdsStatement(ConnectionJDBC2 connection,
int resultSetType,
int resultSetConcurrency) throws SQLException {
// This is a good point to do common validation of the result set type
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY
&& resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE
&& resultSetType != ResultSet.TYPE_SCROLL_SENSITIVE) {
String method;
if (this instanceof JtdsCallableStatement) {
method = "prepareCall";
} else if (this instanceof JtdsPreparedStatement) {
method = "prepareStatement";
} else {
method = "createStatement";
}
throw new SQLException(
Messages.get("error.generic.badparam",
"resultSetType",
method),
"HY092");
}
// ditto for the result set concurrency
if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY
&& resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) {
String method;
if (this instanceof JtdsCallableStatement) {
method = "prepareCall";
} else if (this instanceof JtdsPreparedStatement) {
method = "prepareStatement";
} else {
method = "createStatement";
}
throw new SQLException(
Messages.get("error.generic.badparam",
"resultSetConcurrency",
method),
"HY092");
}
this.connection = connection;
this.resultSetType = resultSetType;
this.resultSetConcurrency = resultSetConcurrency;
this.tds = connection.getCachedTds();
if (this.tds == null) {
this.messages = new SQLDiagnostic(connection.getServerType());
this.tds = new TdsCore(this.connection, messages);
} else {
this.messages = tds.getMessages();
}
}
/**
* Called when this object goes out of scope to close any
* <code>ResultSet</code> object and this statement.
*/
protected void finalize() {
try {
close();
} catch (SQLException e) {
// Ignore errors
}
}
/**
* Get the Statement's TDS object.
*
* @return The TDS support as a <code>TdsCore</core> Object.
*/
TdsCore getTds() {
return tds;
}
/**
* Get the statement's warnings list.
*
* @return The warnings list as a <code>SQLDiagnostic</code>.
*/
SQLDiagnostic getMessages() {
return messages;
}
/**
* Check that this statement is still open.
*
* @throws SQLException if statement closed.
*/
protected void checkOpen() throws SQLException {
if (closed || connection == null || connection.isClosed()) {
throw new SQLException(
Messages.get("error.generic.closed", "Statement"), "HY010");
}
}
/**
* Report that user tried to call a method which has not been implemented.
*
* @param method The method name to report in the error message.
* @throws SQLException
*/
static void notImplemented(String method) throws SQLException {
throw new SQLException(
Messages.get("error.generic.notimp", method), "HYC00");
}
/**
* Close current result set (if any).
*/
void closeCurrentResultSet() throws SQLException {
try {
if (currentResult != null) {
currentResult.close();
}
// } catch (SQLException e) {
// Ignore
} finally {
currentResult = null;
}
}
/**
* Close all result sets.
*/
void closeAllResultSets() throws SQLException {
try {
if (openResultSets != null) {
for (int i = 0; i < openResultSets.size(); i++) {
JtdsResultSet rs = (JtdsResultSet) openResultSets.get(i);
if (rs != null) {
rs.close();
}
}
}
closeCurrentResultSet();
} finally {
openResultSets = null;
}
}
/**
* Add an SQLWarning object to the statment warnings list.
*
* @param w The SQLWarning to add.
*/
void addWarning(SQLWarning w) {
messages.addWarning(w);
}
/**
* This method should be over-ridden by any sub-classes that place values
* other than <code>String</code>s into the <code>batchValues</code> list
* to handle execution properly.
*
* @param value SQL <code>String</code> or list of parameters to execute
* @param last <code>true</code> if this is the last query/parameter list
* in the batch
*/
protected void executeBatchOther(Object value, boolean last)
throws SQLException {
throw new SQLException(
Messages.get("error.statement.badbatch",
value.toString()), "HYC00");
}
/**
* Execute SQL to obtain a result set.
*
* @param sql The SQL statement to execute.
* @param spName Optional stored procedure name.
* @param params Optional parameters.
* @return The result set as a <code>ResultSet</code>.
* @throws SQLException
*/
protected ResultSet executeSQLQuery(String sql,
String spName,
ParamInfo[] params)
throws SQLException {
String warningMessage = null;
// Try to open a cursor result set if required
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY
|| resultSetConcurrency != ResultSet.CONCUR_READ_ONLY
|| cursorName != null) {
try {
if (connection.getServerType() == Driver.SQLSERVER) {
currentResult =
new MSCursorResultSet(this,
sql,
spName,
params,
resultSetType,
resultSetConcurrency);
return currentResult;
} else {
// Use client side cursor for Sybase
currentResult =
new CachedResultSet(this,
sql,
spName,
params,
resultSetType,
resultSetConcurrency);
return currentResult;
}
} catch (SQLException e) {
if (connection == null || connection.isClosed()
|| "HYT00".equals(e.getSQLState())) {
// Serious error or timeout so return exception to caller
throw e;
}
warningMessage = '[' + e.getSQLState() + "] " + e.getMessage();
}
}
// Could not open a cursor (or was not requested) so try a direct select
tds.executeSQL(sql, spName, params, false, queryTimeout, maxRows,
maxFieldSize, true);
// Ignore update counts preceding the result set. All drivers seem to
// do this.
while (!tds.getMoreResults() && !tds.isEndOfResponse());
if (tds.isResultSet()) {
currentResult = new JtdsResultSet(this,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
tds.getColumns());
} else {
throw new SQLException(
Messages.get("error.statement.noresult"), "24000");
}
if (warningMessage != null) {
// Update warning chain if cursor was downgraded
addWarning(new SQLWarning(
Messages.get("warning.cursordowngraded", warningMessage), "01000"));
}
return currentResult;
}
/**
* Execute any type of SQL.
*
* @param sql The SQL statement to execute.
* @param spName Optional stored procedure name.
* @param params Optional parameters.
* @return <code>boolean</code> true if a result set is returned by the statement.
* @throws SQLException if an error condition occurs
*/
protected boolean executeSQL(String sql,
String spName,
String sqlWord,
ParamInfo[] params,
boolean returnKeys,
boolean update)
throws SQLException {
String warningMessage = null;
// For SQL Server, try to open a cursor result set if required
// (and possible).
if (connection.getServerType() == Driver.SQLSERVER
&& (resultSetType != ResultSet.TYPE_FORWARD_ONLY
|| resultSetConcurrency != ResultSet.CONCUR_READ_ONLY
|| cursorName != null)
&& !returnKeys
&& (sqlWord.equals("select") || sqlWord.startsWith("exec"))) {
try {
currentResult = new MSCursorResultSet(this, sql, spName,
params, resultSetType, resultSetConcurrency);
return true;
} catch (SQLException e) {
if (connection == null || connection.isClosed()
|| "HYT00".equals(e.getSQLState())) {
// Serious error or timeout so return exception to caller
throw e;
}
warningMessage = '[' + e.getSQLState() + "] " + e.getMessage();
}
}
// We are talking to a Sybase server or we could not open a cursor
// or we did not have a SELECT so just execute the SQL normally.
tds.executeSQL(sql, spName, params, false, queryTimeout, maxRows,
maxFieldSize, true);
if (warningMessage != null) {
// Update warning chain if cursor was downgraded
addWarning(new SQLWarning(Messages.get(
"warning.cursordowngraded", warningMessage), "01000"));
}
if (processResults(returnKeys, update)) {
Object nextResult = resultQueue.removeFirst();
// Next result is an update count
if (nextResult instanceof Integer) {
updateCount = ((Integer) nextResult).intValue();
return false;
}
// Next result is a ResultSet. Set currentResult and remove it.
currentResult = (JtdsResultSet) nextResult;
return true;
} else {
return false;
}
}
/**
* Queue up update counts into {@link #resultQueue} until the end of the
* response is reached or a <code>ResultSet</code> is encountered. Calling
* <code>processResults</code> while a <code>ResultSet</code> is open will
* not close it, but will consume all remaining rows.
*
* @param returnKeys <code>true</code> if a generated keys
* <code>ResultSet</code> is expected
* @param update <code>true</code> if the method is called from within
* <code>executeUpdate</code>
* @return <code>true</code> if there are any results,
* <code>false</code> otherwise
* @throws SQLException if an error condition occurs
*/
private boolean processResults(boolean returnKeys, boolean update) throws SQLException {
if (!resultQueue.isEmpty()) {
throw new IllegalStateException(
"There should be no queued results.");
}
while (!tds.isEndOfResponse()) {
if (!tds.getMoreResults()) {
if (tds.isUpdateCount()) {
if (update && connection.isLastUpdateCount()) {
resultQueue.clear();
}
resultQueue.addLast(new Integer(tds.getUpdateCount()));
}
} else {
if (returnKeys) {
// This had better be the generated key
// FIXME We could use SELECT @@IDENTITY AS jTDS_SOMETHING and check the column name to make sure
if (tds.getNextRow()) {
genKeyResultSet = new CachedResultSet(this,
tds.getColumns(),
tds.getRowData());
}
} else {
// TODO Should we allow execution of multiple statements via executeUpdate?
if (update && resultQueue.isEmpty()) {
throw new SQLException(
Messages.get("error.statement.nocount"), "07000");
}
resultQueue.add(new JtdsResultSet(
this,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
tds.getColumns()));
break;
}
}
}
return !resultQueue.isEmpty();
}
/**
* Cache as many results as possible (up to the first
* <code>ResultSet</code>). Called by <code>ResultSet</code>s when the
* end is reached.
*/
protected void cacheResults() throws SQLException {
// Cache results
processResults(false, false);
}
/**
* Initialize the <code>Statement</code>, by cleaning up all queued and
* unprocessed results. Called by all execute methods.
*
* @throws SQLException if an error occurs
*/
protected void initialize() throws SQLException {
updateCount = -1;
resultQueue.clear();
genKeyResultSet = null;
tds.clearResponseQueue();
closeAllResultSets();
}
public int getFetchDirection() throws SQLException {
checkOpen();
return this.fetchDirection;
}
public int getFetchSize() throws SQLException {
checkOpen();
return this.fetchSize;
}
public int getMaxFieldSize() throws SQLException {
checkOpen();
return this.maxFieldSize;
}
public int getMaxRows() throws SQLException {
checkOpen();
return this.maxRows;
}
public int getQueryTimeout() throws SQLException {
checkOpen();
return this.queryTimeout;
}
public int getResultSetConcurrency() throws SQLException {
checkOpen();
return this.resultSetConcurrency;
}
public int getResultSetHoldability() throws SQLException {
checkOpen();
return JtdsResultSet.HOLD_CURSORS_OVER_COMMIT;
}
public int getResultSetType() throws SQLException {
checkOpen();
return resultSetType;
}
public int getUpdateCount() throws SQLException {
checkOpen();
return updateCount;
}
public void cancel() throws SQLException {
checkOpen();
if (tds != null) {
tds.cancel();
}
}
public synchronized void clearBatch() throws SQLException {
checkOpen();
if (batchValues != null) {
batchValues.clear();
}
}
public void clearWarnings() throws SQLException {
checkOpen();
messages.clearWarnings();
}
public synchronized void close() throws SQLException {
if (!closed) {
try {
closeAllResultSets();
if (!connection.isClosed()) {
connection.releaseTds(tds);
}
} finally {
closed = true;
tds = null;
connection.removeStatement(this);
connection = null;
}
}
}
public boolean getMoreResults() throws SQLException {
checkOpen();
return getMoreResults(CLOSE_ALL_RESULTS);
}
/**
* Execute batch of SQL Statements.
* <p/>
* The JDBC3 standard says that for a server which does not continue
* processing a batch once the first error has occurred (e.g. SQL Server),
* the returned array will never contain <code>EXECUTE_FAILED</code> in any
* of the elements. If a failure has occurred the array length will be less
* than the count of statements in the batch. For those servers that do
* continue to execute a batch containing an error (e.g. Sybase), elements
* may contain <code>EXECUTE_FAILED</code>. Note: even here the array
* length may also be shorter than the statement count if a serious error
* has prevented the rest of the batch from being executed. In addition,
* when executing batched stored procedures, Sybase will also stop after
* the first error.
*
* @return update counts as an <code>int[]</code>
*/
public synchronized int[] executeBatch()
throws SQLException, BatchUpdateException {
checkOpen();
initialize();
if (batchValues == null || batchValues.size() == 0) {
return new int[0];
}
int size = batchValues.size();
int executeSize = connection.getBatchSize();
executeSize = (executeSize == 0) ? Integer.MAX_VALUE : executeSize;
SQLException sqlEx = null;
ArrayList counts = new ArrayList(size);
try {
tds.startBatch();
for (int i = 0; i < size;) {
Object value = batchValues.get(i);
++i;
// Execute batch now if max size reached or end of batch
boolean executeNow = (i % executeSize == 0) || i == size;
if (value instanceof String) {
tds.executeSQL((String)value, null, null, true, 0, -1, -1,
executeNow);
} else {
executeBatchOther(value, executeNow);
}
// If the batch has been sent, process the results
if (executeNow) {
sqlEx = tds.getBatchCounts(counts, sqlEx);
// If a serious error or a MS server error then we stop
// execution now as count is too small. Sybase continues,
// flagging failed updates in the count array.
if (sqlEx != null && counts.size() != i) {
break;
}
}
}
// Copy the update counts into the int array
int updateCounts[] = new int[counts.size()];
for (int i = 0; i < updateCounts.length; i++) {
updateCounts[i] = ((Integer) counts.get(i)).intValue();
}
// See if we should return an exception
if (sqlEx != null) {
BatchUpdateException batchEx =
new BatchUpdateException(sqlEx.getMessage(),
sqlEx.getSQLState(),
sqlEx.getErrorCode(),
updateCounts);
// Chain any other exceptions
batchEx.setNextException(sqlEx.getNextException());
throw batchEx;
}
return updateCounts;
} catch (BatchUpdateException ex) {
// If it's a BatchUpdateException let it go
throw ex;
} catch (SQLException ex) {
// An SQLException can only occur while sending the batch
// (getBatchCounts() doesn't throw SQLExceptions), so we have to
// end the batch and return the partial results
// FIXME What should we send here to flush out the batch?
// Come to think of it, is there any circumstance under which this
// could actually happen without the connection getting closed?
// No counts will have been returned either as last packet will not
// have been sent.
throw new BatchUpdateException(ex.getMessage(), ex.getSQLState(),
ex.getErrorCode(), new int[0]);
} finally {
clearBatch();
}
}
/*
public synchronized int[] executeBatch() throws SQLException {
checkOpen();
if (batchValues == null || batchValues.size() == 0) {
return new int[0];
}
int size = batchValues.size();
int[] updateCounts = new int[size];
int i = 0;
try {
for (; i < size; i++) {
Object value = batchValues.get(i);
if (value instanceof String) {
updateCounts[i] = executeUpdate((String) value);
} else {
updateCounts[i] = executeBatchOther(value);
}
}
} catch (SQLException e) {
int[] tmpUpdateCounts = new int[i + 1];
System.arraycopy(updateCounts, 0, tmpUpdateCounts, 0, i + 1);
tmpUpdateCounts[i] = EXECUTE_FAILED;
throw new BatchUpdateException(e.getMessage(), tmpUpdateCounts);
} finally {
clearBatch();
}
return updateCounts;
}
*/
public void setFetchDirection(int direction) throws SQLException {
checkOpen();
switch (direction) {
case ResultSet.FETCH_UNKNOWN:
case ResultSet.FETCH_REVERSE:
case ResultSet.FETCH_FORWARD:
this.fetchDirection = direction;
break;
default:
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(direction),
"direction"),
"24000");
}
}
public void setFetchSize(int rows) throws SQLException {
checkOpen();
if (rows < 0 || (maxRows > 0 && rows > maxRows)) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setFetchSize"),
"HY092");
}
this.fetchSize = rows;
}
public void setMaxFieldSize(int max) throws SQLException {
checkOpen();
if (max < 0) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setMaxFieldSize"),
"HY092");
}
maxFieldSize = max;
}
public void setMaxRows(int max) throws SQLException {
checkOpen();
if (max < 0) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setMaxRows"),
"HY092");
}
this.maxRows = max;
}
public void setQueryTimeout(int seconds) throws SQLException {
checkOpen();
if (seconds < 0) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setQueryTimeout"),
"HY092");
}
this.queryTimeout = seconds;
}
public boolean getMoreResults(int current) throws SQLException {
checkOpen();
switch (current) {
case CLOSE_ALL_RESULTS:
updateCount = -1;
closeAllResultSets();
break;
case CLOSE_CURRENT_RESULT:
updateCount = -1;
closeCurrentResultSet();
break;
case KEEP_CURRENT_RESULT:
updateCount = -1;
// If there is an open result set it is transferred to
// the list of open result sets. For JtdsResultSet
// result sets we cache the remaining data. For CachedResultSet
// result sets the data is already cached.
if (openResultSets == null) {
openResultSets = new ArrayList();
}
if (currentResult instanceof MSCursorResultSet
|| currentResult instanceof CachedResultSet) {
// NB. Due to restrictions on the way API cursors are
// created, MSCursorResultSet can never be followed by
// any other result sets, update counts or return variables.
openResultSets.add(currentResult);
} else if (currentResult != null) {
currentResult.cacheResultSetRows();
openResultSets.add(currentResult);
}
currentResult = null;
break;
default:
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(current),
"current"),
"HY092");
}
// Dequeue any results
if (!resultQueue.isEmpty() || processResults(false, false)) {
Object nextResult = resultQueue.removeFirst();
// Next result is an update count
if (nextResult instanceof Integer) {
updateCount = ((Integer) nextResult).intValue();
return false;
}
// Next result is a ResultSet. Set currentResult and remove it.
currentResult = (JtdsResultSet) nextResult;
return true;
} else {
return false;
}
}
public void setEscapeProcessing(boolean enable) throws SQLException {
checkOpen();
this.escapeProcessing = enable;
}
public int executeUpdate(String sql) throws SQLException {
return executeUpdate(sql, NO_GENERATED_KEYS);
}
public synchronized void addBatch(String sql) throws SQLException {
checkOpen();
if (sql == null) {
throw new NullPointerException();
}
if (batchValues == null) {
batchValues = new ArrayList();
}
if (escapeProcessing) {
String tmp[] = SQLParser.parse(sql, null, connection, false);
if (tmp[1].length() != 0) {
throw new SQLException(
Messages.get("error.statement.badsql"), "07000");
}
sql = tmp[0];
}
batchValues.add(sql);
}
public void setCursorName(String name) throws SQLException {
checkOpen();
this.cursorName = name;
if (name != null) {
// Reset statement type to JDBC 1 default.
this.resultSetType = ResultSet.TYPE_FORWARD_ONLY;
this.fetchSize = 1; // Needed for positioned updates
}
}
public boolean execute(String sql) throws SQLException {
return execute(sql, NO_GENERATED_KEYS);
}
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
execute(sql, autoGeneratedKeys);
int res = getUpdateCount();
return res == -1 ? 0 : res;
}
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
checkOpen();
initialize();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
boolean returnKeys;
String sqlWord = "";
if (escapeProcessing) {
String tmp[] = SQLParser.parse(sql, null, connection, false);
if (tmp[1].length() != 0) {
throw new SQLException(
Messages.get("error.statement.badsql"), "07000");
}
sql = tmp[0];
sqlWord = tmp[2];
} else {
// Escape processing turned off so
// see if we can extract "insert" from start of statement
sql = sql.trim();
if (sql.length() > 5) {
sqlWord = sql.substring(0,6).toLowerCase();
}
}
if (autoGeneratedKeys == RETURN_GENERATED_KEYS) {
returnKeys = sqlWord.equals("insert");
} else if (autoGeneratedKeys == NO_GENERATED_KEYS) {
returnKeys = false;
} else {
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(autoGeneratedKeys),
"autoGeneratedKeys"),
"HY092");
}
if (returnKeys) {
if (connection.getServerType() == Driver.SQLSERVER
&& connection.getDatabaseMajorVersion() >= 8) {
sql += " SELECT SCOPE_IDENTITY() AS ID";
} else {
sql += " SELECT @@IDENTITY AS ID";
}
}
return executeSQL(sql, null, sqlWord, null, returnKeys, false);
}
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
checkOpen();
if (columnIndexes == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "executeUpdate"),"HY092");
} else if (columnIndexes.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolindex", "executeUpdate"),"HY092");
}
return executeUpdate(sql, RETURN_GENERATED_KEYS);
}
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
checkOpen();
if (columnIndexes == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "execute"),"HY092");
} else if (columnIndexes.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolindex", "execute"),"HY092");
}
return execute(sql, RETURN_GENERATED_KEYS);
}
public Connection getConnection() throws SQLException {
checkOpen();
return this.connection;
}
public ResultSet getGeneratedKeys() throws SQLException {
checkOpen();
if (genKeyResultSet == null) {
String colNames[] = {"ID"};
int colTypes[] = {Types.INTEGER};
// Return an empty result set
CachedResultSet rs = new CachedResultSet(this, colNames, colTypes);
rs.setConcurrency(ResultSet.CONCUR_READ_ONLY);
genKeyResultSet = rs;
}
return genKeyResultSet;
}
public ResultSet getResultSet() throws SQLException {
checkOpen();
if (currentResult instanceof MSCursorResultSet ||
currentResult instanceof CachedResultSet) {
return currentResult;
}
// See if we are returning a forward read only resultset
if (currentResult == null ||
(resultSetType == ResultSet.TYPE_FORWARD_ONLY &&
resultSetConcurrency == ResultSet.CONCUR_READ_ONLY)) {
return currentResult;
}
// OK Now create a CachedResultSet based on the existng result set.
currentResult = new CachedResultSet(currentResult, true);
return currentResult;
}
public SQLWarning getWarnings() throws SQLException {
checkOpen();
return messages.getWarnings();
}
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
checkOpen();
if (columnNames == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "executeUpdate"),"HY092");
} else if (columnNames.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolname", "executeUpdate"),"HY092");
}
return executeUpdate(sql, RETURN_GENERATED_KEYS);
}
public boolean execute(String sql, String[] columnNames) throws SQLException {
if (columnNames == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "execute"),"HY092");
} else if (columnNames.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolname", "execute"),"HY092");
}
return execute(sql, RETURN_GENERATED_KEYS);
}
public ResultSet executeQuery(String sql) throws SQLException {
checkOpen();
initialize();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
if (escapeProcessing) {
String tmp[] = SQLParser.parse(sql, null, connection, false);
if (tmp[1].length() != 0) {
throw new SQLException(
Messages.get("error.statement.badsql"), "07000");
}
sql = tmp[0];
}
return this.executeSQLQuery(sql, null, null);
}
} |
package com.bencvt.minecraft.mcpacketsniffer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* General purpose Java utility methods.
*/
public abstract class Util {
public static class FileLogger extends Logger {
/** Formats lines like: "2012-05-21 20:57:06.540 [INFO] example message" */
public static class LineFormatter extends Formatter
{
@Override
public String format(LogRecord record) {
StringWriter w = new StringWriter();
String ts = new Timestamp((new Date()).getTime()).toString();
w.append(ts);
for (int pad = ts.length(); pad < 23; pad++) {
w.append('0');
}
w.append(" [").append(record.getLevel().getName());
w.append("] ").append(formatMessage(record)).append('\n');
if (record.getThrown() != null) {
record.getThrown().printStackTrace(new PrintWriter(w));
}
return w.toString();
}
}
public FileLogger(File baseDirectory, String name, boolean append) {
super(name, null);
baseDirectory.mkdirs();
String logFilePattern = baseDirectory.getPath() + File.separatorChar + name + ".log";
try {
FileHandler handler = new FileHandler(logFilePattern, append);
handler.setFormatter(new LineFormatter());
addHandler(handler);
} catch (IOException e) {
throw new RuntimeException("unable to add file handler for " + logFilePattern, e);
}
}
}
/**
* For getting at those pesky private and obfuscated fields.
* @return the nth (usually 0) field of the specified type declared by
* obj's class, or null if there was a reflection error.
* <p>
* Caveat: this is not guaranteed to work correctly if there are
* more than one declared fields of the same type on obj.
* <p>
* From {@link Class#getDeclaredFields}: "The elements in the
* array returned are not sorted and are not in any particular
* order."
* <p>
* In practice things work as expected even if there are multiple
* fields of the same type, but this is dependent on the JVM
* implementation.
*/
@SuppressWarnings("rawtypes")
public static Object getFieldByType(Object obj, Class type, int n) {
try {
int index = 0;
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.getType().equals(type)) {
if (index == n) {
return field.get(obj);
}
index++;
}
}
throw new RuntimeException("field not found");
} catch (Exception e) {
Controller.getEventLog().log(Level.SEVERE,
"unable to reflect field type " + type + "#" + n + " for " + obj, e);
return null;
}
}
public static Object getFieldByName(Object obj, String name) {
try {
Field field = obj.getClass().getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (Exception e) {
Controller.getEventLog().log(Level.SEVERE,
"unable to reflect field named " + name + " for " + obj, e);
return null;
}
}
public static void copyResourceToFile(String resourcePath, File destFile) {
try {
InputStream in = Controller.class.getResourceAsStream(resourcePath);
FileOutputStream out = new FileOutputStream(destFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
Controller.getEventLog().log(Level.SEVERE,
"unable to copy resource " + resourcePath + " to " + destFile, e);
}
}
} |
package org.made.neohabitat.mods;
import org.elkoserver.foundation.json.JSONMethod;
import org.elkoserver.foundation.json.OptBoolean;
import org.elkoserver.foundation.json.OptInteger;
import org.elkoserver.foundation.json.OptString;
import org.elkoserver.json.*;
import org.elkoserver.server.context.Item;
import org.elkoserver.server.context.User;
import org.elkoserver.server.context.UserMod;
import org.elkoserver.util.ArgRunnable;
import org.made.neohabitat.*;
/**
* The Avatar Mod (attached to an Elko User.)
*
* This holds both the Habitat User state, and the Avatar state and behaviors,
* which include action on the User's Avatar, and when interacting with other
* User's Avatars.
*
* @author randy
*
*/
public class Avatar extends Container implements UserMod {
public static final int SIT_GROUND = 132;
public static final int SIT_CHAIR = 133;
public static final int SIT_FRONT = 157;
public static final int STAND_FRONT = 146;
public static final int STAND_LEFT = 251;
public static final int STAND_RIGHT = 252;
public static final int STAND = 129;
public static final int FACE_FRONT = 146;
public static final int FACE_BACK = 143;
public static final int FACE_LEFT = 254;
public static final int FACE_RIGHT = 255;
public static final int GENDER_BIT = 8;
public static final int XRIGHT = 148;
public static final int XLEFT = 12;
public static final int YUP = 159;
public static final int YDOWN = 129;
public static final int STAND_UP = 0;
public static final int SIT_DOWN = 1;
public static final int XMAX = 144;
public static final double XMAXFLOAT = 144.0;
public static final int DOOR_OFFSET = 12;
public static final int BUILDING_OFFSET = 28;
public static final String DEFAULT_TURF = "context-test";
public static final String MAIL_ARRIVED_MSG = "* You have MAIL in your pocket. *";
public int HabitatClass() {
return CLASS_AVATAR;
}
public String HabitatModName() {
return "Avatar";
}
public int capacity() {
return AVATAR_CAPACITY;
}
public int pc_state_bytes() {
return 6;
};
public boolean known() {
return true;
}
public boolean opaque_container() {
return false; // TODO This should be conditionally 'true' depending on the content's slot. FRF
}
public boolean changeable() {
return true;
}
public boolean filler() {
return false;
}
/**
* Static constant CONNECTION_TYPE indicates the kind of client connected
* for this session
*/
protected static int ConnectionType = CONNECTION_JSON; /*
* Soon to default to
* CONNECTION_HABITAT
*/
/**
* Set the ConnectionType for this user.
*
* @param type
* CONNECTION_JSON or CONNECTION_HABITAT
*/
public static void setConnectionType(int type) {
ConnectionType = type;
}
/**
* Get the ConnectionType for this user.
*
* @return CONNECTION_JSON or CONNECTION_HABITAT
*/
public static int getConnectionType() {
return ConnectionType;
}
/** The body type for the avatar TODO IGNORED FOR NOW */
protected String bodyType = "male";
/** A collection of server-side Avatar status flags */
public boolean nitty_bits[] = new boolean[32];
/** Cache of avatar.contents(HEAD).style to restore after a curse. */
public int true_head_style = 0;
/** Non-zero when the Avatar-User is cursed. */
public int curse_type = CURSE_NONE;
/** Non-zero when the Avatar-User is stunned. */
public int stun_count = 0;
/** The number of tokens this avatar has in the bank (not cash-on-hand.) */
public int bankBalance = 0;
/** The current avatar pose */
public int activity = STAND_FRONT;
/** TODO Doc */
public int action = STAND_FRONT;
/** Hit Points. Reaching 0 == death */
public int health = MAX_HEALTH;
/** TODO Doc */
public int restrainer = 0;
/** Avatar customization TODO Doc */
public int custom[] = new int[2];
/** TODO Doc */
public int dest_x = 0;
public int dest_y = 0;
/* FRF Moved Hall of Records per-user stats into the user-avatar for easy access/storage */
protected int stats[] = null;
/** This is workaround - replacing the containership-based original model for seating used by the original Habtiat */
public int sittingIn = 0;
public int sittingSlot = 0;
public int sittingAction = AV_ACT_sit_front;
public String turf = "context-test";
private String from_region = "";
public String to_region = "";
private int from_orientation = 0;
private int from_direction = 0;
private int to_x = 0;
private int to_y = 0;
private int transition_type = WALK_ENTRY;
private MailQueue mail_queue = null;
/**
* Target NOID and magic item saved between events, such as for the GOD TOOL
* (see Magical.java). This is a transient value and not persisted.
*/
public HabitatMod savedTarget = null;
public Magical savedMagical = null;
public String ESPTargetName = null;
public int lastConnectedDay = 0;
public int lastConnectedTime = 0;
public String lastArrivedIn = "";
/** Used to indicate that this avatar-instance should be treated as the "first" instantiation of the session */
public boolean firstConnection = false;
/** Flag to indicate this User/Connection/Avatar is in Ghost state: Observer only **/
public boolean amAGhost = false;
@JSONMethod({ "style", "x", "y", "orientation", "gr_state", "nitty_bits", "bodyType", "stun_count", "bankBalance",
"activity", "action", "health", "restrainer", "transition_type", "from_orientation", "from_direction", "from_region", "to_region",
"to_x", "to_y", "turf", "custom", "lastConnectedDay", "lastConnectedTime", "amAGhost", "firstConnection", "lastArrivedIn", "?stats" })
public Avatar(OptInteger style, OptInteger x, OptInteger y, OptInteger orientation, OptInteger gr_state,
OptInteger nitty_bits, OptString bodyType, OptInteger stun_count, OptInteger bankBalance,
OptInteger activity, OptInteger action, OptInteger health, OptInteger restrainer,
OptInteger transition_type, OptInteger from_orientation, OptInteger from_direction,
OptString from_region, OptString to_region, OptInteger to_x, OptInteger to_y,
OptString turf, int[] custom, OptInteger lastConnectedDay, OptInteger lastConnectedTime,
OptBoolean amAGhost, OptBoolean firstConnection, OptString lastArrivedIn, int[] stats) {
super(style, x, y, orientation, gr_state, new OptBoolean(false));
if (null == stats) {
stats = new int[HS$MAX];
stats[HS$wealth] = bankBalance.value(0);
stats[HS$max_wealth] = bankBalance.value(0);
}
setAvatarState(nitty_bits.present() ? unpackBits(nitty_bits.value()) : new boolean[32],
bodyType.value("male"),
stun_count.value(0),
bankBalance.value(0),
activity.value(STAND_FRONT),
action.value(this.activity),
health.value(MAX_HEALTH),
restrainer.value(0),
transition_type.value(WALK_ENTRY),
from_orientation.value(0),
from_direction.value(0),
from_region.value(""),
to_region.value(""),
to_x.value(0),
to_y.value(0),
turf.value(DEFAULT_TURF),
custom,
lastConnectedDay.value(0),
lastConnectedTime.value(0),
amAGhost.value(false),
firstConnection.value(false),
lastArrivedIn.value(""),
stats);
}
public Avatar(int style, int x, int y, int orientation, int gr_state, boolean[] nitty_bits, String bodyType,
int stun_count, int bankBalance, int activity, int action, int health, int restrainer, int transition_type,
int from_orientation, int from_direction, String from_region, String to_region, int to_x, int to_y,
String turf, int[] custom, int lastConnectedDay, int lastConnectedTime, boolean amAGhost,
boolean firstConnection, String lastArrivedIn, int[] stats) {
super(style, x, y, orientation, gr_state, false);
setAvatarState(nitty_bits, bodyType, stun_count, bankBalance, activity, action, health, restrainer, transition_type,
from_orientation, from_direction, from_region, to_region, to_x, to_y, turf, custom, lastConnectedDay, lastConnectedTime,
amAGhost, firstConnection, lastArrivedIn, stats);
}
protected void setAvatarState(boolean[] nitty_bits, String bodyType,
int stun_count, int bankBalance, int activity, int action, int health, int restrainer, int transition_type,
int from_orientation, int from_direction, String from_region, String to_region, int to_x, int to_y,
String turf, int[] custom, int lastConnectedDay, int lastConnectedTime, boolean amAGhost,
boolean firstConnection, String lastArrivedIn, int[] stats) {
this.nitty_bits = nitty_bits;
this.bodyType = bodyType;
this.stun_count = stun_count;
this.bankBalance = bankBalance;
this.activity = activity;
this.action = action;
this.health = health;
this.restrainer = restrainer;
this.transition_type = transition_type;
this.from_orientation = from_orientation;
this.from_direction = from_direction;
this.from_region = from_region;
this.to_region = to_region;
this.to_x = to_x;
this.to_y = to_y;
this.turf = turf;
this.custom = custom;
this.lastConnectedDay = lastConnectedDay;
this.lastConnectedTime = lastConnectedTime;
this.amAGhost = amAGhost;
this.firstConnection = firstConnection;
this.lastArrivedIn = lastArrivedIn;
this.stats = stats;
}
@Override
public JSONLiteral encode(EncodeControl control) {
JSONLiteral result = super.encodeCommon(new JSONLiteral(HabitatModName(), control));
if (packBits(nitty_bits) != 0) {
result.addParameter("nitty_bits", packBits(nitty_bits));
}
result.addParameter("bodyType", bodyType);
result.addParameter("stun_count", stun_count);
result.addParameter("bankBalance", bankBalance);
result.addParameter("activity", activity);
result.addParameter("action", action);
result.addParameter("health", health);
result.addParameter("restrainer", restrainer);
result.addParameter("custom", custom);
result.addParameter("amAGhost", amAGhost);
if (result.control().toRepository()) {
result.addParameter("transition_type", transition_type);
result.addParameter("from_orientation", from_orientation);
result.addParameter("from_direction", from_direction);
result.addParameter("from_region", from_region);
result.addParameter("to_region", to_region);
result.addParameter("to_x", to_x);
result.addParameter("to_y", to_y);
result.addParameter("turf", turf);
result.addParameter("lastConnectedDay", lastConnectedDay);
result.addParameter("lastConnectedTime",lastConnectedTime);
result.addParameter("firstConnection", firstConnection);
result.addParameter("lastArrivedIn", lastArrivedIn);
result.addParameter("stats", stats);
}
if (result.control().toClient() && sittingIn != 0) {
result.addParameter("sittingIn", sittingIn);
result.addParameter("sittingSlot", sittingSlot);
result.addParameter("sittingAction", sittingAction);
// Having a non-persistent client-only variables is unusual.
// This is a work around because the client expects a seated avatar to be "contained" by the seat
// That's terrible, so the workaround is to say that seating is live-session-only.
// This prevents a LOT of problems since objects can change state/existence between sessions.
}
result.finish();
return result;
}
public String mailQueueRef() {
return String.format("mail-%s", object().name().toLowerCase());
}
/** Avatars need to be repositioned upon arrival in a region based on the method used to arrive. */
public void objectIsComplete() {
/** Was pl1 region_entry_daemon: */
// If traveling as an intentional ghost, don't do ANYTHING fancy
if (amAGhost) {
return;
}
Region.addToNoids(this);
note_object_creation(this);
// If walking in, set the new (x,y) based on the old (x,y), the entry
// direction, the rotation of the region transition, the horizon of the
// new region, and so on
int new_x = x;
int new_y = y & ~FOREGROUND_BIT;
int new_activity = FACE_LEFT;
int rotation = 0;
int arrival_face = 0;
trace_msg("Avatar %s called objectIsComplete, transition_type=%d", obj_id(), transition_type);
if (transition_type == WALK_ENTRY) {
y &= ~FOREGROUND_BIT;
rotation = (from_orientation - current_region().orientation + 4) % 4;
arrival_face = (from_direction + rotation + 2) % 4;
if (arrival_face == 0) {
new_x = XLEFT;
new_activity = FACE_RIGHT;
if (rotation == 0)
new_y = y;
else if (rotation == 1)
new_y = x_scale(x_invert(x));
else if (rotation == 2)
new_y = y_invert(y);
else
new_y = x_scale(x);
} else if (arrival_face == 1) {
new_y = current_region().depth;
new_activity = FACE_FRONT;
if (rotation == 0)
new_x = x;
else if (rotation == 1)
new_x = y_scale(y);
else if (rotation == 2)
new_x = x_invert(x);
else
new_x = y_scale(y_invert(y));
HabitatMod noids[] = current_region().noids;
for (int i=0; i < noids.length; i++) {
HabitatMod obj = noids[i];
if (noids[i] != null) {
if (obj.HabitatClass() == CLASS_DOOR) {
Door door = (Door) obj;
if (door.connection.equals(from_region) || door.connection.isEmpty()) {
new_y = obj.y;
new_x = obj.x + DOOR_OFFSET;
if (test_bit(obj.orientation, 1))
new_x = new_x - 16;
}
} else if (obj.HabitatClass() == CLASS_BUILDING) {
Building bldg = (Building) obj;
if (bldg.connection == from_region || bldg.connection.isEmpty()) {
new_x = obj.x + BUILDING_OFFSET;
}
}
}
}
} else if (arrival_face == 2) {
new_x = XRIGHT;
new_activity = FACE_LEFT;
if (rotation == 0)
new_y = y;
else if (rotation == 1)
new_y = x_scale(x_invert(x));
else if (rotation == 2)
new_y = y_invert(y);
else
new_y = x_scale(x);
} else {
new_y = YDOWN;
new_activity = FACE_BACK;
if (rotation == 0)
new_x = x;
else if (rotation == 1)
new_x = y_scale(y);
else if (rotation == 2)
new_x = x_invert(x);
else
new_x = y_scale(y_invert(y));
}
x = new_x & 0b11111100;
y = Math.min((new_y & ~FOREGROUND_BIT), current_region().depth) | FOREGROUND_BIT;
activity = new_activity;
} else if (transition_type == TELEPORT_ENTRY) {
if ( 0 != to_y) {
x = to_x;
y = to_y;
} else {
x = 8;
y = 130;
HabitatMod noids[] = current_region().noids;
for (int i=0; i < noids.length; i++) {
HabitatMod obj = noids[i];
if (noids[i] != null) {
if (obj.HabitatClass() == CLASS_TELEPORT) {
x = obj.x + 8;
y = obj.y + 3;
}
if (obj.HabitatClass() == CLASS_ELEVATOR) {
x = obj.x + 12;
y = obj.y - 5;
}
}
}
}
// If entering via teleport, make sure we're in foreground
y |= FOREGROUND_BIT;
} else {
trace_msg("ENTRY ERROR: Unknown transition type: " + transition_type);
}
}
private int x_invert(int x) {
return (XMAX - x);
}
private int y_invert(int y) {
return(current_region().depth - y);
}
private int x_scale(int x) {
double scale = current_region().depth / XMAXFLOAT;
return ((int) scale);
}
private int y_scale(int y) {
double scale = XMAXFLOAT / current_region().depth;
return ((int) scale);
}
/**
* Verb (Specific): Grabbing from another avatar.
*
* @param from User representing the connection making the request.
*/
@JSONMethod()
public void GRAB(User from) {
Avatar otherAvatar = avatar(from);
if (amAGhost || otherAvatar.amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
Region curRegion = current_region();
HabitatMod itemMod = null;
if (empty_handed(otherAvatar) && !empty_handed(this)) {
itemMod = this.contents(HANDS);
if (!curRegion.grabable(itemMod)) {
send_reply_msg(from, noid, "item_noid", 0);
if (curRegion.nitty_bits[STEAL_FREE]) {
object_say(from, noid, "This is a theft-free zone.");
}
return;
}
if (!change_containers(itemMod, otherAvatar, HANDS, true)) {
send_reply_msg(from, noid, "item_noid", 0);
return;
}
send_neighbor_msg(from, otherAvatar.noid, "GRABFROM$", "avatar_noid", noid);
otherAvatar.inc_record(HS$grabs);
}
if (itemMod != null) {
send_reply_msg(from, noid, "item_noid", itemMod.noid);
} else {
send_reply_msg(from, noid, "item_noid", 0);
}
}
/**
* Verb (Specific): Handing in-hand item to another avatar.
*
* @param from User representing the connection making the request.
*/
@JSONMethod()
public void HAND(User from) {
Avatar otherAvatar = avatar(from);
if (amAGhost || otherAvatar.amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
HabitatMod itemMod = null;
boolean success = false;
if (empty_handed(this) && !empty_handed(otherAvatar) && sittingIn == 0) {
itemMod = otherAvatar.contents(HANDS);
if (itemMod.HabitatClass() == CLASS_MAGIC_LAMP &&
itemMod.gr_state == MAGIC_LAMP_GENIE) {
object_say(from, itemMod.noid, "You can't give away the Genie!");
success = false;
} else {
if (!change_containers(itemMod, this, HANDS, true)) {
success = false;
} else {
success = true;
activity = STAND;
gen_flags[MODIFIED] = true;
checkpoint_object(this);
send_neighbor_msg(from, noid, "GRABFROM$", "avatar_noid", otherAvatar.noid);
}
}
}
if (success) {
send_reply_success(from);
} else {
send_reply_error(from);
}
}
/**
* Verb (Specific): TODO Change this avatar's posture.
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod({ "pose" })
public void POSTURE(User from, OptInteger pose) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
int new_posture = pose.value(STAND_FRONT);
// if (selfptr == avatarptr) { TODO Bullet Proofing Needed
if (0 <= new_posture && new_posture < 256) {
if (new_posture == SIT_GROUND || new_posture == SIT_CHAIR || new_posture == SIT_FRONT
|| new_posture == STAND || new_posture == STAND_FRONT || new_posture == STAND_LEFT
|| new_posture == STAND_RIGHT || new_posture == FACE_LEFT || new_posture == FACE_RIGHT) {
this.activity = new_posture;
}
if (new_posture != COLOR_POSTURE) {
send_neighbor_msg(from, noid, "POSTURE$", "new_posture", new_posture);
}
if (new_posture < STAND_LEFT || new_posture == COLOR_POSTURE) {
send_reply_success(from);
}
}
}
/**
* Verb (Specific)
*
* @param from
* User representing the connection making the request.
* @param esp
* Byte flag indicating that ESP message mode is active on the
* client (NOTE: ESP is implemented in the Bridge.)
* @param text
* The string to speak...
*/
@JSONMethod({ "esp", "text" })
public void SPEAK(User from, OptInteger esp, OptString text) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
int in_esp = esp.value(TRUE);
String msg = text.value("(missing text)");
if (FALSE == in_esp) {
if (msg.toLowerCase().startsWith("//neohabitat")) {
if (Region.NEOHABITAT_FEATURES) {
Region.tellEveryone("Original Habitat interface enabled globally.");
} else {
Region.tellEveryone("Upgraded NeoHabitat interface enabled globally.");
}
Region.NEOHABITAT_FEATURES = !Region.NEOHABITAT_FEATURES;
} else if (msg.toLowerCase().startsWith("to:")) {
String name = msg.substring(3).trim();
User user = Region.getUserByName(name);
if (user != null && user != from) {
ESPTargetName = name;
in_esp = TRUE;
if (Region.NEOHABITAT_FEATURES) {
object_say(from, UPGRADE_PREFIX + "Tranmitting thoughts to " + user.name() + "...");
}
} else {
send_private_msg(from, this.noid, from, "SPEAK$", "Cannot contact " + name + ".");
}
} else {
send_broadcast_msg(this.noid, "SPEAK$", msg);
inc_record(HS$talkcount);
}
}
send_reply_msg(from, this.noid, "esp", in_esp);
}
/**
* Verb (Specific): TODO Walk across the region.
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod({ "x", "y", "how" })
public void WALK(User from, OptInteger x, OptInteger y, OptInteger how) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
int destination_x = x.value(80);
int destination_y = y.value(10) | FOREGROUND_BIT;
int walk_how = how.value(0);
if (stun_count > 0) {
stun_count -= 1;
send_reply_msg(from, this.noid, "x", this.x, "y", this.y, "how", walk_how);
if (stun_count >= 2) {
send_private_msg(from, this.noid, from, "SPEAK$", "I can't move. I am stunned.");
} else if (stun_count == 1) {
send_private_msg(from, this.noid, from, "SPEAK$", "I am still stunned.");
} else {
send_private_msg(from, this.noid, from, "SPEAK$", "The stun effect is wearing off now.");
}
checkpoint_object(this);
return;
}
if ((destination_y & ~FOREGROUND_BIT) > current_region().depth) {
destination_y = current_region().depth | FOREGROUND_BIT;
}
send_neighbor_msg(from, this.noid, "WALK$", "x", destination_x, "y", destination_y, "how", walk_how);
send_reply_msg(from, this.noid, "x", destination_x, "y", destination_y, "how", walk_how);
this.x = destination_x;
this.y = destination_y;
checkpoint_object(this);
}
/**
* Verb (Specific): TODO Leave the region for another region.
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod({ "direction", "passage_id" })
public void NEWREGION(User from, OptInteger direction, OptInteger passage_id) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
avatar_NEWREGION(from, direction.value(1), passage_id.value(0));
}
/**
* Verb (Specific): TODO Turn to/from being a ghost.
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod
public void DISCORPORATE(User from) {
// if (amAGhost)
// trace_msg("Invalid request: Avatar.DISCORPORATE called with avatar.amAGhost == true.");
// else
if (holding_class(CLASS_MAGIC_LAMP) && heldObject().gr_state == MAGIC_LAMP_GENIE)
object_say(from, "You can't turn into a ghost while you are holding the Genie.");
else
if (holding_restricted_object())
object_say(from, "You can't turn into a ghost while you are holding that.");
else {
send_private_msg(from, THE_REGION, from, "PLAY_$", "sfx_number", 5, "from_noid", noid);
switch_to_ghost(from);
nitty_bits[INTENTIONAL_GHOST] = true;
return;
}
send_reply_error(from);
}
public static final int COPOREAL_FAIL = 0;
public static final int COPOREAL_SUCCESS = 1;
public static final int COPOREAL_ALREADY_THERE = 2;
public static final int COPOREAL_LAST_GHOST = 3;
public void switch_to_ghost(User from) {
if (sittingIn != 0) {
send_reply_error(from);
return;
}
/* First, transform to a ghost (which will create one if needed) */
Ghost ghost = current_region().getGhost();
ghost.total_ghosts++;
amAGhost = true;
send_reply_msg(from, noid,
"success", COPOREAL_ALREADY_THERE,
"newNoid", GHOST_NOID,
"balance", bankBalance);
send_neighbor_msg(from, THE_REGION, "GOAWAY_$", "target", noid); // Tell the neighbors who vanished...
x = SAFE_X; // Prepare for when the avatar comes back. Or reload from DB
y = SAFE_Y;
activity = STAND;
gen_flags[MODIFIED] = true;
current_region().lights_off(this);
/* Clean up the region, recovering scarce c64 resources and noids */
for (int i = 0; i < capacity(); i++) {
HabitatMod obj = contents(i);
if (obj != null) {
note_object_deletion(obj);
Region.removeFromObjList(obj);
}
}
note_object_deletion(this);
Region.removeFromObjList(this);
}
public void switch_to_avatar(User from) {
Region region = current_region();
Ghost ghost = region.getGhost();
int result = COPOREAL_FAIL;
if (region.isRoomForMyAvatar(from)) {
for (int i = 0; i < capacity(); i++) {
HabitatMod obj = contents(i);
if (obj != null) {
Region.addToNoids(obj);
note_object_creation(obj);
}
}
Region.addToNoids(this);
note_object_creation(this);
result = COPOREAL_SUCCESS;
ghost.total_ghosts
amAGhost = false;
if (ghost.total_ghosts == 0) {
result = COPOREAL_LAST_GHOST;
region.destroyGhost(from);
}
}
JSONLiteral msg = new_reply_msg(GHOST_NOID);
msg.addParameter("success", result);
msg.addParameter("newNoid", noid);
msg.addParameter("balance", bankBalance);
if (result == COPOREAL_FAIL) {
from.send(msg);
} else {
x = SAFE_X;
y = SAFE_Y;
gen_flags[MODIFIED] = true;
// msg.addParameter("body", object().encode(EncodeControl.forClient));
msg.addParameter("body", 0);
from.send(msg);
// announce_object_to_neighbors(from, object(), current_region());
fakeMakeMessage(object(), current_region());
current_region().lights_on(this);
for (int i = capacity() - 1; i >= 0; i--) { // TODO - encode the avatar and contents together instead of this HACK! FRF
HabitatMod obj = contents(i);
if (obj != null)
fakeMakeMessage(obj.object(), this);
}
JSONLiteral ready = new JSONLiteral(null, EncodeControl.forClient);
ready.addParameter("to", object().ref());
ready.addParameter("op", "ready");
ready.finish();
context().send(ready);
}
}
/**
* Verb (Specific): Send a point-to-point message to another user/avatar.
*
* @param from
* User representing the connection making the request.
* @param esp
* Byte flag indicating that ESP message mode is active on the
* client (NOTE: ESP is implemented in the Bridge.)
* @param text
* The string to speak...
*/
@JSONMethod({ "esp", "text" })
public void ESP(User from, OptInteger esp, OptString text) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
int in_esp = esp.value(FALSE);
String msg = text.value("");
if (TRUE == in_esp) {
msg = msg.startsWith("ESP:") ? msg.substring(4) : msg;
if (msg.isEmpty()) { // Exit ESP
in_esp = FALSE;
ESPTargetName = null;
if (Region.NEOHABITAT_FEATURES) {
object_say(from, UPGRADE_PREFIX + "ESP connection ended.");
}
} else {
User to = Region.getUserByName(ESPTargetName);
if (to != null) {
object_say(to, "ESP from " + object().name() + ": ");
if (msg.length() < 4) {
msg = " " + msg + " ";
}
object_say(to, msg);
inc_record(HS$esp_send_count);
Avatar.inc_record(to, HS$esp_recv_count);
if (Region.NEOHABITAT_FEATURES) {
object_say(from, UPGRADE_PREFIX + "ESP:" + msg);
}
} else {
object_say(from, "Cannot contact " + ESPTargetName + ".");
in_esp = FALSE;
ESPTargetName = null;
}
}
}
send_reply_msg(from, this.noid, "esp", in_esp);
}
/**
* Verb (Specific): TODO Sit down. [Stand up?]
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod({"up_or_down", "seat_id"})
public void SITORSTAND(User from, int up_or_down, int seat_id) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
// if (up_or_down <= SIT_DOWN) { // TOFO FRF This is always for now until we can work with Elko for a fix.
// unsupported_reply(from, noid, "This furniture has a sign that reads 'Do not sit here. Under repair'.");
// return;
/** Historically was avatar_SITORSTAND in original pl1 */
Region region = current_region();
Seating seat = (Seating) region.noids[seat_id];
int slot = -1;
if (seat != null) {
if (isSeating(seat) && !seat.gen_flags[RESTRICTED]) {
if (up_or_down == STAND_UP) {
if (sittingIn == seat_id) {
slot = sittingSlot;
if (seat.sitters[slot] != noid) {
send_reply_msg(from, noid, "err", FALSE, "slot", 0);
return;
}
activity = STAND;
sittingIn = 0;
seat.sitters[slot] = 0;
gen_flags[MODIFIED] = true;
checkpoint_object(this);
send_reply_msg(from, noid, "err", TRUE, "slot", 0);
send_neighbor_msg(from, noid, "SIT$", "up_or_down", STAND_UP, "cont", seat_id, "slot", 0);
return;
}
} else {
Container cont = (Container) seat;
for (slot = 0; slot < cont.capacity(); slot++) {
if (cont.contents(slot) == null && seat.sitters[slot] == 0) {
if (sittingIn != 0) {
send_reply_msg(from, 0, "err", FALSE, "slot", 0);
return;
}
seat.sitters[slot] = noid;
sittingIn = seat.noid;
sittingSlot = slot;
sittingAction = ((seat.style & 1) == 1) ? AV_ACT_sit_chair : AV_ACT_sit_front;
send_reply_msg(from, noid, "err", TRUE, "slot", slot);
send_neighbor_msg(from, noid, "SIT$", "up_or_down", SIT_DOWN, "cont", seat_id, "slot", slot);
return;
}
}
}
}
}
send_reply_msg(from, noid, "err", FALSE, "slot", 0);
}
/**
* Verb (Specific): TODO Touch another avatar.
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod
public void TOUCH(User from) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
unsupported_reply(from, noid, "Avatar.TOUCH not implemented yet.");
}
/**
* Verb (Specific): Userlist (same as F3 on c64 client)
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod
public void USERLIST(User from) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
sayUserList(from);
}
public void sayUserList(User from) {
String balloon = ""; // TODO Limit to last dozen.
for (String name: Region.NameToUser.keySet()) {
balloon += (Region.NameToUser.get(name).name() + " ").substring(0, 12);
if (balloon.length() > 35) {
object_say(from, balloon);
balloon = "";
}
}
if (!balloon.isEmpty()) {
object_say(from, (balloon + " ").substring(0,36));
}
send_reply_success(from);
}
/**
* Verb (Specific): TODO Deal with FN Key presses.
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod({ "key", "target" })
public void FNKEY(User from, OptInteger key, OptInteger target) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
switch (key.value(0)) {
case 16:
object_say(from, UPGRADE_PREFIX + " You are connected to ");
object_say(from, " The Neoclassical Habitat Server ");
// object_say(from, " ".substring(BuildVersion.version.length())
// + BuildVersion.version + " ");
object_say(from, " The MADE, The Museum of Arts & Digital Entertainment, Oakland CA");
object_say(from, " ");
object_say(from, "Open source - Join us! NeoHabitat.org ");
object_say(from, NeoHabitat.GetBuildVersion());
send_reply_success(from);
break;
case 11: // F3 & F4 (Users list)
sayUserList(from);
break;
case 13: // F5 & F6 (Change Skin Color)
object_say(from, String.format("Light level: " + current_region().lighting + " Current heap: %d", current_region().space_usage));
send_reply_success(from);
break;
default:
unsupported_reply(from, noid, "Avatar.FNKEY not implemented yet.");
}
}
/**
* Verb (Avatar): Reply with the HELP for this avatar.
*
* @param from
* User representing the connection making the request.
*/
@JSONMethod
public void HELP(User from) {
if (amAGhost) {
illegal_request(from, "Avatar commands not allowed when a ghost.");
return;
}
avatar_IDENTIFY(from);
}
/**
* Alternate interface to avatar_IDENTIFY, passing this.noid as the missing
* second argument.
*
* @param from
* User representing the connection making the request.
*/
public void avatar_IDENTIFY(User from) {
avatar_IDENTIFY(from, this.noid);
}
private boolean alreadyShown = false;
private String stripContextDash(String s) {
s = (s.indexOf("context-") == 0) ? s.substring(8) : s;
return s.replace('_', '{');
}
public void showDebugInfo(User from) {
if (!alreadyShown) {
if (nitty_bits[GOD_FLAG] &&
contents(HANDS) instanceof Magical &&
Magical.isGodTool((Magical) contents(HANDS))) {
Region region = current_region();
String msg = stripContextDash(context().ref()) + "(W" + Compass.DIRECTION_ARROWS[region.orientation]+") ";
int arrow = (region.orientation + 3) % 4;
if (!region.neighbors[MAP_NORTH].isEmpty()) {
msg += "N" + Compass.DIRECTION_ARROWS[arrow];
msg += stripContextDash(region.neighbors[MAP_NORTH]) + " ";
}
arrow = ++arrow % 4;
if (!region.neighbors[MAP_WEST].isEmpty()) {
msg += "W" + Compass.DIRECTION_ARROWS[arrow];
msg += stripContextDash(region.neighbors[MAP_WEST]) + " ";
}
arrow = ++arrow % 4;
if (!region.neighbors[MAP_SOUTH].isEmpty()) {
msg += "S" + Compass.DIRECTION_ARROWS[arrow];
msg += stripContextDash(region.neighbors[MAP_SOUTH]) + " ";
}
arrow = ++arrow % 4;
if (!region.neighbors[MAP_EAST].isEmpty()) {
msg += "E" + Compass.DIRECTION_ARROWS[arrow];
msg += stripContextDash(region.neighbors[MAP_EAST]) + " ";
}
this.object_say(from, msg);
alreadyShown = true;
}
}
}
/**
* A different message is returned depending on if this avatar is the "from"
* user or another, the message returned will vary.
*
* @param from
* User representing the connection making the request.
* @param replyNoid
* which avatar.noid is the one getting the reply.
*/
public void avatar_IDENTIFY(User from, int replyNoid) {
User targetUser = (User) this.object();
String targetName = targetUser.name();
String avatarname = from.name();
Avatar avatar = avatar(from);
String result = "";
if (avatar.noid == this.noid) {
result = "Your name is " + avatarname + ". You are ";
if (avatar.stun_count > 0)
result = result + "stunned, and you are ";
if (avatar.health > 200)
result = result + "in the peak of health.";
else if (avatar.health > 150)
result = result + "in good health.";
else if (avatar.health > 100)
result = result + "in fair health.";
else if (avatar.health > 50)
result = result + "in poor health.";
else
result = result + "near death.";
if (has_turf()) {
result = result + " You live at " + turf_name() + ".";
}
} else {
send_private_msg(from, avatar.noid, targetUser, "SPEAK$", "I am " + avatarname);
// p_msg_s(from, avatar.noid, targetUser, SPEAK$, "I am " +
// avatarname);
/*
* OBSOLETE CODE REFACTORED An Elko User == Connection, so there is
* no Turned to Stone state. And since a Elko Habitat Avatar is
* attached 1:1 to a Elko User, this code can never be true in this
* server.
*
* if (UserList(self.avatarslot)->u.online) result = "This is " +
* targetName; else result = "Turned to stone: " + selfname;
*/
result = "This is " + targetName;
}
send_reply_msg(from, replyNoid, "text",
result); /* TODO is replyNoid right? */
}
public void avatar_NEWREGION(User from, int direction, int passage_id) {
Region region = current_region();
String new_region = "";
int entry_type = WALK_ENTRY;
HabitatMod passage = region.noids[passage_id];
int direction_index = (direction + region.orientation + 2) % 4;
if (direction != AUTO_TELEPORT_DIR && passage_id != 0 &&
passage.HabitatClass() == CLASS_DOOR ||
passage.HabitatClass() == CLASS_BUILDING) {
if (passage.HabitatClass() == CLASS_DOOR) {
Door door = (Door) passage;
if (!door.getOpenFlag(OPEN_BIT) ||
door.gen_flags[DOOR_AVATAR_RESTRICTED_BIT]) {
send_reply_error(from);
return;
} else {
new_region = door.connection;
}
} else {
new_region = ((Building) passage).connection;
}
}
else {
if (direction >= 0 && direction < 4) {
new_region = region.neighbors[direction_index]; // East, West, North, South
} else { // direction == AUTO_TELEPORT_DIR
new_region = to_region;
entry_type = TELEPORT_ENTRY;
direction = WEST; // TODO Randy needs to revisit this little hack to prevent a loop..
}
}
if (!new_region.isEmpty()) {
if (holding_restricted_object()) {
heldObject().putMeBack(from, false);
}
if (Region.IsRoomForMyAvatarIn(new_region, from) == false) {
object_say(from, "That region is full. Try entering as a ghost (F1).");
send_reply_error(from);
return;
}
send_neighbor_msg(from, THE_REGION, "WAITFOR_$", "who", this.noid);
send_reply_success(from);
change_regions(new_region, direction, entry_type);
return;
}
object_say(from, "There is nowhere to go in that direction.");
send_reply_error(from);
}
public void change_regions(String contextRef, int direction, int type) {
change_regions(contextRef, direction, type, 0, 0);
}
public void change_regions(String contextRef, int direction, int type, int x, int y) {
Region region = current_region();
User who = (User) this.object();
trace_msg("Avatar %s changing regions to context=%s, direction=%d, type=%d", obj_id(),
contextRef, direction, type);
to_region = contextRef;
to_x = x;
to_y = y;
from_region = region.obj_id(); // Save exit information in avatar for use on arrival.
from_orientation = region.orientation;
from_direction = direction;
transition_type = type;
firstConnection = false;
gen_flags[MODIFIED] = true;
checkpoint_object(this);
if (direction == AUTO_TELEPORT_DIR) {
send_private_msg(who, THE_REGION, who, "AUTO_TELEPORT_$", "direction", direction);
} else {
JSONLiteral msg = new JSONLiteral("changeContext", EncodeControl.forClient);
msg.addParameter("context", contextRef);
msg.addParameter("immediate", (type == TELEPORT_ENTRY && direction == EAST));
msg.finish();
who.send(msg);
}
}
/**
* Drops whatever item is in the current Avatar's hands.
*/
public void drop_object_in_hand() {
if (contents(HANDS) != null) {
HabitatMod obj = contents(HANDS);
obj.x = 8;
obj.y = 130;
obj.gen_flags[MODIFIED] = true;
obj.change_containers(obj, current_region(), obj.y, true);
// For C64-side implementation, see line 110 of actions.m.
send_broadcast_msg(THE_REGION, "CHANGE_CONTAINERS_$",
"object_noid", obj.noid,
"container_noid", THE_REGION,
"x", obj.x,
"y", obj.y);
}
}
/**
* Returns true if the Avatar is holding an item of the provided class.
*
* @param habitat_class The Habitat class to check against.
* @return true/false whether the Avatar is holding an item of the provideed class
*/
public boolean holding_class(int habitat_class) {
HabitatMod obj = contents(HANDS);
if (obj != null) {
return obj.HabitatClass() == habitat_class;
}
return false;
}
/**
* Returns whether the Avatar is holding a restricted object.
*
* @return true/false whether the Avatar is holding a restricted object
*/
public boolean holding_restricted_object() {
HabitatMod obj = contents(HANDS);
if (obj != null) {
return obj.gen_flags[RESTRICTED];
}
return false;
}
/**
* Set a user's record value.
*
* @param recordID
* @param value
*/
public void set_record(int recordID, int value) {
stats[recordID] = value;
stats[HS$max_lifetime] = Math.max(stats[HS$max_lifetime], stats[HS$lifetime]);
stats[HS$max_wealth] = Math.max(stats[HS$max_wealth], stats[HS$wealth]);
stats[HS$max_travel] = Math.max(stats[HS$max_travel], stats[HS$travel]);
gen_flags[MODIFIED] = true;
}
/**
* Returns the Elko User associated with this Avatar.
*
* @return the Elko User associated with this Avatar
*/
public User elko_user() {
return Region.getUserByName(object().name());
}
/**
* Sends a MAILARRIVED$ message to the User associated with this Avatar.
*/
public void send_mail_arrived() {
new Thread(sendMailArrived).start();
}
/**
* Get this user's value for a record.
*
* @param recordID
* @return
*/
public int get_record(int recordID) {
return stats[recordID];
}
/**
* Add one to a user's record value.
*
* @param recordID
*/
public void inc_record(int recordID) {
set_record(recordID, get_record(recordID) + 1);
}
/**
* Static version of set_record. Does the cast for you.
*
* @param whom
* @param recordID
* @param value
*/
static public void set_record(User whom, int recordID, int value) {
((Avatar) whom.getMod(Avatar.class)).set_record(recordID, value);
}
/**
* Static version of get_record. Does the cast for you.
* @param whom
* @param recordID
* @return
*/
static public int get_record(User whom, int recordID) {
return(((Avatar) whom.getMod(Avatar.class)).get_record(recordID));
}
/**
* Static version of inc_record. Does the cast for you.
*
* @param whom
* @param recordID
*/
static public void inc_record(User whom, int recordID) {
((Avatar) whom.getMod(Avatar.class)).inc_record(recordID);
}
/**
* Returns whether this Avatar has an assigned Turf.
*
* @return boolean whether Avatar has an assigned Turf
*/
public boolean has_turf() {
return !turf.equals(DEFAULT_TURF);
}
/**
* Determines the name of the turf (e.g. Popustop #100) from its Elko context reference.
*
* @return Human-readable name of the Avatar's turf
*/
public String turf_name() {
if (!has_turf()) {
return "unknown";
} else {
try {
String[] splitContext = turf.split("-");
String[] splitTurf = splitContext[1].split("\\.");
String realm = splitTurf[0].substring(0, 1).toUpperCase() + splitTurf[0].substring(1);
String turfId = splitTurf[1];
return String.format("%s #%s", realm, turfId);
} catch (ArrayIndexOutOfBoundsException e) {
trace_exception(e);
return "unknown";
}
}
}
/**
* Checks for new Mail and sends a MAILARRIVED$ notification to the Avatar if so.
*/
public void check_mail() {
// If the Avatar has a Paper in their MAIL_SLOT, sends a Mail arrived
// notification and performs no MailQueue operations.
HabitatMod paperMod = contents(MAIL_SLOT);
if (paperMod == null || !(paperMod instanceof Paper)) {
trace_msg("Paper not in MAIL_SLOT for User %s", object().ref());
return;
}
Paper paperInMailSlot = (Paper) paperMod;
if (paperInMailSlot.gr_state == Paper.PAPER_LETTER_STATE) {
if (!amAGhost) {
send_mail_arrived();
}
return;
}
// Otherwise, checks the Avatar's MailQueue for new Mail and modifies the Paper
// in the MAIL_SLOT if any is found.
update_mail_slot(!amAGhost);
}
/**
* If the Paper in the Avatar's pocket indicates that it can receive a new Mail and
* there is new Mail in an Avatar's MailQueue, pops that Mail off the MailQueue
* and adds it to the Paper in the Avatar's MAIL_SLOT, then optionally sends a
* mail arrival message.
*
* @param shouldAnnounce whether to send a MAILARRIVED$ message if the slot is advanced
*/
private void advance_mail_slot(boolean shouldAnnounce) {
if (mail_queue == null) {
return;
}
trace_msg("Advancing Mail slot for User %s (Mail records count: %d)",
object().ref(), mail_queue.size());
boolean advanced = false;
Paper paperInMailSlot = null;
HabitatMod paperMod = contents(MAIL_SLOT);
if (paperMod == null || !(paperMod instanceof Paper)) {
trace_msg("Object in MAIL_SLOT for User %s is not Paper", object().ref());
return;
} else {
paperInMailSlot = (Paper) paperMod;
}
if (mail_queue.nonEmpty()) {
// There is a Paper in the Avatar's MAIL_SLOT, so pops the latest Mail
// record off the MailQueue and sets it on the Paper within the MAIL_SLOT
// so it may be read.
MailQueueRecord nextMail = mail_queue.popNextMail();
paperInMailSlot.gr_state = Paper.PAPER_LETTER_STATE;
paperInMailSlot.text_path = nextMail.paper_ref;
paperInMailSlot.sent_timestamp = nextMail.timestamp;
paperInMailSlot.gen_flags[MODIFIED] = true;
paperInMailSlot.checkpoint_object(paperInMailSlot);
paperInMailSlot.retrievePaperContents();
paperInMailSlot.send_gr_state_fiddle(Paper.PAPER_LETTER_STATE);
context().contextor().odb().putObject(
mailQueueRef(), mail_queue, null, false, finishMailQueueWrite);
inc_record(Constants.HS$mail_recv_count);
advanced = true;
trace_msg("Advanced Mail slot for User %s to %s",
object().ref(), paperInMailSlot.text_path);
} else if (paperInMailSlot.gr_state == Paper.PAPER_LETTER_STATE) {
// Otherwise, there is no more mail, so if the Paper is in a LETTER state,
// renders it as a BLANK state.
paperInMailSlot.ascii = Paper.EMPTY_PAPER;
paperInMailSlot.gr_state = Paper.PAPER_BLANK_STATE;
paperInMailSlot.text_path = Paper.EMPTY_PAPER_REF;
paperInMailSlot.sent_timestamp = 0;
paperInMailSlot.gen_flags[MODIFIED] = true;
paperInMailSlot.checkpoint_object(paperInMailSlot);
paperInMailSlot.send_gr_state_fiddle(Paper.PAPER_BLANK_STATE);
context().contextor().odb().putObject(
mailQueueRef(), mail_queue, null, false, finishMailQueueWrite);
trace_msg("Blanked Mail slot for User %s", object().ref());
}
if (advanced && shouldAnnounce) {
send_mail_arrived();
}
}
/**
* Reads the latest MailQueue from Mongo then updates the Paper in an Avatar's MailSlot with
* the next Mail message on the MailQueue. If no further mail, blanks the Paper instead.
*
* @param shouldAnnounce whether the Avatar should receive a ' * You have MAIL...' notification
*/
public void update_mail_slot(boolean shouldAnnounce) {
JSONObject findPattern = new JSONObject();
findPattern.addProperty("ref", mailQueueRef());
context().contextor().queryObjects(
findPattern, null, 1, new MailQueueReader(shouldAnnounce));
}
private class MailQueueReader implements ArgRunnable {
private boolean shouldAnnounce;
public MailQueueReader(boolean shouldAnnounce) {
this.shouldAnnounce = shouldAnnounce;
}
@Override
public void run(Object obj) {
try {
// Deserializes the MailQueue if it was found in Mongo.
MailQueue newQueue = new MailQueue();
if (obj != null) {
Object[] args = (Object[]) obj;
try {
JSONObject jsonObj = ((JSONObject) args[0]);
newQueue = new MailQueue(jsonObj);
} catch (JSONDecodingException e) {
mail_queue = newQueue;
return;
}
}
// After reading the MailQueue, assigns it as an Avatar instance variable.
mail_queue = newQueue;
trace_msg("Finished reading MailQueue %s for User %s",
mailQueueRef(), object().ref());
// If any Mail exists in the MailQueue, adds it to this Avatar's MailSlot,
// optionally sending a presence notification.
advance_mail_slot(shouldAnnounce);
} catch (Exception e) {
trace_exception(e);
}
}
}
private final ArgRunnable finishMailQueueWrite = new ArgRunnable() {
@Override
public void run(Object obj) {
try {
if (obj != null) {
trace_msg("Failed to write mail queue for User %s: %s",
object().ref(), obj);
}
} catch (Exception e) {
trace_exception(e);
}
}
};
protected Runnable sendMailArrived = new Runnable() {
@Override
public void run() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException neverHappens) {
Thread.currentThread().interrupt();
}
object_say(elko_user(), noid, MAIL_ARRIVED_MSG);
} catch (Exception e) {
trace_exception(e);
}
}
};
} |
// B e a m L i n k e r //
// <editor-fold defaultstate="collapsed" desc="hdr">
// This program is free software: you can redistribute it and/or modify it under the terms of the
// </editor-fold>
package org.audiveris.omr.sheet.stem;
import java.awt.Point;
import org.audiveris.omr.glyph.Glyph;
import org.audiveris.omr.glyph.GlyphFactory;
import org.audiveris.omr.glyph.GlyphGroup;
import org.audiveris.omr.glyph.Glyphs;
import org.audiveris.omr.glyph.Shape;
import org.audiveris.omr.glyph.dynamic.SectionCompound;
import org.audiveris.omr.lag.Section;
import org.audiveris.omr.lag.Sections;
import org.audiveris.omr.math.AreaUtil;
import org.audiveris.omr.math.GeoOrder;
import org.audiveris.omr.math.GeoUtil;
import org.audiveris.omr.math.LineUtil;
import org.audiveris.omr.math.PointUtil;
import org.audiveris.omr.sheet.Profiles;
import org.audiveris.omr.sheet.Scale;
import org.audiveris.omr.sheet.Staff;
import org.audiveris.omr.sheet.SystemInfo;
import org.audiveris.omr.sheet.stem.BeamLinker.BLinker;
import org.audiveris.omr.sheet.stem.BeamLinker.BLinker.VLinker;
import org.audiveris.omr.sheet.stem.HeadLinker.SLinker;
import org.audiveris.omr.sheet.stem.HeadLinker.SLinker.CLinker;
import static org.audiveris.omr.sheet.stem.StemHalfLinker.updateStemLine;
import org.audiveris.omr.sheet.stem.StemItem.GapItem;
import org.audiveris.omr.sheet.stem.StemItem.LinkerItem;
import org.audiveris.omr.sig.SIGraph;
import org.audiveris.omr.sig.inter.AbstractBeamInter;
import org.audiveris.omr.sig.inter.BeamGroupInter;
import org.audiveris.omr.sig.inter.BeamHookInter;
import org.audiveris.omr.sig.inter.HeadInter;
import org.audiveris.omr.sig.inter.Inter;
import org.audiveris.omr.sig.inter.Inters;
import org.audiveris.omr.sig.inter.StemInter;
import org.audiveris.omr.sig.relation.BeamPortion;
import org.audiveris.omr.sig.relation.BeamStemRelation;
import org.audiveris.omr.sig.relation.HeadStemRelation;
import org.audiveris.omr.sig.relation.Link;
import org.audiveris.omr.sig.relation.StemPortion;
import org.audiveris.omr.sig.relation.Relation;
import static org.audiveris.omr.sig.relation.StemPortion.*;
import org.audiveris.omr.sig.relation.Support;
import org.audiveris.omr.util.Navigable;
import org.audiveris.omr.util.HorizontalSide;
import static org.audiveris.omr.util.HorizontalSide.*;
import org.audiveris.omr.util.VerticalSide;
import static org.audiveris.omr.util.VerticalSide.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class BeamLinker
{
private static final Logger logger = LoggerFactory.getLogger(BeamLinker.class);
/** The beam being processed. */
@Navigable(false)
private final AbstractBeamInter beam;
/** The containing beam group. */
private final BeamGroupInter beamGroup;
/** Beam median line. */
private final Line2D median;
/** Beam bounding box. */
private final Rectangle beamBox;
/** All stems seeds in beam vicinity. */
private final Set<Glyph> neighborSeeds;
/** All detected stumps on beam, including side stumps if any. */
private final List<Glyph> stumps = new ArrayList<>();
/** Map of side stumps. */
private final Map<HorizontalSide, Glyph> sideStumps = new EnumMap<>(HorizontalSide.class);
/** List of all BLinker instances. */
private final List<BLinker> allBLinkers = new ArrayList<>();
/** Map of side-based BLinkers. */
private final Map<HorizontalSide, BLinker> sideBLinkers
= new EnumMap<>(HorizontalSide.class);
/** List of stump-based linkers. */
private final List<VLinker> stumpLinkers = new ArrayList<>();
// System-level information
@Navigable(false)
private final StemsRetriever retriever;
@Navigable(false)
private final SystemInfo system;
@Navigable(false)
private final Scale scale;
private final StemsRetriever.Parameters params;
/**
* Creates a new {@code BeamLinker} object and populates beam stumps.
*
* @param beam the beam inter to link
* @param retriever the driving system-level StemsRetriever instance
*/
public BeamLinker (AbstractBeamInter beam,
StemsRetriever retriever)
{
this.beam = beam;
this.median = beam.getMedian();
this.retriever = retriever;
beamGroup = beam.getGroup();
beamBox = beam.getBounds();
system = beam.getSig().getSystem();
scale = system.getSheet().getScale();
params = retriever.getParams();
// Pre-populate seeds and stumps
neighborSeeds = retriever.getNeighboringSeeds(beamBox);
stumps.addAll(retrieveStumps());
// Allocate needed BLinkers and VLinkers
equipStumps();
equipOrphanSides();
}
// equipOrphanSides //
/**
* For each beam horizontal side without usable stump, equip beam with
* one VLinker above and one VLinker below.
*/
private void equipOrphanSides ()
{
if (beam.isVip()) {
logger.info("VIP {} equipOrphanSides", this);
}
for (HorizontalSide hSide : HorizontalSide.values()) {
if (sideBLinkers.get(hSide) == null) {
final Point2D endPt = (hSide == LEFT) ? median.getP1() : median.getP2();
final List<AbstractBeamInter> siblings = getSiblingBeamsAt(endPt);
final AbstractBeamInter b1 = siblings.get(0);
final AbstractBeamInter b2 = siblings.get(siblings.size() - 1);
// NOTA: we test beam glyph to cope with beam & hook on same glyph
if ((beam.getGlyph() != b1.getGlyph()) && (beam.getGlyph() != b2.getGlyph())) {
continue; // Beam inside beam group
}
final BLinker bLinker = new BLinker(null, hSide, null, false);
sideBLinkers.put(hSide, bLinker);
for (VerticalSide vSide : VerticalSide.values()) {
bLinker.vLinkers.put(vSide, bLinker.new VLinker(vSide.direction()));
}
}
}
}
// equipStumps //
/**
* Equip each beam-attached stump with a dedicated VLinker.
* <p>
* Check beam stumps, they give direction to staff which is useful when beam can be processed by
* two systems.
*/
private void equipStumps ()
{
for (Glyph stump : stumps) {
if (stump.isVip()) {
logger.info("VIP {} equipStump at {}", this, stump);
}
// Is this stump located on beam side?
HorizontalSide hSide = null;
for (Entry<HorizontalSide, Glyph> entry : sideStumps.entrySet()) {
if (entry.getValue() == stump) {
hSide = entry.getKey();
}
}
final BLinker bLinker = new BLinker(stump, hSide, null, false);
// Retrieve vertical directions when going away from beam
final Set<VerticalSide> directions = getStumpDirections(stump);
if (directions != null) {
for (VerticalSide vSide : directions) {
final VLinker vLinker = bLinker.new VLinker(vSide.direction());
bLinker.vLinkers.put(vSide, vLinker);
stumpLinkers.add(vLinker);
}
}
}
}
// findLinker //
/**
* Find out or build a beam linker where the provided stem line hits the beam.
*
*
* @param sLine stem (theoretical?) line
* @return the related VLinker instance
*/
public BLinker findLinker (Line2D sLine)
{
// Cross point
final Point2D refPt = LineUtil.intersection(sLine, median);
final double x0 = refPt.getX();
// Check with existing linkers
BLinker bestLinker = null;
double bestDx = Double.MAX_VALUE;
for (BLinker linker : allBLinkers) {
final double dx = Math.abs(linker.refPt.getX() - x0);
if (bestDx > dx) {
bestDx = dx;
bestLinker = linker;
}
}
if (bestDx <= params.maxBeamLinkerDx) {
return bestLinker;
}
// We have to build a brand new (anchord) linker at xp
return new BLinker(null, /* hSide? */ null, refPt, true);
}
// getSiblingBeamsAt //
/**
* Report the top down sequence of beams in current beam group that intersect the
* vertical at provided point.
*
* @param pt provided point
* @return the sequence of relevant beam group members
*/
public List<AbstractBeamInter> getSiblingBeamsAt (Point2D pt)
{
final List<Inter> members = beamGroup.getMembers();
final double slope = system.getSheet().getSkew().getSlope();
final int DY = 1000; // Not significant
final Line2D vertical = new Line2D.Double(
new Point2D.Double(pt.getX() + DY * slope, pt.getY() - DY),
new Point2D.Double(pt.getX() - DY * slope, pt.getY() + DY));
final List<AbstractBeamInter> beams = new ArrayList<>();
final int margin = params.maxBeamSideDx;
for (Inter inter : members) {
final AbstractBeamInter b = (AbstractBeamInter) inter;
final Line2D m = b.getMedian();
final Point2D xp = LineUtil.intersection(vertical, m);
if ((m.getX1() - margin <= xp.getX()) && (xp.getX() <= m.getX2() + margin)) {
beams.add(b);
}
}
// Sort beams top down along the vertical line
Collections.sort(beams, (b1, b2)
-> Double.compare(LineUtil.intersection(vertical, b1.getMedian()).getY(),
LineUtil.intersection(vertical, b2.getMedian()).getY()));
return beams;
}
// inspectVLinkers //
public void inspectVLinkers ()
{
for (BLinker bLinker : allBLinkers) {
if (!bLinker.isAnchor) {
// Maximum possible stemProfile
final int stemProfile = (bLinker.hSide != null)
? Profiles.BEAM_SIDE
: Profiles.BEAM_SEED;
for (VLinker vLinker : bLinker.vLinkers.values()) {
vLinker.inspect(stemProfile);
}
}
}
}
// linkSides //
/**
* Link beam on each horizontal side.
*
* @param linkProfile desired profile level for links
* @return false to delete beam
*/
public boolean linkSides (int linkProfile)
{
if (beam.isVip()) {
logger.info("VIP {} linkSides", this);
}
final BeamHookInter oppoHook = beam.getCompetingHook();
final EnumSet<HorizontalSide> linkedSides = EnumSet.noneOf(HorizontalSide.class);
for (HorizontalSide hSide : HorizontalSide.values()) {
final BLinker bLinker = sideBLinkers.get(hSide);
if (bLinker == null) {
logger.info("No BLinker on {} of {}", hSide, this);
continue;
}
if (bLinker.isLinked()) {
linkedSides.add(hSide);
} else {
final int stemProfile = (beam.isHook() || (oppoHook != null))
? linkProfile
: Profiles.BEAM_SIDE;
final boolean ok = bLinker.link(stemProfile, linkProfile);
if (ok) {
linkedSides.add(hSide);
} else if (!beam.isHook()) {
return false;
}
}
}
if (beam.isHook() && linkedSides.isEmpty()) {
return false;
}
if (!beam.isHook() && (linkedSides.size() == 2)) {
// Discard the competing hook if any
if (oppoHook != null) {
if (oppoHook.isVip()) {
logger.info("VIP {} remove competing {}", this, oppoHook);
}
oppoHook.remove();
}
}
return true;
}
// linkStumps //
public void linkStumps (int profile)
{
if (beam.isVip()) {
logger.info("VIP {} linkStumps", this);
}
for (VLinker vLinker : stumpLinkers) {
final Glyph stump = vLinker.getStump();
if (stump.isVip()) {
logger.info("VIP {} linkStumps at {}", this, stump);
}
// Side stumps have already been processed
if (sideStumps.values().contains(stump)) {
continue;
}
if (!vLinker.isLinked()) {
// Link from a connected beam seed should find a suitable head
vLinker.link(Profiles.BEAM_SEED, profile);
}
}
}
// toString //
@Override
public String toString ()
{
return new StringBuilder(getClass().getSimpleName())
.append("{beam#").append(beam.getId()).append('}').toString();
}
// buildSideStump //
/**
* Try to build a stump on the specified side of the beam.
*
* @param hSide specified beam side
* @return the created stump or null if failed
*/
private Glyph buildSideStump (HorizontalSide hSide)
{
if (beam.isVip()) {
logger.info("VIP {} buildSideStump {}", this, hSide);
}
final Area area = getStumpArea(hSide);
final List<Section> sections = new ArrayList<>(
Sections.intersectedSections(area, system.getVerticalSections()));
// Sort by distance of centroid abscissa WRT refPt
final int xDir = hSide.direction();
final double sideX = (xDir < 0) ? median.getX1() : median.getX2();
final double refX = sideX - xDir * params.maxStemThickness / 2.0;
Collections.sort(sections, (s1, s2)
-> Double.compare(Math.abs(s1.getAreaCenter().getX() - refX),
Math.abs(s2.getAreaCenter().getX() - refX)));
if (sections.isEmpty()) {
return null;
}
final SectionCompound compound = new SectionCompound();
for (Section s : sections) {
compound.addSection(s);
if (compound.getWidth() > params.maxStemThickness) {
compound.removeSection(s);
break;
}
}
if (compound.getWeight() == 0) {
return null; // This can occur when we have a single section, but too wide
}
// Check the stump clearly points out on one vertical side of beam
Glyph stumpGlyph = compound.toGlyph(GlyphGroup.STUMP);
final Set<VerticalSide> directions = getStumpDirections(stumpGlyph);
if (directions == null || directions.isEmpty()) {
return null;
}
stumpGlyph = system.getSheet().getGlyphIndex().registerOriginal(stumpGlyph);
logger.debug("{} {}", this, stumpGlyph);
return stumpGlyph;
}
// getSeedArea //
/**
* Define the lookup area for suitable stem seeds.
*
* @return the seed lookup area
*/
private Area getSeedArea ()
{
// Use beam area, slightly expanded in x and y
final double slope = (median.getY2() - median.getY1()) / (median.getX2() - median.getX1());
final double dx = params.maxBeamSeedDx;
final int profile = Math.max(beam.getProfile(), system.getProfile());
final double dy = params.maxBeamSeedDyRatio
* scale.toPixels(BeamStemRelation.getYGapMaximum(profile));
final Path2D path = AreaUtil.horizontalParallelogramPath(
new Point2D.Double(median.getX1() - dx, median.getY1() - slope * dx),
new Point2D.Double(median.getX2() + dx, median.getY2() + slope * dx),
beam.getHeight() + 2 * dy);
beam.addAttachment("seed", path);
return new Area(path);
}
// getStumpArea //
/**
* Define the lookup area on beam side for suitable stump building.
*
* @return the stump lookup area
*/
private Area getStumpArea (HorizontalSide hSide)
{
final int xDir = hSide.direction();
final double xSide = (xDir < 0) ? median.getX1() : median.getX2();
final double width = params.maxStemThickness;
final Point2D innerPt = LineUtil.intersectionAtX(median, xSide - xDir * width);
final Path2D path = (xDir < 0)
? AreaUtil.horizontalParallelogramPath(median.getP1(), innerPt, beam.getHeight())
: AreaUtil.horizontalParallelogramPath(innerPt, median.getP2(), beam.getHeight());
final String tag = "s" + ((xDir > 0) ? "R" : "L");
beam.addAttachment(tag, path);
return new Area(path);
}
// getStumpDirections //
/**
* Determine stump directions (when going away from beam to head).
*
* @param stump the candidate stump to check
* @return null for beam inside group, top, bottom, both or none
*/
private Set<VerticalSide> getStumpDirections (Glyph stump)
{
if (stump.isVip()) {
logger.info("VIP {} getStumpDirections {}", this, stump);
}
final Point2D stumpCenter = stump.getCenter2D();
final List<AbstractBeamInter> siblings = getSiblingBeamsAt(stumpCenter);
final AbstractBeamInter b1 = siblings.get(0);
final AbstractBeamInter b2 = siblings.get(siblings.size() - 1);
if ((beam != b1) && (beam != b2)) {
return null; // beam is located inside beam group
}
// Look at vertical offsets off of beams
final Set<VerticalSide> set = EnumSet.noneOf(VerticalSide.class);
final double x = stumpCenter.getX();
final Line2D stumpLine = stump.getCenterLine();
final double dy1 = Math.max(0, LineUtil.yAtX(b1.getBorder(TOP), x) - stumpLine.getY1());
if (dy1 >= params.minBeamStumpDy) {
set.add(TOP);
}
final double dy2 = Math.max(0, stumpLine.getY2() - LineUtil.yAtX(b2.getBorder(BOTTOM), x));
if (dy2 >= params.minBeamStumpDy) {
set.add(BOTTOM);
}
return set;
}
// purgeSeeds //
/**
* Purge the collection of seeds, by filtering out those leading to duplicates.
*
* @param seeds the collection to purge (already sorted in abscissa)
*/
private void purgeSeeds (List<Glyph> seeds)
{
NextSeed:
for (int i = 0; i < seeds.size(); i++) {
final Glyph s1 = seeds.get(i);
final Line2D l1 = s1.getCenterLine();
final Point2D p1 = LineUtil.intersection(l1, median);
final double x1 = p1.getX();
for (int j = i + 1; j < seeds.size(); j++) {
final Glyph s2 = seeds.get(j);
final Line2D l2 = s2.getCenterLine();
final Point2D p2 = LineUtil.intersection(l2, median);
final double x2 = p2.getX();
if ((x2 - x1) >= params.minBeamStemsDx) {
break;
}
if (GeoUtil.yOverlap(s1.getBounds(), s2.getBounds()) > 0) {
// Vertical overlap, keep the longer
if (s1.getHeight() >= s2.getHeight()) {
seeds.remove(j);
} else {
seeds.remove(i--);
continue NextSeed;
}
} else {
// No overlap, keep the closer to beam
if (l1.ptSegDistSq(p1) <= l2.ptSegDistSq(p2)) {
seeds.remove(j);
} else {
seeds.remove(i--);
continue NextSeed;
}
}
}
}
}
// retrieveStumps //
/**
* Retrieve stumps for the beam.
* <p>
* We use stem seeds near the beam and complement with one stump on each side of the beam if
* so needed.
*
* @return the beam connectable seeds
*/
private List<Glyph> retrieveStumps ()
{
if (beam.isVip()) {
logger.info("VIP {} retrieveStumps", this);
}
final List<Glyph> list = new ArrayList<>(Glyphs.intersectedGlyphs(neighborSeeds,
getSeedArea()));
Collections.sort(list, (g1, g2) -> Double.compare(
LineUtil.intersection(g1.getCenterLine(), median).getX(),
LineUtil.intersection(g2.getCenterLine(), median).getX()));
// Perhaps some seeds need to be merged or purged
purgeSeeds(list);
// Try to have a stump on both beam sides
if (!list.isEmpty()) {
// Check for presence of seed on beam sides
for (HorizontalSide hSide : HorizontalSide.values()) {
Glyph seed = list.get(hSide == LEFT ? 0 : list.size() - 1);
final double x = LineUtil.intersection(seed.getCenterLine(), median).getX();
BeamPortion portion = BeamStemRelation.computeBeamPortion(beam, x, scale);
if ((portion != null) && (portion.side() == hSide)) {
sideStumps.put(hSide, seed);
}
}
}
for (HorizontalSide hSide : HorizontalSide.values()) {
Glyph stump = sideStumps.get(hSide);
if (stump == null) {
// Try to build a stump on this side of the beam
stump = buildSideStump(hSide);
if (stump != null) {
sideStumps.put(hSide, stump);
if (hSide == LEFT) {
list.add(0, stump);
} else {
list.add(stump);
}
}
}
}
return list;
}
// BLinker //
public class BLinker
extends StemLinker
{
/** To ease debugging. */
private final int id;
/** Horizontal side of beam, if any. Null for a link in beam center portion. */
private final HorizontalSide hSide;
/** Beam reference point on median line. */
private Point2D refPt;
/** Starting beam stump, if any. */
private final Glyph stump;
/** Just an anchor, not meant to explore stem items from this point. */
private boolean isAnchor;
/** Top and bottom linkers. */
private final Map<VerticalSide, VLinker> vLinkers = new EnumMap<>(
VerticalSide.class);
/** Has been successfully linked. */
private boolean linked;
/** Has been closed (no more link attempt). */
private boolean closed;
public BLinker (Glyph stump,
HorizontalSide hSide,
Point2D refPt,
boolean isAnchor)
{
this.stump = stump;
this.hSide = hSide;
this.isAnchor = isAnchor;
id = register();
if (refPt == null) {
if (stump != null) {
this.refPt = LineUtil.intersection(stump.getCenterLine(), median);
} else if (hSide != null) {
final int xDir = hSide.direction();
final double sideX = (xDir < 0) ? median.getX1() : median.getX2();
final double refX = sideX - xDir * params.mainStemThickness / 2.0;
this.refPt = LineUtil.intersectionAtX(median, refX);
}
} else {
this.refPt = new Point2D.Double(refPt.getX(), refPt.getY());
}
if (hSide != null) {
sideBLinkers.put(hSide, this);
}
if (beam.isVip()) {
logger.info("VIP new {}", this);
}
if (isAnchor) {
buildAnchor();
}
}
// getHalfLinkers //
@Override
public Collection<? extends StemHalfLinker> getHalfLinkers ()
{
return vLinkers.values();
}
// isClosed //
@Override
public boolean isClosed ()
{
return closed;
}
// setClosed //
@Override
public void setClosed (boolean closed)
{
this.closed = closed;
}
// isLinked //
@Override
public boolean isLinked ()
{
return linked;
}
// setLinked //
@Override
public void setLinked (boolean linked)
{
this.linked = linked;
}
// getReferencePoint //
@Override
public Point2D getReferencePoint ()
{
return refPt;
}
// getSource //
@Override
public AbstractBeamInter getSource ()
{
return beam;
}
// buildAnchor //
private void buildAnchor ()
{
// Draw a small circle around refPt
final double r = scale.getInterline() / 10.0;
beam.addAttachment(
"" + id,
new Ellipse2D.Double(refPt.getX() - r, refPt.getY() - r, 2 * r, 2 * r));
}
// getStump //
@Override
public Glyph getStump ()
{
return stump;
}
// toString //
@Override
public String toString ()
{
final StringBuilder asb = new StringBuilder(getClass().getSimpleName())
.append("{beam#").append(beam.getId())
.append(' ').append(hSide != null ? hSide.name().charAt(0) : 'C')
.append('-').append(id);
if (isAnchor) {
asb.append(" ANCHOR");
}
if (stump != null) {
asb.append(' ').append(stump);
} else if (refPt != null) {
asb.append(" refPt:").append(PointUtil.toString(refPt));
}
return asb.append('}').toString();
}
// link //
/**
* Try to link beam at this BLinker, based on its StemDraft.
*
* @param stemProfile desired profile level for stem building
* @param linkProfile global desired profile level
*/
private boolean link (int stemProfile,
int linkProfile)
{
// BLinker inside beam group or already linked?
if (vLinkers.isEmpty() || isLinked()) {
return true;
}
for (VLinker vLinker : vLinkers.values()) {
if (!vLinker.sb.getTargetLinkers().isEmpty()) {
if (vLinker.link(stemProfile, linkProfile)) {
setLinked(true);
}
}
}
return isLinked();
}
// register //
private int register ()
{
allBLinkers.add(this);
return allBLinkers.size();
}
// VLinker //
/**
* Beam vertical linker.
* <p>
* It handles connection from beam at a given point (connected seed or beam side) to
* relevant heads in the selected vertical direction.
*/
class VLinker
extends StemHalfLinker
{
/** Vertical side from beam to stems/heads. */
@Navigable(false)
private final VerticalSide vSide;
/** Direction of ordinate values when going away from beam. */
private final int yDir;
/** Lookup area for heads and stem items. */
private Area luArea;
/** The theoretical line from beam. */
private Line2D theoLine;
/** Stem seeds in lookup area. */
private Set<Glyph> seeds;
/** Head side for stopping stem expansion. */
private final HorizontalSide stoppingHeadSide;
/** Items sequence. */
private StemBuilder sb;
/**
* Create a linker in the provided vertical direction if so desired,
* with a starting stump or a beam horizontal side or just a refPt (an anchor).
*
* @param yDir vertical direction, if any, when going away from beam
* @param stump starting glyph, if any
* @param rePt reference point, if any
*/
public VLinker (int yDir)
{
this.yDir = yDir;
vSide = VerticalSide.of(yDir);
stoppingHeadSide = (yDir < 0) ? LEFT : RIGHT;
if (isAnchor) {
///buildAnchor();
} else {
buildGeometry();
}
}
// getReferencePoint //
@Override
public Point2D getReferencePoint ()
{
return refPt;
}
// getSource //
@Override
public AbstractBeamInter getSource ()
{
return beam;
}
// getHalfLinkers //
@Override
public Collection<? extends StemHalfLinker> getHalfLinkers ()
{
return Collections.singleton(this);
}
// toString //
@Override
public String toString ()
{
final StringBuilder asb = new StringBuilder(getClass().getSimpleName())
.append("{beam#").append(beam.getId())
.append(' ')
.append((vSide != null) ? vSide.name().charAt(0) : "")
.append((hSide != null) ? hSide.name().charAt(0) : 'C')
.append('-').append(id);
if (isAnchor) {
asb.append(" ANCHOR");
}
return asb.append('}').toString();
}
// isClosed //
@Override
public boolean isClosed ()
{
return closed;
}
// setClosed //
@Override
public void setClosed (boolean closed)
{
BLinker.this.setClosed(closed);
}
// isLinked //
@Override
public boolean isLinked ()
{
return linked;
}
// setLinked //
public void setLinked (boolean linked)
{
BLinker.this.setLinked(linked);
}
@Override
public Glyph getStump ()
{
return stump;
}
@Override
public Line2D getTheoreticalLine ()
{
return theoLine;
}
@Override
public Area getLookupArea ()
{
return luArea;
}
// buildGeometry //
private void buildGeometry ()
{
luArea = buildLuArea(null); // This gives a first value for theoLine
// theoLine = retriever.getTheoreticalLine(refPt, yDir);
// Check for closer limit (due to some alien beam, for example)
final Line2D closer = getCloserLimit();
if (closer != null) {
luArea = buildLuArea(closer); // This shrinks theoline accordingly
}
beam.addAttachment("t" + id, theoLine);
seeds = Glyphs.intersectedGlyphs(neighborSeeds, luArea);
}
// buildLuArea //
/**
* Define the lookup area, knowing the reference point of the beam.
* <p>
* The LuArea is relevant only for a VLinker going out on beam group border, not for any
* intermediate (anchor) linker inside the group.
* <p>
* Global slope is used (plus and minus slopeMargin).
*
* @param the rather horizontal limit for the area, or null to use system limit
* @return the lookup area
*/
private Area buildLuArea (Line2D limit)
{
final double slope = -system.getSheet().getSkew().getSlope();
final double dSlope = yDir * params.slopeMargin;
final double xRef = refPt.getX();
final Line2D border = beam.getBorder(vSide);
final Point2D pl = LineUtil.intersectionAtX(border, xRef - params.halfBeamLuDx);
final Point2D pr = LineUtil.intersectionAtX(border, xRef + params.halfBeamLuDx);
// Look-up path, start by beam horizontal segment
final Path2D lu = new Path2D.Double();
final int profile = Math.max(beam.getProfile(), system.getProfile());
final double yOffset = yDir * params.maxBeamSeedDyRatio * scale.toPixels(
BeamStemRelation.getYGapMaximum(profile));
lu.moveTo(pl.getX(), pl.getY() + yOffset);
lu.lineTo(pr.getX(), pr.getY() + yOffset);
// Then segment away from beam
double yLimit;
if (limit == null) {
// System limit as starting value
final Rectangle systemBox = system.getBounds();
yLimit = (yDir < 0) ? systemBox.getMaxY() : systemBox.getMinY();
// Use part(s) limit
final Point center = beam.getCenter();
final List<Staff> staves = system.getStavesAround(center);
for (Staff staff : staves) {
final Rectangle partBox = staff.getPart().getAreaBounds();
yLimit = (yDir > 0)
? Math.max(yLimit, partBox.y + partBox.height - 1)
: Math.min(yLimit, partBox.y);
}
} else {
// Use provided limit
yLimit = LineUtil.yAtX(limit, refPt.getX());
}
final double dy = yLimit - refPt.getY();
lu.lineTo(pr.getX() + ((slope + dSlope) * dy), yLimit);
lu.lineTo(pl.getX() + ((slope - dSlope) * dy), yLimit);
lu.closePath();
// Attachment
beam.addAttachment("" + id, lu);
// Compute theoLine
theoLine = retriever.getTheoreticalLine(refPt, yLimit);
beam.addAttachment("t" + id, theoLine);
return new Area(lu);
}
// expand //
/**
* Expand current stem from beam as much as possible.
* <p>
* If {@code stemProfile} == Profiles.BEAM_SIDE then we are linking a beam side, so:
* <ol>
* <li>At least one head must be reached from the beam,
* <li>The stem must end with a head on correct side.
* </ol>
*
* @param stemProfile desired profile for inclusion of additional items
* @param linkProfile desired profile for head-stem link
* @param relations (output) to be populated by head-stem relations
* @param glyphs (output) to be populated that glyphs that do compose the stem
* @return index of last item to pick, or -1 if failed
*/
private int expand (int stemProfile,
int linkProfile,
Map<StemLinker, Relation> relations,
Set<Glyph> glyphs)
{
if (beam.isVip()) {
logger.info("VIP {} expand {}", this, sb);
}
final Scale scale = system.getSheet().getScale();
final int maxIndex = sb.maxIndex();
int maxYGap = retriever.getGapMap().get(stemProfile);
// Expand until a stop condition is met
CLinker stoppingHeadLinker = null;
final Line2D stemLine = (yDir > 0) ? theoLine
: new Line2D.Double(theoLine.getP2(), theoLine.getP1());
for (int i = 0; i <= maxIndex; i++) {
final StemItem ev = sb.get(i);
// Show-stopping gap?
if ((ev instanceof GapItem) && (ev.contrib > maxYGap)) {
return (stoppingHeadLinker != null) ? i - 1 : -1;
} else if (ev instanceof LinkerItem
&& ((LinkerItem) ev).linker instanceof CLinker) {
// Head encountered
final CLinker cl = (CLinker) ((LinkerItem) ev).linker;
final HeadInter clHead = cl.getHead();
// Can we stop before this head?
if (stoppingHeadLinker != null) {
// Gap close before head?
final GapItem gap = sb.getLastGapBefore(i);
if (gap != null) {
final double y = cl.getReferencePoint().getY();
final double dy = (yDir > 0)
? y - gap.line.getY2()
: gap.line.getY1() - y;
if (dy < params.minLinkerLength) {
// We include this coming head only if not tied on other vSide
final CLinker clOpp = clHead.getLinker().getCornerLinker(
cl.getSLinker().getHorizontalSide().opposite(), vSide);
if (clOpp.hasConcreteStart(linkProfile)) {
logger.debug("{} separated from head
this, clHead.getId());
return sb.indexOf(gap) - 1;
}
}
}
}
final HeadStemRelation hsRel = cl.checkStemRelation(stemLine, linkProfile);
if (hsRel == null) {
logger.debug("No relation for {} from {}", cl, this);
continue;
}
relations.put(cl, hsRel);
updateStemLine(ev.glyph, glyphs, stemLine);
// Could this head be a stopping head?
if ((hsRel.getHeadSide() == stoppingHeadSide) && !glyphs.isEmpty()) {
final Glyph stemGlyph = (glyphs.size() > 1)
? GlyphFactory.buildGlyph(glyphs) : glyphs.iterator().next();
final Line2D line = stemGlyph.getCenterLine();
final StemPortion sp = hsRel.getStemPortion(clHead, line, scale);
final boolean isEnd = (sp == ((yDir > 0) ? STEM_BOTTOM : STEM_TOP));
stoppingHeadLinker = isEnd ? cl : null;
// Once a first stopping head has been reached, let's use normal maxYGap
maxYGap = retriever.getGapMap().get(isEnd ? linkProfile : stemProfile);
}
} else if (ev instanceof LinkerItem
&& ((LinkerItem) ev).linker instanceof BLinker) {
// Beam encountered
final BLinker bl = (BLinker) ((LinkerItem) ev).linker;
final AbstractBeamInter beam = bl.getSource();
updateStemLine(ev.glyph, glyphs, stemLine);
// final BeamStemRelation bsRel = BeamStemRelation.checkRelation(
// beam, stemLine, vSide, scale, stemProfile);
// relations.put(bl, bsRel);
} else if (ev instanceof LinkerItem
&& ((LinkerItem) ev).linker instanceof VLinker) {
// (Starting) Beam encountered
final VLinker vl = (VLinker) ((LinkerItem) ev).linker;
final AbstractBeamInter beam = vl.getSource();
updateStemLine(ev.glyph, glyphs, stemLine);
// final BeamStemRelation bsRel = BeamStemRelation.checkRelation(
// beam, stemLine, vSide, scale, stemProfile);
// relations.put(bl, bsRel);
} else if (ev instanceof StemItem.GlyphItem) {
// Plain glyph encountered
updateStemLine(ev.glyph, glyphs, stemLine);
}
}
return maxIndex;
}
// filterBeams //
/**
* Collect BLinkers to address relevant beams in beam group.
* <p>
* All siblings are mutually connected via BLinker instances.
*
* @param siblings relevant beams in beam group
* @return collection of BLinker instances, one per relevant beam
*/
private List<BLinker> filterBeams (List<AbstractBeamInter> siblings)
{
if (beam.isVip()) {
logger.info("VIP {} filterBeams", this);
}
final List<BLinker> bLinkers = new ArrayList<>();
for (Inter bInter : siblings) {
AbstractBeamInter b = (AbstractBeamInter) bInter;
if (b != beam) {
if ((b.getGlyph() != null) && (b.getGlyph() != beam.getGlyph())) {
bLinkers.add(b.getLinker().findLinker(theoLine));
}
}
}
return bLinkers;
}
// filterHeads //
private List<CLinker> filterHeads (List<AbstractBeamInter> siblings)
{
// Last beam border before heads
final Line2D lastBorder = (yDir > 0)
? siblings.get(siblings.size() - 1).getBorder(BOTTOM)
: siblings.get(0).getBorder(TOP);
final double yLastBorder = LineUtil.yAtX(lastBorder, refPt.getX());
final List<Inter> headCandidates = Inters.intersectedInters(
retriever.getSystemHeads(), GeoOrder.BY_ABSCISSA, luArea);
final List<CLinker> cLinkers = new ArrayList<>();
// For void heads
final HorizontalSide imposedVoidHeadSide = (yDir < 0) ? LEFT : RIGHT;
for (Inter hInter : headCandidates) {
final HeadInter head = (HeadInter) hInter;
// Today, standard beams can't link small heads
if (head.getShape().isSmall()) {
continue;
}
// Check head is far enough from beam group end
final double dy = yDir * (head.getCenter().y - yLastBorder);
if (dy < params.minBeamHeadDy) {
continue;
}
for (SLinker sLinker : head.getLinker().getSLinkers().values()) {
if (luArea.contains(sLinker.getReferencePoint())) {
// For void shape, check head hSide
if ((head.getShape() != Shape.NOTEHEAD_VOID)
|| (sLinker.getHorizontalSide() == imposedVoidHeadSide)) {
// TODO: Check possible relation between head and stem/theo line?
cLinkers.add(sLinker.getCornerLinker(vSide.opposite()));
}
}
}
}
return cLinkers;
}
// getBLinker //
private BLinker getBLinker ()
{
return BLinker.this;
}
// getCloserLimit //
/**
* Report the closer limit, if any, for search.
* <p>
* If theoretical line intersects an alien beam, stop there and shrink accordingly
* (excepted if the alien beam belongs to a sibling beam group).
*
* @return the closer limit if any
*/
private Line2D getCloserLimit ()
{
final List<Inter> aliens = retriever
.getNeighboringInters(retriever.getSystemBeams(), beamBox);
aliens.removeAll(beam.getGroup().getMembers());
// Check concrete beam (no hook) intersection with theoLine
// But don't count beams with side aligned with ours in vertical neighborhood
for (Iterator<Inter> it = aliens.iterator(); it.hasNext();) {
final AbstractBeamInter b = (AbstractBeamInter) it.next();
final Line2D m = b.getMedian();
if (b instanceof BeamHookInter) {
it.remove();
} else if (!m.intersectsLine(theoLine)) {
it.remove();
} else {
final Point2D cross = LineUtil.intersection(theoLine, m);
final double dy = Math.abs(cross.getY() - refPt.getY());
if (dy <= params.maxBeamGroupDy) {
final double xc = cross.getX();
final double dx = Math.abs(
xc - ((hSide == LEFT) ? m.getX1() : m.getX2()));
if (dx < params.maxBeamSideDx) {
it.remove();
}
}
}
}
if (aliens.isEmpty()) {
return null;
}
retriever.sortBeamsFromRef(refPt, yDir, aliens);
AbstractBeamInter firstAlien = (AbstractBeamInter) aliens.get(0);
return firstAlien.getBorder(vSide.opposite());
}
// inspect //
/**
* Look for reachable heads (and other beams in same beam group) in linker area,
* ordered by vertical distance.
*
* <p>
* A head is considered as reachable if it has a head stump and the center of this stump
* is located in lookup area.
* <p>
* If head has no stump (this can happen e.g. for lack of black pixels), then we
* consider head refPt instead of head stump center.
* <p>
* Since a void head can appear only at the very end of beam stem, it is constrained by
* its hSide vs beam yDir
*
* @param maxStemProfile maximum possible stem profile
*/
private void inspect (int maxStemProfile)
{
if (beam.isVip()) {
logger.info("VIP {} inspect maxStemProfile:{}", this, maxStemProfile);
}
// Sibling beams
final List<AbstractBeamInter> siblings = getSiblingBeamsAt(refPt);
// Relevants beams and heads
final List<StemLinker> linkers = new ArrayList<>();
linkers.addAll(filterBeams(siblings));
linkers.addAll(filterHeads(siblings));
sb = new StemBuilder(retriever, this, seeds, linkers, maxStemProfile);
}
// link //
/**
* Try to link beam, using items for reachable heads.
* <p>
* Processing is done from beam to heads.
* <p>
* We can stop only at a head for which stem is on correct horizontal head side,
* that is left of head for stem going up, right of head for stem going down.
*
* @param stemProfile profile level for stem building
* @param linkProfile profile level for stem linking (head and beam)
* @return true if OK
*/
private boolean link (int stemProfile,
int linkProfile)
{
if (beam.isVip()) {
logger.info("VIP {} link", this);
}
if (stump != null && stump.isVip()) {
logger.info("VIP {} link at {}", this, stump);
}
// Some head to reach from beam?
final List<CLinker> headLinkers = sb.getCLinkers(null);
if (headLinkers.isEmpty()) {
return false;
}
// Retrieve all relevant items
final Map<StemLinker, Relation> relations = new LinkedHashMap<>();
final Set<Glyph> glyphs = new LinkedHashSet<>();
final int lastIndex = expand(stemProfile, linkProfile, relations, glyphs);
if ((lastIndex == -1) || relations.isEmpty()) {
return false;
}
// Stem built from items
if (glyphs.isEmpty()) {
return false;
}
StemInter stem = sb.createStem(glyphs, stemProfile);
if (stem == null) {
return false;
}
// Check to reuse stem (rare case of a stem with 2 beam groups)
for (Entry<StemLinker, Relation> entry : relations.entrySet()) {
final CLinker cl = (CLinker) entry.getKey();
if (cl.isLinked()) {
final HorizontalSide hs = cl.getSLinker().getHorizontalSide();
final HeadInter head = cl.getSource();
final Set<StemInter> stems = head.getSideStems().get(hs);
if (stems.size() == 1) {
stem = stems.iterator().next();
logger.debug("{} reusing {}", this, stem);
break;
}
}
}
final SIGraph sig = system.getSig();
if (stem.getId() == 0) {
sig.addVertex(stem);
}
// Link between starting beam and stem?
final Link bsLink = BeamStemRelation.checkLink(
beam, stem, vSide.opposite(), scale, stemProfile);
if (bsLink == null) {
logger.info("{} no beam link", this);
return false;
}
bsLink.applyTo(beam);
getBLinker().setLinked(true);
// Link other sibling beams as well
linkSiblings(stem, ((Support) bsLink.relation).getGrade());
// Connections by applying links
for (Entry<StemLinker, Relation> entry : relations.entrySet()) {
// Relation was checked against a temporary stem, perhaps not the final one
final CLinker cl = (CLinker) entry.getKey();
final HeadInter head = cl.getSource();
cl.getSLinker().setLinked(true);
if (null == sig.getRelation(head, stem, HeadStemRelation.class)) {
sig.addEdge(head, stem, entry.getValue());
}
}
// Portion of stem draft still to be processed?
if (lastIndex < sb.maxIndex()) {
///stemDraft.splitAfter(lastIndex);
}
return true;
}
// linkSiblings //
private void linkSiblings (StemInter stem,
double relGrade)
{
if (stem.isVip()) {
logger.info("VIP {} linkSiblings with {}", this, stem);
}
final Line2D stemMedian = stem.getMedian();
final SIGraph sig = system.getSig();
final List<AbstractBeamInter> siblings = getSiblingBeamsAt(refPt);
siblings.remove(beam);
for (AbstractBeamInter b : siblings) {
if (b.getGlyph() == beam.getGlyph()) {
continue;
}
if (sig.getRelation(b, stem, BeamStemRelation.class) == null) {
final BeamStemRelation r = new BeamStemRelation();
final Point2D crossPt = LineUtil.intersection(stemMedian,
b.getMedian());
r.setExtensionPoint(new Point2D.Double(
crossPt.getX(),
crossPt.getY() + (yDir * (b.getHeight() / 2.0))));
// Portion depends on x location of stem WRT beam
r.setBeamPortion(BeamStemRelation.computeBeamPortion(
b, crossPt.getX(), scale));
r.setGrade(relGrade);
sig.addEdge(b, stem, r);
final StemLinker sl = sb.getLinkerOf(b);
if (sl != null) {
sl.setLinked(true);
}
}
}
}
}
}
} |
package org.mcphoton.impl;
import java.util.Scanner;
import org.mcphoton.Photon;
import org.mcphoton.command.Command;
import org.mcphoton.messaging.ChatMessage;
import org.mcphoton.messaging.Messageable;
/**
*
* @author TheElectronWill
*/
public class ConsoleThread extends Thread implements Messageable {
private volatile boolean run = true;
private final Scanner sc = new Scanner(System.in);
/**
* Stops this Thread nicely, as soon as possible but without any forcing.
*/
public void stopNicely() {
run = false;
}
@Override
public void run() {
while (run) {
String line = sc.nextLine();
String[] parts = line.split(" ", 2);
Command cmd = Photon.getCommandsRegistry().getRegistered(parts[0]);
cmd.execute(this, parts[1]);
}
}
@Override
public void sendMessage(CharSequence msg) {
System.out.println(msg);
}
@Override
public void sendMessage(ChatMessage msg) {
System.out.println(msg.toConsoleString());
}
} |
package com.haw.projecthorse.level.city;
import sun.org.mozilla.javascript.internal.ast.WithStatement;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton;
import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.haw.projecthorse.assetmanager.AssetManager;
import com.haw.projecthorse.gamemanager.GameManagerFactory;
import com.haw.projecthorse.gamemanager.navigationmanager.exception.LevelNotFoundException;
import com.haw.projecthorse.gamemanager.navigationmanager.json.CityObject;
import com.haw.projecthorse.gamemanager.navigationmanager.json.GameObject;
import com.haw.projecthorse.intputmanager.InputManager;
import com.haw.projecthorse.level.Level;
import com.haw.projecthorse.swipehandler.StageGestureDetector;
public class City extends Level {
private Stage stage;
private TextureAtlas atlant;
private SpriteBatch batcher = this.getSpriteBatch();
private CityObject cityObject;
private int lastButtonY = GameManagerFactory.getInstance().getSettings().getScreenHeight();
private BitmapFont font;
private AtlasRegion region;
private ImageTextButtonStyle imageButtonStyle;
private VerticalGroup verticalGroup = new VerticalGroup();
@Override
protected void doShow() {
// TODO Auto-generated method stub
atlant = AssetManager.load("hamburg", false, false, true);
stage = new Stage(this.getViewport(), batcher);
addBackground();
font = new BitmapFont(Gdx.files.internal("pictures/selfmade/font.txt"));
font.setScale(.45f, .45f);
font.setColor(Color.MAGENTA);
try {
cityObject = GameManagerFactory.getInstance().getCityObject(getLevelID());
addGameButtons();
} catch (LevelNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
InputManager.addInputProcessor(stage);
}
private void addBackground() {
region = atlant.findRegion("Sankt-Michaelis-Kirche_Hamburg");
Image background = new Image(region);
background.toBack();
stage.addActor(background);
}
private void addGameButtons() throws LevelNotFoundException {
Drawable drawable = new TextureRegionDrawable(atlant.findRegion("raw_game_teaser_icon"));
imageButtonStyle = new ImageTextButton.ImageTextButtonStyle();
imageButtonStyle.down = drawable;
imageButtonStyle.up = drawable;
imageButtonStyle.font = new BitmapFont(Gdx.files.internal("pictures/selfmade/font.txt"));
;
imageButtonStyle.font.scale(-0.5f);
imageButtonStyle.fontColor = Color.BLACK;
GameObject[] games = cityObject.getGames();
for (GameObject game : games) {
addGameButton(game);
}
imageButtonStyle = null;
}
private void addGameButton(final GameObject gameObject) {
ImageTextButton imgTextButton = new ImageTextButton(gameObject.getGameTitle(), imageButtonStyle);
imgTextButton.addListener(new ChangeListener() {
public void changed(ChangeEvent event, Actor actor) {
System.out.println("Spiel " + gameObject.getGameTitle() + " soll gestartet werden");
GameManagerFactory.getInstance().navigateToLevel(gameObject.getLevelID());
}
});
verticalGroup.addActor(imgTextButton);
imgTextButton.setWidth(this.width*0.8F);
imgTextButton.setHeight(this.height * 0.1F);
imgTextButton.setPosition(this.width * 0.1F, lastButtonY);
lastButtonY = (int) (lastButtonY - this.height * 0.2F);
imgTextButton.toFront();
stage.addActor(imgTextButton);
};
@Override
protected void doRender(float delta) {
stage.draw();
batcher.begin();
//batcher.draw(region, 0, 0, GameManagerFactory.getInstance().getSettings().getScreenWidth(), GameManagerFactory.getInstance().getSettings().getScreenHeight());
font.draw(batcher, cityObject.getCityName(), Gdx.graphics.getWidth() / 1.8f, Gdx.graphics.getHeight() / 1.03f);
batcher.end();
}
@Override
protected void doDispose() {
atlant.dispose();
font.dispose();
}
@Override
protected void doResize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
protected void doHide() {
// TODO Auto-generated method stub
}
@Override
protected void doPause() {
// TODO Auto-generated method stub
}
@Override
protected void doResume() {
// TODO Auto-generated method stub
}
} |
package com.ecyrd.jspwiki.plugin;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.WikiPage;
import com.ecyrd.jspwiki.parser.MarkupParser;
/**
* Provides a handler for bug reports. Still under construction.
*
* <ul>
* <li>"title" = title of the bug. This is required. If it is empty (as in "")
* it is a signal to the handler to return quietly.</li>
* </ul>
*
* @author Janne Jalkanen
*/
public class BugReportHandler
implements WikiPlugin
{
private static Logger log = Logger.getLogger( BugReportHandler.class );
public static final String TITLE = "title";
public static final String DESCRIPTION = "description";
public static final String VERSION = "version";
public static final String MAPPINGS = "map";
public static final String PAGE = "page";
public static final String DEFAULT_DATEFORMAT = "dd-MMM-yyyy HH:mm:ss zzz";
public String execute( WikiContext context, Map params )
throws PluginException
{
String title;
String description;
String version;
String submitter = null;
SimpleDateFormat format = new SimpleDateFormat( DEFAULT_DATEFORMAT );
title = (String) params.get( TITLE );
description = (String) params.get( DESCRIPTION );
version = (String) params.get( VERSION );
Principal wup = context.getCurrentUser();
if( wup != null )
{
submitter = wup.getName();
}
if( title == null ) throw new PluginException("Title is required");
if( title.length() == 0 ) return "";
if( description == null ) description = "";
if( version == null ) version = "unknown";
Properties mappings = parseMappings( (String) params.get( MAPPINGS ) );
// Start things
try
{
StringWriter str = new StringWriter();
PrintWriter out = new PrintWriter( str );
Date d = new Date();
// Outputting of basic data
out.println("|"+mappings.getProperty(TITLE,"Title")+"|"+title);
out.println("|"+mappings.getProperty("date","Date")+"|"+format.format(d));
out.println("|"+mappings.getProperty(VERSION,"Version")+"|"+version);
if( submitter != null )
{
out.println("|"+mappings.getProperty("submitter","Submitter")+
"|"+submitter);
}
// Outputting the other parameters added to this.
for( Iterator i = params.entrySet().iterator(); i.hasNext(); )
{
Map.Entry entry = (Map.Entry) i.next();
if( entry.getKey().equals( TITLE ) ||
entry.getKey().equals( DESCRIPTION ) ||
entry.getKey().equals( VERSION ) ||
entry.getKey().equals( MAPPINGS ) ||
entry.getKey().equals( PAGE ) ||
entry.getKey().toString().startsWith("_") )
{
// Ignore this
}
else
{
// If no mapping has been defined, just ignore
String head = mappings.getProperty( (String)entry.getKey(),
(String)entry.getKey() );
if( head.length() > 0 )
{
out.println("|"+head+
"|"+entry.getValue());
}
}
}
out.println();
out.println( description );
out.close();
// Now create a new page for this bug report
String pageName = findNextPage( context, title,
(String)params.get( PAGE ) );
WikiPage newPage = new WikiPage( context.getEngine(), pageName );
WikiContext newContext = (WikiContext)context.clone();
newContext.setPage( newPage );
context.getEngine().saveText( newContext,
str.toString() );
return "A new bug report has been created: <a href=\""+context.getViewURL(pageName)+"\">"+pageName+"</a>";
}
catch( WikiException e )
{
log.error("Unable to save page!",e);
return "Unable to create bug report";
}
}
/**
* Finds a free page name for adding the bug report. Tries to construct a page,
* and if it's found, adds a number to it and tries again.
*/
private synchronized String findNextPage( WikiContext context,
String title,
String baseName )
{
String basicPageName = ((baseName != null)?baseName:"Bug")+MarkupParser.cleanLink(title);
WikiEngine engine = context.getEngine();
String pageName = basicPageName;
long lastbug = 2;
while( engine.pageExists( pageName ) )
{
pageName = basicPageName + lastbug++;
}
return pageName;
}
/**
* Just parses a mappings list in the form of "a=b;b=c;c=d".
* <p>
* FIXME: Should probably be in TextUtil or somewhere.
*/
private Properties parseMappings( String mappings )
{
Properties props = new Properties();
if( mappings == null ) return props;
StringTokenizer tok = new StringTokenizer( mappings, ";" );
while( tok.hasMoreTokens() )
{
String t = tok.nextToken();
int colon = t.indexOf("=");
String key, value;
if( colon > 0 )
{
key = t.substring(0,colon);
value = t.substring(colon+1);
}
else
{
key = t;
value = "";
}
props.setProperty( key, value );
}
return props;
}
} |
package personaje;
import java.awt.Point;
import java.util.Observable;
import output.Sprite;
public abstract class Personaje extends Observable implements Atacable, IamMovil {
protected String nombre;
protected int salud=100;
protected int energia=50;
protected int fuerza=1;
protected int ingenio=1;
protected int defensa=0;
protected int multavsalud=1;
protected int modavsalud=0;
protected float multavenergia=1;
protected int modavenergia=0;
protected float multavingenio=1;
protected int modavingenio=0;
protected float multavfuerza=1;
protected int modavfuerza=0;
protected float multavdefensa=1;
protected int modavdefensa=0;
protected boolean sexo; //= mucho
protected int nivel = 1;
protected int experiencia = 0;
protected String SpritePath;
protected Point pos;
protected Point vel;
protected Point acc;
public final boolean atacar(Atacable atacado) {
if (puedeAtacar() && atacado.estaVivo()) {
atacado.serAtacado(this.obtenerPuntosDeFuerza());
energia -= this.obtenerPuntosDeFuerza(); // Te cansas despues de atacar
if(!atacado.estaVivo())
despuesDeAtacar(atacado.darExperiencia());
return true;
}
return false;
}
// Despues de atacar me fijo si subio de nivel con la experiencia obtenida
// si paso de nivel, la experiencia se me resetea a 0, y me tiene que sumar
// el resto de experiencia que sobro.
// sino solamente me suma la experiencia obtenida.
protected void despuesDeAtacar(int experienciaObtenida) {
if( this.experiencia + experienciaObtenida >= this.getTopeExperienciaNivel()){
this.experiencia = this.experiencia + experienciaObtenida - getTopeExperienciaNivel();
subirDeNivel();
}
else{
this.experiencia += experienciaObtenida;
}
}
protected void subirDeNivel(){
if(this.nivel < 32){
this.nivel++;
}
}
public void revivir() {
this.serCurado();
this.serEnergizado();
}
public abstract boolean puedeAtacar();
public boolean estaVivo() {
return this.salud > 0;
}
@Override
public void serAtacado(int dao) {
if ( ( dao - (this.obtenerPuntosDeDefensa()) /10 ) > 0)
this.salud -= (dao - (this.obtenerPuntosDeDefensa()) /10 );
}
public void serCurado() {
this.salud = this.getmaxsalud(); //por default pongo el maximo
}
public void serCurado(int cant) {
this.salud += cant;
}
public void serEnergizado() {
this.energia = this.getmaxenergia(); // por default pongo el maximo
}
public void serEnergizado(int cant) {
this.energia +=cant;
}
public int getSalud() {
return this.salud;
}
//Las Siguientes funciones calculan el maximo de los attributos, no los valores actuales.
public int getmaxsalud(){
return (int)(100 * this.nivel);
}
public int getmaxenergia(){
return (int)(100 * this.nivel + 10);
}
public int obtenerPuntosDeFuerza() {
return (int)(this.fuerza * this.multavfuerza + this.modavfuerza); // Modificadores + valor inherente
}
public int obtenerPuntosDeSalud() {
return (int)(getmaxsalud() * this.multavsalud + this.modavsalud); // Modificadores + valor inherente
}
public int obtenerPuntosDeEnergia() {
return (int)(getmaxenergia() * this.multavenergia + this.modavenergia); // Modificadores + valor inherente
}
public int obtenerPuntosDeIngenio() {
return (int)(this.ingenio * this.multavingenio + this.modavingenio); // Modificadores + valor inherente
}
public int obtenerPuntosDeDefensa(){
return (int)(this.defensa * this.multavdefensa + this.modavdefensa); // Modificadores + valor inherente
}
@Override
public int darExperiencia() {
return getExperiencia()/10; //Es igual al anterior em el caso default, y es compatible con otras formulas de experiencia.
}
public int getTopeExperienciaNivel() {
return this.nivel * 100;
}
public int getExperiencia() {
return experiencia;
}
public void setExperiencia(int experiencia) {
this.experiencia = experiencia;
}
public int getNivel() {
return nivel;
}
public String getSpritePath(){
return this.SpritePath;
}
public Sprite getSprite(){
return new Sprite(SpritePath);
}
public void setSpritePath(String path){
this.SpritePath=path;
}
public Point getPos() {return this.pos;}
public Point getVel() {return this.vel;}
public Point getAcc() {return this.acc;}
public Point getNextStep(){return this.vel;} // Why? For the glory of Satan of course!
public void mover(){
this.pos=this.vel;
this.vel.setLocation(vel.getX()+acc.getX(), vel.getY()+acc.getY());
}
public Point procMovimiento(){ mover(); return this.pos;}
private void actualizar(){
if (this.hasChanged())
this.notifyObservers();
this.clearChanged();
}
public void step(){
mover();
// actuar()
actualizar();
}
} |
package brooklyn.util.text;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Map;
import javax.annotation.Nullable;
import brooklyn.util.Time;
import com.google.common.base.CharMatcher;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
public class Strings {
/**
* Checks if the given string is null or is an empty string.
* Useful for pre-String.isEmpty. And useful for StringBuilder etc.
*
* @param s the String to check
* @return true if empty or null, false otherwise.
*
* @see #isNonEmpty(CharSequence)
* @see #isBlank(CharSequence)
* @see #isNonBlank(CharSequence)
*/
public static boolean isEmpty(CharSequence s) {
return s == null || s.length()==0;
}
/**
* Checks if the given string is empty or only consists of whitespace.
*
* @param s the String to check
* @return true if blank, empty or null, false otherwise.
*
* @see #isEmpty(CharSequence)
* @see #isNonEmpty(CharSequence)
* @see #isNonBlank(CharSequence)
*/
public static boolean isBlank(CharSequence s) {
return isEmpty(s) || CharMatcher.WHITESPACE.matchesAllOf(s);
}
/**
* The inverse of {@link #isEmpty(CharSequence)}.
*
* @param s the String to check
* @return true if non empty, false otherwise.
*
* @see #isEmpty(CharSequence)
* @see #isBlank(CharSequence)
* @see #isNonBlank(CharSequence)
*/
public static boolean isNonEmpty(CharSequence s) {
return !isEmpty(s);
}
/**
* The inverse of {@link #isBlank(CharSequence)}.
*
* @param s the String to check
* @return true if non blank, false otherwise.
*
* @see #isEmpty(CharSequence)
* @see #isNonEmpty(CharSequence)
* @see #isBlank(CharSequence)
*/
public static boolean isNonBlank(CharSequence s) {
return !isBlank(s);
}
public static void checkNonEmpty(CharSequence s) {
if (s==null) throw new IllegalArgumentException("String must not be null");
if (s.length()==0) throw new IllegalArgumentException("String must not be empty");
}
public static void checkNonEmpty(CharSequence s, String message) {
if (isEmpty(s)) throw new IllegalArgumentException(message);
}
/** removes the first suffix in the list which is present at the end of string
* and returns that string; ignores subsequent suffixes if a matching one is found;
* returns the original string if no suffixes are at the end
*/
public static String removeFromEnd(String string, String ...suffixes) {
if (isEmpty(string)) return string;
for (String suffix : suffixes)
if (string.endsWith(suffix)) return string.substring(0, string.length() - suffix.length());
return string;
}
/** as removeFromEnd, but repeats until all such suffixes are gone */
public static String removeAllFromEnd(String string, String ...suffixes) {
boolean anotherLoopNeeded = true;
while (anotherLoopNeeded) {
if (isEmpty(string)) return string;
anotherLoopNeeded = false;
for (String suffix : suffixes)
if (string.endsWith(suffix)) {
string = string.substring(0, string.length() - suffix.length());
anotherLoopNeeded = true;
break;
}
}
return string;
}
/** removes the first prefix in the list which is present at the start of string
* and returns that string; ignores subsequent prefixes if a matching one is found;
* returns the original string if no prefixes match
*/
public static String removeFromStart(String string, String ...prefixes) {
if (isEmpty(string)) return string;
for (String prefix : prefixes)
if (string.startsWith(prefix)) return string.substring(prefix.length());
return string;
}
/** as removeFromStart, but repeats until all such suffixes are gone */
public static String removeAllFromStart(String string, String ...prefixes) {
boolean anotherLoopNeeded = true;
while (anotherLoopNeeded) {
if (isEmpty(string)) return string;
anotherLoopNeeded = false;
for (String prefix : prefixes)
if (string.startsWith(prefix)) {
string = string.substring(prefix.length());
anotherLoopNeeded = true;
break;
}
}
return string;
}
/** @deprecated use {@link com.google.common.base.Joiner} */
@Deprecated public static String join(Iterable<? extends Object> list, String seperator) {
boolean app = false;
StringBuilder out = new StringBuilder();
for (Object s: list) {
if (app) out.append(seperator);
out.append(s);
app = true;
}
return out.toString();
}
/** @deprecated use {@link com.google.common.base.Joiner} */
@Deprecated public static String join(Object[] list, String seperator) {
boolean app = false;
StringBuilder out = new StringBuilder();
for (Object s: list) {
if (app) out.append(seperator);
out.append(s);
app = true;
}
return out.toString();
}
/** replaces all key->value entries from the replacement map in source (non-regex) */
@SuppressWarnings("rawtypes")
public static String replaceAll(String source, Map replacements) {
for (Object rr: replacements.entrySet()) {
Map.Entry r = (Map.Entry)rr;
source = replaceAllNonRegex(source, ""+r.getKey(), ""+r.getValue());
}
return source;
}
/** NON-REGEX replaceAll -
* replaces all instances in source, of the given pattern, with the given replacement
* (not interpreting any arguments as regular expressions)
*/
public static String replaceAll(String source, String pattern, String replacement) {
if (source==null) return source;
StringBuilder result = new StringBuilder(source.length());
for (int i=0; i<source.length(); ) {
if (source.substring(i).startsWith(pattern)) {
result.append(replacement);
i += pattern.length();
} else {
result.append(source.charAt(i));
i++;
}
}
return result.toString();
}
/** NON-REGEX replacement -- explicit method name for reabaility, doing same as Strings.replaceAll */
public static String replaceAllNonRegex(String source, String pattern, String replacement) {
return replaceAll(source, pattern, replacement);
}
/** REGEX replacement -- explicit method name for reabaility, doing same as String.replaceAll */
public static String replaceAllRegex(String source, String pattern, String replacement) {
return source.replaceAll(pattern, replacement);
}
/** Valid non alphanumeric characters for filenames. */
public static final String VALID_NON_ALPHANUM_FILE_CHARS = "-_.";
public static String makeValidFilename(String s) {
Preconditions.checkNotNull(s, "Cannot make valid filename from null string");
Preconditions.checkArgument(isNonBlank(s), "Cannot make valid filename from blank string");
return CharMatcher.anyOf(VALID_NON_ALPHANUM_FILE_CHARS).or(CharMatcher.JAVA_LETTER_OR_DIGIT)
.negate()
.trimAndCollapseFrom(s, '_');
}
/**
* A {@link CharMatcher} that matches valid Java identifier characters.
*
* @see Character#isJavaIdentifierPart(char)
*/
public static final CharMatcher IS_JAVA_IDENTIFIER_PART = CharMatcher.forPredicate(new Predicate<Character>() {
@Override
public boolean apply(@Nullable Character input) {
return input != null && Character.isJavaIdentifierPart(input);
}
});
/**
* Returns a valid Java identifier name based on the input.
*
* Removes certain characterss (like apostrophe), replaces one or more invalid
* characterss with {@literal _}, and prepends {@literal _} if the first character
* is only valid as an identifier part (not start).
* <p>
* The result is usually unique to s, though this isn't guaranteed, for example if
* all characters are invalid. For a unique identifier use {@link #makeValidUniqueJavaName(String)}.
*
* @see #makeValidUniqueJavaName(String)
*/
public static String makeValidJavaName(String s) {
if (s==null) return "__null";
if (s.length()==0) return "__empty";
String name = IS_JAVA_IDENTIFIER_PART.negate().collapseFrom(CharMatcher.is('\'').removeFrom(s), '_');
if (!Character.isJavaIdentifierStart(s.charAt(0))) return "_" + name;
return name;
}
/**
* Returns a unique valid java identifier name based on the input.
*
* Translated as per {@link #makeValidJavaName(String)} but with {@link String#hashCode()}
* appended where necessary to guarantee uniqueness.
*
* @see #makeValidJavaName(String)
*/
public static String makeValidUniqueJavaName(String s) {
String name = makeValidJavaName(s);
if (isEmpty(s) || IS_JAVA_IDENTIFIER_PART.matchesAllOf(s) || CharMatcher.is('\'').matchesNoneOf(s)) {
return name;
} else {
return name + "_" + s.hashCode();
}
}
/** @see {@link Identifiers#makeRandomId(int)} */
public static String makeRandomId(int l) {
return Identifiers.makeRandomId(l);
}
/** pads the string with 0's at the left up to len; no padding if i longer than len */
public static String makeZeroPaddedString(int i, int len) {
return makePaddedString(""+i, len, "0", "");
}
/** pads the string with "pad" at the left up to len; no padding if base longer than len */
public static String makePaddedString(String base, int len, String left_pad, String right_pad) {
String s = ""+(base==null ? "" : base);
while (s.length()<len) s=left_pad+s+right_pad;
return s;
}
public static void trimAll(String[] s) {
for (int i=0; i<s.length; i++)
s[i] = (s[i]==null ? "" : s[i].trim());
}
/** creates a string from a real number, with specified accuracy (more iff it comes for free, ie integer-part);
* switches to E notation if needed to fit within maxlen; can be padded left up too (not useful)
* @param x number to use
* @param maxlen maximum length for the numeric string, if possible (-1 to suppress)
* @param prec number of digits accuracy desired (more kept for integers)
* @param leftPadLen will add spaces at left if necessary to make string this long (-1 to suppress) [probably not usef]
* @return such a string
*/
public static String makeRealString(double x, int maxlen, int prec, int leftPadLen) {
return makeRealString(x, maxlen, prec, leftPadLen, 0.00000000001, true);
}
/** creates a string from a real number, with specified accuracy (more iff it comes for free, ie integer-part);
* switches to E notation if needed to fit within maxlen; can be padded left up too (not useful)
* @param x number to use
* @param maxlen maximum length for the numeric string, if possible (-1 to suppress)
* @param prec number of digits accuracy desired (more kept for integers)
* @param leftPadLen will add spaces at left if necessary to make string this long (-1 to suppress) [probably not usef]
* @param skipDecimalThreshhold if positive it will not add a decimal part if the fractional part is less than this threshhold
* (but for a value 3.00001 it would show zeroes, e.g. with 3 precision and positive threshhold <= 0.00001 it would show 3.00);
* if zero or negative then decimal digits are always shown
* @param useEForSmallNumbers whether to use E notation for numbers near zero
* @return such a string
*/
public static String makeRealString(double x, int maxlen, int prec, int leftPadLen, double skipDecimalThreshhold, boolean useEForSmallNumbers) {
NumberFormat df = DecimalFormat.getInstance();
//df.setMaximumFractionDigits(maxlen);
df.setMinimumFractionDigits(0);
//df.setMaximumIntegerDigits(prec);
df.setMinimumIntegerDigits(1);
df.setGroupingUsed(false);
String s;
if (x==0) {
if (skipDecimalThreshhold>0 || prec<=1) s="0";
else {
s="0.0";
while (s.length()<prec+1) s+="0";
}
} else {
// long bits= Double.doubleToLongBits(x);
// int s = ((bits >> 63) == 0) ? 1 : -1;
// int e = (int)((bits >> 52) & 0x7ffL);
// long m = (e == 0) ?
// (bits & 0xfffffffffffffL) << 1 :
// (bits & 0xfffffffffffffL) | 0x10000000000000L;
// //s*m*2^(e-1075);
int log = (int)Math.floor(Math.log10(x));
int numFractionDigits = (log>=prec ? 0 : prec-log-1);
if (numFractionDigits>0) { //need decimal digits
if (skipDecimalThreshhold>0) {
int checkFractionDigits = 0;
double multiplier = 1;
while (checkFractionDigits < numFractionDigits) {
if (Math.abs(x - Math.rint(x*multiplier)/multiplier)<skipDecimalThreshhold)
break;
checkFractionDigits++;
multiplier*=10;
}
numFractionDigits = checkFractionDigits;
}
df.setMinimumFractionDigits(numFractionDigits);
df.setMaximumFractionDigits(numFractionDigits);
} else {
//x = Math.rint(x);
df.setMaximumFractionDigits(0);
}
s = df.format(x);
if (maxlen>0 && s.length()>maxlen) {
//too long:
double signif = x/Math.pow(10,log);
if (s.indexOf('.')>=0) {
//have a decimal point; either we are very small 0.000001
//or prec is larger than maxlen
if (Math.abs(x)<1 && useEForSmallNumbers) {
//very small-- use alternate notation
s = makeRealString(signif, -1, prec, -1) + "E"+log;
} else {
//leave it alone, user error or E not wanted
}
} else {
//no decimal point, integer part is too large, use alt notation
s = makeRealString(signif, -1, prec, -1) + "E"+log;
}
}
}
if (leftPadLen>s.length())
return makePaddedString(s, leftPadLen, " ", "");
else
return s;
}
/** creates a string from a real number, with specified accuracy (more iff it comes for free, ie integer-part);
* switches to E notation if needed to fit within maxlen; can be padded left up too (not useful)
* @param x number to use
* @param maxlen maximum length for the numeric string, if possible (-1 to suppress)
* @param prec number of digits accuracy desired (more kept for integers)
* @param leftPadLen will add spaces at left if necessary to make string this long (-1 to suppress) [probably not usef]
* @return such a string
*/
public static String makeRealStringNearZero(double x, int maxlen, int prec, int leftPadLen) {
if (Math.abs(x)<0.0000000001) x=0;
NumberFormat df = DecimalFormat.getInstance();
//df.setMaximumFractionDigits(maxlen);
df.setMinimumFractionDigits(0);
//df.setMaximumIntegerDigits(prec);
df.setMinimumIntegerDigits(1);
df.setGroupingUsed(false);
String s;
if (x==0) {
if (prec<=1) s="0";
else {
s="0.0";
while (s.length()<prec+1) s+="0";
}
} else {
// long bits= Double.doubleToLongBits(x);
// int s = ((bits >> 63) == 0) ? 1 : -1;
// int e = (int)((bits >> 52) & 0x7ffL);
// long m = (e == 0) ?
// (bits & 0xfffffffffffffL) << 1 :
// (bits & 0xfffffffffffffL) | 0x10000000000000L;
// //s*m*2^(e-1075);
int log = (int)Math.floor(Math.log10(x));
int scale = (log>=prec ? 0 : prec-log-1);
if (scale>0) { //need decimal digits
double scale10 = Math.pow(10, scale);
x = Math.rint(x*scale10)/scale10;
df.setMinimumFractionDigits(scale);
df.setMaximumFractionDigits(scale);
} else {
//x = Math.rint(x);
df.setMaximumFractionDigits(0);
}
s = df.format(x);
if (maxlen>0 && s.length()>maxlen) {
//too long:
double signif = x/Math.pow(10,log);
if (s.indexOf('.')>=0) {
//have a decimal point; either we are very small 0.000001
//or prec is larger than maxlen
if (Math.abs(x)<1) {
//very small-- use alternate notation
s = makeRealString(signif, -1, prec, -1) + "E"+log;
} else {
//leave it alone, user error
}
} else {
//no decimal point, integer part is too large, use alt notation
s = makeRealString(signif, -1, prec, -1) + "E"+log;
}
}
}
if (leftPadLen>s.length())
return makePaddedString(s, leftPadLen, " ", "");
else
return s;
}
public static String getLastWord(String s) {
if (s==null) return null;
s = s.trim();
int x = s.lastIndexOf(' ');
if (x==-1) return s;
return s.substring(x+1);
}
public static String makeTimeString(long utcMillis) {
return Time.makeTimeString(utcMillis);
}
/** returns e.g. { "prefix01", ..., "prefix96" };
* see more functional NumericRangeGlobExpander for "prefix{01-96}"
*/
public static String[] makeArray(String prefix, int count) {
String[] result = new String[count];
int len = (""+count).length();
for (int i=1; i<=count; i++)
result[i-1] = prefix + makePaddedString("", len, "0", ""+i);
return result;
}
public static String[] combineArrays(String[] ...arrays) {
int totalLen = 0;
for (String[] array : arrays) {
if (array!=null) totalLen += array.length;
}
String[] result = new String[totalLen];
int i=0;
for (String[] array : arrays) {
if (array!=null) for (String s : array) {
result[i++] = s;
}
}
return result;
}
public static String toInitialCapOnly(String value) {
if (value==null || value.length()==0) return value;
return value.substring(0, 1).toUpperCase() + value.substring(1).toLowerCase();
}
public static String reverse(String name) {
return new StringBuffer(name).reverse().toString();
}
public static boolean isLowerCase(String s) {
return s.toLowerCase().equals(s);
}
public static String makeRepeated(char c, int length) {
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
result.append(c);
}
return result.toString();
}
public static String trimEnd(String s) {
return ("a"+s).trim().substring(1);
}
/** returns up to maxlen characters from the start of s */
public static String maxlen(String s, int maxlen) {
return s.substring(0, Math.min(s.length(), maxlen));
}
/** returns toString of the object if it is not null, otherwise null */
public static String toString(Object o) {
if (o==null) return null;
return o.toString();
}
public static boolean containsLiteralIgnoreCase(CharSequence input, CharSequence fragment) {
if (input==null) return false;
if (isEmpty(fragment)) return true;
int lastValidStartPos = input.length()-fragment.length();
char f0u = Character.toUpperCase(fragment.charAt(0));
char f0l = Character.toLowerCase(fragment.charAt(0));
i: for (int i=0; i<=lastValidStartPos; i++) {
char ii = input.charAt(i);
if (ii==f0l || ii==f0u) {
for (int j=1; j<fragment.length(); j++) {
if (Character.toLowerCase(input.charAt(i+j))!=Character.toLowerCase(fragment.charAt(j)))
continue i;
}
return true;
}
}
return false;
}
public static boolean containsLiteral(CharSequence input, CharSequence fragment) {
if (input==null) return false;
if (isEmpty(fragment)) return true;
int lastValidStartPos = input.length()-fragment.length();
char f0 = fragment.charAt(0);
i: for (int i=0; i<=lastValidStartPos; i++) {
char ii = input.charAt(i);
if (ii==f0) {
for (int j=1; j<fragment.length(); j++) {
if (input.charAt(i+j)!=fragment.charAt(j))
continue i;
}
return true;
}
}
return false;
}
} |
package com.ecyrd.jspwiki.render;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.filters.FilterException;
import com.ecyrd.jspwiki.filters.FilterManager;
import com.ecyrd.jspwiki.filters.PageFilter;
import com.ecyrd.jspwiki.modules.InternalModule;
import com.ecyrd.jspwiki.parser.JSPWikiMarkupParser;
import com.ecyrd.jspwiki.parser.MarkupParser;
import com.ecyrd.jspwiki.parser.WikiDocument;
import com.ecyrd.jspwiki.providers.CachingProvider;
import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.NeedsRefreshException;
/**
* This class provides a facade towards the differing rendering routines. You should
* use the routines in this manager instead of the ones in WikiEngine, if you don't
* want the different side effects to occur - such as WikiFilters.
* <p>
* This class also manages a rendering cache, i.e. documents are stored between calls.
* You may control the size of the cache by using the "jspwiki.renderingManager.cacheSize"
* parameter in jspwiki.properties. The property value is the number of items that
* are stored in the cache. By default, the value of this parameter is taken from
* the "jspwiki.cachingProvider.cacheSize" parameter (i.e. the rendering cache is
* the same size as the page cache), but you may control them separately.
* <p>
* You can turn caching completely off by stating a cacheSize of zero.
*
* @author jalkanen
* @since 2.4
*/
public class RenderingManager implements PageFilter, InternalModule
{
private static Logger log = Logger.getLogger( RenderingManager.class );
private int m_cacheExpiryPeriod = 24*60*60; // This can be relatively long
public static final String PROP_CACHESIZE = "jspwiki.renderingManager.capacity";
private static final int DEFAULT_CACHESIZE = 1000;
private static final String OSCACHE_ALGORITHM = "com.opensymphony.oscache.base.algorithm.LRUCache";
private static final String PROP_RENDERER = "jspwiki.renderingManager.renderer";
public static final String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
/**
* Stores the WikiDocuments that have been cached.
*/
private Cache m_documentCache;
private Constructor m_rendererConstructor;
/**
* Initializes the RenderingManager.
* Checks for cache size settings, initializes the document cache.
* Looks for alternative WikiRenderers, initializes one, or the default
* XHTMLRenderer, for use.
*
* @param engine A WikiEngine instance.
* @param properties A list of properties to get parameters from.
*/
public void initialize( WikiEngine engine, Properties properties )
throws WikiException
{
int cacheSize = TextUtil.getIntegerProperty( properties, PROP_CACHESIZE, -1 );
if( cacheSize == -1 )
{
cacheSize = TextUtil.getIntegerProperty( properties,
CachingProvider.PROP_CACHECAPACITY,
DEFAULT_CACHESIZE );
}
if( cacheSize > 0 )
{
m_documentCache = new Cache(true,false,false,false,
OSCACHE_ALGORITHM,
cacheSize);
}
else
{
log.info( "RenderingManager caching is disabled." );
}
String renderImplName = properties.getProperty( PROP_RENDERER );
if( renderImplName == null ) {
renderImplName = DEFAULT_RENDERER;
}
Class[] rendererParams = { WikiContext.class, WikiDocument.class };
try
{
Class c = Class.forName( renderImplName );
m_rendererConstructor = c.getConstructor( rendererParams );
}
catch( ClassNotFoundException e )
{
log.error( "Unable to find WikiRenderer implementation " + renderImplName );
}
catch( SecurityException e )
{
log.error( "Unable to access the WikiRenderer(WikiContext,WikiDocument) constructor for " + renderImplName );
}
catch( NoSuchMethodException e )
{
log.error( "Unable to locate the WikiRenderer(WikiContext,WikiDocument) constructor for " + renderImplName );
}
if( m_rendererConstructor == null )
{
throw new WikiException( "Failed to get WikiRenderer '" + renderImplName + "'." );
}
log.info( "Rendering content with " + renderImplName + "." );
engine.getFilterManager().addPageFilter( this, FilterManager.SYSTEM_FILTER_PRIORITY );
}
/**
* Returns the default Parser for this context.
*
* @param context the wiki context
* @param pagedata the page data
* @return A MarkupParser instance.
*/
public MarkupParser getParser( WikiContext context, String pagedata )
{
MarkupParser parser = new JSPWikiMarkupParser( context, new StringReader(pagedata) );
return parser;
}
/**
* Returns a cached document, if one is found.
*
* @param context the wiki context
* @param pagedata the page data
* @return the rendered wiki document
* @throws IOException
*/
// FIXME: The cache management policy is not very good: deleted/changed pages
// should be detected better.
protected WikiDocument getRenderedDocument( WikiContext context, String pagedata )
throws IOException
{
String pageid = context.getRealPage().getName()+"::"+context.getRealPage().getVersion();
boolean wasUpdated = false;
if( m_documentCache != null )
{
try
{
WikiDocument doc = (WikiDocument) m_documentCache.getFromCache( pageid,
m_cacheExpiryPeriod );
wasUpdated = true;
// This check is needed in case the different filters have actually
// changed the page data.
// FIXME: Figure out a faster method
if( pagedata.equals(doc.getPageData()) )
{
if( log.isDebugEnabled() ) log.debug("Using cached HTML for page "+pageid );
return doc;
}
}
catch( NeedsRefreshException e )
{
if( log.isDebugEnabled() ) log.debug("Re-rendering and storing "+pageid );
}
}
// Refresh the data content
try
{
MarkupParser parser = getParser( context, pagedata );
WikiDocument doc = parser.parse();
doc.setPageData( pagedata );
if( m_documentCache != null )
{
m_documentCache.putInCache( pageid, doc );
wasUpdated = true;
}
return doc;
}
catch( IOException ex )
{
log.error("Unable to parse",ex);
}
finally
{
if( m_documentCache != null && !wasUpdated ) m_documentCache.cancelUpdate( pageid );
}
return null;
}
/**
* Simply renders a WikiDocument to a String. This version does not get the document
* from the cache - in fact, it does not cache the document at all. This is
* very useful, if you have something that you want to render outside the caching
* routines. Because the cache is based on full pages, and the cache keys are
* based on names, use this routine if you're rendering anything for yourself.
*
* @param context The WikiContext to render in
* @param doc A proper WikiDocument
* @return Rendered HTML.
* @throws IOException If the WikiDocument is poorly formed.
*/
public String getHTML( WikiContext context, WikiDocument doc )
throws IOException
{
WikiRenderer rend = new XHTMLRenderer( context, doc );
return rend.getString();
}
/**
* Returns a WikiRenderer instance, initialized with the given
* context and doc. The object is an XHTMLRenderer, unless overridden
* in jspwiki.properties with PROP_RENDERER.
*/
public WikiRenderer getRenderer( WikiContext context, WikiDocument doc )
{
Object[] params = { context, doc };
WikiRenderer rval = null;
try {
rval = (WikiRenderer)m_rendererConstructor.newInstance( params );
} catch( Exception e ) {
log.error( "Unable to create WikiRenderer", e );
}
return rval;
}
/**
* Convinience method for rendering, using the default parser and renderer. Note that
* you can't use this method to do any arbitrary rendering, as the pagedata MUST
* be the data from the that the WikiContext refers to - this method caches the HTML
* internally, and will return the cached version. If the pagedata is different
* from what was cached, will re-render and store the pagedata into the internal cache.
*
* @param context the wiki context
* @param pagedata the page data
* @return XHTML data.
*/
public String getHTML( WikiContext context, String pagedata )
{
try
{
WikiDocument doc = getRenderedDocument( context, pagedata );
return getHTML( context, doc );
}
catch( IOException e )
{
log.error("Unable to parse",e);
}
return null;
}
// The following methods are for the PageFilter interface
public void initialize( Properties properties ) throws FilterException
{
}
/**
* Flushes the cache objects that refer to this page.
*/
public void postSave( WikiContext wikiContext, String content ) throws FilterException
{
String pageName = wikiContext.getPage().getName();
if( m_documentCache != null )
{
m_documentCache.flushPattern( pageName );
Set referringPages = wikiContext.getEngine().getReferenceManager().findReferredBy( pageName );
// Flush also those pages that refer to this page (if an nonexistant page
// appears; we need to flush the HTML that refers to the now-existant page
if( referringPages != null )
{
Iterator i = referringPages.iterator();
while (i.hasNext())
{
String page = (String) i.next();
log.debug( "Flusing " + page );
m_documentCache.flushPattern( page );
}
}
}
}
public String postTranslate( WikiContext wikiContext, String htmlContent ) throws FilterException
{
return htmlContent;
}
public String preSave( WikiContext wikiContext, String content ) throws FilterException
{
return content;
}
public String preTranslate( WikiContext wikiContext, String content ) throws FilterException
{
return content;
}
} |
package com.esotericsoftware.yamlbeans;
import static com.esotericsoftware.yamlbeans.parser.EventType.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.esotericsoftware.yamlbeans.Beans.Property;
import com.esotericsoftware.yamlbeans.parser.AliasEvent;
import com.esotericsoftware.yamlbeans.parser.CollectionStartEvent;
import com.esotericsoftware.yamlbeans.parser.Event;
import com.esotericsoftware.yamlbeans.parser.Parser;
import com.esotericsoftware.yamlbeans.parser.ScalarEvent;
import com.esotericsoftware.yamlbeans.parser.Parser.ParserException;
import com.esotericsoftware.yamlbeans.scalar.ScalarSerializer;
import com.esotericsoftware.yamlbeans.tokenizer.Tokenizer.TokenizerException;
/**
* Deserializes Java objects from YAML.
* @author <a href="mailto:misc@n4te.com">Nathan Sweet</a>
*/
public class YamlReader {
private final YamlConfig config;
Parser parser;
private final Map<String, Object> anchors = new HashMap();
public YamlReader (Reader reader) {
this(reader, new YamlConfig());
}
public YamlReader (Reader reader, YamlConfig config) {
this.config = config;
parser = new Parser(reader, config.readConfig.defaultVersion);
}
public YamlReader (String yaml) {
this(new StringReader(yaml));
}
public YamlReader (String yaml, YamlConfig config) {
this(new StringReader(yaml), config);
}
public YamlConfig getConfig () {
return config;
}
public void close () throws IOException {
parser.close();
anchors.clear();
}
/**
* Reads the next YAML document and deserializes it into an object. The type of object is defined by the YAML tag. If there is
* no YAML tag, the object will be an {@link ArrayList}, {@link HashMap}, or String.
*/
public Object read () throws YamlException {
return read(null);
}
/**
* Reads an object of the specified type from YAML.
* @param type The type of object to read. If null, behaves the same as {{@link #read()}.
*/
public <T> T read (Class<T> type) throws YamlException {
return read(type, null);
}
/**
* Reads an array, Map, List, or Collection object of the specified type from YAML, using the specified element type.
* @param type The type of object to read. If null, behaves the same as {{@link #read()}.
*/
public <T> T read (Class<T> type, Class elementType) throws YamlException {
try {
while (true) {
Event event = parser.getNextEvent();
if (event == null) return null;
if (event.type == STREAM_END) return null;
if (event.type == DOCUMENT_START) break;
}
return (T)readValue(type, elementType, null);
} catch (ParserException ex) {
throw new YamlException("Error parsing YAML.", ex);
} catch (TokenizerException ex) {
throw new YamlException("Error tokenizing YAML.", ex);
}
}
/**
* Reads an object from the YAML. Can be overidden to take some action for any of the objects returned.
*/
protected Object readValue (Class type, Class elementType, Class defaultType) throws YamlException, ParserException,
TokenizerException {
String tag = null, anchor = null;
Event event = parser.peekNextEvent();
switch (event.type) {
case ALIAS:
parser.getNextEvent();
anchor = ((AliasEvent)event).anchor;
Object value = anchors.get(anchor);
if (value == null) throw new YamlReaderException("Unknown anchor: " + anchor);
return value;
case MAPPING_START:
case SEQUENCE_START:
tag = ((CollectionStartEvent)event).tag;
anchor = ((CollectionStartEvent)event).anchor;
break;
case SCALAR:
tag = ((ScalarEvent)event).tag;
anchor = ((ScalarEvent)event).anchor;
break;
}
if (tag != null) {
type = config.tagToClass.get(tag);
if (type == null) {
try {
if (config.readConfig.classLoader != null)
type = Class.forName(tag, true, config.readConfig.classLoader);
else
type = Class.forName(tag);
} catch (ClassNotFoundException ex) {
throw new YamlReaderException("Unable to find class specified by tag: " + tag);
}
}
} else if (defaultType != null) {
type = defaultType;
}
return readValueInternal(type, elementType, anchor);
}
private Object readValueInternal (Class type, Class elementType, String anchor) throws YamlException, ParserException,
TokenizerException {
if (type == null || type == Object.class) {
Event event = parser.peekNextEvent();
switch (event.type) {
case MAPPING_START:
type = HashMap.class;
break;
case SCALAR:
type = String.class;
break;
case SEQUENCE_START:
type = ArrayList.class;
break;
default:
throw new YamlReaderException("Expected scalar, sequence, or mapping but found: " + event.type);
}
}
if (type == String.class) {
Event event = parser.getNextEvent();
if (event.type != SCALAR) throw new YamlReaderException("Expected scalar for String type but found: " + event.type);
String value = ((ScalarEvent)event).value;
if (anchor != null) anchors.put(anchor, value);
return value;
}
if (Beans.isScalar(type)) {
Event event = parser.getNextEvent();
if (event.type != SCALAR)
throw new YamlReaderException("Expected scalar for primitive type '" + type.getClass() + "' but found: " + event.type);
String value = ((ScalarEvent)event).value;
try {
Object convertedValue;
if (type == String.class) {
convertedValue = value;
} else if (type == Integer.TYPE) {
convertedValue = Integer.valueOf(value);
} else if (type == Integer.class) {
convertedValue = value.length() == 0 ? null : Integer.valueOf(value);
} else if (type == Boolean.TYPE) {
convertedValue = Boolean.valueOf(value);
} else if (type == Boolean.class) {
convertedValue = value.length() == 0 ? null : Boolean.valueOf(value);
} else if (type == Float.TYPE) {
convertedValue = Float.valueOf(value);
} else if (type == Float.class) {
convertedValue = value.length() == 0 ? null : Float.valueOf(value);
} else if (type == Double.TYPE) {
convertedValue = Double.valueOf(value);
} else if (type == Double.class) {
convertedValue = value.length() == 0 ? null : Double.valueOf(value);
} else if (type == Long.TYPE) {
convertedValue = Long.valueOf(value);
} else if (type == Long.class) {
convertedValue = value.length() == 0 ? null : Long.valueOf(value);
} else if (type == Short.TYPE) {
convertedValue = Short.valueOf(value);
} else if (type == Short.class) {
convertedValue = value.length() == 0 ? null : Short.valueOf(value);
} else if (type == Character.TYPE) {
convertedValue = value.charAt(0);
} else if (type == Character.class) {
convertedValue = value.length() == 0 ? null : value.charAt(0);
} else if (type == Byte.TYPE) {
convertedValue = Byte.valueOf(value);
} else if (type == Byte.class) {
convertedValue = value.length() == 0 ? null : Byte.valueOf(value);
} else
throw new YamlException("Unknown field type.");
if (anchor != null) anchors.put(anchor, convertedValue);
return convertedValue;
} catch (Exception ex) {
throw new YamlReaderException("Unable to convert value to required type \"" + type + "\": " + value, ex);
}
}
if (Enum.class.isAssignableFrom(type)) {
Event event = parser.getNextEvent();
if (event.type != SCALAR) throw new YamlReaderException("Expected scalar for enum type but found: " + event.type);
String enumValueName = ((ScalarEvent)event).value;
if (enumValueName.length() == 0) return null;
try {
return Enum.valueOf(type, enumValueName);
} catch (Exception ex) {
throw new YamlReaderException("Unable to find enum value '" + enumValueName + "' for enum class: " + type.getName());
}
}
for (Entry<Class, ScalarSerializer> entry : config.scalarSerializers.entrySet()) {
if (entry.getKey().isAssignableFrom(type)) {
ScalarSerializer serializer = entry.getValue();
Event event = parser.getNextEvent();
if (event.type != SCALAR)
throw new YamlReaderException("Expected scalar for type '" + type + "' to be deserialized by scalar serializer '"
+ serializer.getClass().getName() + "' but found: " + event.type);
Object value = serializer.read(((ScalarEvent)event).value);
if (anchor != null) anchors.put(anchor, value);
return value;
}
}
Event event = parser.peekNextEvent();
switch (event.type) {
case MAPPING_START: {
// Must be a map or an object.
event = parser.getNextEvent();
Object object;
try {
object = createObject(type);
} catch (InvocationTargetException ex) {
throw new YamlReaderException("Error creating object.", ex);
}
if (anchor != null) anchors.put(anchor, object);
while (true) {
if (parser.peekNextEvent().type == MAPPING_END) {
parser.getNextEvent();
break;
}
Object key = readValue(null, null, null);
// Explicit key/value pairs (using "? key\n: value\n") will come back as a map.
boolean isExplicitKey = key instanceof Map;
Object value = null;
if (isExplicitKey) {
Entry nameValuePair = (Entry)((Map)key).entrySet().iterator().next();
key = nameValuePair.getKey();
value = nameValuePair.getValue();
}
if (object instanceof Map) {
// Add to map.
if (!isExplicitKey) value = readValue(elementType, null, null);
((Map)object).put(key, value);
} else {
// Set field on object.
try {
Property property = Beans.getProperty(type, (String)key, config.beanProperties, config.privateFields, config);
if (property == null)
throw new YamlReaderException("Unable to find property '" + key + "' on class: " + type.getName());
Class propertyElementType = config.propertyToElementType.get(property);
Class propertyDefaultType = config.propertyToDefaultType.get(property);
if (!isExplicitKey) value = readValue(property.getType(), propertyElementType, propertyDefaultType);
property.set(object, value);
} catch (Exception ex) {
if (ex instanceof YamlReaderException) throw (YamlReaderException)ex;
throw new YamlReaderException("Error setting property '" + key + "' on class: " + type.getName(), ex);
}
}
}
if (object instanceof DeferredConstruction) {
try {
object = ((DeferredConstruction)object).construct();
if (anchor != null) anchors.put(anchor, object); // Update anchor with real object.
} catch (InvocationTargetException ex) {
throw new YamlReaderException("Error creating object.", ex);
}
}
return object;
}
case SEQUENCE_START: {
// Must be a collection or an array.
event = parser.getNextEvent();
Collection collection;
if (Collection.class.isAssignableFrom(type)) {
try {
collection = (Collection)Beans.createObject(type);
} catch (InvocationTargetException ex) {
throw new YamlReaderException("Error creating object.", ex);
}
} else if (type.isArray()) {
collection = new ArrayList();
elementType = type.getComponentType();
} else
throw new YamlReaderException("A sequence is not a valid value for the type: " + type.getName());
if (!type.isArray() && anchor != null) anchors.put(anchor, collection);
while (true) {
event = parser.peekNextEvent();
if (event.type == SEQUENCE_END) {
parser.getNextEvent();
break;
}
collection.add(readValue(elementType, null, null));
}
if (!type.isArray()) return collection;
Object array = Array.newInstance(elementType, collection.size());
int i = 0;
for (Object object : collection)
Array.set(array, i++, object);
if (anchor != null) anchors.put(anchor, array);
return array;
}
case SCALAR:
// Interpret an empty scalar as null.
if (((ScalarEvent)event).value.length() == 0) {
event = parser.getNextEvent();
return null;
}
// Fall through.
default:
throw new YamlReaderException("Expected data for a " + type.getName() + " field but found: " + event.type);
}
}
/**
* Returns a new object of the requested type.
*/
protected Object createObject (Class type) throws InvocationTargetException {
// Use deferred construction if a non-zero-arg constructor is available.
DeferredConstruction deferredConstruction = Beans.getDeferredConstruction(type, config);
if (deferredConstruction != null) return deferredConstruction;
return Beans.createObject(type);
}
public class YamlReaderException extends YamlException {
public YamlReaderException (String message, Throwable cause) {
super("Line " + parser.getLineNumber() + ", column " + parser.getColumn() + ": " + message, cause);
}
public YamlReaderException (String message) {
this(message, null);
}
}
public static void main (String[] args) throws Exception {
YamlReader reader = new YamlReader(new FileReader("test/test.yml"));
System.out.println(reader.read());
}
} |
package team3543;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import ftclib.FtcOpMode;
import ftclib.FtcAndroidTone;
import hallib.HalDashboard;
import trclib.TrcEvent;
import trclib.TrcSong;
import trclib.TrcSongPlayer;
import trclib.TrcStateMachine;
@TeleOp(name="Test: Android Song", group="3543TestSamples")
@Disabled
public class FtcMusic extends FtcOpMode
{
private static final FtcAndroidTone.Waveform WAVE_FORM = FtcAndroidTone.Waveform.SINE_WAVE;
private static final int SAMPLE_RATE = 16*1024; // ~16kHz
private static final double ATTACK = 0.0; // in seconds
private static final double DECAY = 0.0; // in seconds
private static final double SUSTAIN = 1.0; // in proportion
private static final double RELEASE = 0.02; // in seconds
private static final double BAR_DURATION = 1.920; // in seconds
// Note string syntax:
// <note>[#|b]<octave>.<noteType>[+]{.<noteType>[+]}
// where <note> - 'A' through 'G'
// # - sharp
// b - flat
// <octave> - 1 through 8 (e.g. C4 is the middle C)
// <noteType> - note type (1: whole, 2: half, 4: quarter, ...)
// - add half time
private static final String[] starWarsSections =
{
// section 1
"1:G4.12,G4.12,G4.12,"
+ "C5.2,G5.2,"
+ "F5.12,E5.12,D5.12,C6.2,G5.4,"
+ "F5.12,E5.12,D5.12,C6.2,G5.4,"
+ "F5.12,E5.12,F5.12,D5.2,G4.8,G4.8,"
+ "C5.2,G5.2",
// section 2
"2:F5.12,E5.12,D5.12,C6.2,G5.4,"
+ "F5.12,E5.12,D5.12,C6.2,G5.4,"
+ "F5.12,E5.12,F5.12,D5.2,G4.8,G4.8,"
+ "A4.4+,A4.8,F5.8,E5.8,D5.8,C5.8,"
+ "C5.12,D5.12,E5.12,D5.4,B4.4,G4.8,G4.8,"
+ "A4.4+,A4.8,F5.8,E5.8,D5.8,C5.8,"
+ "G5.4,D5.2,G4.8,G4.8",
// section 3
"3:A4.4+,A4.8,F5.8,E5.8,D5.8,C5.8,"
+ "C5.12,D5.12,E5.12,D5.4,B4.4,G5.8,G5.8,"
+ "C6.8,Bb5.8,Ab5.8,G5.8,F5.8,Eb5.8,D5.8,C5.8,"
+ "G5.2+"
};
private static final String starWarsSequence = "1,2,3";
private static final String[] lesMiserablesSections =
{
// section 1
"1:A4.8+,G4.16,"
+ "F4.8+,G4.16,A4.8+,Bb4.16,C5.4,A4.12,G4.12,F4.12,"
+ "E4.8+,D4.16,E4.8+,F4.16,C4.4,D4.12,C4.12,Bb3.12,"
+ "A3.8+,C4.16,F4.8+,A4.16,G4.8+,F#4.16,G4.8+,D4.16,"
+ "F4.8+,E4.16,E4.8+,F4.16,G4.4,A4.8+,G4.16",
// section 2
"2:F4.8+,G4.16,A4.8+,Bb4.16,C5.4,A4.12,G4.12,F4.12,"
+ "E4.8+,D4.16,E4.8+,F4.16,C4.4,D4.12,C4.12,Bb3.12,"
+ "A3.8+,C4.16,F4.8+,A4.16,G4.12,F#4.12,G4.12,Bb4.8+,E4.16,"
+ "F4.4,R.2,E4.8+,E4.16",
// section 3
"3:A4.8+,G#4.16,A4.8+,B4.16,C5.8+,B4.16,A4.8+,C5.16,"
+ "B4.8+,A4.16,G4.8+,A4.16,B4.4,R.12,B4.12,C5.12,"
+ "D5.8+,C5.16,B4.8+,C5.16,D5.8+,C5.16,B4.8+,D5.16,"
+ "C5.8+,B4.16,A4.8+,B4.16,C5.4,R.8+,A4.16",
// section 4
"4:C5.12,B4.12,A4.12,C5.12,B4.12,A4.12,C5.12,B4.12,A4.12,C5.12,B4.12,C5.12,"
+ "D5.2,R.4,E5.8+,D5.16,"
+ "C5.8+,D5.16,E5.8+,F5.16,G5.4,E5.12,D5.12,C5.12,"
+ "B4.8+,A4.16,B4.8+,C5.16,G4.4,A4.12,G4.12,F4.12",
// section 5
"5:E4.8+,G4.16,C5.8+,E5.16,D5.8+,C#5.16,D5.8+,A4.16,"
+ "C5.8+,B4.16,B4.8+,C5.16,D5.4,E5.8+,D5.16,"
+ "C5.8+,D5.16,E5.8+,F5.16,G5.4,E5.12,D5.12,C5.12,"
+ "B4.8+,A4.16,B4.8+,C5.16,G4.4,A4.12,G4.12,F4.12",
// section 6
"6:E4.8+,G4.16,C5.8+,E5.16,D5.12,C#5.12,D5.12,F5.8+,B4.16,"
+ "C5.4,R.2,E4.8+,E4.16",
// section 7
"7:E4.8+,G4.16,C5.8+,E5.16,D5.12,C#5.12,D5.12,F5.8+,B4.16,"
+ "C5.4,R.2.4"
};
private static final String lesMiserablesSequence = "1,2,3,4,5,6,3,4,5,7";
private static final String[] memesMashup =
{
"1:F#4.1,F#4.1,"
+ "G4.4,F#4.4,C4.1,G4.4,B3.1,G4.4,F#4.4,C4.1,"
+ "G4.4,B3.4,G4.4",
"2:F#4.1,F#4.1,"
+ "G4.4,F#4.4,C4.1,G4.4,B3.1,G4.4,F#4.4,C4.1,"
+ "G4.4,B3.4",
};
private static final String memesMashupSequence = "1,2";
private enum State
{
PLAY_STARWARS,
PLAY_LESMISERABLES,
PLAY_MEMES,
DONE
} //enum State
private HalDashboard dashboard;
private FtcAndroidTone androidTone;
private TrcSong starWars = new TrcSong("StarWars", starWarsSections, starWarsSequence);
private TrcSong lesMiserables = new TrcSong("LesMiserables", lesMiserablesSections, lesMiserablesSequence);
private TrcSong dankestMemes = new TrcSong("DankMemes", memesMashup, memesMashupSequence);
private TrcSongPlayer songPlayer;
private TrcStateMachine sm;
private TrcEvent event = null;
// Implements FtcOpMode abstract methods.
@Override
public void initRobot()
{
hardwareMap.logDevices();
dashboard = HalDashboard.getInstance();
androidTone = new FtcAndroidTone("AndroidTone", WAVE_FORM, SAMPLE_RATE);
androidTone.setSoundEnvelope(ATTACK, DECAY, SUSTAIN, RELEASE);
androidTone.setSoundEnvelopeEnabled(true);
songPlayer = new TrcSongPlayer("SongPlayer", androidTone);
sm = new TrcStateMachine("SongPlayer");
event = new TrcEvent("SongCompletion");
} //initRobot
// Overrides TrcRobot.RobotMode methods.
@Override
public void startMode()
{
dashboard.clearDisplay();
sm.start(State.PLAY_MEMES);
} //startMode
@Override
public void stopMode()
{
sm.stop();
songPlayer.stop();
} //startMode
@Override
public void runPeriodic(double elapsedTime)
{
State state = (State)sm.getState();
dashboard.displayPrintf(1, "State: %s", state == null? "Null": state.toString());
if (sm.isReady())
{
state = (State)sm.getState();
switch (state)
{
case PLAY_STARWARS:
songPlayer.playSong(starWars, BAR_DURATION, false, event);
sm.addEvent(event);
sm.waitForEvents(State.PLAY_LESMISERABLES);
break;
case PLAY_LESMISERABLES:
songPlayer.playSong(lesMiserables, BAR_DURATION, false, event);
sm.addEvent(event);
sm.waitForEvents(State.DONE);
break;
case PLAY_MEMES:
songPlayer.playSong(dankestMemes, BAR_DURATION, false, event);
sm.addEvent(event);
sm.waitForEvents(State.DONE);
break;
case DONE:
default:
sm.stop();
break;
}
}
} //runPeriodic
} //class FtcTestSong |
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.NameProvider;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.math.Mapper;
import org.myrobotlab.math.MathUtils;
import org.myrobotlab.service.abstracts.AbstractEncoder;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.EncoderControl;
import org.myrobotlab.service.interfaces.MotorControl;
import org.myrobotlab.service.interfaces.PinArrayControl;
import org.myrobotlab.service.interfaces.PinListener;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
public class DiyServo extends Service implements ServoControl, PinListener {
/**
* Sweeper - thread used to sweep motor back and forth
*
*/
public class Sweeper extends Thread {
public Sweeper(String name) {
super(String.format("%s.sweeper", name));
}
@Override
public void run() {
double sweepMin = 0.0;
double sweepMax = 0.0;
// start in the middle
double sweepPos = mapper.getMinX() + (mapper.getMaxX() - mapper.getMinX()) / 2;
isSweeping = true;
try {
while (isSweeping) {
// set our range to be inside 'real' min & max input
sweepMin = mapper.getMinX() + 1;
sweepMax = mapper.getMaxX() - 1;
// if pos is too small or too big flip direction
if (sweepPos >= sweepMax || sweepPos <= sweepMin) {
sweepStep = sweepStep * -1;
}
sweepPos += sweepStep;
moveTo(sweepPos);
Thread.sleep(sweepDelay);
}
} catch (Exception e) {
isSweeping = false;
}
}
}
/**
* MotorUpdater The control loop to update the MotorControl with new values
* based on the PID calculations
*
*/
public class MotorUpdater extends Thread {
double lastOutput = 0.0;
/**
* In most cases TargetPos is never reached So we need to emulate it ! if
* currentPosInput is the same since X we guess it is reached based on
* targetPosAngleTolerence
*/
private int nbSamePosInputSinceX = 0;
private double lastCurrentPosInput = 0;
// goal is to not use this
private double targetPosAngleTolerence = 15;
public MotorUpdater(String name) {
super(String.format("%s.motorUpdater", name));
}
@Override
public void run() {
try {
while (isEnabled()) {
if (motorControl != null) {
// Calculate the new value for the motor
if (pid.compute(pidKey)) {
// double setPoint = pid.getSetpoint(pidKey);
// TEMP SANTA TRICK TO CONTROL MAX VELOCITY
deltaVelocity = 1;
if (currentVelocity > maxVelocity && maxVelocity > 0) {
deltaVelocity = currentVelocity / maxVelocity;
}
// END TEMP SANTA TRICK
double output = pid.getOutput(pidKey) / deltaVelocity;
motorControl.setPowerLevel(output);
// log.debug(String.format("setPoint(%s), processVariable(%s),
// output(%s)", setPoint, processVariable, output));
if (output != lastOutput) {
motorControl.move(output);
lastOutput = output;
if (isMoving()) {
// tolerance
if (currentPosInput == lastCurrentPosInput && Math.abs(targetPos - getCurrentPosOutput()) <= targetPosAngleTolerence) {
nbSamePosInputSinceX += 1;
} else {
nbSamePosInputSinceX = 0;
}
// ok targetPos is reached ( with tolerance )
if (nbSamePosInputSinceX >= 3 || getCurrentPosOutput() == targetPos) {
onServoEvent(SERVO_EVENT_STOPPED, getCurrentPosOutput());
} else {
if (getCurrentPosOutput() != targetPos) {
onServoEvent(SERVO_EVENT_POSITION_UPDATE, getCurrentPosOutput());
}
}
}
}
}
lastCurrentPosInput = currentPosInput;
Thread.sleep(1000 / sampleTime);
}
}
} catch (Exception e) {
if (e instanceof InterruptedException) {
// info("Shutting down MotorUpdater");
} else {
log.error("motor updater threw", e);
}
}
}
}
public class EncoderUpdater extends Thread {
public EncoderUpdater(String name) {
super(String.format("%s.encoderUpdater", name));
}
public void run() {
// here we want to poll the encoder control to keep our "currentPosition" value up to date..
// effectively this replaces onPin ...
while (true) {
currentPosInput = ((AbstractEncoder)encoderControl).lastPosition;
try {
// someting to keep the cpu from thrashing.
pid.setInput(pidKey, currentPosInput);
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO: clean this up.
e.printStackTrace();
break;
}
}
}
}
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(DiyServo.class);
/**
* controls low level methods of the motor
*/
transient MotorControl motorControl;
public String motorControlName = "motor";
/**
* Reference to the Analog input service
*/
public List<String> pinArrayControls;
/**
* // Handle to the selected analog input service and it's name
*/
transient PinArrayControl pinArrayControl;
public String pinControlName;
transient EncoderControl encoderControl;
/**
* List of available pins on the analog input service
*/
public List<Integer> pinList = new ArrayList<Integer>();
public Integer pin;
/**
* mapper to be able to remap input values
*/
Mapper mapper;
Double rest = 90.0;
long lastActivityTime = 0;
double currentVelocity = 0;
/**
* the requested INPUT position of the servo
*/
Double targetPos;
/**
* the calculated output for the servo
*/
double targetOutput;
/**
* Round pos values based on this digit count useful later to compare
* target>pos
*/
int roundPos = 0;
/**
* list of names of possible controllers
*/
public List<String> controllers;
// FIXME - currently is only computer control - needs to be either
// microcontroller or computer
boolean isSweeping = false;
double sweepMin = 0.0;
double sweepMax = 180.0;
int sweepDelay = 1;
double sweepStep = 1.0;
boolean sweepOneWay = false;
double lastPos;
transient Thread sweeper = null;
/**
* feedback of both incremental position and stops. would allow blocking
* moveTo if desired
*/
boolean isEventsEnabled = false;
private double maxVelocity = -1;
private boolean isAttached = false;
private boolean isControllerSet = false;
private boolean isPinArrayControlSet = false;
// Initial parameters for PID.
static final public int MODE_AUTOMATIC = 1;
static final public int MODE_MANUAL = 0;
public int mode = MODE_MANUAL;
public Pid pid;
private String pidKey;
private double kp = 0.020;
private double ki = 0.001; // 0.020;
private double kd = 0.0; // 0.020;
public double setPoint = 90.0; // Intial
// setpoint
// corresponding
// centered
// servo
// The
// pinListener
// value
// depends
// the
// hardwawe
// behind
// the
// value
// from
// the
/**
* AD converter needs to be remapped to 0 - 180. D1024 is the default for the
* Arduino
*/
double resolution = 1024;
/**
* Sample time 20 ms = 50 Hz
*/
int sampleTime = 20;
transient MotorUpdater motorUpdater = null;
transient EncoderUpdater encoderUpdater = null;
double powerLevel = 0;
double maxPower = 1.0;
double minPower = -1.0;
Mapper powerMap = new Mapper(-1.0, 1.0, -255.0, 255.0);
public String disableDelayIfVelocity;
public String defaultDisableDelayNoVelocity;
Double currentPosInput = 0.0;
double deltaVelocity = 1;
private boolean moving = false;
private boolean autoDisable;
private boolean overrideAutoDisable = false;
private transient Timer autoDisableTimer;
transient Object moveToBlocked = new Object();
/**
* disableDelayGrace : a timer is launched after targetpos reached
*
* @param disableDelayGrace
* - milliSeconds
* @default - 1000
*/
public int disableDelayGrace = 1000;
public transient static final int SERVO_EVENT_STOPPED = 1;
public transient static final int SERVO_EVENT_POSITION_UPDATE = 2;
/**
* Constructor
*
* @param n
* name of the service
*/
public DiyServo(String n) {
super(n);
refreshPinArrayControls();
motorControl = (MotorControl) createPeer("motor", "MotorDualPwm");
initPid();
subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered");
lastActivityTime = System.currentTimeMillis();
this.addServoEventListener(this);
}
/*
* Update the list of PinArrayControls
*/
public void onRegistered(ServiceInterface s) {
refreshPinArrayControls();
broadcastState();
}
/**
* Initiate the PID controller
*/
void initPid() {
pid = (Pid) createPeer("pid");
pidKey = this.getName();
pid.setPID(pidKey, kp, ki, kd); // Create a PID with the name of this
// service instance
pid.setMode(pidKey, MODE_AUTOMATIC); // Initial mode is manual
pid.setOutputRange(pidKey, -1.0, 1.0); // Set the Output range to match
// the
// Motor input
pid.setSampleTime(pidKey, sampleTime); // Sets the sample time
pid.setSetpoint(pidKey, setPoint);
pid.startService();
}
@Override
public void addServoEventListener(NameProvider service) {
addListener("publishServoEvent", service.getName(), "onServoEvent");
}
/**
* Re-attach to servo's current pin. The pin must have be set previously.
* Equivalent to Arduino's Servo.attach(currentPin) In this service it stops
* the motor and PID is set to manual mode
*/
@Override
public void attach() {
attach(pin);
broadcastState();
}
/**
* Equivalent to Arduino's Servo.attach(pin). It energizes the servo sending
* pulses to maintain its current position.
*/
@Override
public void attach(int pin) {
// TODO Activate the motor and PID
lastActivityTime = System.currentTimeMillis();
isAttached = true;
broadcastState();
}
/**
* Equivalent to Arduino's Servo.detach() it de-energizes the servo
*/
@Override
// TODO DeActivate the motor and PID
public void detach() {
if (motorControl != null) {
motorControl.stop();
}
isAttached = false;
broadcastState();
}
/*
* Method to check if events are enabled or not
*/
public boolean eventsEnabled(boolean b) {
isEventsEnabled = b;
broadcastState();
return b;
}
public long getLastActivityTime() {
return lastActivityTime;
}
public double getMax() {
return mapper.getMaxX();
}
public double getPos() {
if (targetPos == null) {
return rest;
} else {
return MathUtils.round(targetPos, roundPos);
}
}
public double getRest() {
return rest;
}
// FIXME - change to enabled()
public boolean isAttached() {
return isAttached;
}
public boolean isControllerSet() {
return isControllerSet;
}
public boolean isPinArrayControlSet() {
return isPinArrayControlSet;
}
public boolean isInverted() {
return mapper.isInverted();
}
public void map(double minX, double maxX, double minY, double maxY) {
if (mapper == null) {
mapper = new Mapper(0, 180, 0, 180);
}
if (minX != mapper.getMinX() || maxX != mapper.getMaxX() || minY != mapper.getMinY() || maxY != mapper.getMaxY()) {
mapper = new Mapper(minX, maxX, minY, maxY);
broadcastState();
}
}
/**
* The most important method, that tells the servo what position it should
* move to
*/
public void moveTo(double pos) {
synchronized (moveToBlocked) {
moveToBlocked.notify(); // Will wake up MoveToBlocked.wait()
}
deltaVelocity = 1;
double lastPosInput = mapper.calcInput(lastPos);
if (motorControl == null) {
error(String.format("%s's controller is not set", getName()));
return;
}
if (!isEnabled()) {
if (pos != lastPosInput || overrideAutoDisable || !getAutoDisable()) {
enable();
}
}
if (lastPosInput != pos) {
moving = true;
if (motorUpdater == null) {
// log.info("Starting MotorUpdater");
motorUpdater = new MotorUpdater(getName());
motorUpdater.start();
// log.info("MotorUpdater started");
}
if (encoderUpdater == null) {
encoderUpdater = new EncoderUpdater(getName());
encoderUpdater.start();
}
}
targetPos = pos;
targetOutput = getTargetOutput();
pid.setSetpoint(pidKey, targetOutput);
lastActivityTime = System.currentTimeMillis();
// if (isEventsEnabled) {
// update others of our position change
invoke("publishServoEvent", targetOutput);
broadcastState();
}
/*
* basic move command of the servo - usually is 0 - 180 valid range but can be
* adjusted and / or re-mapped with min / max and map commands
*
* TODO - moveToBlocking - blocks until servo sends "ARRIVED_TO_POSITION"
* response
*/
// uber good
public Double publishServoEvent(Double position) {
return position;
}
public List<String> refreshPinArrayControls() {
pinArrayControls = Runtime.getServiceNamesFromInterface(PinArrayControl.class);
return pinArrayControls;
}
@Override
public void releaseService() {
// FYI - super.releaseService() calls detach
// detach();
if (motorUpdater != null) {
// shutting down motor updater thread
motorUpdater.interrupt();
}
super.releaseService();
}
@Override
public void startService() {
super.startService();
if (mapper == null) {
mapper = new Mapper(0, 180, 0, 180);
}
}
public void rest() {
moveTo(rest);
}
public void setInverted(boolean invert) {
mapper.setInverted(invert);
motorControl.setInverted(invert);
broadcastState();
}
@Override
public void setMinMax(double min, double max) {
map(min, max, min, max);
}
public void setRest(double rest) {
this.rest = rest;
}
public void setSweepDelay(int delay) {
sweepDelay = delay;
}
/*
* (non-Javadoc)
*
* @see org.myrobotlab.service.interfaces.ServoControl#stopServo()
*/
@Override
public void stop() {
isSweeping = false;
sweeper = null;
// TODO Replace with internal logic for motor and PID
// getController().servoSweepStop(this);
broadcastState();
}
public void sweep() {
double min = mapper.getMinX();
double max = mapper.getMaxX();
sweep(min, max, 50, 1.0);
}
public void sweep(double min, double max) {
sweep(min, max, 1, 1.0);
}
// FIXME - is it really speed control - you don't currently thread for
// fractional speed values
public void sweep(double min, double max, int delay, double step) {
sweep(min, max, delay, step, false);
}
public void sweep(double min, double max, int delay, double step, boolean oneWay) {
this.sweepMin = min;
this.sweepMax = max;
this.sweepDelay = delay;
this.sweepStep = step;
this.sweepOneWay = oneWay;
if (isSweeping) {
stop();
}
sweeper = new Sweeper(getName());
sweeper.start();
isSweeping = true;
broadcastState();
}
/**
* Writes a value in microseconds (uS) to the servo, controlling the shaft
* accordingly. On a standard servo, this will set the angle of the shaft. On
* standard servos a parameter value of 1000 is fully counter-clockwise, 2000
* is fully clockwise, and 1500 is in the middle.
*
* Note that some manufactures do not follow this standard very closely so
* that servos often respond to values between 700 and 2300. Feel free to
* increase these endpoints until the servo no longer continues to increase
* its range. Note however that attempting to drive a servo past its endpoints
* (often indicated by a growling sound) is a high-current state, and should
* be avoided.
*
* Continuous-rotation servos will respond to the writeMicrosecond function in
* an analogous manner to the write function.
*
* @param uS
* - the microseconds value
*/
public void writeMicroseconds(Integer uS) {
// log.info("writeMicroseconds({})", uS);
// TODO. This need to be remapped to Motor and PID internal to this
// Service
// getController().servoWriteMicroseconds(this, uS);
lastActivityTime = System.currentTimeMillis();
broadcastState();
}
/*
* @Override public void setPin(int pin) { this.pin = pin; }
*/
@Override
public Integer getPin() {
return this.pin;
}
@Override
public double getMin() {
return mapper.getMinX();
}
@Override
public double getTargetOutput() {
if (targetPos == null) {
targetPos = rest;
}
targetOutput = mapper.calcOutput(targetPos);
return targetOutput;
}
/*
* public void attach(String controllerName) throws Exception {
* attach((MotorController) Runtime.getService(controllerName)); }
*/
@Override
public void detach(String controllerName) {
ServiceInterface si = Runtime.getService(controllerName);
if (si instanceof PinArrayControl) {
detach((PinArrayControl) Runtime.getService(controllerName));
}
}
public void detach(PinArrayControl pinArrayControl) {
if (this.pinArrayControl == pinArrayControl) {
this.pinArrayControl = null;
isPinArrayControlSet = false;
broadcastState();
}
}
public void setMaxVelocity(double velocity) {
this.maxVelocity = velocity;
broadcastState();
}
@Override
public double getMaxVelocity() {
return maxVelocity;
}
@Override
public void onPin(PinData pindata) {
int inputValue = pindata.value;
currentPosInput = 180 * inputValue / resolution;
// log.debug(String.format("onPin received value %s converted to
// %s",inputValue, processVariable));
// we need to read here real angle / seconds
// before try to control velocity
currentVelocity = MathUtils.round(Math.abs(((currentPosInput - lastPos) * (500 / sampleTime))), roundPos);
// log.info("currentPosInput : " + currentPosInput);
// info(currentVelocity + " " + currentPosInput);
pid.setInput(pidKey, currentPosInput);
// offline feedback ! if diy servo is disabled
// useful to "learn" gestures ( later ... ) or simply start a moveTo() at
// real lastPos & sync with UI
if (!isEnabled() && MathUtils.round(lastPos, roundPos) != MathUtils.round(currentPosInput, roundPos)) {
targetPos = mapper.calcInput(lastPos);
broadcastState();
}
lastPos = currentPosInput;
}
public void attach(EncoderControl encoder) {
// TODO: do i need anything else?
this.encoderControl = encoder;
}
public void attach(String pinArrayControlName, Integer pin) throws Exception {
// myServo = (DiyServo) Runtime.getService(boundServiceName);
attach((PinArrayControl) Runtime.getService(pinArrayControlName), (int) pin);
}
public void attach(PinArrayControl pinArrayControl, int pin) throws Exception {
this.pinArrayControl = pinArrayControl;
if (pinArrayControl != null) {
pinControlName = pinArrayControl.getName();
isPinArrayControlSet = true;
this.pin = pin;
}
// TODO The resolution is a property of the AD converter and should be
// fetched thru a method call like controller.getADResolution()
if (pinArrayControl instanceof Arduino) {
resolution = 1024;
}
if (pinArrayControl instanceof Ads1115) {
resolution = 65536;
}
// log.debug(String.format("Detected %s %s. Setting AD resolution to
// %s",pinArrayControl.getClass(), pinArrayControl.getName(),resolution));
int rate = 1000 / sampleTime;
pinArrayControl.attach(this, pin);
pinArrayControl.enablePin(pin, rate);
broadcastState();
}
public void setPowerLevel(double power) {
this.powerLevel = power;
}
/**
* // A bunch of unimplemented methods from ServoControl. // Perhaps I should
* create a new // DiyServoControl interface. // I was hoping to be able to
* avoid that, but might be a better solution
*/
@Override
@Deprecated
public void setSpeed(double speed) {
log.error("speed is depreciated, use setVelocity instead");
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(DiyServo.class.getCanonicalName());
meta.addDescription("Controls a motor so that it can be used as a Servo");
meta.addCategory("control", "servo");
meta.addPeer("motor", "MotorDualPwm", "MotorControl service");
meta.addPeer("pid", "Pid", "PID service");
return meta;
}
@Override
public void setPin(int pin) {
// This method should never be used in DiyServo since it's a method specific
// to the Servo service
}
@Override
public double getAcceleration() {
return 1.0;
}
@Override
public void setVelocity(double velocity) {
warn("TODO !");
}
@Override
public double getVelocity() {
// TODO Auto-generated method stub
return 0;
}
@Override
public double getMinInput() {
return mapper.getMinInput();
}
@Override
public double getMaxInput() {
return mapper.getMaxInput();
}
@Override
public void addIKServoEventListener(NameProvider service) {
// TODO Auto-generated method stub
}
@Override
public void sync(ServoControl sc) {
// TODO Auto-generated method stub
}
// None of the methods below can or should be implemented in DiyServo
// DiyServo uses a Motor peer
@Override
public void attachServoController(ServoController controller) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void detachServoController(ServoController controller) throws Exception {
// TODO Auto-generated method stub
}
@Override
public boolean isAttachedServoController(ServoController controller) {
// TODO Auto-generated method stub
return false;
}
@Override
public void attach(ServoController controller, int pin) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void attach(ServoController controller, int pin, double pos) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void attach(ServoController controller, int pin, double pos, double speed) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void setAutoDisable(boolean autoDisable) {
this.autoDisable = autoDisable;
}
@Override
public boolean getAutoDisable() {
return this.autoDisable;
}
@Override
public boolean moveToBlocking(double pos) {
targetPos = pos;
this.moveTo(pos);
// breakMoveToBlocking=false;
waitTargetPos();
return true;
}
@Override
public void setOverrideAutoDisable(boolean overrideAutoDisable) {
// TODO Auto-generated method stub
}
@Override
public void waitTargetPos() {
if (isMoving()) {
synchronized (moveToBlocked) {
try {
// Will block until moveToBlocked.notify() is called on another
// thread.
log.info("servo {} moveToBlocked was initiate", getName());
moveToBlocked.wait(15000);// 30s timeout security delay
} catch (InterruptedException e) {
log.info("servo {} moveToBlocked was interrupted", getName());
}
}
}
}
@Override
public void onServoEvent(Integer eventType, double currentPos) {
if (eventType == SERVO_EVENT_STOPPED) {
moving = false;
} else {
moving = true;
}
onServoEvent(currentPos);
}
public void onServoEvent(double currentPos) {
if (!isMoving() && isEnabled()) {
delayDisable();
}
}
private void delayDisable() {
if (!isMoving()) {
log.info("AutoDisable called");
if (autoDisable) {
if (autoDisableTimer != null) {
autoDisableTimer.cancel();
autoDisableTimer = null;
}
autoDisableTimer = new Timer();
autoDisableTimer.schedule(new TimerTask() {
@Override
public void run() {
if (!overrideAutoDisable && !isMoving()) {
disable();
targetPos = getCurrentPosOutput();
}
synchronized (moveToBlocked) {
moveToBlocked.notify(); // Will wake up MoveToBlocked.wait()
}
}
}, (long) disableDelayGrace);
} else {
synchronized (moveToBlocked) {
moveToBlocked.notify(); // Will wake up MoveToBlocked.wait()
}
targetPos = getCurrentPosOutput();
}
}
broadcastState();
}
/**
* getCurrentPos() - return the calculated position of the servo use
* lastActivityTime and velocity for the computation
*
* @return the current position of the servo
*/
public Double getCurrentPos() {
return MathUtils.round(currentPosInput, roundPos);
}
@Override
public double getCurrentPosOutput() {
return MathUtils.round(mapper.calcInput(getCurrentPos()), roundPos);
}
public double getMinOutput() {
return mapper.getMinOutput();
}
public double getMaxOutput() {
return mapper.getMaxOutput();
}
public boolean isEnabled() {
return !motorControl.isLocked();
}
public boolean isSweeping() {
return isSweeping;
}
public boolean isEventsEnabled() {
// TODO Auto-generated method stub
return false;
}
/**
* getCurrentVelocity() - return Current velocity ( realtime / based on
* frequency)
*
* @return degrees / second
*/
public double getCurrentVelocity() {
return currentVelocity;
}
public boolean isMoving() {
return moving;
}
public void setDisableDelayGrace(int disableDelayGrace) {
this.disableDelayGrace = disableDelayGrace;
}
@Override
public void enable() {
motorControl.unlock();
if (motorUpdater == null) {
motorUpdater = new MotorUpdater(getName());
}
if (!motorUpdater.isAlive()) {
motorUpdater.start();
}
broadcastState();
}
@Override
public void disable() {
motorControl.stopAndLock();
if (motorUpdater != null) {
motorUpdater.interrupt();
motorUpdater = null;
}
broadcastState();
}
@Override
public void stopService() {
super.stopService();
disable();
}
@Override
public String getControllerName() {
// TODO Auto-generated method stub
return null;
}
public static void main(String[] args) throws InterruptedException {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
try {
// Runtime.start("webgui", "WebGui");
Runtime.start("gui", "SwingGui");
// VirtualArduino virtual = (VirtualArduino) Runtime.start("virtual", "VirtualArduino");
// virtual.connect("COM3");
// boolean done = false;
// if (done) {
// return;
String port = "COM4";
Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
// arduino.setBoardUno();
arduino.connect(port);
// Adafruit16CServoDriver adafruit16CServoDriver =
// (Adafruit16CServoDriver) Runtime.start("adafruit16CServoDriver",
// "Adafruit16CServoDriver");
// adafruit16CServoDriver.attach(arduino,"1","0x40");
// Ads1115 ads = (Ads1115) Runtime.start("ads", "Ads1115");
// ads.attach(arduino,"2","0x40");
MotorDualPwm motor = (MotorDualPwm) Runtime.start("diyServo.motor", "MotorDualPwm");
int leftPwmPin = 6;
int rightPwmPin = 7;
motor.setPwmPins(leftPwmPin, rightPwmPin);
motor.attach(arduino);
Thread.sleep(1000);
// let's start the encoder!!
Amt203Encoder encoder = new Amt203Encoder("encoder");
encoder.pin = 3;
arduino.attach(encoder);
Thread.sleep(1000);
// Ads1115 ads = (Ads1115) Runtime.start("Ads1115", "Ads1115");
// ads.setController(arduino, "1", "0x48");
DiyServo diyServo = (DiyServo) Runtime.create("diyServo", "DiyServo");
Python python = (Python) Runtime.start("python", "Python");
// diyServo.attachServoController((ServoController)arduino);
// diyServo.attach((ServoController)arduino);
// diyServo.map(0, 180, 60, 175);
diyServo = (DiyServo) Runtime.start("diyServo", "DiyServo");
diyServo.pid.setPID("diyServo", 1.0, 0.2, 0.1);
// diyServo.pid.setOutputRange("diyServo", 1, -1);
// diyServo.pid.setOutput("diyS, Output);
// diyServo.attach((PinArrayControl) arduino, 14); // PIN 14 = A0
// diyServo.setInverted(true);
diyServo.attach(encoder);
diyServo.setMaxVelocity(-1);
// diyServo.setAutoDisable(true);
// diyServo.setMaxVelocity(10);
// diyServo.moveToBlocking(0);
// diyServo.moveToBlocking(180);
// diyServo.setMaxVelocity(-1);
// diyServo.moveTo(0);
// Servo Servo = (Servo) Runtime.start("Servo", "Servo");
// servo.test();
} catch (Exception e) {
Logging.logError(e);
}
}
} |
package hudson.model;
import hudson.Launcher;
import hudson.Proc.LocalProc;
import hudson.Util;
import hudson.tasks.Fingerprinter.FingerprintAction;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.maven.MavenBuild;
import static hudson.model.Hudson.isWindows;
import hudson.model.listeners.SCMListener;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.Fingerprint.BuildPtr;
import hudson.scm.CVSChangeLogParser;
import hudson.scm.ChangeLogParser;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.SCM;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.xml.sax.SAXException;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
/**
* Base implementation of {@link Run}s that build software.
*
* For now this is primarily the common part of {@link Build} and {@link MavenBuild}.
*
* @author Kohsuke Kawaguchi
* @see AbstractProject
*/
public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Run<P,R> implements Runnable {
/**
* PluginName of the slave this project was built on.
* Null or "" if built by the master. (null happens when we read old record that didn't have this information.)
*/
private String builtOn;
/**
* SCM used for this build.
* Maybe null, for historical reason, in which case CVS is assumed.
*/
private ChangeLogParser scm;
/**
* Changes in this build.
*/
private volatile transient ChangeLogSet<? extends Entry> changeSet;
protected AbstractBuild(P job) throws IOException {
super(job);
}
protected AbstractBuild(P job, Calendar timestamp) {
super(job, timestamp);
}
protected AbstractBuild(P project, File buildDir) throws IOException {
super(project, buildDir);
}
public final P getProject() {
return getParent();
}
/**
* Returns a {@link Slave} on which this build was done.
*/
public Node getBuiltOn() {
if(builtOn==null)
return Hudson.getInstance();
else
return Hudson.getInstance().getSlave(builtOn);
}
/**
* Returns the name of the slave it was built on, or null if it was the master.
*/
public String getBuiltOnStr() {
return builtOn;
}
protected abstract class AbstractRunner implements Runner {
/**
* Since configuration can be changed while a build is in progress,
* stick to one launcher and use it.
*/
protected Launcher launcher;
/**
* Returns the current {@link Node} on which we are buildling.
*/
protected final Node getCurrentNode() {
return Executor.currentExecutor().getOwner().getNode();
}
public Result run(BuildListener listener) throws Exception {
Node node = Executor.currentExecutor().getOwner().getNode();
assert builtOn==null;
builtOn = node.getNodeName();
launcher = node.createLauncher(listener);
if(node instanceof Slave)
listener.getLogger().println("Building remotely on "+node.getNodeName());
if(checkout(listener))
return Result.FAILURE;
Result result = doRun(listener);
if(result!=null)
return result; // abort here
if(getResult()==null || getResult()==Result.SUCCESS)
createLastSuccessfulLink(listener);
return Result.SUCCESS;
}
private void createLastSuccessfulLink(BuildListener listener) {
if(!isWindows()) {
try {
// ignore a failure.
new LocalProc(new String[]{"rm","-f","../lastSuccessful"},new String[0],listener.getLogger(),getProject().getBuildDir()).join();
int r = new LocalProc(new String[]{
"ln","-s","builds/"+getId()/*ugly*/,"../lastSuccessful"},
new String[0],listener.getLogger(),getProject().getBuildDir()).join();
if(r!=0)
listener.getLogger().println("ln failed: "+r);
} catch (IOException e) {
PrintStream log = listener.getLogger();
log.println("ln failed");
Util.displayIOException(e,listener);
e.printStackTrace( log );
}
}
}
private boolean checkout(BuildListener listener) throws Exception {
if(!project.checkout(AbstractBuild.this,launcher,listener,new File(getRootDir(),"changelog.xml")))
return true;
SCM scm = project.getScm();
AbstractBuild.this.scm = scm.createChangeLogParser();
AbstractBuild.this.changeSet = AbstractBuild.this.calcChangeSet();
for (SCMListener l : Hudson.getInstance().getSCMListeners())
l.onChangeLogParsed(AbstractBuild.this,listener,changeSet);
return false;
}
/**
* The portion of a build that is specific to a subclass of {@link AbstractBuild}
* goes here.
*
* @return
* null to continue the build normally (that means the doRun method
* itself run successfully)
* Return a non-null value to abort the build right there with the specified result code.
*/
protected abstract Result doRun(BuildListener listener) throws Exception;
}
/**
* Gets the changes incorporated into this build.
*
* @return never null.
*/
public ChangeLogSet<? extends Entry> getChangeSet() {
if(scm==null)
scm = new CVSChangeLogParser();
if(changeSet==null) // cached value
changeSet = calcChangeSet();
return changeSet;
}
/**
* Returns true if the changelog is already computed.
*/
public boolean hasChangeSetComputed() {
File changelogFile = new File(getRootDir(), "changelog.xml");
return changelogFile.exists();
}
private ChangeLogSet<? extends Entry> calcChangeSet() {
File changelogFile = new File(getRootDir(), "changelog.xml");
if(!changelogFile.exists())
return ChangeLogSet.createEmpty(this);
try {
return scm.parse(this,changelogFile);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return ChangeLogSet.createEmpty(this);
}
@Override
public Map<String,String> getEnvVars() {
Map<String,String> env = super.getEnvVars();
JDK jdk = project.getJDK();
if(jdk !=null)
jdk.buildEnvVars(env);
project.getScm().buildEnvVars(env);
return env;
}
public Calendar due() {
return timestamp;
}
/**
* Gets {@link AbstractTestResultAction} associated with this build if any.
* <p>
*/
public abstract AbstractTestResultAction getTestResultAction();
/**
* Invoked by {@link Executor} to performs a build.
*/
public abstract void run();
// fingerprint related stuff
@Override
public String getWhyKeepLog() {
// if any of the downstream project is configured with 'keep dependency component',
// we need to keep this log
for (Map.Entry<AbstractProject, RangeSet> e : getDownstreamBuilds().entrySet()) {
AbstractProject<?,?> p = e.getKey();
if(!p.isKeepDependencies()) continue;
// is there any active build that depends on us?
for (AbstractBuild build : p.getBuilds()) {
if(e.getValue().includes(build.getNumber()))
return "kept because of "+build;
}
}
return super.getWhyKeepLog();
}
/**
* Gets the dependency relationship from this build (as the source)
* and that project (as the sink.)
*
* @return
* range of build numbers that represent which downstream builds are using this build.
* The range will be empty if no build of that project matches this.
*/
public RangeSet getDownstreamRelationship(AbstractProject that) {
RangeSet rs = new RangeSet();
FingerprintAction f = getAction(FingerprintAction.class);
if(f==null) return rs;
// look for fingerprints that point to this build as the source, and merge them all
for (Fingerprint e : f.getFingerprints().values()) {
BuildPtr o = e.getOriginal();
if(o!=null && o.is(this))
rs.add(e.getRangeSet(that));
}
return rs;
}
/**
* Gets the dependency relationship from this build (as the sink)
* and that project (as the source.)
*
* @return
* Build number of the upstream build that feed into this build,
* or -1 if no record is available.
*/
public int getUpstreamRelationship(AbstractProject that) {
FingerprintAction f = getAction(FingerprintAction.class);
if(f==null) return -1;
int n = -1;
// look for fingerprints that point to the given project as the source, and merge them all
for (Fingerprint e : f.getFingerprints().values()) {
BuildPtr o = e.getOriginal();
if(o!=null && o.is(that))
n = Math.max(n,o.getNumber());
}
return n;
}
/**
* Gets the downstream builds of this build, which are the builds of the
* downstream projects that use artifacts of this build.
*
* @return
* For each project with fingerprinting enabled, returns the range
* of builds (which can be empty if no build uses the artifact from this build.)
*/
public Map<AbstractProject,RangeSet> getDownstreamBuilds() {
Map<AbstractProject,RangeSet> r = new HashMap<AbstractProject,RangeSet>();
for (AbstractProject p : getParent().getDownstreamProjects()) {
if(p.isFingerprintConfigured())
r.put(p,getDownstreamRelationship(p));
}
return r;
}
/**
* Gets the upstream builds of this build, which are the builds of the
* upstream projects whose artifacts feed into this build.
*/
public Map<AbstractProject,Integer> getUpstreamBuilds() {
Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
for (AbstractProject p : getParent().getUpstreamProjects()) {
int n = getUpstreamRelationship(p);
if(n>=0)
r.put(p,n);
}
return r;
}
/**
* Gets the changes in the dependency between the given build and this build.
*/
public Map<AbstractProject,DependencyChange> getDependencyChanges(AbstractBuild from) {
if(from==null) return Collections.emptyMap(); // make it easy to call this from views
FingerprintAction n = this.getAction(FingerprintAction.class);
FingerprintAction o = from.getAction(FingerprintAction.class);
if(n==null || o==null) return Collections.emptyMap();
Map<AbstractProject,Integer> ndep = n.getDependencies();
Map<AbstractProject,Integer> odep = o.getDependencies();
Map<AbstractProject,DependencyChange> r = new HashMap<AbstractProject,DependencyChange>();
for (Map.Entry<AbstractProject,Integer> entry : odep.entrySet()) {
AbstractProject p = entry.getKey();
Integer oldNumber = entry.getValue();
Integer newNumber = ndep.get(p);
if(newNumber!=null && oldNumber.compareTo(newNumber)<0) {
r.put(p,new DependencyChange(p,oldNumber,newNumber));
}
}
return r;
}
/**
* Represents a change in the dependency.
*/
public static final class DependencyChange {
/**
* The dependency project.
*/
public final AbstractProject project;
/**
* Version of the dependency project used in the previous build.
*/
public final int fromId;
/**
* {@link Build} object for {@link #fromId}. Can be null if the log is gone.
*/
public final AbstractBuild from;
/**
* Version of the dependency project used in this build.
*/
public final int toId;
public final AbstractBuild to;
public DependencyChange(AbstractProject<?,?> project, int fromId, int toId) {
this.project = project;
this.fromId = fromId;
this.toId = toId;
this.from = project.getBuildByNumber(fromId);
this.to = project.getBuildByNumber(toId);
}
}
// web methods
/**
* Stops this build if it's still going.
*
* If we use this/executor/stop URL, it causes 404 if the build is already killed,
* as {@link #getExecutor()} returns null.
*/
public synchronized void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
Executor e = getExecutor();
if(e!=null)
e.doStop(req,rsp);
else
// nothing is building
rsp.forwardToPreviousPage(req);
}
} |
package hudson.tasks;
import com.google.common.collect.ImmutableMap;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.Util;
import hudson.matrix.MatrixConfiguration;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.DependecyDeclarer;
import hudson.model.DependencyGraph;
import hudson.model.DependencyGraph.Dependency;
import hudson.model.Fingerprint;
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.FingerprintMap;
import jenkins.model.Jenkins;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.RunAction;
import hudson.model.TaskListener;
import hudson.remoting.VirtualChannel;
import hudson.util.FormValidation;
import hudson.util.IOException2;
import hudson.util.PackedMap;
import hudson.util.RunList;
import net.sf.json.JSONObject;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Records fingerprints of the specified files.
*
* @author Kohsuke Kawaguchi
*/
public class Fingerprinter extends Recorder implements Serializable, DependecyDeclarer {
public static boolean enableFingerprintsInDependencyGraph = Boolean.parseBoolean(System.getProperty(Fingerprinter.class.getName() + ".enableFingerprintsInDependencyGraph", "false"));
/**
* Comma-separated list of files/directories to be fingerprinted.
*/
private final String targets;
/**
* Also record all the finger prints of the build artifacts.
*/
private final boolean recordBuildArtifacts;
@DataBoundConstructor
public Fingerprinter(String targets, boolean recordBuildArtifacts) {
this.targets = targets;
this.recordBuildArtifacts = recordBuildArtifacts;
}
public String getTargets() {
return targets;
}
public boolean getRecordBuildArtifacts() {
return recordBuildArtifacts;
}
@Override
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException {
try {
listener.getLogger().println(Messages.Fingerprinter_Recording());
Map<String,String> record = new HashMap<String,String>();
EnvVars environment = build.getEnvironment(listener);
if(targets.length()!=0) {
String expandedTargets = environment.expand(targets);
record(build, listener, record, expandedTargets);
}
if(recordBuildArtifacts) {
ArtifactArchiver aa = build.getProject().getPublishersList().get(ArtifactArchiver.class);
if(aa==null) {
// configuration error
listener.error(Messages.Fingerprinter_NoArchiving());
build.setResult(Result.FAILURE);
return true;
}
String expandedArtifacts = environment.expand(aa.getArtifacts());
record(build, listener, record, expandedArtifacts);
}
build.getActions().add(new FingerprintAction(build,record));
if (enableFingerprintsInDependencyGraph) {
Jenkins.getInstance().rebuildDependencyGraph();
}
} catch (IOException e) {
e.printStackTrace(listener.error(Messages.Fingerprinter_Failed()));
build.setResult(Result.FAILURE);
}
// failing to record fingerprints is an error but not fatal
return true;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) {
if (enableFingerprintsInDependencyGraph) {
RunList builds = owner.getBuilds();
Set<String> seenUpstreamProjects = new HashSet<String>();
for ( ListIterator iter = builds.listIterator(); iter.hasNext(); ) {
Run build = (Run) iter.next();
List<FingerprintAction> fingerprints = build.getActions(FingerprintAction.class);
for (FingerprintAction action : fingerprints) {
Map<AbstractProject,Integer> deps = action.getDependencies();
for (AbstractProject key : deps.keySet()) {
if (key == owner) {
continue; // Avoid self references
}
AbstractProject p = key;
if (key instanceof MatrixConfiguration) {
p = key.getRootProject();
}
if (seenUpstreamProjects.contains(p.getName())) {
continue;
}
seenUpstreamProjects.add(p.getName());
graph.addDependency(new Dependency(p, owner) {
@Override
public boolean shouldTriggerBuild(AbstractBuild build,
TaskListener listener,
List<Action> actions) {
// Fingerprints should not trigger builds.
return false;
}
});
}
}
}
}
}
private void record(AbstractBuild<?,?> build, BuildListener listener, Map<String,String> record, final String targets) throws IOException, InterruptedException {
final class Record implements Serializable {
final boolean produced;
final String relativePath;
final String fileName;
final String md5sum;
public Record(boolean produced, String relativePath, String fileName, String md5sum) {
this.produced = produced;
this.relativePath = relativePath;
this.fileName = fileName;
this.md5sum = md5sum;
}
Fingerprint addRecord(AbstractBuild build) throws IOException {
FingerprintMap map = Jenkins.getInstance().getFingerprintMap();
return map.getOrCreate(produced?build:null, fileName, md5sum);
}
private static final long serialVersionUID = 1L;
}
final long buildTimestamp = build.getTimeInMillis();
FilePath ws = build.getWorkspace();
if(ws==null) {
listener.error(Messages.Fingerprinter_NoWorkspace());
build.setResult(Result.FAILURE);
return;
}
List<Record> records = ws.act(new FileCallable<List<Record>>() {
public List<Record> invoke(File baseDir, VirtualChannel channel) throws IOException {
List<Record> results = new ArrayList<Record>();
FileSet src = Util.createFileSet(baseDir,targets);
DirectoryScanner ds = src.getDirectoryScanner();
for( String f : ds.getIncludedFiles() ) {
File file = new File(baseDir,f);
// consider the file to be produced by this build only if the timestamp
// is newer than when the build has started.
// 2000ms is an error margin since since VFAT only retains timestamp at 2sec precision
boolean produced = buildTimestamp <= file.lastModified()+2000;
try {
results.add(new Record(produced,f,file.getName(),new FilePath(file).digest()));
} catch (IOException e) {
throw new IOException2(Messages.Fingerprinter_DigestFailed(file),e);
} catch (InterruptedException e) {
throw new IOException2(Messages.Fingerprinter_Aborted(),e);
}
}
return results;
}
});
for (Record r : records) {
Fingerprint fp = r.addRecord(build);
if(fp==null) {
listener.error(Messages.Fingerprinter_FailedFor(r.relativePath));
continue;
}
fp.add(build);
record.put(r.relativePath,fp.getHashString());
}
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return Messages.Fingerprinter_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/project-config/fingerprint.html";
}
/**
* Performs on-the-fly validation on the file mask wildcard.
*/
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value) throws IOException {
return FilePath.validateFileMask(project.getSomeWorkspace(),value);
}
@Override
public Publisher newInstance(StaplerRequest req, JSONObject formData) {
return req.bindJSON(Fingerprinter.class, formData);
}
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
}
/**
* Action for displaying fingerprints.
*/
public static final class FingerprintAction implements RunAction {
private final AbstractBuild build;
private static final Random rand = new Random();
/**
* From file name to the digest.
*/
private /*almost final*/ PackedMap<String,String> record;
private transient WeakReference<Map<String,Fingerprint>> ref;
public FingerprintAction(AbstractBuild build, Map<String, String> record) {
this.build = build;
this.record = PackedMap.of(record);
onLoad(); // make compact
}
public void add(Map<String,String> moreRecords) {
Map<String,String> r = new HashMap<String, String>(record);
r.putAll(moreRecords);
record = PackedMap.of(r);
ref = null;
onLoad();
}
public String getIconFileName() {
return "fingerprint.png";
}
public String getDisplayName() {
return Messages.Fingerprinter_Action_DisplayName();
}
public String getUrlName() {
return "fingerprints";
}
public AbstractBuild getBuild() {
return build;
}
/**
* Obtains the raw data.
*/
public Map<String,String> getRecords() {
return record;
}
public void onLoad() {
// share data structure with nearby builds, but to keep lazy loading efficient,
// don't go back the history forever. By RAND!=0, 4 neighboring builds will share
// the data structure, so we'll get good enough saving.
if (rand.nextInt(4)!=0) {
Run pb = build.getPreviousBuild();
if (pb!=null) {
FingerprintAction a = pb.getAction(FingerprintAction.class);
if (a!=null)
compact(a);
}
}
}
public void onAttached(Run r) {
}
public void onBuildComplete() {
}
/**
* Reuse string instances from another {@link FingerprintAction} to reduce memory footprint.
*/
protected void compact(FingerprintAction a) {
Map<String,String> intern = new HashMap<String, String>(); // string intern map
for (Entry<String, String> e : a.record.entrySet()) {
intern.put(e.getKey(),e.getKey());
intern.put(e.getValue(),e.getValue());
}
Map<String,String> b = new HashMap<String, String>();
for (Entry<String,String> e : record.entrySet()) {
String k = intern.get(e.getKey());
if (k==null) k = e.getKey();
String v = intern.get(e.getValue());
if (v==null) v = e.getValue();
b.put(k,v);
}
record = PackedMap.of(b);
}
/**
* Map from file names of the fingerprinted file to its fingerprint record.
*/
public synchronized Map<String,Fingerprint> getFingerprints() {
if(ref!=null) {
Map<String,Fingerprint> m = ref.get();
if(m!=null)
return m;
}
Jenkins h = Jenkins.getInstance();
Map<String,Fingerprint> m = new TreeMap<String,Fingerprint>();
for (Entry<String, String> r : record.entrySet()) {
try {
Fingerprint fp = h._getFingerprint(r.getValue());
if(fp!=null)
m.put(r.getKey(), fp);
} catch (IOException e) {
logger.log(Level.WARNING,e.getMessage(),e);
}
}
m = ImmutableMap.copyOf(m);
ref = new WeakReference<Map<String,Fingerprint>>(m);
return m;
}
/**
* Gets the dependency to other existing builds in a map.
*/
public Map<AbstractProject,Integer> getDependencies() {
return getDependencies(false);
}
/**
* Gets the dependency to other builds in a map.
*
* @param includeMissing true if the original build should be included in
* the result, even if it doesn't exist
* @since 1.430
*/
public Map<AbstractProject,Integer> getDependencies(boolean includeMissing) {
Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
for (Fingerprint fp : getFingerprints().values()) {
BuildPtr bp = fp.getOriginal();
if(bp==null) continue; // outside Hudson
if(bp.is(build)) continue; // we are the owner
AbstractProject job = bp.getJob();
if (job==null) continue; // project no longer exists
if (job.getParent()==build.getParent())
continue; // we are the parent of the build owner, that is almost like we are the owner
if(job.getBuildByNumber(bp.getNumber())==null && !includeMissing)
continue; // build no longer exists
Integer existing = r.get(job);
if(existing!=null && existing>bp.getNumber())
continue; // the record in the map is already up to date
r.put(job,bp.getNumber());
}
return r;
}
}
private static final Logger logger = Logger.getLogger(Fingerprinter.class.getName());
private static final long serialVersionUID = 1L;
} |
package com.irccloud.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.Toast;
public class MessageActivityPager extends HorizontalScrollView {
private int startX = 0;
private int buffersDisplayWidth = 0;
private int usersDisplayWidth = 0;
MessageActivity activity = null;
private boolean overrideScrollPos = false;
private long lastKeyEventTime = 0;
public MessageActivityPager(Context context, AttributeSet attrs) {
super(context, attrs);
buffersDisplayWidth = (int)getResources().getDimension(R.dimen.drawer_width);
usersDisplayWidth = (int)getResources().getDimension(R.dimen.userlist_width);
if(!isInEditMode())
activity = (MessageActivity)context;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if(System.currentTimeMillis() - lastKeyEventTime > 100) {
View v = findFocus();
if(v == null || v.getId() != R.id.messageTxt) {
if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if(getScrollX() >= buffersDisplayWidth + usersDisplayWidth)
scrollTo(buffersDisplayWidth, 0);
else {
scrollTo(0,0);
activity.showUpButton(false);
}
} else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
if(getScrollX() >= buffersDisplayWidth)
scrollTo(buffersDisplayWidth + usersDisplayWidth, 0);
else {
scrollTo(buffersDisplayWidth,0);
activity.showUpButton(true);
}
}
lastKeyEventTime = System.currentTimeMillis();
}
}
return super.dispatchKeyEvent(event);
}
@Override
public void scrollTo(int x, int y) {
if(x < buffersDisplayWidth)
super.scrollTo(0, 0);
else if(x > buffersDisplayWidth + usersDisplayWidth / 4)
super.scrollTo(buffersDisplayWidth + usersDisplayWidth, 0);
else
super.scrollTo(buffersDisplayWidth, 0);
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
overrideScrollPos = true;
return super.requestChildRectangleOnScreen(child, rectangle, immediate);
}
@Override
public void computeScroll() {
super.computeScroll();
if(overrideScrollPos) {
super.scrollTo(buffersDisplayWidth, 0);
overrideScrollPos = false;
}
}
@Override
protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if(changed)
scrollTo(buffersDisplayWidth, 0);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(isEnabled()) {
if(event.getAction() == MotionEvent.ACTION_MOVE && startX == 0) {
startX = getScrollX();
}
if(event.getAction() == MotionEvent.ACTION_MOVE) { //Prevent dragging from one drawer to the other
if((startX < buffersDisplayWidth && getScrollX() >= buffersDisplayWidth) ||
(startX >= buffersDisplayWidth + usersDisplayWidth / 4 && getScrollX() <= buffersDisplayWidth))
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP) { //Finger is lifted, snap into place!
if(Math.abs(startX - getScrollX()) > buffersDisplayWidth / 4) { //If they've dragged a drawer more than 25% on screen, snap the drawer onto the screen
if(startX < buffersDisplayWidth + usersDisplayWidth / 4 && getScrollX() < startX) {
smoothScrollTo(0, 0);
activity.showUpButton(false);
if(!activity.getSharedPreferences("prefs", 0).getBoolean("bufferSwipeTip", false)) {
SharedPreferences.Editor editor = activity.getSharedPreferences("prefs", 0).edit();
editor.putBoolean("bufferSwipeTip", true);
editor.commit();
}
} else if(startX >= buffersDisplayWidth && getScrollX() > startX) {
smoothScrollTo(buffersDisplayWidth + usersDisplayWidth, 0);
activity.showUpButton(true);
if(!activity.getSharedPreferences("prefs", 0).getBoolean("userSwipeTip", false)) {
SharedPreferences.Editor editor = activity.getSharedPreferences("prefs", 0).edit();
editor.putBoolean("userSwipeTip", true);
editor.commit();
}
} else {
smoothScrollTo(buffersDisplayWidth, 0);
activity.showUpButton(true);
}
} else { //Snap back
if(startX < buffersDisplayWidth)
smoothScrollTo(0, 0);
else if(startX > buffersDisplayWidth + usersDisplayWidth / 4)
smoothScrollTo(buffersDisplayWidth + usersDisplayWidth, 0);
else
smoothScrollTo(buffersDisplayWidth, 0);
}
startX = 0;
return true;
}
return super.onTouchEvent(event);
} else {
return false;
}
}
} |
package org.testng.reporters;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.collections.ListMultiMap;
import org.testng.collections.Maps;
import org.testng.internal.Utils;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class JqReporter implements IReporter {
private String m_outputDirectory;
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,
String outputDirectory) {
m_outputDirectory = "/Users/cedric/java/misc/jquery";
XMLStringBuffer xsb = new XMLStringBuffer(" ");
xsb.push("div", "id", "suites");
generateSuites(xmlSuites, suites, xsb);
xsb.pop("div");
String all;
try {
all = Files.readFile(new File("/Users/cedric/java/misc/jquery/head"));
Utils.writeFile(m_outputDirectory, "index2.html", all + xsb.toXML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private XMLStringBuffer generateSuites(List<XmlSuite> xmlSuites,
List<ISuite> suites, XMLStringBuffer xsb) {
for (ISuite suite : suites) {
if (suite.getResults().size() == 0) {
continue;
}
xsb.push("div", "class", "suite");
xsb.addOptional("span", suite.getName(), "class", "suite-name");
xsb.push("div", "class", "suite-content");
Map<String, ISuiteResult> results = suite.getResults();
XMLStringBuffer xs1 = new XMLStringBuffer(" ");
XMLStringBuffer xs2 = new XMLStringBuffer(" ");
XMLStringBuffer xs3 = new XMLStringBuffer(" ");
for (ISuiteResult result : results.values()) {
ITestContext context = result.getTestContext();
generateTests("failed", context.getFailedTests(), context, xs1);
generateTests("skipped", context.getSkippedTests(), context, xs2);
generateTests("passed", context.getPassedTests(), context, xs3);
}
xsb.addOptional("div", "Failed" + " tests", "class", "result-banner " + "failed");
xsb.addString(xs1.toXML());
xsb.addOptional("div", "Skipped" + " tests", "class", "result-banner " + "skipped");
xsb.addString(xs2.toXML());
xsb.addOptional("div", "Passed" + " tests", "class", "result-banner " + "passed");
xsb.addString(xs3.toXML());
}
xsb.pop("div");
xsb.pop("div");
return xsb;
}
private String capitalize(String s) {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
private void generateTests(String tagClass, IResultMap tests, ITestContext context,
XMLStringBuffer xsb) {
if (tests.getAllMethods().isEmpty()) return;
xsb.push("div", "class", "test" + (tagClass != null ? " " + tagClass : ""));
ListMultiMap<Class<?>, ITestResult> map = Maps.newListMultiMap();
for (ITestResult m : tests.getAllResults()) {
map.put(m.getTestClass().getRealClass(), m);
}
xsb.push("a", "href", "
xsb.addOptional("span", context.getName(), "class", "test-name");
xsb.pop("a");
xsb.push("div", "class", "test-content");
for (Class<?> c : map.getKeys()) {
xsb.push("div", "class", "class");
xsb.push("div", "class", "class-header");
xsb.addEmptyElement("img", "src", getImage(tagClass));
xsb.addOptional("span", c.getName(), "class", "class-name");
xsb.pop("div");
xsb.push("div", "class", "class-content");
List<ITestResult> l = map.get(c);
for (ITestResult m : l) {
generateMethod(tagClass, m, context, xsb);
}
xsb.pop("div");
xsb.pop("div");
}
xsb.pop("div");
xsb.pop("div");
}
private static String getImage(String tagClass) {
return tagClass + ".png";
}
private void generateMethod(String tagClass, ITestResult tr,
ITestContext context, XMLStringBuffer xsb) {
long time = tr.getEndMillis() - tr.getStartMillis();
xsb.push("div", "class", "method");
xsb.push("div", "class", "method-content");
xsb.addOptional("span", tr.getMethod().getMethodName(), "class", "method-name");
if (tr.getParameters().length > 0) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object p : tr.getParameters()) {
if (!first) sb.append(", ");
first = false;
sb.append(p.toString());
}
xsb.addOptional("span", "(" + sb.toString() + ")", "class", "parameters");
}
xsb.addOptional("span", " " + Long.toString(time) + " ms", "class", "method-time");
xsb.pop("div");
xsb.pop("div");
}
/**
* Overridable by subclasses to create different directory names (e.g. with timestamps).
* @param outputDirectory the output directory specified by the user
*/
protected String generateOutputDirectoryName(String outputDirectory) {
return outputDirectory;
}
} |
package com.obidea.semantika.cli2.runtime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import jline.Terminal;
import jline.console.ConsoleReader;
import jline.console.history.FileHistory;
import jline.console.history.PersistentHistory;
import com.obidea.semantika.knowledgebase.IPrefixManager;
import com.obidea.semantika.queryanswer.IQueryEngine;
public class Console
{
private String mConsoleName;
private InputStream mInputStream;
private static PrintStream mOutputStream;
private static PrintStream mErrorStream;
private Thread mPipeThread;
private Thread mRunningThread;
private boolean mInterrupted;
private volatile boolean mRunning;
private volatile boolean mEof;
private BlockingQueue<Integer> mQueue = new ArrayBlockingQueue<Integer>(1024);
private ConsoleReader mConsoleReader;
private ConsoleSession mConsoleSession;
public Console(IQueryEngine engine, IPrefixManager pm, String name, InputStream inputSource,
Terminal terminal) throws IOException
{
mConsoleName = name;
mInputStream = inputSource;
mOutputStream = System.out;
mErrorStream = System.err;
mConsoleReader = createConsoleReader(name, terminal);
mConsoleSession = new ConsoleSession(engine, pm);
mPipeThread = new Thread(new Pipe());
mPipeThread.setDaemon(true);
}
private ConsoleReader createConsoleReader(String name, Terminal terminal) throws IOException
{
ConsoleReader reader = new ConsoleReader(name, new ConsoleInputStream(), mOutputStream, terminal);
reader.setHistoryEnabled(false); // we will insert history manually
reader.setHistory(new FileHistory(getHistoryFile()));
return reader;
}
protected File getHistoryFile()
{
String defaultHistoryPath = new File(System.getProperty("user.home"), ".semantika_history").toString();
return new File(System.getProperty("semantika.history", defaultHistoryPath));
}
private String getPrompt()
{
return mConsoleName + "> ";
}
private String getAltPrompt()
{
return "> ";
}
public void run() throws Exception
{
boolean graceExit = false;
try {
mConsoleSession.start();
mPipeThread.start();
mRunningThread = Thread.currentThread();
mRunning = true;
while (mRunning) {
try {
String command = readCommand();
if (command == null) {
break; // exit the loop if command is null
}
Object result = mConsoleSession.execute(command);
if (result != null) {
mConsoleSession.getCommand().printOutput(mOutputStream, result);
}
}
catch (Exception e) {
error(e.getMessage());
}
}
graceExit = true;
}
finally {
terminate(graceExit);
}
}
public void terminate(boolean terminatedByUser) throws Exception
{
if (!mRunning) {
return;
}
if (mConsoleReader.getHistory() instanceof PersistentHistory) {
try {
((PersistentHistory) mConsoleReader.getHistory()).flush();
}
catch (IOException e) {
error(e.getMessage());
}
}
mRunning = false;
mConsoleSession.destroy();
mPipeThread.interrupt();
if (terminatedByUser) {
info("Terminated by user. Good bye."); //$NON-NLS-1$
}
}
private String readCommand()
{
StringBuilder command = new StringBuilder();
boolean loop = true;
boolean first = true;
while (loop) {
try {
checkInterrupt();
String line = mConsoleReader.readLine(first ? getPrompt() : getAltPrompt());
if (line == null) {
return null; // line can be null due to Ctrl+D signal
}
if (line.length() == 0 && first) {
continue; // skip the processing if the first input line is empty
}
if (endOfCommand(line)) {
line = line.substring(0, line.length() - 2); // remove EOC marker
loop = false;
}
else {
loop = true;
first = false;
}
command.append(line).append("\n");
// Save to history if the line is not empty
if (line.trim().length() > 0) {
mConsoleReader.getHistory().add(line);
}
}
catch (IOException e) {
first = true; // back to initial prompt
if (e.getMessage() != null) {
error(e.getMessage());
}
}
}
return command.toString().trim();
}
private boolean endOfCommand(String line)
{
if (line.length() < 2) {
return false;
}
return line.charAt(line.length() - 1) == line.charAt(line.length() - 2);
}
private void interrupt()
{
mInterrupted = true;
mRunningThread.interrupt();
}
private void checkInterrupt() throws IOException
{
if (Thread.interrupted() || mInterrupted) {
mInterrupted = false;
throw new InterruptedIOException("Keyboard interruption");
}
}
private class Pipe implements Runnable
{
@Override
public void run()
{
try {
while (mRunning) {
try {
int c = mInputStream.read();
switch (c) {
case -1 :
return;
case 3 : // ASCII code for CTRL+C
info("^C");
mConsoleReader.getCursorBuffer().clear();
interrupt();
break;
case 4 : // ASCII code for CTRL+D
info("^D");
return;
default :
mQueue.put(c);
}
}
catch (Throwable t) {
return;
}
}
}
finally {
mEof = true;
try {
mQueue.put(-1);
}
catch (InterruptedException e) {
error(e.getMessage());
}
}
}
}
private class ConsoleInputStream extends InputStream
{
@Override
public int read() throws IOException
{
if (!mRunning) {
return -1;
}
checkInterrupt();
if (mEof && mQueue.isEmpty()) {
return -1;
}
Integer i;
try {
i = mQueue.take();
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
checkInterrupt();
if (i == null) {
return -1;
}
return i;
}
}
protected static void error(String message)
{
mErrorStream.println(message); //$NON-NLS-1$
}
protected static void info(String message)
{
mOutputStream.println(message);
}
} |
package br.eti.rslemos.ad;
import java.util.Arrays;
import java.util.Iterator;
public abstract class Node implements Iterable<Node>, Skippable {
private final String function;
private final String form;
private final String[] info;
protected final int depth;
private Iterator<Node> children;
Node(final ADCorpus corpus) {
String line = corpus.line;
int i = 0;
while(i < line.length() && line.charAt(i) == '=')
i++;
depth = i-1;
line = line.substring(depth);
String[] parts;
if (line.contains(":") && !line.startsWith(":")) {
parts = line.split(":");
corpus.assertBoolean(parts[0].length() > 0);
function = parts[0];
line = line.substring((function + ":").length());
parts = line.split("[(\t]");
form = parts[0];
line = line.substring(form.length());
if (line.length() > 0 && line.charAt(0) == '(') {
String info_chunk = line.substring(1, line.indexOf(')'));
info = info_chunk.split(" ");
} else
info = null;
} else {
function = null;
form = null;
info = null;
}
children = new NodeIterator(this, corpus);
}
public String getFunction() {
return function;
}
public String getForm() {
return form;
}
public String[] getInfo() {
return info;
}
public int getDepth() {
return depth;
}
public Iterator<Node> children() {
return children;
}
public Iterator<Node> iterator() {
return children();
}
public void skip() {
while(children.hasNext())
children.next().skip();
}
private static String buildDepthPrefix(int length) {
char[] prefixChars = new char[length];
Arrays.fill(prefixChars, '=');
return new String(prefixChars);
}
private static class NodeIterator extends Analysis.RootNodeIterator {
private final Node node;
private NodeIterator(Node node, ADCorpus corpus) {
super(corpus);
this.node = node;
}
@Override
protected boolean testForNext() {
return corpus.line.startsWith(buildDepthPrefix(node.depth + 1)) && corpus.line.length() > (node.depth + 1);
}
}
} |
package com.robrua.orianna.api.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.robrua.orianna.api.Utils;
import com.robrua.orianna.api.dto.BaseRiotAPI;
import com.robrua.orianna.type.api.LoadPolicy;
import com.robrua.orianna.type.core.staticdata.Champion;
import com.robrua.orianna.type.core.staticdata.Item;
import com.robrua.orianna.type.core.staticdata.MapDetails;
import com.robrua.orianna.type.core.staticdata.Mastery;
import com.robrua.orianna.type.core.staticdata.Realm;
import com.robrua.orianna.type.core.staticdata.Rune;
import com.robrua.orianna.type.core.staticdata.SummonerSpell;
import com.robrua.orianna.type.dto.staticdata.ChampionList;
import com.robrua.orianna.type.dto.staticdata.ItemList;
import com.robrua.orianna.type.dto.staticdata.MapData;
import com.robrua.orianna.type.dto.staticdata.MasteryList;
import com.robrua.orianna.type.dto.staticdata.RuneList;
import com.robrua.orianna.type.dto.staticdata.SummonerSpellList;
public abstract class StaticDataAPI {
private static Set<Long> IGNORE_ITEMS = new HashSet<>(Arrays.asList(new Long[] {0L, 1080L, 1304L, 1309L, 1314L, 1319L, 1324L, 1329L, 2037L, 2039L, 2040L,
3005L, 3039L, 3123L, 3128L, 3131L, 3160L, 3166L, 3167L, 3168L, 3169L, 3175L, 3176L, 3171L, 3186L, 3188L, 3205L, 3206L, 3207L, 3209L, 3210L, 3244L,
3405L, 3406L, 3407L, 3408L, 3409L, 3410L, 3411L, 3412L, 3413L, 3414L, 3415L, 3416L, 3417L, 3419L, 3420L}));
private static Set<Long> IGNORE_RUNES = new HashSet<>(Arrays.asList(new Long[] {8028L}));
private static Set<Long> IGNORE_SPELLS = new HashSet<>(Arrays.asList(new Long[] {10L}));
private static Map<Long, Long> REMAPPED_ITEMS = remappedItems();
/**
* @param ID
* the ID of the champion to get
* @return the champion
*/
public synchronized static Champion getChampionByID(final long ID) {
Champion champion = RiotAPI.store.get(Champion.class, (int)ID);
if(champion != null) {
return champion;
}
final com.robrua.orianna.type.dto.staticdata.Champion champ = BaseRiotAPI.getChampion(ID);
if(champ == null) {
return null;
}
champion = new Champion(champ);
if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) {
RiotAPI.getItems(new ArrayList<>(champ.getItemIDs()));
}
RiotAPI.store.store(champion, (int)ID);
return champion;
}
/**
* @param name
* the name of the champion to get
* @return the champion
*/
public static Champion getChampionByName(final String name) {
final List<Champion> champions = getChampions();
for(final Champion champion : champions) {
if(champion.getName().equals(name)) {
return champion;
}
}
return null;
}
/**
* @return all the champions
*/
public synchronized static List<Champion> getChampions() {
if(RiotAPI.store.hasAll(Champion.class)) {
return RiotAPI.store.getAll(Champion.class);
}
final ChampionList champs = BaseRiotAPI.getChampions();
final List<Champion> champions = new ArrayList<>(champs.getData().size());
final List<Long> IDs = new ArrayList<>(champions.size());
for(final com.robrua.orianna.type.dto.staticdata.Champion champ : champs.getData().values()) {
champions.add(new Champion(champ));
IDs.add(champ.getId().longValue());
}
if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) {
RiotAPI.getItems(new ArrayList<>(champs.getItemIDs()));
}
RiotAPI.store.store(champions, Utils.toIntegers(IDs), true);
return Collections.unmodifiableList(champions);
}
/**
* @param IDs
* the IDs of the champions to get
* @return the champions
*/
public synchronized static List<Champion> getChampionsByID(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Champion> champions = RiotAPI.store.get(Champion.class, Utils.toIntegers(IDs));
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(champions.get(i) == null) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return champions;
}
if(toGet.size() == 1) {
champions.set(index.get(0), getChampionByID(toGet.get(0)));
return champions;
}
getChampions();
final List<Champion> gotten = RiotAPI.store.get(Champion.class, Utils.toIntegers(toGet));
int count = 0;
for(final Integer id : index) {
champions.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(champions);
}
/**
* @param IDs
* the IDs of the champions to get
* @return the champions
*/
public static List<Champion> getChampionsByID(final long... IDs) {
return getChampionsByID(Utils.convert(IDs));
}
/**
* @param names
* the names of the champions to get
* @return the champions
*/
public static List<Champion> getChampionsByName(final List<String> names) {
final Map<String, Integer> indices = new HashMap<>();
final List<Champion> result = new ArrayList<>(names.size());
int i = 0;
for(final String name : names) {
indices.put(name, i++);
result.add(null);
}
final List<Champion> champions = getChampions();
for(final Champion champ : champions) {
final Integer index = indices.get(champ.getName());
if(index != null) {
result.set(index, champ);
}
}
return result;
}
/**
* @param names
* the names of the champions to get
* @return the champions
*/
public static List<Champion> getChampionsByName(final String... names) {
return getChampionsByName(Arrays.asList(names));
}
/**
* @param ID
* the ID of the item to get
* @return the item
*/
public synchronized static Item getItem(long ID) {
if(IGNORE_ITEMS.contains(ID)) {
return null;
}
final Long newID = REMAPPED_ITEMS.get(ID);
if(newID != null) {
ID = newID.longValue();
}
Item item = RiotAPI.store.get(Item.class, (int)ID);
if(item != null) {
return item;
}
final com.robrua.orianna.type.dto.staticdata.Item it = BaseRiotAPI.getItem(ID);
item = new Item(it);
RiotAPI.store.store(item, (int)ID);
return item;
}
/**
* @return all the items
*/
public synchronized static List<Item> getItems() {
if(RiotAPI.store.hasAll(Item.class)) {
return RiotAPI.store.getAll(Item.class);
}
final ItemList its = BaseRiotAPI.getItems();
final List<Item> items = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(items.size());
for(final com.robrua.orianna.type.dto.staticdata.Item item : its.getData().values()) {
items.add(new Item(item));
IDs.add(item.getId().longValue());
}
RiotAPI.store.store(items, Utils.toIntegers(IDs), true);
return Collections.unmodifiableList(items);
}
/**
* @param IDs
* the IDs of the items to get
* @return the items
*/
public synchronized static List<Item> getItems(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Item> items = RiotAPI.store.get(Item.class, Utils.toIntegers(IDs));
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
Long ID = IDs.get(i);
if(items.get(i) == null && !IGNORE_ITEMS.contains(ID)) {
final Long newID = REMAPPED_ITEMS.get(ID);
if(newID != null) {
ID = newID.longValue();
}
toGet.add(ID);
index.add(i);
}
}
if(toGet.isEmpty()) {
return items;
}
if(toGet.size() == 1) {
items.set(index.get(0), getItem(toGet.get(0)));
return items;
}
getItems();
final List<Item> gotten = RiotAPI.store.get(Item.class, Utils.toIntegers(toGet));
int count = 0;
for(final Integer id : index) {
items.add(id, gotten.get(count++));
}
return Collections.unmodifiableList(items);
}
/**
* @param IDs
* the IDs of the items to get
* @return the items
*/
public static List<Item> getItems(final long... IDs) {
return getItems(Utils.convert(IDs));
}
/**
* @return the languages
*/
public static List<String> getLanguages() {
return BaseRiotAPI.getLanguages();
}
/**
* @return the language strings
*/
public static Map<String, String> getLanguageStrings() {
final com.robrua.orianna.type.dto.staticdata.LanguageStrings str = BaseRiotAPI.getLanguageStrings();
return str.getData();
}
/**
* @return information for the maps
*/
public synchronized static List<MapDetails> getMapInformation() {
if(RiotAPI.store.hasAll(MapDetails.class)) {
return RiotAPI.store.getAll(MapDetails.class);
}
final MapData inf = BaseRiotAPI.getMapInformation();
final List<MapDetails> info = new ArrayList<>(inf.getData().size());
final List<Long> IDs = new ArrayList<>(info.size());
for(final com.robrua.orianna.type.dto.staticdata.MapDetails map : inf.getData().values()) {
info.add(new MapDetails(map));
IDs.add(map.getMapId().longValue());
}
RiotAPI.store.store(info, Utils.toIntegers(IDs), true);
return Collections.unmodifiableList(info);
}
/**
* @return all the masteries
*/
public synchronized static List<Mastery> getMasteries() {
if(RiotAPI.store.hasAll(Mastery.class)) {
return RiotAPI.store.getAll(Mastery.class);
}
final MasteryList its = BaseRiotAPI.getMasteries();
final List<Mastery> masteries = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(masteries.size());
for(final com.robrua.orianna.type.dto.staticdata.Mastery mastery : its.getData().values()) {
masteries.add(new Mastery(mastery));
IDs.add(mastery.getId().longValue());
}
RiotAPI.store.store(masteries, Utils.toIntegers(IDs), true);
return Collections.unmodifiableList(masteries);
}
/**
* @param IDs
* the IDs of the masteries to get
* @return the masteries
*/
public synchronized static List<Mastery> getMasteries(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Mastery> masteries = RiotAPI.store.get(Mastery.class, Utils.toIntegers(IDs));
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(masteries.get(i) == null) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return masteries;
}
if(toGet.size() == 1) {
masteries.set(index.get(0), getMastery(toGet.get(0)));
return masteries;
}
getMasteries();
final List<Mastery> gotten = RiotAPI.store.get(Mastery.class, Utils.toIntegers(toGet));
int count = 0;
for(final Integer id : index) {
masteries.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(masteries);
}
/**
* @param IDs
* the IDs of the masteries to get
* @return the masteries
*/
public static List<Mastery> getMasteries(final long... IDs) {
return getMasteries(Utils.convert(IDs));
}
/**
* @param ID
* the ID of the mastery to get
* @return the mastery
*/
public synchronized static Mastery getMastery(final long ID) {
Mastery mastery = RiotAPI.store.get(Mastery.class, (int)ID);
if(mastery != null) {
return mastery;
}
final com.robrua.orianna.type.dto.staticdata.Mastery mast = BaseRiotAPI.getMastery(ID);
mastery = new Mastery(mast);
RiotAPI.store.store(mastery, (int)ID);
return mastery;
}
/**
* @return the realm
*/
public synchronized static Realm getRealm() {
Realm realm = RiotAPI.store.get(Realm.class, 0L);
if(realm != null) {
return realm;
}
realm = new Realm(BaseRiotAPI.getRealm());
RiotAPI.store.store(realm, 0);
return realm;
}
/**
* @param ID
* the ID of the rune to get
* @return the rune
*/
public synchronized static Rune getRune(final long ID) {
if(IGNORE_RUNES.contains(ID)) {
return null;
}
Rune rune = RiotAPI.store.get(Rune.class, (int)ID);
if(rune != null) {
return rune;
}
final com.robrua.orianna.type.dto.staticdata.Rune run = BaseRiotAPI.getRune(ID);
rune = new Rune(run);
RiotAPI.store.store(rune, (int)ID);
return rune;
}
/**
* @return all the runes
*/
public synchronized static List<Rune> getRunes() {
if(RiotAPI.store.hasAll(Rune.class)) {
return RiotAPI.store.getAll(Rune.class);
}
final RuneList its = BaseRiotAPI.getRunes();
final List<Rune> runes = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(runes.size());
for(final com.robrua.orianna.type.dto.staticdata.Rune rune : its.getData().values()) {
runes.add(new Rune(rune));
IDs.add(rune.getId().longValue());
}
RiotAPI.store.store(runes, Utils.toIntegers(IDs), true);
return Collections.unmodifiableList(runes);
}
/**
* @param IDs
* the IDs of the runes to get
* @return the runes
*/
public synchronized static List<Rune> getRunes(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<Rune> runes = RiotAPI.store.get(Rune.class, Utils.toIntegers(IDs));
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(runes.get(i) == null && !IGNORE_RUNES.contains(IDs.get(i))) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return runes;
}
if(toGet.size() == 1) {
runes.set(index.get(0), getRune(toGet.get(0)));
return runes;
}
getRunes();
final List<Rune> gotten = RiotAPI.store.get(Rune.class, Utils.toIntegers(toGet));
int count = 0;
for(final Integer id : index) {
runes.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(runes);
}
/**
* @param IDs
* the IDs of the runes to get
* @return the runes
*/
public static List<Rune> getRunes(final long... IDs) {
return getRunes(Utils.convert(IDs));
}
/**
* @param ID
* the ID of the summoner spell to get
* @return the summoner spell
*/
public synchronized static SummonerSpell getSummonerSpell(final long ID) {
if(IGNORE_SPELLS.contains(ID)) {
return null;
}
SummonerSpell spell = RiotAPI.store.get(SummonerSpell.class, (int)ID);
if(spell != null) {
return spell;
}
final com.robrua.orianna.type.dto.staticdata.SummonerSpell spl = BaseRiotAPI.getSummonerSpell(ID);
spell = new SummonerSpell(spl);
RiotAPI.store.store(spell, (int)ID);
return spell;
}
/**
* @return all the summoner spells
*/
public synchronized static List<SummonerSpell> getSummonerSpells() {
if(RiotAPI.store.hasAll(SummonerSpell.class)) {
return RiotAPI.store.getAll(SummonerSpell.class);
}
final SummonerSpellList its = BaseRiotAPI.getSummonerSpells();
final List<SummonerSpell> spells = new ArrayList<>(its.getData().size());
final List<Long> IDs = new ArrayList<>(spells.size());
for(final com.robrua.orianna.type.dto.staticdata.SummonerSpell spell : its.getData().values()) {
spells.add(new SummonerSpell(spell));
IDs.add(spell.getId().longValue());
}
RiotAPI.store.store(spells, Utils.toIntegers(IDs), true);
return Collections.unmodifiableList(spells);
}
/**
* @param IDs
* the IDs of the summoner spells to get
* @return the summoner spells
*/
public synchronized static List<SummonerSpell> getSummonerSpells(final List<Long> IDs) {
if(IDs.isEmpty()) {
return Collections.emptyList();
}
final List<SummonerSpell> spells = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(IDs));
final List<Long> toGet = new ArrayList<>();
final List<Integer> index = new ArrayList<>();
for(int i = 0; i < IDs.size(); i++) {
if(spells.get(i) == null && !IGNORE_SPELLS.contains(IDs.get(i))) {
toGet.add(IDs.get(i));
index.add(i);
}
}
if(toGet.isEmpty()) {
return spells;
}
if(toGet.size() == 1) {
spells.set(index.get(0), getSummonerSpell(toGet.get(0)));
return spells;
}
getSummonerSpells();
final List<SummonerSpell> gotten = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(toGet));
int count = 0;
for(final Integer id : index) {
spells.set(id, gotten.get(count++));
}
return Collections.unmodifiableList(spells);
}
/**
* @param IDs
* the IDs of the summoner spells to get
* @return the summoner spells
*/
public static List<SummonerSpell> getSummonerSpells(final long... IDs) {
return getSummonerSpells(Utils.convert(IDs));
}
/**
* @return the versions
*/
public static List<String> getVersions() {
return BaseRiotAPI.getVersions();
}
/*
* a Fix for remapped boot enchants (and any others that crop up)
*/
private static Map<Long, Long> remappedItems() {
final Map<Long, Long> map = new HashMap<>();
map.put(3280L, 1309L);
map.put(3282L, 1305L);
map.put(3281L, 1307L);
map.put(3284L, 1306L);
map.put(3283L, 1308L);
map.put(3278L, 1333L);
map.put(3279L, 1331L);
map.put(3250L, 1304L);
map.put(3251L, 1302L);
map.put(3254L, 1301L);
map.put(3255L, 1314L);
map.put(3252L, 1300L);
map.put(3253L, 1303L);
map.put(3263L, 1318L);
map.put(3264L, 1316L);
map.put(3265L, 1324L);
map.put(3266L, 1322L);
map.put(3260L, 1319L);
map.put(3261L, 1317L);
map.put(3262L, 1315L);
map.put(3257L, 1310L);
map.put(3256L, 1312L);
map.put(3259L, 1311L);
map.put(3258L, 1313L);
map.put(3276L, 1332L);
map.put(3277L, 1330L);
map.put(3274L, 1326L);
map.put(3275L, 1334L);
map.put(3272L, 1325L);
map.put(3273L, 1328L);
map.put(3270L, 1329L);
map.put(3271L, 1327L);
map.put(3269L, 1321L);
map.put(3268L, 1323L);
map.put(3267L, 1320L);
return map;
}
} |
package com.smartnsoft.droid4me.cache;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.smartnsoft.droid4me.bo.Business;
import com.smartnsoft.droid4me.log.Logger;
import com.smartnsoft.droid4me.log.LoggerFactory;
// TODO: turn the derived classes exception into actual Persistence.PersistenceException instances!
public abstract class Persistence
implements Business.IOStreamer<String, Persistence.PersistenceException>
{
/**
* The exception thrown when an error occurs during a persistence operation.
*/
public final static class PersistenceException
extends Error
{
private static final long serialVersionUID = -5246441820601050842L;
}
protected final static class UriUsage
implements Comparable<Persistence.UriUsage>
{
public int accessCount = 0;
public final String storageFilePath;
/**
* Redundant but there for optimization reasons.
*/
public final String uri;
public UriUsage(String storageFilePath, String uri)
{
this.storageFilePath = storageFilePath;
this.uri = uri;
}
public int compareTo(Persistence.UriUsage another)
{
if (accessCount > another.accessCount)
{
return -1;
}
else if (accessCount < another.accessCount)
{
return 1;
}
return 0;
}
}
protected final static Logger log = LoggerFactory.getInstance(Persistence.class);
private static volatile Persistence[] instances;
public static String[] CACHE_DIRECTORY_PATHS = new String[] { "/sdcard" };
public static int CACHES_COUNT = 1;
/**
* The fully qualified name of the {@link Persistence} instances implementation.
*/
public static String IMPLEMENTATION_FQN;
public static int MAXIMUM_URI_CONTENTS_SIZE_IN_BYTES = 512 * 1024;
protected boolean storageBackendAvailable;
private final String storageDirectoryPath;
protected final Map<String, Persistence.UriUsage> uriUsages;
protected final Set<String> beingProcessed = new HashSet<String>();
public static Persistence getInstance()
{
return Persistence.getInstance(0);
}
/**
* This is a lazy instantiation.
*/
// We accept the "out-of-order writes" case
@SuppressWarnings("unchecked")
public static Persistence getInstance(int position)
{
if (Persistence.instances == null)
{
synchronized (Persistence.class)
{
if (Persistence.instances == null)
{
try
{
// We do that way, because the Persistence initialization may be long, and we want the "instances" attribute to be atomic
final Class<? extends Persistence> implementationClass = (Class<? extends Persistence>) Class.forName(Persistence.IMPLEMENTATION_FQN);
final Persistence[] newInstances = (Persistence[]) Array.newInstance(implementationClass, Persistence.CACHES_COUNT);
final Constructor<? extends Persistence> constructor = implementationClass.getDeclaredConstructor(String.class, int.class);
for (int index = 0; index < Persistence.CACHES_COUNT; index++)
{
newInstances[index] = constructor.newInstance(Persistence.CACHE_DIRECTORY_PATHS[index], index);
newInstances[index].initialize();
}
// We only assign the instances class variable here, once all instances have actually been created
Persistence.instances = newInstances;
}
catch (Exception exception)
{
if (log.isFatalEnabled())
{
log.fatal("Cannot instantiate properly the persistence instances", exception);
}
}
}
}
}
return Persistence.instances[position];
}
/**
* @param outputStream
* it is closed by this method
*/
// TODO: simplify all this!
public static InputStream storeInputStream(OutputStream outputStream, InputStream inputStream, boolean closeInput, String logMessageSuffix)
{
final InputStream actualInputStream;
final BufferedInputStream bufferedInputStream;
final ByteArrayInputStream byteArrayInputStream;
if (inputStream == null)
{
bufferedInputStream = null;
byteArrayInputStream = new ByteArrayInputStream(new byte[0]);
actualInputStream = byteArrayInputStream;
}
else if (closeInput == false)
{
byteArrayInputStream = null;
bufferedInputStream = new BufferedInputStream(inputStream, 8192);
bufferedInputStream.mark(MAXIMUM_URI_CONTENTS_SIZE_IN_BYTES);
actualInputStream = bufferedInputStream;
}
else
{
bufferedInputStream = null;
byteArrayInputStream = null;
actualInputStream = inputStream;
}
try
{
final byte buffer[] = new byte[8092];
int length;
while ((length = actualInputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, length);
}
if (bufferedInputStream != null)
{
try
{
bufferedInputStream.reset();
}
catch (IOException exception)
{
if (log.isErrorEnabled())
{
log.error("Could not reset the buffered input stream" + logMessageSuffix, exception);
}
return inputStream;
}
return bufferedInputStream;
}
else if (byteArrayInputStream != null)
{
byteArrayInputStream.close();
return null;
}
else
{
// And we do not forget to close the original input stream
inputStream.close();
return null;
}
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn("Not enough memory for properly writing to the output stream" + logMessageSuffix, exception);
}
System.gc();
return inputStream;
}
catch (IOException exception)
{
if (log.isErrorEnabled())
{
log.error("Could not properly write to the output stream" + logMessageSuffix, exception);
}
return inputStream;
}
finally
{
if (outputStream != null)
{
try
{
outputStream.close();
}
catch (IOException exception)
{
if (log.isWarnEnabled())
{
log.warn("Could not properly close the output stream" + logMessageSuffix, exception);
}
}
}
}
}
public static InputStream storeInputStreamToFile(String filePath, InputStream inputStream, boolean closeInput)
{
try
{
return Persistence.storeInputStream(new FileOutputStream(filePath), inputStream, closeInput, " corresponding to the file '" + filePath + "'");
}
catch (FileNotFoundException exception)
{
if (log.isWarnEnabled())
{
log.warn("Could not access to the file '" + filePath + "' for writing", exception);
}
return null;
}
}
/**
* The unique constructor.
*
* @param storageDirectoryPath
* the location where the persistence should be performed
* @param instanceIndex
* the ordinal of the instance which is bound to be created. Starts with <code>0</code>.
*/
protected Persistence(String storageDirectoryPath, int instanceIndex)
{
this.storageDirectoryPath = storageDirectoryPath;
uriUsages = new HashMap<String, Persistence.UriUsage>();
}
protected abstract void initialize();
public abstract InputStream getRawInputStream(String uri)
throws Persistence.PersistenceException;
public abstract InputStream cacheInputStream(String uri, InputStream inputStream)
throws Persistence.PersistenceException;
/**
* Empties the specific part of the persistence.
*
* When called, the persistence storage is ensured to be available.
*/
protected abstract void empty()
throws Persistence.PersistenceException;
public final String getStorageDirectoryPath()
{
return storageDirectoryPath;
}
/**
* Totally clears the cache related to the current instance.
*/
public final synchronized void clear()
throws Persistence.PersistenceException
{
if (log.isDebugEnabled())
{
log.debug("Emptying the persistence instance");
}
if (storageBackendAvailable == true)
{
empty();
}
uriUsages.clear();
beingProcessed.clear();
}
/**
* Totally clears all caches.
*/
public static synchronized void clearAll()
throws Persistence.PersistenceException
{
if (log.isDebugEnabled())
{
log.debug("Emptying all persistence instances");
}
for (int index = 0; index < Persistence.CACHES_COUNT; index++)
{
Persistence.instances[index].clear();
}
}
} |
package pt.davidafsilva.hashids;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class Hashids {
// the default instance
private static final class DefaultInstanceHolder {
private static final Hashids DEFAULT_INSTANCE = newInstance(new char[0]);
}
// algorithm constant definitions
private static final int LOTTERY_MOD = 100;
private static final double GUARD_THRESHOLD = 12;
private static final double SEPARATOR_THRESHOLD = 3.5;
private static final int MIN_ALPHABET_LENGTH = 16;
private static final Pattern HEX_VALUES_PATTERN = Pattern.compile("[\\w\\W]{1,12}");
// algorithm defaults
public static final char[] DEFAULT_ALPHABET = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'
};
private static final char[] DEFAULT_SEPARATORS = {
'c', 'f', 'h', 'i', 's', 't', 'u', 'C', 'F', 'H', 'I', 'S', 'T', 'U'
};
// algorithm properties
private final char[] alphabet;
private final char[] separators;
private final char[] salt;
private final char[] guards;
private final int minLength;
// auxiliary structure for fast reads
private final Set<Character> separatorsSet;
/**
* Creates a new instance of the algorithm with the given configuration.
*
* @param salt the salt that shall be used for entropy
* @param alphabet the alphabet that the algorithm must follow while computing hashes
* @param minLength the minimum length of the hashes produced by the algorithm
*/
private Hashids(final char[] salt, final char[] alphabet, final int minLength) {
this.minLength = minLength;
this.salt = Arrays.copyOf(salt, salt.length);
// filter and shuffle separators
char[] tmpSeparators = shuffle(filterSeparators(DEFAULT_SEPARATORS, alphabet), this.salt);
// validate and filter the alphabet
char[] tmpAlphabet = validateAndFilterAlphabet(alphabet, tmpSeparators);
// check separator threshold
if (tmpSeparators.length == 0 ||
(tmpAlphabet.length / tmpSeparators.length) > SEPARATOR_THRESHOLD) {
final int minSeparatorsSize = (int) Math.ceil(tmpAlphabet.length / SEPARATOR_THRESHOLD);
// check minimum size of separators
if (minSeparatorsSize > tmpSeparators.length) {
// fill separators from alphabet
final int missingSeparators = minSeparatorsSize - tmpSeparators.length;
tmpSeparators = Arrays.copyOf(tmpSeparators, tmpSeparators.length + missingSeparators);
System.arraycopy(tmpAlphabet, 0, tmpSeparators,
tmpSeparators.length - missingSeparators, missingSeparators);
System.arraycopy(tmpAlphabet, 0, tmpSeparators,
tmpSeparators.length - missingSeparators, missingSeparators);
tmpAlphabet = Arrays.copyOfRange(tmpAlphabet, missingSeparators, tmpAlphabet.length);
}
}
// shuffle the current alphabet
shuffle(tmpAlphabet, this.salt);
// check guards
this.guards = new char[(int) Math.ceil(tmpAlphabet.length / GUARD_THRESHOLD)];
if (alphabet.length < 3) {
System.arraycopy(tmpSeparators, 0, guards, 0, guards.length);
this.separators = Arrays.copyOfRange(tmpSeparators, guards.length, tmpSeparators.length);
this.alphabet = tmpAlphabet;
} else {
System.arraycopy(tmpAlphabet, 0, guards, 0, guards.length);
this.separators = tmpSeparators;
this.alphabet = Arrays.copyOfRange(tmpAlphabet, guards.length, tmpAlphabet.length);
}
// create the separators set
separatorsSet = IntStream.range(0, separators.length)
.mapToObj(idx -> separators[idx])
.collect(Collectors.toSet());
}
// Static factory methods
/**
* Returns the default instance of the algorithm which uses the following parameters:
* <table summary="Algorithm parametrization">
* <tr>
* <th>Parameter</th>
* <th>Value</th>
* </tr>
* <tr>
* <td><b>salt</b></td>
* <td>--</td>
* </tr>
* <tr>
* <td><b>alphabet</b></td>
* <td>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890</td>
* </tr>
* <tr>
* <td><b>minLength</b></td>
* <td>--</td>
* </tr>
* </table>
*
* @return the default algorithm instance
*/
public static Hashids getInstance() {
return DefaultInstanceHolder.DEFAULT_INSTANCE;
}
/**
* Returns a new instance of the algorithm with the given salt and the {@link #DEFAULT_ALPHABET
* default alphabet} with no minimum hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final String salt) {
return newInstance(salt.toCharArray(), DEFAULT_ALPHABET, -1);
}
/**
* Returns a new instance of the algorithm with the given salt and the {@link #DEFAULT_ALPHABET
* default alphabet} with no minimum hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final char[] salt) {
return newInstance(salt, DEFAULT_ALPHABET, -1);
}
/**
* Returns a new instance of the algorithm with the given salt and the alphabet and no minimum
* hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @param alphabet the alphabet to be used for the hash generation
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final String salt, final String alphabet) {
return newInstance(salt.toCharArray(), alphabet.toCharArray(), -1);
}
/**
* Returns a new instance of the algorithm with the given salt and the alphabet and no minimum
* hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @param alphabet the alphabet to be used for the hash generation
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final char[] salt, final char[] alphabet) {
return newInstance(salt, alphabet, -1);
}
/**
* Returns a new instance of the algorithm with the given salt and the {@link #DEFAULT_ALPHABET
* default alphabet} with {@code minLength} as the minimum hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @param minLength the minimum hash length
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final String salt, final int minLength) {
return newInstance(salt.toCharArray(), DEFAULT_ALPHABET, minLength);
}
/**
* Returns a new instance of the algorithm with the given salt and the {@link #DEFAULT_ALPHABET
* default alphabet} with {@code minLength} as the minimum hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @param minLength the minimum hash length
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final char[] salt, final int minLength) {
return newInstance(salt, DEFAULT_ALPHABET, minLength);
}
/**
* Returns a new instance of the algorithm with the given salt and the alphabet and
* {@code minLength} as the minimum hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @param alphabet the alphabet to be used for the hash generation
* @param minLength the minimum hash length
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final String salt, final String alphabet, final int minLength) {
return newInstance(salt.toCharArray(), alphabet.toCharArray(), minLength);
}
/**
* Returns a new instance of the algorithm with the given salt and the alphabet and
* {@code minLength} as the minimum hash length.
*
* @param salt the salt to be used as entropy for the algorithm
* @param alphabet the alphabet to be used for the hash generation
* @param minLength the minimum hash length
* @return a new instance of the algorithm
*/
public static Hashids newInstance(final char[] salt, final char[] alphabet, final int minLength) {
return new Hashids(salt, alphabet, minLength);
}
// Encode
public String encodeHex(final String hexNumbers) {
if (hexNumbers == null) {
return null;
}
// remove the prefix, if present
final String hex = hexNumbers.startsWith("0x") || hexNumbers.startsWith("0X") ?
hexNumbers.substring(2) : hexNumbers;
// get the associated long value and encode it
LongStream values = LongStream.empty();
final Matcher matcher = HEX_VALUES_PATTERN.matcher(hex);
while (matcher.find()) {
final long value = new BigInteger("1" + matcher.group(), 16).longValue();
values = LongStream.concat(values, LongStream.of(value));
}
return encode(values.toArray());
}
public String encode(final long... numbers) {
if (numbers == null) {
return null;
}
// copy alphabet
final char[] currentAlphabet = Arrays.copyOf(alphabet, alphabet.length);
// determine the lottery number
final long lotteryId = LongStream.range(0, numbers.length)
.reduce(0, (state, i) -> {
final long number = numbers[(int) i];
if (number < 0) {
throw new IllegalArgumentException("invalid number: " + number);
}
return state + number % (i + LOTTERY_MOD);
});
final char lottery = currentAlphabet[(int) (lotteryId % currentAlphabet.length)];
// encode each number
final StringBuilder global = new StringBuilder();
IntStream.range(0, numbers.length)
.forEach(idx -> {
// derive alphabet
deriveNewAlphabet(currentAlphabet, salt, lottery);
// encode
final int initialLength = global.length();
translate(numbers[idx], currentAlphabet, global, initialLength);
// prepend the lottery
if (idx == 0) {
global.insert(0, lottery);
}
// append the separator, if more numbers are pending encoding
if (idx + 1 < numbers.length) {
long n = numbers[idx] % (global.charAt(initialLength) + 1);
global.append(separators[(int) (n % separators.length)]);
}
});
// add the guards, if there's any space left
if (minLength > global.length()) {
int guardIdx = (int) ((lotteryId + lottery) % guards.length);
global.insert(0, guards[guardIdx]);
if (minLength > global.length()) {
guardIdx = (int) ((lotteryId + global.charAt(2)) % guards.length);
global.append(guards[guardIdx]);
}
}
// add the necessary padding
int paddingLeft = minLength - global.length();
while (paddingLeft > 0) {
shuffle(currentAlphabet, Arrays.copyOf(currentAlphabet, currentAlphabet.length));
final int alphabetHalfSize = currentAlphabet.length / 2;
final int initialSize = global.length();
if (paddingLeft > currentAlphabet.length) {
// entire alphabet with the current encoding in the middle of it
int offset = alphabetHalfSize + (currentAlphabet.length % 2 == 0 ? 0 : 1);
global.insert(0, currentAlphabet, alphabetHalfSize, offset);
global.insert(offset + initialSize, currentAlphabet, 0, alphabetHalfSize);
// decrease the padding left
paddingLeft -= currentAlphabet.length;
} else {
// calculate the excess
final int excess = currentAlphabet.length + global.length() - minLength;
final int secondHalfStartOffset = alphabetHalfSize + Math.floorDiv(excess, 2);
final int secondHalfLength = currentAlphabet.length - secondHalfStartOffset;
final int firstHalfLength = paddingLeft - secondHalfLength;
global.insert(0, currentAlphabet, secondHalfStartOffset, secondHalfLength);
global.insert(secondHalfLength + initialSize, currentAlphabet, 0, firstHalfLength);
paddingLeft = 0;
}
}
return global.toString();
}
// Decode
public String decodeHex(final String hash) {
if (hash == null) {
return null;
}
final StringBuilder sb = new StringBuilder();
Arrays.stream(decode(hash))
.mapToObj(Long::toHexString)
.forEach(hex -> sb.append(hex, 1, hex.length()));
return sb.toString();
}
public long[] decode(final String hash) {
if (hash == null) {
return null;
}
// create a set of the guards
final Set<Character> guardsSet = IntStream.range(0, guards.length)
.mapToObj(idx -> guards[idx])
.collect(Collectors.toSet());
// count the total guards used
final int[] guardsIdx = IntStream.range(0, hash.length())
.filter(idx -> guardsSet.contains(hash.charAt(idx)))
.toArray();
// get the start/end index base on the guards count
final int startIdx, endIdx;
if (guardsIdx.length > 0) {
startIdx = guardsIdx[0] + 1;
endIdx = guardsIdx.length > 1 ? guardsIdx[1] : hash.length();
} else {
startIdx = 0;
endIdx = hash.length();
}
LongStream decoded = LongStream.empty();
// parse the hash
if (hash.length() > 0) {
final char lottery = hash.charAt(startIdx);
// create the initial accumulation string
final int length = hash.length() - guardsIdx.length - 1;
StringBuilder block = new StringBuilder(length);
// create the base salt
final char[] decodeSalt = new char[alphabet.length];
decodeSalt[0] = lottery;
final int saltLength = salt.length >= alphabet.length ? alphabet.length - 1 : salt.length;
System.arraycopy(salt, 0, decodeSalt, 1, saltLength);
final int saltLeft = alphabet.length - saltLength - 1;
// copy alphabet
final char[] currentAlphabet = Arrays.copyOf(alphabet, alphabet.length);
for (int i = startIdx + 1; i < endIdx; i++) {
if (!separatorsSet.contains(hash.charAt(i))) {
block.append(hash.charAt(i));
// continue if we have not reached the end, yet
if (i < endIdx - 1) {
continue;
}
}
if (block.length() > 0) {
// create the salt
if (saltLeft > 0) {
System.arraycopy(currentAlphabet, 0, decodeSalt,
alphabet.length - saltLeft, saltLeft);
}
// shuffle the alphabet
shuffle(currentAlphabet, decodeSalt);
// prepend the decoded value
final long n = translate(block.toString().toCharArray(), currentAlphabet);
decoded = LongStream.concat(decoded, LongStream.of(n));
// create a new block
block = new StringBuilder(length);
}
}
}
// validate the hash
final long[] decodedValue = decoded.toArray();
if (!Objects.equals(hash, encode(decodedValue))) {
throw new IllegalArgumentException("invalid hash: " + hash);
}
return decodedValue;
}
// Utility functions
private StringBuilder translate(final long n, final char[] alphabet,
final StringBuilder sb, final int start) {
long input = n;
do {
// prepend the chosen char
sb.insert(start, alphabet[(int) (input % alphabet.length)]);
// trim the input
input = input / alphabet.length;
} while (input > 0);
return sb;
}
private long translate(final char[] hash, final char[] alphabet) {
long number = 0;
final Map<Character, Integer> alphabetMapping = IntStream.range(0, alphabet.length)
.mapToObj(idx -> new Object[]{alphabet[idx], idx})
.collect(Collectors.groupingBy(arr -> (Character) arr[0],
Collectors.mapping(arr -> (Integer) arr[1],
Collectors.reducing(null, (a, b) -> a == null ? b : a))));
for (int i = 0; i < hash.length; ++i) {
number += alphabetMapping.get(hash[i]) *
(long) Math.pow(alphabet.length, hash.length - i - 1);
}
return number;
}
private char[] deriveNewAlphabet(final char[] alphabet, final char[] salt, final char lottery) {
// create the new salt
final char[] newSalt = new char[alphabet.length];
// 1. lottery
newSalt[0] = lottery;
int spaceLeft = newSalt.length - 1;
int offset = 1;
// 2. salt
if (salt.length > 0 && spaceLeft > 0) {
int length = salt.length > spaceLeft ? spaceLeft : salt.length;
System.arraycopy(salt, 0, newSalt, offset, length);
spaceLeft -= length;
offset += length;
}
// 3. alphabet
if (spaceLeft > 0) {
System.arraycopy(alphabet, 0, newSalt, offset, spaceLeft);
}
// shuffle
return shuffle(alphabet, newSalt);
}
private char[] validateAndFilterAlphabet(final char[] alphabet, final char[] separators) {
// validate size
if (alphabet.length < MIN_ALPHABET_LENGTH) {
throw new IllegalArgumentException(String.format("alphabet must contain at least %d unique " +
"characters: %d", MIN_ALPHABET_LENGTH, alphabet.length));
}
final Set<Character> seen = new LinkedHashSet<>(alphabet.length);
final Set<Character> invalid = IntStream.range(0, separators.length)
.mapToObj(idx -> separators[idx])
.collect(Collectors.toSet());
// add to seen set (without duplicates)
IntStream.range(0, alphabet.length)
.forEach(i -> {
if (alphabet[i] == ' ') {
throw new IllegalArgumentException(String.format("alphabet must not contain spaces: " +
"index %d", i));
}
final Character c = alphabet[i];
if (!invalid.contains(c)) {
seen.add(c);
}
});
// check if got the same untouched alphabet
if (seen.size() == alphabet.length) {
return Arrays.copyOf(alphabet, alphabet.length);
}
// create a new alphabet without the duplicates
final char[] uniqueAlphabet = new char[seen.size()];
int idx = 0;
for (char c : seen) {
uniqueAlphabet[idx++] = c;
}
return uniqueAlphabet;
}
private char[] filterSeparators(final char[] separators, final char[] alphabet) {
final Set<Character> valid = IntStream.range(0, alphabet.length)
.mapToObj(idx -> alphabet[idx])
.collect(Collectors.toSet());
return IntStream.range(0, separators.length)
.mapToObj(idx -> (separators[idx]))
.filter(valid::contains)
// ugly way to convert back to char[]
.map(c -> Character.toString(c))
.collect(Collectors.joining())
.toCharArray();
}
private char[] shuffle(final char[] alphabet, final char[] salt) {
for (int i = alphabet.length - 1, v = 0, p = 0, j, z; salt.length > 0 && i > 0; i
v %= salt.length;
p += z = salt[v];
j = (z + v + p) % i;
final char tmp = alphabet[j];
alphabet[j] = alphabet[i];
alphabet[i] = tmp;
}
return alphabet;
}
} |
package com.wakatime.intellij.plugin;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.PasswordAuthentication;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Dependencies {
private static String pythonLocation = null;
private static String resourcesLocation = null;
public static boolean isPythonInstalled() {
return Dependencies.getPythonLocation() != null;
}
public static String getResourcesLocation() {
if (Dependencies.resourcesLocation == null) {
if (System.getenv("WAKATIME_HOME") != null && !System.getenv("WAKATIME_HOME").trim().isEmpty()) {
File resourcesFolder = new File(System.getenv("WAKATIME_HOME"));
if (resourcesFolder.exists()) {
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
WakaTime.log.debug("Using $WAKATIME_HOME for resources folder: " + Dependencies.resourcesLocation);
return Dependencies.resourcesLocation;
}
}
if (isWindows()) {
File appDataFolder = new File(System.getenv("APPDATA"));
File resourcesFolder = new File(appDataFolder, "WakaTime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
} else {
File userHomeDir = new File(System.getProperty("user.home"));
File resourcesFolder = new File(userHomeDir, ".wakatime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
}
}
return Dependencies.resourcesLocation;
}
public static String getPythonLocation() {
if (Dependencies.pythonLocation != null)
return Dependencies.pythonLocation;
ArrayList<String> paths = new ArrayList<String>();
paths.add(null);
paths.add("/");
paths.add("/usr/local/bin/");
paths.add("/usr/bin/");
if (isWindows()) {
File resourcesLocation = new File(Dependencies.getResourcesLocation());
paths.add(combinePaths(resourcesLocation.getAbsolutePath(), "python"));
try {
paths.add(getPythonFromRegistry(WinReg.HKEY_CURRENT_USER));
paths.add(getPythonFromRegistry(WinReg.HKEY_LOCAL_MACHINE));
} catch(NoClassDefFoundError e) {
WakaTime.log.debug(e);
}
for (int i=50; i>=27; i
paths.add("\\python" + i);
paths.add("\\Python" + i);
}
}
for (String path : paths) {
if (runPython(combinePaths(path, "pythonw"))) {
Dependencies.pythonLocation = combinePaths(path, "pythonw");
break;
} else if (runPython(combinePaths(path, "python3"))) {
Dependencies.pythonLocation = combinePaths(path, "python3");
break;
} else if (runPython(combinePaths(path, "python"))) {
Dependencies.pythonLocation = combinePaths(path, "python");
break;
}
}
if (Dependencies.pythonLocation != null) {
WakaTime.log.debug("Found python binary: " + Dependencies.pythonLocation);
} else {
WakaTime.log.warn("Could not find python binary.");
}
return Dependencies.pythonLocation;
}
public static String getPythonFromRegistry(WinReg.HKEY hkey) {
String path = null;
if (isWindows()) {
try {
String key = "Software\\\\Wow6432Node\\\\Python\\\\PythonCore";
for (String version : Advapi32Util.registryGetKeys(hkey, key)) {
path = Advapi32Util.registryGetStringValue(hkey, key + "\\" + version + "\\InstallPath", "");
if (path != null) {
break;
}
}
} catch (Exception e) {
WakaTime.log.debug(e);
}
if (path == null) {
try {
String key = "Software\\\\Python\\\\PythonCore";
for (String version : Advapi32Util.registryGetKeys(hkey, key)) {
path = Advapi32Util.registryGetStringValue(hkey, key + "\\" + version + "\\InstallPath", "");
if (path != null) {
break;
}
}
} catch (Exception e) {
WakaTime.log.debug(e);
}
}
}
return path;
}
public static boolean isCLIInstalled() {
File cli = new File(Dependencies.getCLILocation());
return cli.exists();
}
public static boolean isCLIOld() {
if (!Dependencies.isCLIInstalled()) {
return false;
}
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getPythonLocation());
cmds.add(Dependencies.getCLILocation());
cmds.add("--version");
try {
Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
p.waitFor();
String output = "";
String s;
while ((s = stdInput.readLine()) != null) {
output += s;
}
while ((s = stdError.readLine()) != null) {
output += s;
}
WakaTime.log.debug("wakatime cli version check output: \"" + output + "\"");
WakaTime.log.debug("wakatime cli version check exit code: " + p.exitValue());
if (p.exitValue() == 0) {
String cliVersion = latestCliVersion();
WakaTime.log.debug("Current cli version from GitHub: " + cliVersion);
if (output.contains(cliVersion))
return false;
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
return true;
}
public static String latestCliVersion() {
String url = "https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py";
try {
String aboutText = getUrlAsString(url);
Pattern p = Pattern.compile("__version_info__ = \\('([0-9]+)', '([0-9]+)', '([0-9]+)'\\)");
Matcher m = p.matcher(aboutText);
if (m.find()) {
return m.group(1) + "." + m.group(2) + "." + m.group(3);
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
return "Unknown";
}
public static String getCLILocation() {
return combinePaths(Dependencies.getResourcesLocation(), "wakatime-master", "wakatime", "cli.py");
}
public static void installCLI() {
File cli = new File(Dependencies.getCLILocation());
if (!cli.getParentFile().getParentFile().getParentFile().exists())
cli.getParentFile().getParentFile().getParentFile().mkdirs();
String url = "https://codeload.github.com/wakatime/wakatime/zip/master";
String zipFile = combinePaths(cli.getParentFile().getParentFile().getParentFile().getAbsolutePath(), "wakatime-cli.zip");
File outputDir = cli.getParentFile().getParentFile().getParentFile();
// download wakatime-master.zip file
if (downloadFile(url, zipFile)) {
// Delete old wakatime-master directory if it exists
File dir = cli.getParentFile().getParentFile();
if (dir.exists()) {
deleteDirectory(dir);
}
try {
Dependencies.unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
} catch (IOException e) {
WakaTime.log.warn(e);
}
}
}
public static void upgradeCLI() {
Dependencies.installCLI();
}
public static void installPython() {
if (isWindows()) {
String pyVer = "3.5.2";
String arch = "win32";
if (is64bit()) arch = "amd64";
String url = "https:
File dir = new File(Dependencies.getResourcesLocation());
File zipFile = new File(combinePaths(dir.getAbsolutePath(), "python.zip"));
if (downloadFile(url, zipFile.getAbsolutePath())) {
File targetDir = new File(combinePaths(dir.getAbsolutePath(), "python"));
// extract python
try {
Dependencies.unzip(zipFile.getAbsolutePath(), targetDir);
} catch (IOException e) {
WakaTime.log.warn(e);
}
zipFile.delete();
}
}
}
public static boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(downloadUrl.openStream());
fos = new FileOutputStream(saveAs);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
return true;
} catch (RuntimeException e) {
WakaTime.log.warn(e);
try {
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection)downloadUrl.openConnection();
InputStream inputStream = conn.getInputStream();
fos = new FileOutputStream(saveAs);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
inputStream.close();
fos.close();
return true;
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.warn(e1);
} catch (KeyManagementException e1) {
WakaTime.log.warn(e1);
} catch (IOException e1) {
WakaTime.log.warn(e1);
}
} catch (IOException e) {
WakaTime.log.warn(e);
}
return false;
}
public static String getUrlAsString(String url) {
StringBuilder text = new StringBuilder();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
try {
InputStream inputStream = downloadUrl.openStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
} catch (RuntimeException e) {
WakaTime.log.warn(e);
try {
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[]{new LocalSSLTrustManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection) downloadUrl.openConnection();
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.warn(e1);
} catch (KeyManagementException e1) {
WakaTime.log.warn(e1);
} catch (UnknownHostException e1) {
WakaTime.log.warn(e1);
} catch (IOException e1) {
WakaTime.log.warn(e1);
}
} catch (UnknownHostException e) {
WakaTime.log.warn(e);
} catch (Exception e) {
WakaTime.log.warn(e);
}
return text.toString();
}
/**
* Configures a proxy if one is set in ~/.wakatime.cfg.
*/
public static void configureProxy() {
String proxyConfig = ConfigFile.get("settings", "proxy");
if (proxyConfig != null && !proxyConfig.trim().equals("")) {
try {
URL proxyUrl = new URL(proxyConfig);
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
final String user = userInfo.split(":")[0];
final String pass = userInfo.split(":")[1];
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(user, pass.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
System.setProperty("https.proxyHost", proxyUrl.getHost());
System.setProperty("https.proxyPort", Integer.toString(proxyUrl.getPort()));
} catch (MalformedURLException e) {
WakaTime.log.error("Proxy string must follow https://user:pass@host:port format: " + proxyConfig);
}
}
}
private static boolean runPython(String path) {
try {
WakaTime.log.debug(path + " --version");
String[] cmds = {path, "--version"};
Process p = Runtime.getRuntime().exec(cmds);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
p.waitFor();
String output = "";
String s;
while ((s = stdInput.readLine()) != null) {
output += s;
}
while ((s = stdError.readLine()) != null) {
output += s;
}
if (output != "")
WakaTime.log.debug(output);
if (p.exitValue() != 0)
throw new Exception("NonZero Exit Code: " + p.exitValue());
return true;
} catch (Exception e) {
WakaTime.log.debug(e.toString());
return false;
}
}
private static void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
path.delete();
}
public static boolean is64bit() {
boolean is64bit = false;
if (isWindows()) {
is64bit = (System.getenv("ProgramFiles(x86)") != null);
} else {
is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
}
return is64bit;
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
public static String combinePaths(String... args) {
File path = null;
for (String arg : args) {
if (arg != null) {
if (path == null)
path = new File(arg);
else
path = new File(path, arg);
}
}
if (path == null)
return null;
return path.toString();
}
} |
package com.xruby.runtime.lang;
import com.xruby.runtime.value.RubyArray;
import com.xruby.runtime.value.ObjectFactory;
/**
* Java does not have multiple inheritance, and RubyException has to be inheritated from Exception.
*/
public class RubyExceptionValue extends RubyBasic {
private RubyException exception_;
private String message_;
public RubyExceptionValue(RubyClass c) {
super(c);
GlobalVariables.set(this, "$!");
}
public RubyExceptionValue(RubyClass c, String message) {
super(c);
message_ = message;
GlobalVariables.set(this, "$!");
}
public void setMessage(String message) {
message_ = message;
}
void setException(RubyException exception) {
exception_ = exception;
}
public String toString() {
return message_;
}
public RubyArray backtrace() {
RubyArray a = new RubyArray();
StackTraceElement[] trace = exception_.getStackTrace();
for (StackTraceElement e : trace) {
String s = e.getClassName();
if (!s.startsWith("com.xruby")) {//filter internal calls
a.add(ObjectFactory.createString(s));
}
}
return a;
}
} |
package sds.assemble.controlflow;
import java.util.LinkedHashSet;
import java.util.Set;
import sds.assemble.LineInstructions;
import sds.classfile.bytecode.BranchOpcode;
import sds.classfile.bytecode.OpcodeInfo;
import sds.classfile.bytecode.LookupSwitch;
import sds.classfile.bytecode.TableSwitch;
/**
* This class is for node of control flow graph.
* @author inagaki
*/
public class CFNode {
private Set<CFEdge> parents;
private Set<CFEdge> children;
private CFNode dominator;
private CFNode immediateDominator;
private OpcodeInfo start;
private OpcodeInfo end;
private int jumpPoint = -1;
private int[] switchJump = new int[0];
// package-private fields.
CFNodeType nodeType;
boolean inTry = false;
boolean inCatch = false;
boolean inFinally = false;
/**
* constructor.
* @param inst instrcutions of a line.
*/
public CFNode(LineInstructions inst) {
int size = inst.getOpcodes().size();
this.start = inst.getOpcodes().getAll()[0];
if(size == 1) {
this.end = start;
} else {
this.end = inst.getOpcodes().getAll()[size-1];
}
this.nodeType = CFNodeType.getType(inst.getOpcodes(), end);
if(nodeType == CFNodeType.Entry) { // if_xx
for(OpcodeInfo op : inst.getOpcodes().getAll()) {
if(op instanceof BranchOpcode) {
this.jumpPoint = ((BranchOpcode)op).getBranch() + op.getPc();
}
}
} else if(nodeType == CFNodeType.Exit || nodeType == CFNodeType.LoopExit) { // goto
this.jumpPoint = ((BranchOpcode)end).getBranch() + end.getPc();
} else if(nodeType == CFNodeType.Switch) { // switch
for(OpcodeInfo op : inst.getOpcodes().getAll()) {
if(op instanceof LookupSwitch) {
LookupSwitch look = (LookupSwitch)op;
this.switchJump = new int[look.getMatch().length + 1];
int[] offsets = look.getOffset();
for(int i = 0; i < switchJump.length-1; i++) {
switchJump[i] = offsets[i] + look.getPc();
}
switchJump[switchJump.length - 1] = look.getDefault() + look.getPc();
break;
} else if(op instanceof TableSwitch) {
TableSwitch table = (TableSwitch)op;
this.switchJump = new int[table.getJumpOffsets().length + 1];
int[] offsets = table.getJumpOffsets();
for(int i = 0; i < switchJump.length-1; i++) {
switchJump[i] = offsets[i] + table.getPc();
}
switchJump[switchJump.length - 1] = table.getDefault() + table.getPc();
break;
}
}
}
this.parents = new LinkedHashSet<>();
this.children = new LinkedHashSet<>();
}
/**
* returns index into code array of jump point.<br>
* if this node type is Entry or Exit (and that of Loop), this method returns -1.
* @return jump point index
*/
public int getJumpPoint() {
return jumpPoint;
}
/**
* returns indexes into code array of jump point.
* @return jump point indexes
*/
public int[] getSwitchJump() {
return switchJump;
}
/**
* returns node type.
* @return node type
*/
public CFNodeType getType() {
return nodeType;
}
/**
* returns parent nodes.
* @return parent nodes
*/
public Set<CFEdge> getParents() {
return parents;
}
/**
* returns immediate dominator node.
* @return immediate dominator node
*/
public CFNode getImmediateDominator() {
return immediateDominator;
}
/**
* returns dominator node.
* @return dominator node
*/
public CFNode getDominator() {
return dominator;
}
/**
* sets immediate dominator node.
* @param node immediate dominator node
*/
public void setImmediateDominator(CFNode node) {
this.immediateDominator = node;
}
/**
* sets dominator node.
* @param node dominator node
*/
public void setDominator(CFNode node) {
this.dominator = node;
}
/**
* adds parent node of this.
* @param parent parent node
*/
public void addParent(CFNode parent) {
addParent(parent, CFEdgeType.Normal);
}
/**
* adds parent node of this.
* @param parent parent node
* @param type edge type
*/
public void addParent(CFNode parent, CFEdgeType type) {
if(!isRoot()) {
CFEdge edge = new CFEdge(this, parent, type);
if(parents.isEmpty()) {
this.immediateDominator = parent;
this.parents.add(edge);
} else {
if(!parents.contains(edge)) {
parents.add(edge);
}
}
}
}
/**
* adds child node of this.
* @param child child node
*/
public void addChild(CFNode child) {
addChild(child, CFEdgeType.Normal);
}
/**
* adds child node of this.
* @param child child node
* @param type edge type
*/
public void addChild(CFNode child, CFEdgeType type) {
CFEdge edge = new CFEdge(this, child, type);
if(!children.contains(edge)) {
children.add(edge);
}
}
/**
* returns whether specified pc is in range of opcode pc of this opcodes.
* @param pc index into code array
* @return if specified pc is in range of opcode pc, this method returns true.<br>
* Otherwise, this method returns false.
*/
public boolean isInPcRange(int pc) {
return start.getPc() <= pc && pc <= end.getPc();
}
/**
* returns whether this node is root.
* @return if this node is root, this method returns true.<br>
* Otherwise, this method returns false.
*/
public boolean isRoot() {
return start.getPc() == 0;
}
/**
* returns start opcode of instructions of this node.
* @return start opcode
*/
public OpcodeInfo getStart() {
return start;
}
/**
* returns end opcode of instructions of this node.
* @return end opcode
*/
public OpcodeInfo getEnd() {
return end;
}
@Override
public int hashCode() {
int h = 0;
char[] val1 = String.valueOf(start.getPc()).toCharArray();
char[] val2 = String.valueOf(end.getPc()).toCharArray();
char[] val3 = start.getOpcodeType().toString().toCharArray();
char[] val4 = end.getOpcodeType().toString().toCharArray();
for(int i = 0; i < val1.length; i++) {
h = 31 * h + val1[i];
}
for(int i = 0; i < val2.length; i++) {
h = 31 * h + val2[i];
}
for(int i = 0; i < val3.length; i++) {
h = 31 * h + val3[i];
}
for(int i = 0; i < val4.length; i++) {
h = 31 * h + val4[i];
}
return h;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof CFNode)) {
return false;
}
CFNode node = (CFNode)obj;
return start.getPc() == node.getStart().getPc()
&& end.getPc() == node.getEnd().getPc();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("#").append(start.getPc()).append("-").append(end.getPc())
.append(" [").append(nodeType).append("]").append("\n");
if(inTry) sb.append(" in try\n");
if(inCatch) sb.append(" in catch\n");
if(inFinally) sb.append(" in finally\n");
if(parents.size() == 1) {
sb.append(" immediate dominator: ").append(parents.iterator().next());
} else if(parents.size() > 1) {
sb.append(" dominator: ")
.append(dominator.getStart().getPc()).append("-")
.append(dominator.getEnd().getPc())
.append("\n parents: ");
for(CFEdge edge : parents) {
sb.append(edge.toString()).append(" ");
}
} else {
sb.append(" parents: not exist");
}
sb.append("\n children: ");
for(CFEdge edge : children) {
sb.append(edge.toString()).append(" ");
}
return sb.toString();
}
} |
package tigase.server;
import tigase.annotations.TODO;
import tigase.net.ConnectionOpenListener;
import tigase.net.ConnectionOpenThread;
import tigase.net.ConnectionType;
import tigase.net.SocketReadThread;
import tigase.net.SocketType;
import tigase.server.script.CommandIfc;
import tigase.stats.StatisticsList;
import tigase.util.DataTypes;
import tigase.xmpp.JID;
import tigase.xmpp.XMPPIOService;
import tigase.xmpp.XMPPIOServiceListener;
import java.io.IOException;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.Bindings;
/**
* Describe class ConnectionManager here.
*
*
* Created: Sun Jan 22 22:52:58 2006
*
* @param <IO>
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public abstract class ConnectionManager<IO extends XMPPIOService<?>>
extends AbstractMessageReceiver implements XMPPIOServiceListener<IO> {
private static final Logger log = Logger.getLogger(ConnectionManager.class.getName());
/** Field description */
public static final String NET_BUFFER_ST_PROP_KEY = "--net-buff-standard";
/** Field description */
public static final String NET_BUFFER_HT_PROP_KEY = "--net-buff-high-throughput";
protected static final String PORT_KEY = "port-no";
protected static final String PROP_KEY = "connections/";
protected static final String PORTS_PROP_KEY = PROP_KEY + "ports";
protected static final String PORT_TYPE_PROP_KEY = "type";
protected static final String PORT_SOCKET_PROP_KEY = "socket";
protected static final String PORT_IFC_PROP_KEY = "ifc";
protected static final String PORT_CLASS_PROP_KEY = "class";
protected static final String PORT_REMOTE_HOST_PROP_KEY = "remote-host";
protected static final String PORT_REMOTE_HOST_PROP_VAL = "localhost";
protected static final String TLS_PROP_KEY = PROP_KEY + "tls/";
protected static final String TLS_USE_PROP_KEY = TLS_PROP_KEY + "use";
protected static final boolean TLS_USE_PROP_VAL = true;
protected static final String TLS_REQUIRED_PROP_KEY = TLS_PROP_KEY + "required";
protected static final boolean TLS_REQUIRED_PROP_VAL = false;
//protected static final String TLS_KEYS_STORE_PROP_KEY = TLS_PROP_KEY + JKS_KEYSTORE_FILE_KEY;
//protected static final String TLS_KEYS_STORE_PROP_VAL = JKS_KEYSTORE_FILE_VAL;
//protected static final String TLS_DEF_CERT_PROP_KEY = TLS_PROP_KEY + DEFAULT_DOMAIN_CERT_KEY;
//protected static final String TLS_DEF_CERT_PROP_VAL = DEFAULT_DOMAIN_CERT_VAL;
//protected static final String TLS_KEYS_STORE_PASSWD_PROP_KEY = TLS_PROP_KEY
// + JKS_KEYSTORE_PWD_KEY;
//protected static final String TLS_KEYS_STORE_PASSWD_PROP_VAL = JKS_KEYSTORE_PWD_VAL;
//protected static final String TLS_TRUSTS_STORE_PASSWD_PROP_KEY = TLS_PROP_KEY
// + TRUSTSTORE_PWD_KEY;
//protected static final String TLS_TRUSTS_STORE_PASSWD_PROP_VAL = TRUSTSTORE_PWD_VAL;
//protected static final String TLS_TRUSTS_STORE_PROP_KEY = TLS_PROP_KEY + TRUSTSTORE_FILE_KEY;
//protected static final String TLS_TRUSTS_STORE_PROP_VAL = TRUSTSTORE_FILE_VAL;
//protected static final String TLS_CONTAINER_CLASS_PROP_KEY = TLS_PROP_KEY
// + SSL_CONTAINER_CLASS_KEY;
//protected static final String TLS_CONTAINER_CLASS_PROP_VAL = SSL_CONTAINER_CLASS_VAL;
//protected static final String TLS_SERVER_CERTS_DIR_PROP_KEY = TLS_PROP_KEY + SERVER_CERTS_DIR_KEY;
//protected static final String TLS_SERVER_CERTS_DIR_PROP_VAL = SERVER_CERTS_DIR_VAL;
//protected static final String TLS_TRUSTED_CERTS_DIR_PROP_KEY = TLS_PROP_KEY
// + TRUSTED_CERTS_DIR_KEY;
//protected static final String TLS_TRUSTED_CERTS_DIR_PROP_VAL = TRUSTED_CERTS_DIR_VAL;
//protected static final String TLS_ALLOW_SELF_SIGNED_CERTS_PROP_KEY = TLS_PROP_KEY
// + ALLOW_SELF_SIGNED_CERTS_KEY;
//protected static final String TLS_ALLOW_SELF_SIGNED_CERTS_PROP_VAL = ALLOW_SELF_SIGNED_CERTS_VAL;
//protected static final String TLS_ALLOW_INVALID_CERTS_PROP_KEY = TLS_PROP_KEY
// + ALLOW_INVALID_CERTS_KEY;
//protected static final String TLS_ALLOW_INVALID_CERTS_PROP_VAL = ALLOW_INVALID_CERTS_VAL;
protected static final String MAX_RECONNECTS_PROP_KEY = "max-reconnects";
protected static final String NET_BUFFER_PROP_KEY = "net-buffer";
protected static final int NET_BUFFER_ST_PROP_VAL = 2 * 1024;
protected static final int NET_BUFFER_HT_PROP_VAL = 64 * 1024;
/** Field description */
public static final String PORT_LOCAL_HOST_PROP_KEY = "local-host";
private static ConnectionOpenThread connectThread = ConnectionOpenThread.getInstance();
private static SocketReadThread readThread = SocketReadThread.getInstance();
/** Field description */
public String[] PORT_IFC_PROP_VAL = { "*" };
private long bytesReceived = 0;
private long bytesSent = 0;
// services.size() call is very slow due to the implementation details
// Therefore for often size retrieval this value is calculated separately.
private int services_size = 0;
private long socketOverflow = 0;
private Thread watchdog = null;
private long watchdogRuns = 0;
private long watchdogStopped = 0;
private long watchdogTests = 0;
private LinkedList<Map<String, Object>> waitingTasks = new LinkedList<Map<String, Object>>();
private ConcurrentHashMap<String, IO> services = new ConcurrentHashMap<String, IO>();
private Set<ConnectionListenerImpl> pending_open =
Collections.synchronizedSet(new HashSet<ConnectionListenerImpl>());;
protected int net_buffer = NET_BUFFER_ST_PROP_VAL;
private IOServiceStatisticsGetter ioStatsGetter = new IOServiceStatisticsGetter();
//protected long startDelay = 5 * SECOND;
private boolean initializationCompleted = false;
protected long connectionDelay = 2 * SECOND;
/**
* Method description
*
*
* @param serv
*
* @return
*/
public abstract Queue<Packet> processSocketData(IO serv);
/**
* Method description
*
*
* @param port_props
*/
public abstract void reconnectionFailed(Map<String, Object> port_props);
protected abstract long getMaxInactiveTime();
protected abstract IO getXMPPIOServiceInstance();
/**
* Method description
*
*/
@Override
public synchronized void everyMinute() {
super.everyMinute();
doForAllServices(ioStatsGetter);
}
/**
* Method description
*
*
* @param params
*
* @return
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
log.log(Level.CONFIG, "{0} defaults: {1}", new Object[] { getName(), params.toString() });
Map<String, Object> props = super.getDefaults(params);
props.put(TLS_USE_PROP_KEY, TLS_USE_PROP_VAL);
// props.put(TLS_DEF_CERT_PROP_KEY, TLS_DEF_CERT_PROP_VAL);
// props.put(TLS_KEYS_STORE_PROP_KEY, TLS_KEYS_STORE_PROP_VAL);
// props.put(TLS_KEYS_STORE_PASSWD_PROP_KEY, TLS_KEYS_STORE_PASSWD_PROP_VAL);
// props.put(TLS_TRUSTS_STORE_PROP_KEY, TLS_TRUSTS_STORE_PROP_VAL);
// props.put(TLS_TRUSTS_STORE_PASSWD_PROP_KEY, TLS_TRUSTS_STORE_PASSWD_PROP_VAL);
// props.put(TLS_SERVER_CERTS_DIR_PROP_KEY, TLS_SERVER_CERTS_DIR_PROP_VAL);
// props.put(TLS_TRUSTED_CERTS_DIR_PROP_KEY, TLS_TRUSTED_CERTS_DIR_PROP_VAL);
// props.put(TLS_ALLOW_SELF_SIGNED_CERTS_PROP_KEY, TLS_ALLOW_SELF_SIGNED_CERTS_PROP_VAL);
// props.put(TLS_ALLOW_INVALID_CERTS_PROP_KEY, TLS_ALLOW_INVALID_CERTS_PROP_VAL);
// if (params.get("--" + SSL_CONTAINER_CLASS_KEY) != null) {
// props.put(TLS_CONTAINER_CLASS_PROP_KEY, (String) params.get("--" + SSL_CONTAINER_CLASS_KEY));
// } else {
// props.put(TLS_CONTAINER_CLASS_PROP_KEY, TLS_CONTAINER_CLASS_PROP_VAL);
int buffSize = NET_BUFFER_ST_PROP_VAL;
if (isHighThroughput()) {
buffSize = DataTypes.parseSizeInt((String) params.get(NET_BUFFER_HT_PROP_KEY),
NET_BUFFER_HT_PROP_VAL);
} else {
buffSize = DataTypes.parseSizeInt((String) params.get(NET_BUFFER_ST_PROP_KEY),
NET_BUFFER_ST_PROP_VAL);
}
props.put(NET_BUFFER_PROP_KEY, buffSize);
int[] ports = null;
String ports_str = (String) params.get("--" + getName() + "-ports");
if (ports_str != null) {
String[] ports_stra = ports_str.split(",");
ports = new int[ports_stra.length];
int k = 0;
for (String p : ports_stra) {
try {
ports[k++] = Integer.parseInt(p);
} catch (Exception e) {
log.warning("Incorrect ports default settings: " + p);
}
}
}
int ports_size = 0;
if (ports != null) {
log.config("Port settings preset: " + Arrays.toString(ports));
for (int port : ports) {
putDefPortParams(props, port, SocketType.plain);
} // end of for (int i = 0; i < idx; i++)
props.put(PORTS_PROP_KEY, ports);
} else {
int[] plains = getDefPlainPorts();
if (plains != null) {
ports_size += plains.length;
} // end of if (plains != null)
int[] ssls = getDefSSLPorts();
if (ssls != null) {
ports_size += ssls.length;
} // end of if (ssls != null)
if (ports_size > 0) {
ports = new int[ports_size];
} // end of if (ports_size > 0)
if (ports != null) {
int idx = 0;
if (plains != null) {
idx = plains.length;
for (int i = 0; i < idx; i++) {
ports[i] = plains[i];
putDefPortParams(props, ports[i], SocketType.plain);
} // end of for (int i = 0; i < idx; i++)
} // end of if (plains != null)
if (ssls != null) {
for (int i = idx; i < idx + ssls.length; i++) {
ports[i] = ssls[i - idx];
putDefPortParams(props, ports[i], SocketType.ssl);
} // end of for (int i = 0; i < idx + ssls.length; i++)
} // end of if (ssls != null)
props.put(PORTS_PROP_KEY, ports);
} // end of if (ports != null)
}
return props;
}
/**
* Generates the component statistics.
* @param list is a collection to put the component statistics in.
*/
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
list.add(getName(), "Open connections", services_size, Level.INFO);
if (list.checkLevel(Level.FINEST)) {
int waitingToSendSize = 0;
for (IO serv : services.values()) {
waitingToSendSize += serv.waitingToSendSize();
}
list.add(getName(), "Waiting to send", waitingToSendSize, Level.FINEST);
}
list.add(getName(), "Bytes sent", bytesSent, Level.FINE);
list.add(getName(), "Bytes received", bytesReceived, Level.FINE);
list.add(getName(), "Socket overflow", socketOverflow, Level.FINE);
list.add(getName(), "Watchdog runs", watchdogRuns, Level.FINER);
list.add(getName(), "Watchdog tests", watchdogTests, Level.FINE);
list.add(getName(), "Watchdog stopped", watchdogStopped, Level.FINE);
// StringBuilder sb = new StringBuilder("All connected: ");
// for (IOService serv: services.values()) {
// sb.append("\nService ID: " + getUniqueId(serv)
// + ", local-hostname: " + serv.getSessionData().get("local-hostname")
// + ", remote-hostname: " + serv.getSessionData().get("remote-hostname")
// + ", is-connected: " + serv.isConnected()
// + ", connection-type: " + serv.connectionType());
// log.finest(sb.toString());
}
/**
* This method can be overwritten in extending classes to get a different
* packets distribution to different threads. For PubSub, probably better
* packets distribution to different threads would be based on the
* sender address rather then destination address.
* @param packet
* @return
*/
@Override
public int hashCodeForPacket(Packet packet) {
if (packet.getStanzaTo() != null) {
return packet.getStanzaTo().hashCode();
}
if (packet.getTo() != null) {
return packet.getTo().hashCode();
}
return super.hashCodeForPacket(packet);
}
/**
* Method description
*
*
* @param binds
*/
@Override
public void initBindings(Bindings binds) {
super.initBindings(binds);
binds.put(CommandIfc.SERVICES_MAP, services);
}
/**
* Method description
*
*/
@Override
public void initializationCompleted() {
initializationCompleted = true;
for (Map<String, Object> params : waitingTasks) {
reconnectService(params, connectionDelay);
}
waitingTasks.clear();
}
// Implementation of tigase.net.PacketListener
///**
// * Describe <code>packetsReady</code> method here.
// *
// * @param s an <code>IOService</code> value
// * @throws IOException
// */
//@SuppressWarnings({"unchecked"})
//@Override
//public void packetsReady(IOService s) throws IOException {
// if (log.isLoggable(Level.FINEST)) {
// log.finest("packetsReady called");
// IO serv = (IO)s;
// packetsReady(serv);
/**
* Method description
*
*
* @param serv
*
* @throws IOException
*/
@Override
public void packetsReady(IO serv) throws IOException {
writePacketsToSocket(serv, processSocketData(serv));
}
/**
* Method description
*
*
* @param packet
*/
@Override
public void processPacket(Packet packet) {
writePacketToSocket(packet);
}
/**
* Method description
*
*
* @return
*/
@Override
public int processingThreads() {
return Runtime.getRuntime().availableProcessors() * 8;
}
/**
* Method description
*
*/
@Override
public void release() {
// delayedTasks.cancel();
releaseListeners();
super.release();
}
/**
* Method description
*
*
* @param service
*/
@TODO(note = "Do something if service with the same unique ID is already started, "
+ "possibly kill the old one...")
public void serviceStarted(final IO service) {
// synchronized(services) {
String id = getUniqueId(service);
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "[[{0}]] Connection started: {1}", new Object[] { getName(), service });
}
IO serv = services.get(id);
if (serv != null) {
if (serv == service) {
log.log(Level.WARNING,
"{0}: That would explain a lot, adding the same service twice, ID: {1}",
new Object[] { getName(),
serv });
} else {
// Is it at all possible to happen???
// let's log it for now....
log.log(Level.WARNING, "{0}: Attempt to add different service with the same ID: {1}",
new Object[] { getName(),
service });
// And stop the old service....
serv.stop();
}
}
services.put(id, service);
++services_size;
}
//@SuppressWarnings({"unchecked"})
//@Override
//public void serviceStopped(IOService s) {
// IO ios = (IO)s;
// serviceStopped(ios);
/**
*
* @param service
* @return
*/
@Override
public boolean serviceStopped(IO service) {
// Hopefuly there is no exception at this point, but just in case...
// This is a very fresh code after all
try {
ioStatsGetter.check(service);
} catch (Exception e) {
log.log(Level.INFO, "Nothing serious to worry about but please notify the developer.", e);
}
// synchronized(service) {
String id = getUniqueId(service);
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "[[{0}]] Connection stopped: {1}", new Object[] { getName(), service });
}
// id might be null if service is stopped in accept method due to
// an exception during establishing TCP/IP connection
// IO serv = (id != null ? services.get(id) : null);
if (id != null) {
boolean result = services.remove(id, service);
if (result) {
--services_size;
} else {
// Is it at all possible to happen???
// let's log it for now....
log.log(Level.WARNING, "[[{0}]] Attempt to stop incorrect service: {1}",
new Object[] { getName(),
service });
Thread.dumpStack();
}
return result;
}
return false;
}
/**
* Method description
*
*
* @param name
*/
@Override
public void setName(String name) {
super.setName(name);
watchdog = new Thread(new Watchdog(), "Watchdog - " + name);
watchdog.setDaemon(true);
watchdog.start();
}
/**
* Method description
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
net_buffer = (Integer) props.get(NET_BUFFER_PROP_KEY);
releaseListeners();
int[] ports = (int[]) props.get(PORTS_PROP_KEY);
if (ports != null) {
for (int i = 0; i < ports.length; i++) {
Map<String, Object> port_props = new LinkedHashMap<String, Object>(20);
for (Map.Entry<String, Object> entry : props.entrySet()) {
if (entry.getKey().startsWith(PROP_KEY + ports[i])) {
int idx = entry.getKey().lastIndexOf('/');
String key = entry.getKey().substring(idx + 1);
log.log(Level.CONFIG, "Adding port property key: {0}={1}", new Object[] { key,
entry.getValue() });
port_props.put(key, entry.getValue());
} // end of if (entry.getKey().startsWith())
} // end of for ()
port_props.put(PORT_KEY, ports[i]);
addWaitingTask(port_props);
// reconnectService(port_props, startDelay);
} // end of for (int i = 0; i < ports.length; i++)
} // end of if (ports != null)
if ((Boolean) props.get(TLS_USE_PROP_KEY)) {
Map<String, String> tls_params = new LinkedHashMap<String, String>(20);
// tls_params.put(SSL_CONTAINER_CLASS_KEY, (String) props.get(TLS_CONTAINER_CLASS_PROP_KEY));
// tls_params.put(DEFAULT_DOMAIN_CERT_KEY, (String) props.get(TLS_DEF_CERT_PROP_KEY));
// tls_params.put(JKS_KEYSTORE_FILE_KEY, (String) props.get(TLS_KEYS_STORE_PROP_KEY));
// tls_params.put(JKS_KEYSTORE_PWD_KEY, (String) props.get(TLS_KEYS_STORE_PASSWD_PROP_KEY));
// tls_params.put(TRUSTSTORE_FILE_KEY, (String) props.get(TLS_TRUSTS_STORE_PROP_KEY));
// tls_params.put(TRUSTSTORE_PWD_KEY, (String) props.get(TLS_TRUSTS_STORE_PASSWD_PROP_KEY));
// tls_params.put(SERVER_CERTS_DIR_KEY, (String) props.get(TLS_SERVER_CERTS_DIR_PROP_KEY));
// tls_params.put(TRUSTED_CERTS_DIR_KEY, (String) props.get(TLS_TRUSTED_CERTS_DIR_PROP_KEY));
// tls_params.put(ALLOW_SELF_SIGNED_CERTS_KEY,
// (String) props.get(TLS_ALLOW_SELF_SIGNED_CERTS_PROP_KEY));
// tls_params.put(ALLOW_INVALID_CERTS_KEY, (String) props.get(TLS_ALLOW_INVALID_CERTS_PROP_KEY));
// TLSUtil.configureSSLContext(getName(), tls_params);
} // end of if (use.equalsIgnoreCase())
}
/**
* Method description
*
*/
@Override
public void start() {
super.start();
// delayedTasks = new Timer(getName() + " - delayed connections", true);
}
/**
* Method description
*
*
* @param ios
* @param p
*
* @return
*/
public boolean writePacketToSocket(IO ios, Packet p) {
if (ios != null) {
if (log.isLoggable(Level.FINER) &&!log.isLoggable(Level.FINEST)) {
log.log(Level.FINER, "{0}, Processing packet: {1}, type: {2}", new Object[] { ios,
p.getElemName(), p.getType() });
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] { ios, p });
}
// synchronized (ios) {
ios.addPacketToSend(p);
try {
ios.processWaitingPackets();
readThread.addSocketService(ios);
return true;
} catch (Exception e) {
log.log(Level.WARNING, ios + "Exception during writing packets: ", e);
try {
ios.stop();
} catch (Exception e1) {
log.log(Level.WARNING, ios + "Exception stopping XMPPIOService: ", e1);
} // end of try-catch
} // end of try-catch
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Can''t find service for packet: <{0}> {1}, service id: {2}",
new Object[] { p.getElemName(),
p.getTo(), getServiceId(p) });
}
} // end of if (ios != null) else
return false;
}
/**
* Method description
*
*
* @param serv
* @param packets
*/
public void writePacketsToSocket(IO serv, Queue<Packet> packets) {
if (serv != null) {
// synchronized (serv) {
if ((packets != null) && (packets.size() > 0)) {
Packet p = null;
while ((p = packets.poll()) != null) {
if (log.isLoggable(Level.FINER) &&!log.isLoggable(Level.FINEST)) {
log.log(Level.FINER, "{0}, Processing packet: {1}, type: {2}", new Object[] { serv,
p.getElemName(), p.getType() });
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] { serv, p });
}
serv.addPacketToSend(p);
} // end of for ()
try {
serv.processWaitingPackets();
readThread.addSocketService(serv);
} catch (Exception e) {
log.log(Level.WARNING, serv + "Exception during writing packets: ", e);
try {
serv.stop();
} catch (Exception e1) {
log.log(Level.WARNING, serv + "Exception stopping XMPPIOService: ", e1);
} // end of try-catch
} // end of try-catch
}
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Can't find service for packets: [{0}] ", packets);
}
} // end of if (ios != null) else
}
protected void addWaitingTask(Map<String, Object> conn) {
if (initializationCompleted) {
reconnectService(conn, connectionDelay);
} else {
waitingTasks.add(conn);
}
}
//@SuppressWarnings({"unchecked"})
//@Override
//public void streamClosed(IO s) {
// IO serv = (IO)s;
// xmppStreamClosed(serv);
//public abstract void xmppStreamClosed(IO serv);
///**
// * The method is called upon XMPP stream open event.
// * @param s is an XMPPIOService object associated with the newly opened network
// * connection.
// * @param attribs is a Map with all attributes found in the XMPP Stream open element.
// * @return A String of raw data which should be sent back to the network
// * connection.
// */
//@SuppressWarnings({"unchecked"})
//@Override
//public String streamOpened(IO s, Map<String, String> attribs) {
// IO serv = (IO)s;
// return xmppStreamOpened(serv, attribs);
///**
// * Method is called on the new XMPP Stream open event. This method is normally
// * called from streamOpen(...) method.
// * @param s is an IOService object associated with the network connection
// * where the XMPP Stream open event occured.
// * @param attribs is a Map with all attributes found in the XMPP Stream open element.
// * @return A String of raw data which should be sent back to the network
// * connection.
// */
//public abstract String xmppStreamOpened(IO s, Map<String, String> attribs);
/**
* Returns number of active network connections (IOServices).
* @return number of active network connections (IOServices).
*/
protected int countIOServices() {
return services.size();
}
/**
* Perform a given action defined by ServiceChecker for all active IOService
* objects (active network connections).
* @param checker is a <code>ServiceChecker</code> instance defining an action
* to perform for all IOService objects.
*/
protected void doForAllServices(ServiceChecker<IO> checker) {
for (IO service : services.values()) {
checker.check(service);
}
}
protected int[] getDefPlainPorts() {
return null;
}
protected int[] getDefSSLPorts() {
return null;
}
protected Map<String, Object> getParamsForPort(int port) {
return null;
}
protected String getServiceId(Packet packet) {
return getServiceId(packet.getTo());
}
protected String getServiceId(JID jid) {
return jid.getResource();
}
protected String getUniqueId(IO serv) {
return serv.getUniqueId();
}
protected IO getXMPPIOService(String serviceId) {
return services.get(serviceId);
}
protected IO getXMPPIOService(Packet p) {
return services.get(getServiceId(p));
}
protected boolean isHighThroughput() {
return false;
}
/**
*
* @param p
* @return
*/
protected boolean writePacketToSocket(Packet p) {
IO ios = getXMPPIOService(p);
if (ios != null) {
return writePacketToSocket(ios, p);
} else {
return false;
}
}
protected boolean writePacketToSocket(Packet p, String serviceId) {
IO ios = getXMPPIOService(serviceId);
if (ios != null) {
return writePacketToSocket(ios, p);
} else {
return false;
}
}
protected void writeRawData(IO ios, String data) {
// synchronized (ios) {
try {
ios.writeRawData(data);
readThread.addSocketService(ios);
} catch (Exception e) {
log.log(Level.WARNING, ios + "Exception during writing data: " + data, e);
try {
ios.stop();
} catch (Exception e1) {
log.log(Level.WARNING, ios + "Exception stopping XMPPIOService: ", e1);
} // end of try-catch
}
}
private void putDefPortParams(Map<String, Object> props, int port, SocketType sock) {
log.log(Level.CONFIG, "Generating defaults for port: {0}", port);
props.put(PROP_KEY + port + "/" + PORT_TYPE_PROP_KEY, ConnectionType.accept);
props.put(PROP_KEY + port + "/" + PORT_SOCKET_PROP_KEY, sock);
props.put(PROP_KEY + port + "/" + PORT_IFC_PROP_KEY, PORT_IFC_PROP_VAL);
props.put(PROP_KEY + port + "/" + PORT_REMOTE_HOST_PROP_KEY, PORT_REMOTE_HOST_PROP_VAL);
props.put(PROP_KEY + port + "/" + TLS_REQUIRED_PROP_KEY, TLS_REQUIRED_PROP_VAL);
Map<String, Object> extra = getParamsForPort(port);
if (extra != null) {
for (Map.Entry<String, Object> entry : extra.entrySet()) {
props.put(PROP_KEY + port + "/" + entry.getKey(), entry.getValue());
} // end of for ()
} // end of if (extra != null)
}
private void reconnectService(final Map<String, Object> port_props, long delay) {
if (log.isLoggable(Level.FINER)) {
String cid = "" + port_props.get("local-hostname") + "@" + port_props.get("remote-hostname");
log.log(Level.FINER,
"Reconnecting service for: {0}, scheduling next try in {1}secs, cid: {2}",
new Object[] { getName(),
delay / 1000, cid });
}
addTimerTask(new TimerTask() {
@Override
public void run() {
String host = (String) port_props.get(PORT_REMOTE_HOST_PROP_KEY);
if (host == null) {
host = (String) port_props.get("remote-hostname");
}
int port = (Integer) port_props.get(PORT_KEY);
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE,
"Reconnecting service for component: {0}, to remote host: {1} on port: {2}",
new Object[] { getName(),
host, port });
}
startService(port_props);
}
}, delay);
}
private void releaseListeners() {
for (ConnectionListenerImpl cli : pending_open) {
connectThread.removeConnectionOpenListener(cli);
}
pending_open.clear();
}
private void startService(Map<String, Object> port_props) {
ConnectionListenerImpl cli = new ConnectionListenerImpl(port_props);
if (cli.getConnectionType() == ConnectionType.accept) {
pending_open.add(cli);
}
connectThread.addConnectionOpenListener(cli);
}
private class ConnectionListenerImpl implements ConnectionOpenListener {
private Map<String, Object> port_props = null;
private ConnectionListenerImpl(Map<String, Object> port_props) {
this.port_props = port_props;
}
/**
* Method description
*
*
* @param sc
*/
@SuppressWarnings({ "unchecked" })
@Override
public void accept(SocketChannel sc) {
String cid = "" + port_props.get("local-hostname") + "@" + port_props.get("remote-hostname");
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Accept called for service: {0}", cid);
}
IO serv = getXMPPIOServiceInstance();
// serv.setSSLId(getName());
serv.setIOServiceListener(ConnectionManager.this);
serv.setSessionData(port_props);
try {
serv.accept(sc);
if (getSocketType() == SocketType.ssl) {
serv.startSSL(false);
} // end of if (socket == SocketType.ssl)
serviceStarted(serv);
readThread.addSocketService(serv);
} catch (SocketException e) {
if (getConnectionType() == ConnectionType.connect) {
// Accept side for component service is not ready yet?
// Let's wait for a few secs and try again.
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Problem reconnecting the service: {0}, cid: {1}",
new Object[] { serv,
cid });
}
boolean reconnect = false;
Integer reconnects = (Integer) port_props.get(MAX_RECONNECTS_PROP_KEY);
if (reconnects != null) {
int recon = reconnects.intValue();
if (recon != 0) {
port_props.put(MAX_RECONNECTS_PROP_KEY, (--recon));
reconnect = true;
} // end of if (recon != 0)
}
if (reconnect) {
reconnectService(port_props, connectionDelay);
} else {
reconnectionFailed(port_props);
}
} else {
// Ignore
}
} catch (Exception e) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Can not accept connection cid: " + cid, e);
}
log.log(Level.WARNING, "Can not accept connection.", e);
serv.stop();
} // end of try-catch
}
/**
* Method description
*
*
* @return
*/
@Override
public ConnectionType getConnectionType() {
String type = null;
if (port_props.get(PORT_TYPE_PROP_KEY) == null) {
log.warning(getName() + ": connection type is null: "
+ port_props.get(PORT_KEY).toString());
} else {
type = port_props.get(PORT_TYPE_PROP_KEY).toString();
}
return ConnectionType.valueOf(type);
}
/**
* Method description
*
*
* @return
*/
@Override
public String[] getIfcs() {
return (String[]) port_props.get(PORT_IFC_PROP_KEY);
}
/**
* Method description
*
*
* @return
*/
@Override
public int getPort() {
return (Integer) port_props.get(PORT_KEY);
}
/**
* Method description
*
*
* @return
*/
@Override
public int getReceiveBufferSize() {
return net_buffer;
}
/**
* Method description
*
*
* @return
*/
public SocketType getSocketType() {
return SocketType.valueOf(port_props.get(PORT_SOCKET_PROP_KEY).toString());
}
/**
* Method description
*
*
* @return
*/
@Override
public int getTrafficClass() {
if (isHighThroughput()) {
return IPTOS_THROUGHPUT;
} else {
return DEF_TRAFFIC_CLASS;
}
}
/**
* Method description
*
*
* @return
*/
@Override
public String toString() {
return port_props.toString();
}
}
private class IOServiceStatisticsGetter implements ServiceChecker<IO> {
private StatisticsList list = new StatisticsList(Level.ALL);
/**
* Method description
*
*
* @param service
*/
@Override
public synchronized void check(IO service) {
service.getStatistics(list, true);
bytesReceived += list.getValue("socketio", "Bytes received", -1l);
bytesSent += list.getValue("socketio", "Bytes sent", -1l);
socketOverflow += list.getValue("socketio", "Buffers overflow", -1l);
}
}
/**
* Looks in all established connections and checks whether any of them
* is dead....
*
*/
private class Watchdog implements Runnable {
/**
* Method description
*
*/
@Override
public void run() {
while (true) {
try {
// Sleep...
Thread.sleep(10 * MINUTE);
++watchdogRuns;
// Walk through all connections and check whether they are
// really alive...., try to send space for each service which
// is inactive for hour or more and close the service
// on Exception
doForAllServices(new ServiceChecker<IO>() {
@Override
public void check(final XMPPIOService service) {
// for (IO service: services.values()) {
// service = (XMPPIOService)serv;
try {
if (null != service) {
long curr_time = System.currentTimeMillis();
long lastTransfer = service.getLastTransferTime();
if (curr_time - lastTransfer >= getMaxInactiveTime()) {
// Stop the service is max keep-alive time is acceeded
// for non-active connections.
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO, "{0}: Max inactive time exceeded, stopping: {1}",
new Object[] { getName(),
service });
}
++watchdogStopped;
service.stop();
} else {
if (curr_time - lastTransfer >= (29 * MINUTE)) {
// At least once an hour check if the connection is
// still alive.
service.writeRawData(" ");
++watchdogTests;
}
}
}
} catch (Exception e) {
// Close the service....
try {
if (service != null) {
log.info(getName() + "Found dead connection, stopping: " + service);
++watchdogStopped;
service.forceStop();
}
} catch (Exception ignore) {
// Do nothing here as we expect Exception to be thrown here...
}
}
}
});
} catch (InterruptedException e) { /* Do nothing here */
}
}
}
}
} // ConnectionManager
//~ Formatted in Sun Code Convention |
package com.fpt.u0.main;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
/**
* Application
*
* @author senycorp
*/
public class Application extends javafx.application.Application{
private Button[][] btnArray;
private Label lblOn;
private Label lblOff;
public static void main(String[] args) {
System.out.println("Launching application...");
javafx.application.Application.launch(args);
}
@Override
/**
* Test sufian
* Start GUI-Application
*/
public void start(Stage primaryStage) throws Exception {
this.btnArray = new Button[5][5];
GridPane frame = new GridPane();
frame.setHgap(1.5);
frame.setVgap(1.5);
frame.setPadding(new Insets(0, 0, 0, 0));
// Create buttons in array
for (int i = 0 ; i < 5 ; i++) {
for (int j = 0 ; j < 5 ; j++) {
// Create button
this.btnArray[i][j] = new Button();
// Add it to the frame
frame.add(this.btnArray[i][j], i+1, j);
// Setting some style properties
this.btnArray[i][j].setMinSize(60, 70);
this.btnArray[i][j].setStyle("-fx-background-color: Blue");
// Set coordinates of button as user data
ButtonState btnState = new ButtonState(i, j , false);
this.btnArray[i][j].setUserData(btnState);
// Set action handler
this.btnArray[i][j].setOnAction(e -> {btnClick(e);});
}
}
// Introduce reset button
Button btnReset = new Button("Reset");
btnReset.setOnAction(e -> {
// Create buttons in array
for (int i = 0 ; i < 5 ; i++) {
for (int j = 0 ; j < 5 ; j++) {
((ButtonState)this.btnArray[i][j].getUserData()).setState(false);
}
}
this.drawBtns();
});
// Introduce labels
this.lblOn = new Label("0");
this.lblOff = new Label("25");
frame.add(btnReset, 1, 7);
frame.add(lblOn, 4, 7);
frame.add(lblOff, 5, 7);
// Setting some Styling
lblOff.setStyle("-fx-background-color: Blue");
lblOn.setStyle("-fx-background-color: yellow");
// Create scene and prepare stage
Scene scene = new Scene(frame,311,400);
primaryStage.setScene(scene);
primaryStage.setTitle("Hello World");
primaryStage.show();
}
/**
* Event handler for buttons in grid pane
*
* @param e
*/
public void btnClick(Event e) {
Object source = e.getSource();
if (source instanceof Button) { //should always be true in your example
Button clickedBtn = (Button) source; // that's the button that was clicked
ButtonState btnState = ((ButtonState)clickedBtn.getUserData());
System.out.println(clickedBtn.getUserData());
// Check for false state of clicked button
//if (btnState.getState() == false) {
// Set to true
btnState.invert();
// Set states of neighbours
if ((btnState.getRow() - 1) >= 0) {
((ButtonState) this.btnArray[btnState.getRow() - 1][btnState.getColumn()].getUserData()).invert();
System.out.println((btnState.getRow()) +" "+ (btnState.getColumn()+1));
}
if ((btnState.getRow() + 1) <= 4) {
((ButtonState)this.btnArray[btnState.getRow() + 1][btnState.getColumn()].getUserData()).invert();
System.out.println((btnState.getRow() + 2) +" "+ (btnState.getColumn()+1));
}
if ((btnState.getColumn() - 1) >= 0) {
((ButtonState)this.btnArray[btnState.getRow()][btnState.getColumn()-1].getUserData()).invert();
System.out.println((btnState.getRow() + 1) +" "+ (btnState.getColumn()));
}
if ((btnState.getColumn() + 1) <= 4) {
((ButtonState)this.btnArray[btnState.getRow()][btnState.getColumn()+1].getUserData()).invert();
System.out.println((btnState.getRow() + 1) +" "+ (btnState.getColumn()+2));
}
// Draw buttons
this.drawBtns();
}
}
/**
* Mark Buttons
*/
private void drawBtns() {
int on = 0;
// Iterate over all buttons an count the states
for (int i = 0 ; i < 5 ; i++) {
for (int j = 0 ; j < 5 ; j++) {
if (((ButtonState)(this.btnArray[i][j].getUserData())).getState() == true ) {
this.btnArray[i][j].setStyle("-fx-background-color: yellow");
on++;
} else {
this.btnArray[i][j].setStyle("-fx-background-color: Blue");
}
}
}
// Set label text
this.lblOff.setText(Integer.toString(25-on));
this.lblOn.setText(Integer.toString(on));
}
} |
package tonius.zoom.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import tonius.zoom.ItemBinoculars;
import tonius.zoom.Zoom;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.RenderTickEvent;
public class EventHandler {
private static final Minecraft mc = Minecraft.getMinecraft();
private static final ResourceLocation OVERLAY_TEXTURE = new ResourceLocation(Zoom.MODID, "textures/gui/binoculars.png");
private static final float MIN_ZOOM = 1 / 1.5F;
private static final float MAX_ZOOM = 1 / 10.0F;
private static float currentZoom = 1 / 6.0F;
private static boolean renderPlayerAPILoaded = false;
public static void init() {
renderPlayerAPILoaded = Loader.isModLoaded("RenderPlayerAPI");
EventHandler handler = new EventHandler();
FMLCommonHandler.instance().bus().register(handler);
MinecraftForge.EVENT_BUS.register(handler);
}
@SubscribeEvent
public void onFOVUpdate(FOVUpdateEvent evt) {
if (isUsingBinoculars() && mc.gameSettings.thirdPersonView == 0) {
evt.newfov = currentZoom;
}
}
@SubscribeEvent
public void onMouseScroll(MouseEvent evt) {
if (isUsingBinoculars() && evt.dwheel != 0 && mc.gameSettings.thirdPersonView == 0) {
currentZoom = 1 / Math.min(Math.max(1 / currentZoom + evt.dwheel / 180F, 1 / MIN_ZOOM), 1 / MAX_ZOOM);
evt.setCanceled(true);
}
}
@SubscribeEvent
public void onRenderTick(RenderTickEvent evt) {
if (evt.phase != Phase.END) {
return;
}
if (isUsingBinoculars() && mc.gameSettings.thirdPersonView == 0) {
GL11.glPushMatrix();
mc.entityRenderer.setupOverlayRendering();
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_ALPHA_TEST);
mc.renderEngine.bindTexture(OVERLAY_TEXTURE);
ScaledResolution res = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
double width = res.getScaledWidth_double();
double height = res.getScaledHeight_double();
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0.0D, height, -90.0D, 0.0D, 1.0D);
tessellator.addVertexWithUV(width, height, -90.0D, 1.0D, 1.0D);
tessellator.addVertexWithUV(width, 0.0D, -90.0D, 1.0D, 0.0D);
tessellator.addVertexWithUV(0.0D, 0.0D, -90.0D, 0.0D, 0.0D);
tessellator.draw();
GL11.glPopMatrix();
}
}
@SubscribeEvent
public void onRenderHand(RenderHandEvent evt) {
if (isUsingBinoculars()) {
evt.setCanceled(true);
}
}
@SubscribeEvent
public void onRenderHeldItem(RenderPlayerEvent.Specials.Pre evt) {
if (renderPlayerAPILoaded && isUsingBinoculars(evt.entityPlayer, false)) {
evt.renderItem = false;
}
}
private static boolean isUsingBinoculars(EntityPlayer player, boolean keybind) {
ItemStack stack = player.getItemInUse();
if (stack != null && stack.getItem() instanceof ItemBinoculars) {
return true;
} else if (keybind && KeyHandler.keyZoom.getIsKeyPressed()) {
for (ItemStack invStack : player.inventory.mainInventory) {
if (invStack != null && invStack.getItem() instanceof ItemBinoculars) {
return true;
}
}
}
return false;
}
private static boolean isUsingBinoculars(boolean keybind) {
EntityPlayer player = mc.thePlayer;
if (player == null) {
return false;
}
return isUsingBinoculars(player, keybind);
}
private static boolean isUsingBinoculars() {
return isUsingBinoculars(true);
}
} |
package tsdaggregator;
import org.apache.log4j.Logger;
import org.joda.time.Period;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
public class RRDSingleListener {
static final Logger _Logger = Logger.getLogger(RRDSingleListener.class);
private String _FileName;
private DecimalFormat doubleFormat = new DecimalFormat("
public RRDSingleListener(AggregatedData data) {
String rrdName = data.getHost() + "." + data.getMetric() + "." + data.getPeriod().toString() + data.getStatistic().getName() + ".rrd";
rrdName = rrdName.replace("/", "-");
String before = rrdName;
rrdName = rrdName.replaceAll("-\\d+", "");
if (!before.equals(rrdName)) {
_Logger.info("replaced a numeric chunk: " + before + " became " + rrdName);
}
_FileName = rrdName;
Long startTime = data.getPeriodStart().getMillis() / 1000;
createRRDFile(rrdName, data.getPeriod(), data.getMetric(), startTime);
}
private void createRRDFile(String rrdName, Period period, String dsName, Long startTime) {
if (new File(rrdName).exists()) {
return;
}
_Logger.info("Creating rrd file " + rrdName);
String[] argsList = new String [] {"rrdtool", "create", rrdName, "-b", startTime.toString(), "-s", Integer.toString(period.toStandardSeconds().getSeconds()),
"DS:" + "metric" + ":GAUGE:" + Integer.toString(period.toStandardSeconds().getSeconds() * 3) + ":U:U",
"RRA:AVERAGE:0.5:1:1000"};
executeProcess(argsList);
}
private void executeProcess(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader stdOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder procOutput = new StringBuilder();
while ((line = stdOut.readLine()) != null) {
procOutput.append(line + "\n");
}
try {
p.waitFor();
} catch (InterruptedException e) {
_Logger.error("Interrupted waiting for process to exit", e);
}
if (p.exitValue() != 0) {
StringBuilder builder = new StringBuilder();
for (String arg : args) {
builder.append(arg).append(" ");
}
_Logger.error("executed: " + builder.toString());
_Logger.error("Process exit code " + p.exitValue());
_Logger.error("Process output:\n" + procOutput.toString());
}
} catch (IOException e) {
_Logger.error("IOException while trying to create RRD file", e);
}
}
public void storeData(AggregatedData data) {
Long unixTime = data.getPeriodStart().getMillis() / 1000;
String value = unixTime.toString() + ":" + doubleFormat.format(data.getValue());
String[] argsList = new String [] {"rrdtool", "update", _FileName, value};
executeProcess(argsList);
}
} |
package uk.ac.edukapp.renderer;
import javax.persistence.EntityManager;
import uk.ac.edukapp.model.Widgetprofile;
public class Renderer {
public static String render(EntityManager em,Widgetprofile widgetprofile){
//deduce whether is w3c or open social
byte w3cOrOs = widgetprofile.getW3cOrOs();
if (w3cOrOs==0){//is w3c
return WidgetRenderer.getInstance().render(widgetprofile.getWidId());
}else if (w3cOrOs==1){//is os
return GadgetRenderer.render(widgetprofile.getWidId());
}
return null;
}
} |
package uk.co.omegaprime.mdbi;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* A slightly simplified version of {@link StatementlikeBatchRead} that consumes a {@code ResultSet}.
* <p>
* Useful instances of this can be obtained from {@link BatchReads}.
*/
public interface BatchRead<T> {
/**
* Consume one or more row from the {@code ResultSet}, returning a corresponding Java object.
* <p>
* When it arrives, the {@code ResultSet} will be on the row before the first one that you can consume -- i.e.
* it will not be on a valid row. Consequently you need to call {@link ResultSet#next()} before you access any column.
* <p>
* If you cease consuming the {@code ResultSet} early, you should leave the {@code ResultSet}
* on the last row that you have decided to consume. This means that there is no difference between
* leaving the {@code ResultSet} on the final row and leaving it after the end of the whole {@code ResultSet}.
*/
T get(Read.Context ctxt, ResultSet rs) throws SQLException;
} |
package uk.gov.verify.guice;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import com.hubspot.dropwizard.guice.JerseyModule;
import com.hubspot.dropwizard.guice.JerseyUtil;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import java.util.Optional;
import static com.google.common.collect.Iterables.concat;
import static java.util.Arrays.asList;
public class GuiceBundle<T extends Configuration> implements ConfiguredBundle<T> {
private final Optional<Class<T>> configClass;
private final Iterable<Module> modules;
@SuppressWarnings("unused")
public Injector getInjector() {
return injector;
}
private Injector injector;
GuiceBundle(Optional<Class<T>> configClass, Iterable<Module> modules) {
this.configClass = configClass;
this.modules = modules;
}
@Override
public void run(T configuration, Environment environment) {
injector = Guice.createInjector(Stage.PRODUCTION, getModules(configuration, environment));
JerseyUtil.registerGuiceBound(injector, environment.jersey());
JerseyUtil.registerGuiceFilter(environment);
}
@Override
public void initialize(Bootstrap<?> bootstrap) {}
private Iterable<? extends Module> getModules(T configuration, Environment environment) {
DropwizardEnvironmentModule dropwizardEnvironmentModule = new DropwizardEnvironmentModule<T>(configClass, configuration, environment);
JerseyModule jerseyModule = new JerseyModule();
return concat(asList(dropwizardEnvironmentModule, jerseyModule), modules);
}
} |
package org.apache.jmeter.testbeans;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.jmeter.control.NextIsNullException;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestElementTraverser;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.MapProperty;
import org.apache.jmeter.testelement.property.NullProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
* This is an experimental class. An attempt to address the complexity of
* writing new JMeter components.
* <p>
* TestBean currently extends AbstractTestElement to support
* backward-compatibility, but the property-value-map may later on be
* separated from the test beans themselves. To ensure this will be doable
* with minimum damage, all inherited methods are deprecated.
*/
public abstract class TestBean extends AbstractTestElement
{
protected static final Logger log = LoggingManager.getLoggerForClass();
/**
* Property name to property descriptor method map.
*/
private Map descriptors;
/**
* Parameter-less constructor.
* <p>
* This implementation will take care of obtaining bean-management
* information if this was not already done.
*/
protected TestBean()
{
super();
try
{
// Obtain the property descriptors:
BeanInfo beanInfo= Introspector.getBeanInfo(this.getClass(),
TestBean.class);
PropertyDescriptor[] desc= beanInfo.getPropertyDescriptors();
descriptors= new HashMap();
for (int i=0; i<desc.length; i++)
{
descriptors.put(desc[i].getName(), desc[i]);
}
}
catch (IntrospectionException e)
{
log.error("Can't get beanInfo for "+this.getClass().getName(),
e);
throw new Error(e.toString()); // Programming error. Don't continue.
}
}
/**
* Prepare the bean for work by populating the bean's properties from the
* property value map.
* <p>
* @deprecated to limit it's usage in expectation of moving it elsewhere.
*/
public void prepare()
{
Object[] param= new Object[1];
if (log.isDebugEnabled()) log.debug("Preparing "+this.getClass());
for (PropertyIterator jprops= propertyIterator(); jprops.hasNext(); )
{
// Obtain a value of the appropriate type for this property.
JMeterProperty jprop= jprops.next();
PropertyDescriptor descriptor= (PropertyDescriptor)descriptors.get(jprop.getName());
if (descriptor == null)
{
if (log.isDebugEnabled())
{
log.debug("Ignoring auxiliary property "+jprop.getName());
}
continue;
}
Class type= descriptor.getPropertyType();
Object value= unwrapProperty(jprop, type);
if (log.isDebugEnabled()) log.debug("Setting "+jprop.getName()+"="+value);
// Set the bean's property to the value we just obtained:
if (value != null || !type.isPrimitive())
// We can't assign null to primitive types.
{
param[0]= value;
invokeOrBailOut(descriptor.getWriteMethod(), param);
}
}
}
/**
* Utility method that invokes a method and does the error handling
* around the invocation.
*
* @param method
* @param params
* @return the result of the method invocation.
*/
private Object invokeOrBailOut(Method method, Object[] params)
{
try
{
return method.invoke(this, params);
}
catch (IllegalArgumentException e)
{
log.error("This should never happen.", e);
throw new Error(e.toString()); // Programming error: bail out.
}
catch (IllegalAccessException e)
{
log.error("This should never happen.", e);
throw new Error(e.toString()); // Programming error: bail out.
}
catch (InvocationTargetException e)
{
log.error("This should never happen.", e);
throw new Error(e.toString()); // Programming error: bail out.
}
}
/**
* Utility method to obtain the value of a property in the given type.
* <p>
* I plan to get rid of this sooner than later, so please don't use it much.
*
* @param property Property to get the value of.
* @param type Type of the result.
* @return an object of the given type if it is one of the known supported
* types, or the value returned by property.getObjectValue
* @deprecated
*/
private static Object unwrapProperty(JMeterProperty property, Class type)
{
// TODO: Awful, but there will be time to improve... maybe using
// property editors? Or just having each property know its
// proper type? Or pre-building a type-to-valuegetter map?
// Or maybe just getting rid of all this property mess and storing
// the original objects instead?
Object value;
if (property instanceof NullProperty)
{
// Because we work through primitive types, we need to handle
// the null case differently.
value= null;
}
else if (type == boolean.class || type == Boolean.class)
{
value= new Boolean(property.getBooleanValue());
}
else if (type == double.class || type == Double.class)
{
value= new Double(property.getDoubleValue());
}
else if (type == float.class || type == Float.class)
{
value= new Float(property.getFloatValue());
}
else if (type == int.class || type == Integer.class)
{
value= new Integer(property.getIntValue());
}
else if (type == long.class || type == Long.class)
{
value= new Long(property.getLongValue());
}
else if (type == String.class)
{
value= property.getStringValue();
}
else
{
value= property.getObjectValue();
}
return value;
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#addProperty(org.apache.jmeter.testelement.property.JMeterProperty)
* @deprecated
*/
protected void addProperty(JMeterProperty property)
{
super.addProperty(property);
}
/**
* @see org.apache.jmeter.testelement.TestElement#addTestElement(org.apache.jmeter.testelement.TestElement)
* @deprecated
*/
public void addTestElement(TestElement el)
{
// Scan all properties for a writable property of the appropriate type:
for (Iterator descs= descriptors.values().iterator();
descs.hasNext(); )
{
PropertyDescriptor desc= (PropertyDescriptor)descs.next();
if (desc.getPropertyType().isInstance(el)
&& desc.getPropertyEditorClass() == null)
// Note we ignore those for which we have an editor,
// in assumption that they are already provided via
// the GUI. Not very nice, but it's a solution.
// TODO: find a nicer way to specify which TestElement
// properties should be in the GUI and which should come
// from the tree structure.
{
invokeOrBailOut(desc.getWriteMethod(), new Object[] { el });
return; // We're done
}
}
// If we found no property for this one...
super.addTestElement(el);
}
/**
* @see org.apache.jmeter.testelement.TestElement#clear()
* @deprecated
*/
public void clear()
{
super.clear();
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#clearTemporary(org.apache.jmeter.testelement.property.JMeterProperty)
* @deprecated
*/
protected void clearTemporary(JMeterProperty property)
{
super.clearTemporary(property);
}
/**
* @see java.lang.Object#clone()
* @deprecated
*/
public Object clone()
{
return super.clone();
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#emptyTemporary()
* @deprecated
*/
protected void emptyTemporary()
{
super.emptyTemporary();
}
/**
* @see java.lang.Object#equals(java.lang.Object)
* @deprecated
*/
public boolean equals(Object o)
{
return super.equals(o);
}
/**
* This one is NOT deprecated.
*
* @see org.apache.jmeter.testelement.AbstractTestElement#getName()
*/
public String getName()
{
return super.getName();
}
/**
* @see org.apache.jmeter.testelement.TestElement#getProperty(java.lang.String)
* @deprecated
*/
public JMeterProperty getProperty(String key)
{
return super.getProperty(key);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#getPropertyAsBoolean(java.lang.String, boolean)
* @deprecated
*/
public boolean getPropertyAsBoolean(String key, boolean defaultVal)
{
return super.getPropertyAsBoolean(key, defaultVal);
}
/**
* @see org.apache.jmeter.testelement.TestElement#getPropertyAsBoolean(java.lang.String)
* @deprecated
*/
public boolean getPropertyAsBoolean(String key)
{
return super.getPropertyAsBoolean(key);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#getPropertyAsDouble(java.lang.String)
* @deprecated
*/
public double getPropertyAsDouble(String key)
{
return super.getPropertyAsDouble(key);
}
/**
* @see org.apache.jmeter.testelement.TestElement#getPropertyAsFloat(java.lang.String)
* @deprecated
*/
public float getPropertyAsFloat(String key)
{
return super.getPropertyAsFloat(key);
}
/**
* @see org.apache.jmeter.testelement.TestElement#getPropertyAsInt(java.lang.String)
* @deprecated
*/
public int getPropertyAsInt(String key)
{
return super.getPropertyAsInt(key);
}
/**
* @see org.apache.jmeter.testelement.TestElement#getPropertyAsLong(java.lang.String)
* @deprecated
*/
public long getPropertyAsLong(String key)
{
return super.getPropertyAsLong(key);
}
/**
* @see org.apache.jmeter.testelement.TestElement#getPropertyAsString(java.lang.String)
* @deprecated
*/
public String getPropertyAsString(String key)
{
return super.getPropertyAsString(key);
}
/**
* @see org.apache.jmeter.testelement.TestElement#isRunningVersion()
* @deprecated
*/
public boolean isRunningVersion()
{
return super.isRunningVersion();
}
/**
* @see org.apache.jmeter.testelement.TestElement#isTemporary(org.apache.jmeter.testelement.property.JMeterProperty)
* @deprecated
*/
public boolean isTemporary(JMeterProperty property)
{
return super.isTemporary(property);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#logProperties()
* @deprecated
*/
protected void logProperties()
{
super.logProperties();
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#mergeIn(org.apache.jmeter.testelement.TestElement)
* @deprecated
*/
protected void mergeIn(TestElement element)
{
super.mergeIn(element);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#nextIsNull()
* @deprecated
*/
protected Sampler nextIsNull() throws NextIsNullException
{
return super.nextIsNull();
}
/**
* @see org.apache.jmeter.testelement.TestElement#propertyIterator()
* @deprecated
*/
public PropertyIterator propertyIterator()
{
return super.propertyIterator();
}
/**
* @see org.apache.jmeter.testelement.TestElement#recoverRunningVersion()
* @deprecated
*/
public void recoverRunningVersion()
{
super.recoverRunningVersion();
}
/**
* @see org.apache.jmeter.testelement.TestElement#removeProperty(java.lang.String)
* @deprecated
*/
public void removeProperty(String key)
{
super.removeProperty(key);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#setName(java.lang.String)
* @deprecated
*/
public void setName(String name)
{
super.setName(name);
}
/**
* @see org.apache.jmeter.testelement.TestElement#setProperty(org.apache.jmeter.testelement.property.JMeterProperty)
* @deprecated
*/
public void setProperty(JMeterProperty property)
{
super.setProperty(property);
}
/**
* @see org.apache.jmeter.testelement.TestElement#setProperty(java.lang.String, java.lang.String)
* @deprecated
*/
public void setProperty(String name, String value)
{
super.setProperty(name, value);
}
/**
* @see org.apache.jmeter.testelement.TestElement#setRunningVersion(boolean)
* @deprecated
*/
public void setRunningVersion(boolean runningVersion)
{
super.setRunningVersion(runningVersion);
}
/**
* @see org.apache.jmeter.testelement.TestElement#setTemporary(org.apache.jmeter.testelement.property.JMeterProperty)
* @deprecated
*/
public void setTemporary(JMeterProperty property)
{
super.setTemporary(property);
}
/**
* @see org.apache.jmeter.testelement.TestElement#traverse(org.apache.jmeter.testelement.TestElementTraverser)
* @deprecated
*/
public void traverse(TestElementTraverser traverser)
{
super.traverse(traverser);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#traverseCollection(org.apache.jmeter.testelement.property.CollectionProperty, org.apache.jmeter.testelement.TestElementTraverser)
* @deprecated
*/
protected void traverseCollection(
CollectionProperty col,
TestElementTraverser traverser)
{
super.traverseCollection(col, traverser);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#traverseMap(org.apache.jmeter.testelement.property.MapProperty, org.apache.jmeter.testelement.TestElementTraverser)
* @deprecated
*/
protected void traverseMap(MapProperty map, TestElementTraverser traverser)
{
super.traverseMap(map, traverser);
}
/**
* @see org.apache.jmeter.testelement.AbstractTestElement#traverseProperty(org.apache.jmeter.testelement.TestElementTraverser, org.apache.jmeter.testelement.property.JMeterProperty)
* @deprecated
*/
protected void traverseProperty(
TestElementTraverser traverser,
JMeterProperty value)
{
super.traverseProperty(traverser, value);
}
} |
package yokohama.unit.position;
import lombok.Value;
@Value
public class Position {
private int line;
private int column;
public static Position of(int line) {
return new Position(line, -1);
}
public static Position of(int line, int column) {
return new Position(line, column);
}
private static Position dummyPos = new Position(-1, -1);
public static Position dummyPos() {
return dummyPos;
}
} |
package org.openlca.core.model;
import java.util.Objects;
import java.util.UUID;
class ProcessCopy {
public Process create(Process origin) {
Process copy = new Process();
copy.setRefId(UUID.randomUUID().toString());
copy.setName(origin.getName());
copyFields(origin, copy);
copyParameters(origin, copy);
copyExchanges(origin, copy);
copyAllocationFactors(origin, copy);
return copy;
}
private void copyFields(Process origin, Process copy) {
copy.setDefaultAllocationMethod(origin.getDefaultAllocationMethod());
copy.setCategory(origin.getCategory());
copy.setDescription(origin.getDescription());
copy.setLocation(origin.getLocation());
copy.setProcessType(origin.getProcessType());
copy.setInfrastructureProcess(origin.isInfrastructureProcess());
if (origin.getDocumentation() != null)
copy.setDocumentation(origin.getDocumentation().clone());
}
private void copyExchanges(Process origin, Process copy) {
for (Exchange exchange : origin.getExchanges()) {
Exchange clone = exchange.clone();
copy.getExchanges().add(clone);
if (exchange.equals(origin.getQuantitativeReference()))
copy.setQuantitativeReference(clone);
}
}
private void copyParameters(Process origin, Process copy) {
for (Parameter parameter : origin.getParameters()) {
Parameter p = parameter.clone();
copy.getParameters().add(p);
}
}
private void copyAllocationFactors(Process origin, Process copy) {
for (AllocationFactor factor : origin.getAllocationFactors()) {
AllocationFactor clone = factor.clone();
// not that the cloned factor has a reference to an exchange of
// the original process
Exchange copyExchange = findExchange(clone.getExchange(), copy);
clone.setExchange(copyExchange);
copy.getAllocationFactors().add(clone);
}
}
private Exchange findExchange(Exchange origin, Process processCopy) {
if(origin == null)
return null;
for(Exchange copy : processCopy.getExchanges()) {
boolean equal = origin.isInput() == copy.isInput()
&& Objects.equals(origin.getFlow(), copy.getFlow())
&& origin.getAmountValue() == copy.getAmountValue()
&& Objects.equals(origin.getUnit(), copy.getUnit());
if(equal)
return copy;
}
return null;
}
} |
package org.codehaus.groovy.tools;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
/**
* This ClassLoader should be used as root of class loaders. Any
* RootLoader does have it's own classpath. When searching for a
* class or resource this classpath will be used. Parent
* Classloaders are ignored first. If a class or resource
* can't be found in the classpath of the RootLoader, then parent is
* checked.
*
* <b>Note:</b> this is very against the normal behavior of
* classloaders. Normal is to frist check parent and then look in
* the ressources you gave this classloader.
*
* It's possible to add urls to the classpath at runtime through
* @see #addURL(URL)
*
* <b>Why using RootLoader?</b>
* If you have to load classes with multiple classloaders and a
* classloader does know a class which depends on a class only
* a child of this loader does know, then you won't be able to
* load the class. To load the class the child is not allowed
* to redirect it's search for the class to the parent first.
* That way the child can load the class. If the child does not
* have all classes to do this, this fails of course.
*
* For example:
*
* <pre>
* parentLoader (has classpath: a.jar;c.jar)
* |
* |
* childLoader (has classpath: a.jar;b.jar;c.jar)
* </pre>
*
* class C (from c.jar) extends B (from b.jar)
*
* childLoader.find("C")
* --> parentLoader does know C.class, try to load it
* --> to load C.class it has to load B.class
* --> parentLoader is unable to find B.class in a.jar or c.jar
* --> NoClassDefFoundException!
*
* if childLoader had tried to load the class by itself, there
* would be no problem. Changing childLoader to be a RootLoader
* instance will solve that problem.
*
* @author Jochen Theodorou
*/
public class RootLoader extends URLClassLoader {
/**
* constructs a new RootLoader without classpath
* @param parent the parent Loader
*/
private RootLoader(ClassLoader parent) {
this(new URL[0],parent);
}
/**
* constructs a new RootLoader with a parent loader and an
* array of URLs as classpath
*/
public RootLoader(URL[] urls, ClassLoader parent) {
super(urls,parent);
}
private static ClassLoader chooseParent(){
ClassLoader cl = RootLoader.class.getClassLoader();
if (cl!=null) return cl;
return ClassLoader.getSystemClassLoader();
}
/**
* constructs a new RootLoader with a @see LoaderConfiguration
* object which holds the classpath
*/
public RootLoader(LoaderConfiguration lc) {
this(chooseParent());
Thread.currentThread().setContextClassLoader(this);
URL[] urls = lc.getClassPathUrls();
for (int i=0; i<urls.length; i++) {
addURL(urls[i]);
}
}
/**
* loads a class using the name of the class
*/
protected Class loadClass(final String name, boolean resolve) throws ClassNotFoundException {
Class c = this.findLoadedClass(name);
if (c!=null) return c;
try {
c = findClass(name);
} catch (ClassNotFoundException cnfe) {}
if (c==null) c= super.loadClass(name,resolve);
if (resolve) resolveClass(c);
return c;
}
/**
* returns the URL of a resource, or null if it is not found
*/
public URL getResource(String name) {
URL url = findResource(name);
if (url==null) url=super.getResource(name);
return url;
}
/**
* adds an url to the classpath of this classloader
*/
public void addURL(URL url) {
System.out.println("RL: added url "+url);
super.addURL(url);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.