answer
stringlengths 17
10.2M
|
|---|
package com.wc1.felisBotus;
import java.io.IOException;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Pattern;
import com.wc1.felisBotus.irc.IRCChannel;
import com.wc1.felisBotus.streamAPIs.beam.Beam_API;
import com.wc1.felisBotus.streamAPIs.beam.Beam_Stream;
import com.wc1.felisBotus.streamAPIs.hitBox.HitBox_API;
import com.wc1.felisBotus.streamAPIs.hitBox.HitBox_Stream;
import com.wc1.felisBotus.streamAPIs.twitch.Twitch_API;
import com.wc1.felisBotus.streamAPIs.twitch.Twitch_Stream;
public class BotCommandHelper {
private FelisBotus parentBot;
public BotCommandHelper(FelisBotus felisBotus) {
parentBot = felisBotus;
}
public void runBotCommand(FelisBotus felisBotus, String channel, String sender, String message, String lowercaseCommand) {
boolean isOp = false;
if (channel.equalsIgnoreCase(sender)){ //private message!
for (IRCChannel currChannel:parentBot.getIRCServer().getChannels()){
if (currChannel.checkOp(sender)){
isOp = true; //if future security requires it, save what channel they are oped on too.
break;
}
}
} else{
isOp = parentBot.getIRCServer().getChannel(channel).checkOp(sender);
}
switch(lowercaseCommand){ //substring removes the command section of the string
case("addcommand"):
addCommand(sender, message, isOp);
break;
case("removecommand"):
removeCommand(sender, message, isOp);
break;
case("leavechannel"):
leaveChannel(channel, sender, message, isOp);
break;
case("leaveserver"):
leaveServer(sender, message, isOp);
break;
case("joinchannel"):
Thread thread = new Thread(new JoinChannel(sender, message, isOp));
thread.start();
//joinChannel(sender, message, isOp);
break;
case("joinserver"):
//TODO
break;
case("shutdown"):
shutdownBot(sender, message, isOp);
break;
case("twitch"):
twitch(channel, sender, message);
break;
case("hitbox"):
hitbox(channel, sender, message);
break;
case("beam"):
beam(channel, sender, message);
break;
case("commands"):
//TODO parse command
break;
case("roll"):
dice(channel, sender, message);
break;
case("listchannels"):
getChannels(channel, message, sender);
break;
default:
String response = Main.getResponse(lowercaseCommand);
if (response != null){
felisBotus.sendMessage(channel, response);
}
else{
felisBotus.sendNotice(sender, lowercaseCommand + " is an invalid command, please ensure it is spelled correctly");
}
}
}
private void dice(String channel, String sender, String message) {
String[] splitMessage = message.split(" ");
if (!Pattern.matches("roll( \\d+( \\d+)?)?", message)){ //matches "roll[ num[ num]]"
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart + "roll [numOfdice] [numOfSides]."
+ " If no numbers are given, two 6-sided dice are rolled. If only number of dice is given then 6-sided dice will be rolled");
}
else{
Random rand = new Random();
int numDice = splitMessage.length >=2 ? Integer.parseInt(splitMessage[1]) : 2;
int numSides = splitMessage.length == 3 ? Integer.parseInt(splitMessage[2]) : 6;
String[] rolls = new String[numDice];
int total = 0;
for (int i=0; i<numDice; i++){
int currRoll = rand.nextInt(numSides) + 1; //nextint is 0 (inclusive) to bound (exclusive)
rolls[i] = String.valueOf(currRoll);
total += currRoll;
}
parentBot.sendMessage(channel, String.format("%s rolled a %d (Individual rolls: %s)", sender, total, String.join(", ", rolls)));
}
}
private void beam(String channel, String sender, String message) {
String[] splitMessage = message.split(" ");
if (splitMessage.length == 2){
String userName = splitMessage[1];
Beam_Stream bStream = Beam_API.getStream(userName);
String bStatus = String.format(bStream.getUser()+" is Live! | Title: "+bStream.getTitle()+" | Game: "+bStream.getGame()+" | Url: "+bStream.getUrl());
if (bStream.getIsOnline()){
parentBot.sendMessage(channel, bStatus);
}else
{
parentBot.sendMessage(channel,"Stream is Currently Offline");
}
}else
{
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart + "beam <channel>");
}
}
private void hitbox(String channel, String sender, String message) {
String[] splitMessage = message.split(" ");
if (splitMessage.length == 2){
String userName = splitMessage[1];
HitBox_Stream hStream = HitBox_API.getStream(userName);
String hStatus = String.format(hStream.getUser()+" is Live! | Title: "+hStream.getTitle()+" | Game: "+hStream.getGame()+" | Url: "+hStream.getUrl());
if (hStream.getIsOnline()){
parentBot.sendMessage(channel, hStatus);
}else
{
parentBot.sendMessage(channel,"Stream is Currently Offline");
}
}else
{
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart + "hitbox <channel>");
}
}
private void twitch(String channel, String sender, String message) {
String[] splitMessage;
splitMessage = message.split(" ");
if (splitMessage.length == 2){
String userName = splitMessage[1];
Twitch_Stream stream = Twitch_API.getStream(userName);
String status = String.format("%s is live! | Game = %s | Title = %s | URL = %s", userName.toUpperCase(), stream.getGame(), stream.getStatus(), stream.getUrl());
if (stream.isOnline()){
parentBot.sendMessage(channel, status);
}else
{
parentBot.sendMessage(channel,"Stream is Currently Offline");
}
} else {
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart + "twitch <channel>");
}
}
private void shutdownBot(String sender, String message, boolean isOp) {
String[] splitMessage;
if (isOp){
splitMessage = message.split(" ");
if (splitMessage.length == 2 && splitMessage[1].equalsIgnoreCase("force")){
try {
Main.shutItDown(true);
} catch (IOException e) {
//Will never throw exception here
}
}
else if (splitMessage.length == 1){
try {
Main.shutItDown(false);
} catch (IOException e) {
parentBot.sendNotice(sender, "Error while attempting to save before shutdown :[ \n"
+ "If you wish to ignore this use " + FelisBotus.commandStart + "shutdown force.");
System.out.printf("Error encounted while attempting to save while shuting down\n");
e.printStackTrace();
}
}
else{
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart +"shutdown [force]. "
+ "If the word 'force' is supplied then bot will shutdown even if an error occurs.");
}
}else{
parentBot.sendNotice(sender, "You must be an OP to use this command");
}
}
private void leaveServer(String sender, String message, boolean isOp) {
String[] splitMessage;
if (isOp){
splitMessage = message.split(" ");
if (splitMessage.length > 2){
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart +"leaveserver [server]. "
+ "If no server is supplied then bot will leave this server");
}
else if (splitMessage.length == 1 || splitMessage[1].equals(parentBot.getIRCServer().getServerAddress())){
Main.removeBot(parentBot);
}
else{
FelisBotus botToDisconnect = Main.getBotConnectedTo(splitMessage[1]);
if (botToDisconnect == null){
parentBot.sendNotice(sender, "I am not connected to that server");
}
else{
Main.removeBot(botToDisconnect);
parentBot.sendNotice(sender, "Successfully disconnected from " + splitMessage[1]);
}
}
}else{
parentBot.sendNotice(sender, "You must be an OP to use this command");
}
}
private void leaveChannel(String channel, String sender, String message,
boolean isOp) {
String[] splitMessage;
if (isOp){
splitMessage = message.split(" ");
if ((splitMessage.length == 2 && !splitMessage[1].startsWith("#")) || splitMessage.length > 2){
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart +"leavechannel [channel]. "
+ "Channel must be prefixed by a #. If no channel is supplied then bot will leave this channel");
}
else if (splitMessage.length == 1 || splitMessage[1].equals(channel)){
parentBot.partChannel(channel, "Requested to leave channel");
parentBot.getIRCServer().removeChannel(channel);
if (parentBot.getIRCServer().getChannels().size() == 0){ //not connected to any channels, disconnect from the server
Main.removeBot(parentBot);
}
}
else{
if (parentBot.getIRCServer().isConnectedTo(splitMessage[1])){
parentBot.partChannel(splitMessage[1], "Remote channel leave request");
parentBot.getIRCServer().removeChannel(splitMessage[1]);
parentBot.sendNotice(sender, "Successfully left " + splitMessage[1]);
}
else{
parentBot.sendNotice(sender, "I am not connected to this channel");
}
}
}
else{
parentBot.sendNotice(sender, "You must be an OP to use this command");
}
}
private void removeCommand(String sender, String message, boolean isOp) {
String[] splitMessage;
if (isOp){
splitMessage = message.split(" ",3);
if (splitMessage.length == 2){
String result = Main.removeCommand(splitMessage[1]);
if (result==null){
parentBot.sendNotice(sender, splitMessage[1] + " was never a saved command");
}
else{
parentBot.sendNotice(sender, "Command successfully removed! :]");
try {
Main.save();
} catch (IOException e) {
parentBot.sendNotice(sender, "Failed to save command removal. Command will come back on bot restart :[");
System.out.printf("\nFailed to save bot!\n");
e.printStackTrace();
}
}
}
else{
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart +"removecommand <oldCommand>");
}
}
else{
parentBot.sendNotice(sender, "You must be an OP to use this command");
}
}
private void addCommand(String sender, String message, boolean isOp) {
String[] splitMessage;
splitMessage = message.split(" ",3);
if (isOp && splitMessage.length >= 3){
String result = Main.putCommand(splitMessage[1].toLowerCase(Locale.ROOT), splitMessage[2]);
if (result !=null){
parentBot.sendNotice(sender, "Command successfully overwritten :]. Previous response was '" +result+"'");
}
else{
parentBot.sendNotice(sender, "Command successfully added :]");
}
try {
Main.save();
} catch (IOException e) {
parentBot.sendNotice(sender, "Failed to save command. Command will be lost on bot restart :[");
System.out.printf("\nFailed to save bot!\n");
e.printStackTrace();
}
}
else if (splitMessage.length < 3){
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart +"addcommand <newCommand> <Response>");
}
else{
parentBot.sendNotice(sender, "You must be an OP to use this command");
}
}
//private void joinChannel(String sender, String message, boolean isOp) {
private void getChannels(String channel, String message, String sender){ //TODO support for entering another server to check if its connected and what channels there?
String[] splitMessage = message.split(" ");
if (splitMessage.length == 2 || (splitMessage.length == 3 && splitMessage[2].equalsIgnoreCase(parentBot.getServer()))){ //get the channels of the current server
String[] channelNames = parentBot.getChannels();
parentBot.sendMessage(channel, "Channels in this server I am currently connected to are:");
parentBot.sendMessage(channel, String.join(", ", channelNames) + ".");
}
else if (splitMessage.length == 3){
String[] channelNames = Main.getConnectedChannelsOnServer(splitMessage[2]);
if (channelNames != null){
parentBot.sendMessage(channel, "Channels on " + splitMessage[2] + " I am currently connected to are:");
parentBot.sendMessage(channel, String.join(", ", channelNames) + ".");
} else{
parentBot.sendMessage(channel, "I am not connected to " + splitMessage[2]);
}
} else{
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart +"listchannels [server]");
}
}
private class JoinChannel implements Runnable{
private String sender;
private String message;
private boolean isOp;
public JoinChannel(String sender, String message, boolean isOp) {
this.sender = sender;
this.message = message;
this.isOp = isOp;
}
@Override
public void run() {
if (isOp){
String[] splitMessage = message.split(" ");
if ((splitMessage.length == 2 && !splitMessage[1].startsWith("#")) || splitMessage.length > 3 || splitMessage.length < 2){
parentBot.sendNotice(sender, "Syntax Error. Correct usage is " + FelisBotus.commandStart +"joinchannel <channel> [pass]. "
+ "Channel must be prefixed by a
}
else if (parentBot.getIRCServer().isConnectedTo(splitMessage[1])){
parentBot.sendNotice(sender, "This bot is already connected to that channel");
}
else if (splitMessage.length == 2){
if(parentBot.joinIRCChannel(splitMessage[1])){
parentBot.sendNotice(sender, "Successfully joined " + splitMessage[1]);
} else{
parentBot.sendNotice(sender, "unable to join " + splitMessage[1] + ". Please check details are correct and that there is no password required.");
}
}
else if (splitMessage.length == 3){ //password supplied
if (parentBot.joinIRCChannel(splitMessage[1], splitMessage[2])){
parentBot.sendNotice(sender, "Successfully joined " + splitMessage[1]);
} else{
parentBot.sendNotice(sender, "unable to join " + splitMessage[1] + ". Please check details are correct.");
}
}
}else{
parentBot.sendNotice(sender, "You must be an OP to use this command");
}
}
}
}
|
import java.text.ParseException;
import org.joda.time.LocalTime;
public class SYSMEvent extends ReaderInterface{
public static final String header = "\"RT\",\"System\",\"Light/Scale\",\"Sys Ok\",\"Remarks\"";
public static final int hcount = 5;
public enum System{
Light,
Scale
}
public float rt = Float.NaN;
public System system;
public String ls;
public Boolean sysok;
public String remarks = "";
public SYSMEvent(){}
public SYSMEvent(String line) throws ParseException{
parse(line);
}
@Override
public LocalTime parse(String line) throws ParseException {
if (line.isEmpty() || line.charAt(0) == '
throw new ParseException("Invalid line: '" + line + "'", 0);
String[] parts = line.split(del);
time = readDate(parts[0]);
for (int i = 1; i < parts.length; ++i){
String part = parts[i];
if (part.matches("^-?[0-9]+(\\.[0-9])?$")){
rt = Float.parseFloat(part);
} else if (part.matches("^(Light|Scale)$")){
if (part == "Light"){
system = System.Light;
} else {
system = System.Scale;
}
} else if (part.matches("(TRUE|FALSE)")){
sysok = Boolean.parseBoolean(part);
} else if (part.startsWith("-")){
remarks = part.replaceAll(ccleaner, "");
} else {
ls = part.replaceAll(ccleaner, "");
}
}
return time;
}
@Override
public String toString() {
String ret = "\"" + (Float.isNaN(rt)?"":rt) + "\",\"" + (system==System.Light?"Light":"Scale") +
"\",\"" + ls + "\",\"" + (sysok!=null?sysok:"") + "\",\"" + remarks + "\"";
return ret;
}
}
|
package game;
import model.*;
import java.util.ArrayList;
import java.util.Collections;
public class Game {
private Grid grid;
private Player players[];
private int level;
private Tetromino activeTetromino;
private Tetromino nextTetromino;
private Tetromino stockTetromino;
private ArrayList<Tetromino> tetrominosBag;
private int tetrominosBagCounter;
private long lastUpdateTime; // nanoseconds
private ArrayList<GridObserver> gridObservers;
private ArrayList<ScoreObserver> scoreObservers;
public Game()
{
// Setup game environment here
this.grid = new Grid();
this.players = new Player[] {new Player("Player1"), new Player("Player2")};
this.level = 1;
this.initTetrominosBag();
this.lastUpdateTime = System.nanoTime();
}
/**
* Launch the main loop of the game
*/
public void loop()
{
long now = System.nanoTime(), deltaTime;
System.out.println("Startup time: " + (now - this.lastUpdateTime));
this.lastUpdateTime = now;
boolean gameLooping = true;
while (gameLooping)
{
now = System.nanoTime();
deltaTime = (now - this.lastUpdateTime);
if (now % 100000 == 0) System.out.println("DT: " + String.valueOf(deltaTime / 1_000_000f) + "ms");
if (deltaTime >= 1_000_000_000) {
update();
this.lastUpdateTime = now;
}
}
}
private void update()
{
System.out.println("Update");
this.grid.update();
this.notifyGridObservers();
this.notifyScoreObservers();
}
public Grid getGrid()
{
return grid;
}
public Player[] getPlayers() {
return players;
}
public int getLevel() {
return level;
}
public Tetromino getActiveTetromino() {
return activeTetromino;
}
public Tetromino getNextTetromino() {
return nextTetromino;
}
public Tetromino getStockTetromino() {
return stockTetromino;
}
public void addGridObserver(GridObserver obs) {
this.gridObservers.add(obs);
}
public void addScoreObserver(ScoreObserver obs) {
this.scoreObservers.add(obs);
}
private void notifyGridObservers() {
for (GridObserver obs : this.gridObservers) {
obs.gridChanged();
}
}
private void notifyScoreObservers() {
for (ScoreObserver obs : this.scoreObservers) {
obs.scoreChanged();
}
}
private void initTetrominosBag() {
this.tetrominosBag = new ArrayList<Tetromino>(7);
for (TetrominoType type : TetrominoType.values()) {
this.tetrominosBag.add(new Tetromino(type, new Position(0, 0)));
}
this.shuffleTetrominosBag();
}
private void shuffleTetrominosBag() {
this.tetrominosBagCounter = 0;
Collections.shuffle(this.tetrominosBag);
}
private Tetromino getRandomTetromino() {
if (this.tetrominosBagCounter == this.tetrominosBag.size())
this.shuffleTetrominosBag();
return this.tetrominosBag.get(this.tetrominosBagCounter++);
}
}
|
package jdbj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public final class JDBJ {
/**
* @param resource
* @return a phase 2 builder
*/
public static ReturnsQuery query(String resource) {
final URL url = JDBJ.class.getClassLoader().getResource(resource);
if (url == null) {
throw new IllegalArgumentException("resource not found: " + resource);
}
return queryString(readQueryResource(url));
}
/**
* @param queryString
* @return a phase 2 builder
*/
public static ReturnsQuery queryString(String queryString) {
final NamedParameterStatement statement = NamedParameterStatement.make(queryString);
return new ReturnsQuery(statement);
}
/**
* @param queryString
* @return a phase 2 builder
*/
public static InsertQuery insertQueryString(String queryString) {
final NamedParameterStatement statement = NamedParameterStatement.make(queryString);
return new InsertQuery(statement);
}
JDBJ() {
}
private static String readQueryResource(URL url) {
final StringBuilder queryString = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
while ((line = br.readLine()) != null) {
queryString.append(line).append('\n');
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return queryString.toString();
}
}
|
package me.flibio.minigamecore.arena;
import me.flibio.minigamecore.events.ArenaStateChangeEvent;
import org.spongepowered.api.Game;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.gamemode.GameModes;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.text.sink.MessageSinks;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
public class Arena {
private CopyOnWriteArrayList<ArenaState> arenaStates = new CopyOnWriteArrayList<ArenaState>(getDefaultArenaStates());
private ConcurrentHashMap<ArenaState,Runnable> runnables = new ConcurrentHashMap<ArenaState,Runnable>();
private Location<World> lobbySpawnLocation;
private Location<World> failedJoinLocation;
private ConcurrentHashMap<String, Location<World>> spawnLocations = new ConcurrentHashMap<String, Location<World>>();
private CopyOnWriteArrayList<Player> onlinePlayers = new CopyOnWriteArrayList<Player>();
private int currentLobbyCountdown;
private Task lobbyCountdownTask;
private ArenaState arenaState;
private ArenaOptions arenaOptions;
private Game game;
private Object plugin;
//TODO - Scoreboard implementation throughout arena
/**
* An arena is an object that can handle spawn locations, lobbies, games, and more.
* @param arenaName
* The name of the arena
* @param game
* An instance of the game
* @param plugin
* An instance of the main class of your plugin
*/
public Arena(String arenaName, Game game, Object plugin) {
this.arenaOptions = new ArenaOptions(arenaName);
this.game = game;
this.plugin = plugin;
this.arenaState = ArenaStates.LOBBY_WAITING;
game.getEventManager().registerListeners(plugin, this);
}
/**
* Adds an online player
* @param player
* The player to add
*/
public void addOnlinePlayer(Player player) {
if(arenaOptions.isDefaultPlayerEventActions()) {
//Check if the game is in the correct state
if(arenaState.equals(ArenaStates.LOBBY_WAITING)||arenaState.equals(ArenaStates.LOBBY_COUNTDOWN)) {
if(onlinePlayers.size()>=arenaOptions.getMaxPlayers()) {
//Lobby is full
if(arenaOptions.isDedicatedServer()) {
//Kick the player
player.kick(arenaOptions.lobbyFull);
} else {
//Try to teleport the player to the failed join location
if(failedJoinLocation!=null) {
player.sendMessage(arenaOptions.lobbyFull);
player.setLocation(failedJoinLocation);
} else {
player.kick(arenaOptions.lobbyFull);
}
}
} else {
//Player can join
onlinePlayers.add(player);
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
//TODO - replace %name% with the player name
onlinePlayer.sendMessage(arenaOptions.playerJoined);
}
if(lobbySpawnLocation!=null) {
player.setLocation(lobbySpawnLocation);
}
if(arenaState.equals(ArenaStates.LOBBY_WAITING)&&onlinePlayers.size()>=arenaOptions.getMinPlayers()) {
arenaStateChange(ArenaStates.LOBBY_COUNTDOWN);
}
}
} else {
if(arenaOptions.isDedicatedServer()) {
//Kick the player
player.kick(arenaOptions.gameInProgress);
} else {
//Try to teleport the player to the failed join location
if(failedJoinLocation!=null) {
player.sendMessage(arenaOptions.gameInProgress);
player.setLocation(failedJoinLocation);
} else {
player.kick(arenaOptions.gameInProgress);
}
}
}
} else {
onlinePlayers.add(player);
}
}
/**
* Removes an online player
* @param player
* The player to remove
*/
public void removeOnlinePlayer(Player player) {
onlinePlayers.remove(player);
if(arenaOptions.isDefaultPlayerEventActions()) {
if(arenaState.equals(ArenaStates.LOBBY_COUNTDOWN)&&onlinePlayers.size()<arenaOptions.getMinPlayers()) {
arenaStateChange(ArenaStates.COUNTDOWN_CANCELLED);
}
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
//TODO - replace %name% with the player name
onlinePlayer.sendMessage(arenaOptions.playerQuit);
}
}
}
/**
* Gets all of the players in an arena
* @return
* All the players in the arena
*/
public CopyOnWriteArrayList<Player> getOnlinePlayers() {
return onlinePlayers;
}
/**
* Calls an state change on the arena
* @param changeTo
* The state to change the arena to
*/
public void arenaStateChange(ArenaState changeTo) {
if(!arenaStates.contains(changeTo)) {
return;
}
arenaState = changeTo;
//Post the arena state change event
game.getEventManager().post(new ArenaStateChangeEvent(this));
//Run a runnable if it is set
if(arenaStateRunnableExists(changeTo)) {
runnables.get(changeTo).run();
}
//Run default actions ifthey are enabled
if(arenaOptions.isDefaultStateChangeActions()) {
if(arenaState.equals(ArenaStates.LOBBY_COUNTDOWN)) {
currentLobbyCountdown = arenaOptions.getLobbyCountdownTime();
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
//TODO - replace %time% with the seconds to go
onlinePlayer.sendMessage(arenaOptions.lobbyCountdownStarted);
}
//Register task the run the countdown every 1 second
lobbyCountdownTask = game.getScheduler().createTaskBuilder().execute(new Runnable() {
@Override
public void run() {
if(currentLobbyCountdown==0) {
arenaStateChange(ArenaStates.GAME_COUNTDOWN);
lobbyCountdownTask.cancel();
return;
}
if(arenaOptions.getLobbyCountdownTime()/2==currentLobbyCountdown||
currentLobbyCountdown<=10) {
//Send a message
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
//TODO - replace %time% with the seconds to go
onlinePlayer.sendMessage(arenaOptions.lobbyCountdownProgress);
}
}
currentLobbyCountdown
}
}).async().interval(1,TimeUnit.SECONDS).submit(plugin);
} else if(arenaState.equals(ArenaStates.COUNTDOWN_CANCELLED)) {
currentLobbyCountdown = arenaOptions.getLobbyCountdownTime();
if(lobbyCountdownTask!=null) {
lobbyCountdownTask.cancel();
}
arenaState = ArenaStates.LOBBY_WAITING;
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
onlinePlayer.sendMessage(arenaOptions.lobbyCountdownCancelled);
}
} else if(arenaState.equals(ArenaStates.GAME_COUNTDOWN)) {
currentLobbyCountdown = arenaOptions.getLobbyCountdownTime();
//TODO
arenaStateChange(ArenaStates.GAME_PLAYING);
} else if(arenaState.equals(ArenaStates.GAME_OVER)) {
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
onlinePlayer.sendMessage(arenaOptions.gameOver);
//End game spectator only works with end game delay on
if(arenaOptions.isEndGameDelay()&&arenaOptions.isEndGameSpectator()) {
//TODO - Save the gamemode
onlinePlayer.offer(Keys.GAME_MODE,GameModes.SPECTATOR);
}
}
if(arenaOptions.isEndGameDelay()) {
game.getScheduler().createTaskBuilder().execute(new Runnable() {
@Override
public void run() {
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
onlinePlayer.sendMessage(arenaOptions.gameOver);
if(arenaOptions.isEndGameSpectator()) {
//TODO load the gamemode
onlinePlayer.offer(Keys.GAME_MODE,GameModes.SURVIVAL);
}
if(arenaOptions.isDedicatedServer()) {
onlinePlayer.kick(arenaOptions.gameOver);
} else {
if(lobbySpawnLocation!=null) {
onlinePlayer.setLocation(lobbySpawnLocation);
}
}
}
}
}).async().delay(5,TimeUnit.SECONDS).submit(plugin);
} else {
//No delay
for(Player onlinePlayer : game.getServer().getOnlinePlayers()) {
onlinePlayer.sendMessage(arenaOptions.gameOver);
if(arenaOptions.isEndGameSpectator()) {
//TODO load the gamemode
onlinePlayer.offer(Keys.GAME_MODE,GameModes.SURVIVAL);
}
if(arenaOptions.isDedicatedServer()) {
onlinePlayer.kick(arenaOptions.gameOver);
} else {
if(lobbySpawnLocation!=null) {
onlinePlayer.setLocation(lobbySpawnLocation);
}
}
}
}
}
}
}
//Spawn Locations
/**
* Gets all of the possible spawn locations
* @return
* All of the possible spawn locations
*/
public ConcurrentHashMap<String, Location<World>> getSpawnLocations() {
return spawnLocations;
}
/**
* Adds a spawn location to the list of possible spawn locations
* @param name
* The name of the spawn location
* @param location
* The location to add
* @return
* Boolean based on if the method was successful or not
*/
public boolean addSpawnLocation(String name, Location<World> location) {
if(spawnLocations.containsKey(name)) {
return false;
}
spawnLocations.put(name, location);
return true;
}
/**
* Removes a spawn location from the list of possible spawn locations
* @param name
* The name of the spawn location
* @return
* Boolean based on if the method was successful or not
*/
public boolean removeSpawnLocation(String name) {
if(!spawnLocations.containsKey(name)) {
return false;
}
spawnLocations.remove(name);
return true;
}
/**
* Gets a spawn location by name
* @param name
* The name of the spawn location to get
* @return
* Optional of the spawn location
*/
public Optional<Location<World>> getSpawnLocation(String name) {
if(!spawnLocations.containsKey(name)) {
return Optional.empty();
}
return Optional.of(spawnLocations.get(name));
}
/**
* Selects a random spawn location from the list of available spawn locations
* @return
* Optional of the spawn location
*/
public Optional<Location<World>> randomSpawnLocation() {
if(spawnLocations.isEmpty()) {
return Optional.empty();
}
//TODO
return Optional.empty();
}
/**
* Disperses the players among all the spawn locations
*/
public void dispersePlayers() {
//TODO
}
//Other Arena Properties
/**
* Sets the location a player will teleport to if
* they failed to join the arena(Non-Dedicated Arenas Only)
* @param location
* The location to set the failed join location to
*/
public void setFailedJoinLocation(Location<World> location) {
failedJoinLocation = location;
}
/**
* Gets the set of arena options
* @return
* The ArenaOptions
*/
public ArenaOptions getOptions() {
return arenaOptions;
}
/**
* Gets the state of the arena
* @return
* The state of the arena
*/
public ArenaState getArenaState() {
return arenaState;
}
/**
* Adds a new arena state
* @param state
* The arena state to add
* @return
* If the method was successful or not
*/
public boolean addArenaState(ArenaState state) {
//Check ifthe state exists
if(arenaStateExists(state)) {
return false;
} else {
arenaStates.add(state);
return true;
}
}
/**
* Removes an arena state
* @param state
* The arena state to remove
* @return
* If the method was successful or not
*/
public boolean removeArenaState(ArenaState state) {
//Check ifthe state is a default state
if(getDefaultArenaStates().contains(state)||!arenaStateExists(state)) {
return false;
} else {
if(runnables.keySet().contains(state)) {
runnables.remove(state);
}
arenaStates.remove(state);
return true;
}
}
/**
* Checks if an arena state exists
* @param arenaState
* The arena state to check for
* @return
* If the arena state exists
*/
public boolean arenaStateExists(ArenaState arenaState) {
return arenaStates.contains(arenaState);
}
/**
* Gets a list of the default arena states
* @return
* A list of the default arena states
*/
public List<ArenaState> getDefaultArenaStates() {
return Arrays.asList(ArenaStates.LOBBY_WAITING,ArenaStates.LOBBY_COUNTDOWN,ArenaStates.GAME_COUNTDOWN,
ArenaStates.GAME_PLAYING,ArenaStates.GAME_OVER,ArenaStates.COUNTDOWN_CANCELLED);
}
/**
* Adds an arena state runnable
* @param state
* The state to add
* @param runnable
* The runnable to add
* @return
* If the method was successful or not
*/
public boolean addArenaStateRunnable(ArenaState state, Runnable runnable) {
if(!arenaStateExists(state)||arenaStateRunnableExists(state)) {
return false;
}
runnables.put(state, runnable);
return true;
}
/**
* Removes an arena state runnable
* @param state
* The arena state to remove
* @return
* If the method was successful or not
*/
public boolean removeArenaStateRunnable(ArenaState state) {
if(!arenaStateExists(state)||!arenaStateRunnableExists(state)) {
return false;
}
runnables.remove(state);
return true;
}
/**
* Checks if an arena state runnable exists
* @param state
* The state to check for
* @return
* If the arena state runnable exists
*/
public boolean arenaStateRunnableExists(ArenaState state) {
return runnables.keySet().contains(state);
}
/**
* Gets an arena state runnable
* @param state
* The state to get the runnable of
* @return
* The arena state runnable
*/
public Optional<Runnable> getArenaStateRunnable(ArenaState state) {
if(arenaStateRunnableExists(state)) {
return Optional.of(runnables.get(state));
} else {
return Optional.empty();
}
}
/**
* Sets the lobby spawn location of the arena
* @param location
* The lobby spawn location of the arena
*/
public void setLobbySpawnLocation(Location<World> location) {
lobbySpawnLocation = location;
}
//Listeners
@Listener
public void onPlayerDisconnect(ClientConnectionEvent.Disconnect event) {
if(arenaOptions.isDedicatedServer()&&arenaOptions.isTriggerPlayerEvents()) {
Player player = event.getTargetEntity();
removeOnlinePlayer(player);
event.setSink(MessageSinks.toNone());
}
}
@Listener
public void onPlayerJoin(ClientConnectionEvent.Join event) {
if(arenaOptions.isDedicatedServer()&&arenaOptions.isTriggerPlayerEvents()) {
Player player = event.getTargetEntity();
addOnlinePlayer(player);
event.setSink(MessageSinks.toNone());
}
}
}
|
package test;
public class Demo {
public static void main(String[] args) {
System.out.println("b");
System.out.println("ksajdhas");
System.out.println("sss");
System.out.println();
}
}
|
package mobi.hsz.idea.gitignore.util;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.containers.ContainerUtil;
import mobi.hsz.idea.gitignore.GitignoreLanguage;
import mobi.hsz.idea.gitignore.command.CreateFileCommandAction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Utils {
public static final double JAVA_VERSION = getJavaVersion();
private static double getJavaVersion() {
String version = System.getProperty("java.version");
int pos = 0, count = 0;
for (; pos < version.length() && count < 2; pos++) {
if (version.charAt(pos) == '.') count++;
}
return Double.parseDouble(version.substring(0, pos - 1));
}
@Nullable
public static String getRelativePath(@NotNull VirtualFile directory, @NotNull VirtualFile file) {
return VfsUtilCore.getRelativePath(file, directory, '/');
}
@Nullable
public static PsiFile getGitignoreFile(@NotNull Project project) {
return getGitignoreFile(project, null, false);
}
@Nullable
public static PsiFile getGitignoreFile(@NotNull Project project, @Nullable PsiDirectory directory) {
return getGitignoreFile(project, directory, false);
}
@Nullable
public static PsiFile getGitignoreFile(@NotNull Project project, @Nullable PsiDirectory directory, boolean createIfMissing) {
if (directory == null) {
directory = PsiManager.getInstance(project).findDirectory(project.getBaseDir());
}
assert directory != null;
PsiFile file = directory.findFile(GitignoreLanguage.FILENAME);
if (file == null && createIfMissing) {
file = new CreateFileCommandAction(project, directory).execute().getResultObject();
}
return file;
}
public static void openFile(@NotNull Project project, @NotNull PsiFile file) {
openFile(project, file.getVirtualFile());
}
public static void openFile(@NotNull Project project, @NotNull VirtualFile file) {
FileEditorManager.getInstance(project).openFile(file, true);
}
public static Collection<VirtualFile> getGitignoreFiles(@NotNull Project project) {
return FilenameIndex.getVirtualFilesByName(project, GitignoreLanguage.FILENAME, GlobalSearchScope.projectScope(project));
}
public static List<VirtualFile> getSuitableGitignoreFiles(@NotNull Project project, @NotNull VirtualFile file) throws ExternalFileException {
List<VirtualFile> files = new ArrayList<VirtualFile>();
if (file.getCanonicalPath() == null || !VfsUtilCore.isAncestor(project.getBaseDir(), file, true)) {
throw new ExternalFileException();
}
if (!project.getBaseDir().equals(file)) {
do {
file = file.getParent();
VirtualFile gitignore = file.findChild(GitignoreLanguage.FILENAME);
ContainerUtil.addIfNotNull(gitignore, files);
} while (!file.equals(project.getBaseDir()));
}
return files;
}
}
|
package edu.isep.sixcolors;
import edu.isep.sixcolors.controller.*;
import edu.isep.sixcolors.model.*;
import edu.isep.sixcolors.view.*;
import java.util.Random;
// TODO factorize random color generation (duplicated in this and model.Board)
/**
* Main class of the game : manages inputs and
*/
public class SixColors {
/**
* Main method of the game (currently)
* @param args
*/
public static void main(String[] args) {
Random random = new Random();
Game game = new Game();
String name;
for(int i = 0; i < game.getPlayers().length; i++) {
name = Console.promptPlayerName(i + 1);
game.getPlayer(i).setName(name);
}
// TODO store board width as an independant parameter
Board board = new Board(4);
board.getTile(0, 0).setOwner(game.getPlayer(0));
while(board.getTile(3, 3).getColor() == board.getTile(0, 0).getColor()) {
board.getTile(3, 3).setColor(Color.values()[random.nextInt(Color.values().length)]);
}
board.getTile(3, 3).setOwner(game.getPlayer(1));
// Setting current and previous colors of the players :
game.getPlayer(0).setColor(board.getTile(0, 0).getColor());
game.getPlayer(0).setPreviousColor(board.getTile(0, 0).getColor());
game.getPlayer(1).setColor(board.getTile(3, 3).getColor());
game.getPlayer(1).setPreviousColor(board.getTile(3, 3).getColor());
// Updating board to give the players ownership of the tiles of their colors next to their starting point.
board.update(0, 0, game.getPlayer(0));
board.update(3, 3, game.getPlayer(1));
while(true) {
Player currentPlayer = game.getCurrentPlayer();
System.out.println("It's " + currentPlayer.getName() + "'s turn !");
System.out.println("Your current color : "+currentPlayer.getColor().name());
Console.showBoard(board);
Color chosenColor = Console.promptColorChoice();
// TODO refactor those checks smartly :
while (chosenColor == currentPlayer.getColor()) {
System.out.println("You already control this color");
chosenColor = Console.promptColorChoice();
}
boolean err = true;
while (err) {
err = false;
for(Player player: game.getPlayers()) {
if(player.getColor() == chosenColor) {
err = true;
System.out.println(player.getName() + " already controls this color. Choose another one.");
chosenColor = Console.promptColorChoice();
}
}
}
System.out.println("Chosen color : "+chosenColor.name());
// updating previous and current colors :
// TODO setPrevious private and called in setColor ?
currentPlayer.setPreviousColor(currentPlayer.getColor());
currentPlayer.setColor(chosenColor);
// TODO Player.originTileCoordinates
int tileX, tileY;
if(game.getCurrentPlayerId() == 0) {
tileX = 0;
tileY = 0;
}
else {
tileX = 3;
tileY = 3;
}
board.update(tileY, tileX, currentPlayer);
// set the current player to the next player :
game.nextPlayer();
}
}
}
|
package org.adligo.j2se.util;
import org.adligo.i.log.client.Log;
import org.adligo.i.log.client.LogFactory;
import org.adligo.i.log.client.SimpleLog;
import org.adligo.i.util.client.Event;
import org.adligo.j2se.util.init.Init;
import junit.framework.TestCase;
public class TestLogLevels extends TestCase {
private static final Object init = Init.init();
private static final Log infoLog = LogFactory.getLog(System.class);
private static final Log debugLog = LogFactory.getLog(TestLogLevels.class);
private static final Log warnLog = LogFactory.getLog(Event.class);
public void testLevels() {
assertTrue("System should be set to info",
infoLog.isInfoEnabled());
assertFalse("System should NOT be set to debug" +
((SimpleLog) infoLog).getLevel(),
infoLog.isDebugEnabled());
assertTrue("System should be set to warn" +
((SimpleLog) infoLog).getLevel(),
infoLog.isWarnEnabled());
assertTrue("TestLogLevels should be set to debug",
debugLog.isDebugEnabled());
assertTrue("TestLogLevels should be set to info",
debugLog.isInfoEnabled());
assertFalse("TestLogLevels should NOT be set to trace",
debugLog.isTraceEnabled());
assertTrue("Event should be set to warn",
warnLog.isWarnEnabled());
assertTrue("Event should be set to Error",
warnLog.isErrorEnabled());
assertFalse("Event should NOT be set to Info",
warnLog.isInfoEnabled());
}
}
|
package org.anddev.andengine.engine;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.audio.music.MusicManager;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.audio.sound.SoundManager;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.entity.IUpdateHandler;
import org.anddev.andengine.entity.Scene;
import org.anddev.andengine.entity.SplashScene;
import org.anddev.andengine.entity.UpdateHandlerList;
import org.anddev.andengine.entity.handler.timer.ITimerCallback;
import org.anddev.andengine.entity.handler.timer.TimerHandler;
import org.anddev.andengine.opengl.GLHelper;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.font.FontManager;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureFactory;
import org.anddev.andengine.opengl.texture.TextureManager;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.source.ITextureSource;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.sensor.orientation.IOrientationListener;
import org.anddev.andengine.sensor.orientation.OrientationData;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.constants.TimeConstants;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* @author Nicolas Gramlich
* @since 12:21:31 - 08.03.2010
*/
public class Engine implements SensorEventListener, OnTouchListener {
// Constants
private static final float LOADING_SCREEN_DURATION = 2;
// Fields
private boolean mRunning = false;
private long mLastTick = System.nanoTime();
private float mSecondsElapsedTotal = 0;
private final EngineOptions mEngineOptions;
private SoundManager mSoundManager;
private MusicManager mMusicManager;
private final TextureManager mTextureManager = new TextureManager();
private final FontManager mFontManager = new FontManager();
protected Scene mScene;
private IAccelerometerListener mAccelerometerListener;
private AccelerometerData mAccelerometerData;
private IOrientationListener mOrientationListener;
private OrientationData mOrientationData ;
private final UpdateHandlerList mPreFrameHandlers = new UpdateHandlerList();
private final UpdateHandlerList mPostFrameHandlers = new UpdateHandlerList();
protected int mSurfaceWidth = 1; // 1 to prevent accidental DIV/0
protected int mSurfaceHeight = 1; // 1 to prevent accidental DIV/0
private final Thread mUpdateThread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
Engine.this.onUpdate();
}
}
}, "UpdateThread");
private final State mThreadLocker = new State();
private boolean mIsMethodTracing;
private Vibrator mVibrator;
// Constructors
public Engine(final EngineOptions pEngineOptions) {
TextureRegionFactory.setAssetBasePath("");
SoundFactory.setAssetBasePath("");
MusicFactory.setAssetBasePath("");
FontFactory.setAssetBasePath("");
this.mEngineOptions = pEngineOptions;
BufferObjectManager.clear();
if(this.mEngineOptions.needsSound()) {
this.mSoundManager = new SoundManager();
}
if(this.mEngineOptions.needsMusic()) {
this.mMusicManager = new MusicManager();
}
if(this.mEngineOptions.hasLoadingScreen()) {
initLoadingScreen();
}
this.mUpdateThread.start();
}
// Getter & Setter
public boolean isRunning() {
return this.mRunning;
}
public void start() {
if(!this.mRunning){
this.mLastTick = System.nanoTime();
}
this.mRunning = true;
}
public void stop() {
this.mRunning = false;
}
public Scene getScene() {
return this.mScene;
}
public void setScene(final Scene pScene) {
this.mScene = pScene;
}
public EngineOptions getEngineOptions() {
return this.mEngineOptions;
}
public Camera getCamera() {
return this.mEngineOptions.getCamera();
}
public float getSecondsElapsedTotal() {
return this.mSecondsElapsedTotal;
}
public void setSurfaceSize(final int pSurfaceWidth, final int pSurfaceHeight) {
this.mSurfaceWidth = pSurfaceWidth;
this.mSurfaceHeight = pSurfaceHeight;
}
public int getSurfaceWidth() {
return this.mSurfaceWidth;
}
public int getSurfaceHeight() {
return this.mSurfaceHeight;
}
public AccelerometerData getAccelerometerData() {
return this.mAccelerometerData;
}
public OrientationData getOrientationData() {
return this.mOrientationData;
}
public SoundManager getSoundManager() throws IllegalStateException {
if(this.mSoundManager != null) {
return this.mSoundManager;
} else {
throw new IllegalStateException("To enable the SoundManager, check the EngineOptions!");
}
}
public MusicManager getMusicManager() throws IllegalStateException {
if(this.mMusicManager != null) {
return this.mMusicManager;
} else {
throw new IllegalStateException("To enable the MusicManager, check the EngineOptions!");
}
}
public TextureManager getTextureManager() {
return this.mTextureManager;
}
public FontManager getFontManager() {
return this.mFontManager;
}
public void clearPreFrameHandlers() {
this.mPreFrameHandlers.clear();
}
public void clearPostFrameHandlers() {
this.mPostFrameHandlers.clear();
}
public void registerPreFrameHandler(final IUpdateHandler pUpdateHandler) {
this.mPreFrameHandlers.add(pUpdateHandler);
}
public void registerPostFrameHandler(final IUpdateHandler pUpdateHandler) {
this.mPostFrameHandlers.add(pUpdateHandler);
}
public void unregisterPreFrameHandler(final IUpdateHandler pUpdateHandler) {
this.mPreFrameHandlers.remove(pUpdateHandler);
}
public void unregisterPostFrameHandler(final IUpdateHandler pUpdateHandler) {
this.mPostFrameHandlers.remove(pUpdateHandler);
}
public boolean isMethodTracing() {
return this.mIsMethodTracing;
}
public void startMethodTracing(final String pTraceFileName) {
if(!this.mIsMethodTracing) {
this.mIsMethodTracing = true;
android.os.Debug.startMethodTracing(pTraceFileName);
}
}
public void stopMethodTracing() {
if(this.mIsMethodTracing) {
android.os.Debug.stopMethodTracing();
this.mIsMethodTracing = false;
}
}
// Methods for/from SuperClass/Interfaces
@Override
public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) {
if(this.mRunning){
switch(pSensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
this.mAccelerometerData.setAccuracy(pAccuracy);
this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData);
break;
}
}
}
@Override
public void onSensorChanged(final SensorEvent pEvent) {
if(this.mRunning){
switch(pEvent.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
this.mAccelerometerData.setValues(pEvent.values);
this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData);
break;
case Sensor.TYPE_ORIENTATION:
this.mOrientationData.setValues(pEvent.values);
this.mOrientationListener.onOrientationChanged(this.mOrientationData);
break;
}
}
}
@Override
public boolean onTouch(final View pView, final MotionEvent pSurfaceMotionEvent) {
if(this.mRunning) {
/* Let the engine determine which scene and camera this event should be handled by. */
final Scene scene = this.getSceneFromSurfaceMotionEvent(pSurfaceMotionEvent);
final Camera camera = this.getCameraFromSurfaceMotionEvent(pSurfaceMotionEvent);
this.convertSurfaceToSceneMotionEvent(camera, pSurfaceMotionEvent);
if(this.onTouchHUD(camera, pSurfaceMotionEvent)) {
return true;
} else {
/* If HUD didn't handle it, Scene may handle it. */
return this.onTouchScene(scene, pSurfaceMotionEvent);
}
} else {
return false;
}
}
protected boolean onTouchHUD(final Camera pCamera, final MotionEvent pSceneMotionEvent) {
if(pCamera.hasHUD()) {
return pCamera.getHUD().onSceneTouchEvent(pSceneMotionEvent);
} else {
return false;
}
}
protected boolean onTouchScene(final Scene pScene, final MotionEvent pSceneMotionEvent) {
if(pScene != null) {
return pScene.onSceneTouchEvent(pSceneMotionEvent);
} else {
return false;
}
}
// Methods
private void initLoadingScreen() {
final ITextureSource loadingScreenTextureSource = this.getEngineOptions().getLoadingScreenTextureSource();
final Texture loadingScreenTexture = TextureFactory.createForTextureSourceSize(loadingScreenTextureSource);
final TextureRegion loadingScreenTextureRegion = TextureRegionFactory.createFromSource(loadingScreenTexture, loadingScreenTextureSource, 0, 0);
this.setScene(new SplashScene(this.getCamera(), loadingScreenTextureRegion));
}
public void onResume() {
this.mTextureManager.reloadTextures();
BufferObjectManager.reloadBufferObjects();
}
public void onPause() {
this.stop();
}
protected Camera getCameraFromSurfaceMotionEvent(final MotionEvent pMotionEvent) {
return this.getCamera();
}
protected Scene getSceneFromSurfaceMotionEvent(final MotionEvent pMotionEvent) {
return this.mScene;
}
protected void convertSurfaceToSceneMotionEvent(final Camera pCamera, final MotionEvent pSurfaceMotionEvent) {
pCamera.convertSurfaceToSceneMotionEvent(pSurfaceMotionEvent, this.mSurfaceWidth, this.mSurfaceHeight);
}
public void onLoadComplete(final Scene pScene) {
// final Scene loadingScene = this.mScene; // TODO Free texture from loading-screen.
if(this.mEngineOptions.hasLoadingScreen()){
this.registerPreFrameHandler(new TimerHandler(LOADING_SCREEN_DURATION, new ITimerCallback() {
@Override
public void onTimePassed(final TimerHandler pTimerHandler) {
Engine.this.unregisterPreFrameHandler(pTimerHandler);
Engine.this.setScene(pScene);
}
}));
} else {
this.setScene(pScene);
}
}
protected void onUpdate() {
final float secondsElapsed = getSecondsElapsed();
if(this.mRunning) {
this.updatePreFrameHandlers(secondsElapsed);
if(this.mScene != null){
onUpdateScenePreFrameHandlers(secondsElapsed);
onUpdateScene(secondsElapsed);
this.mThreadLocker.notifyCanDraw();
this.mThreadLocker.waitUntilCanUpdate();
onUpdateScenePostFrameHandlers(secondsElapsed);
} else {
this.mThreadLocker.notifyCanDraw();
this.mThreadLocker.waitUntilCanUpdate();
}
this.updatePostFrameHandlers(secondsElapsed);
// if(secondsElapsed < 0.033f) {
// try {
// final int sleepTimeMilliseconds = (int)((0.033f - secondsElapsed) * 1000);
// Thread.sleep(sleepTimeMilliseconds);
// } catch (InterruptedException e) {
// Debug.e("UpdateThread interrupted from sleep.", e);
} else {
this.mThreadLocker.notifyCanDraw();
this.mThreadLocker.waitUntilCanUpdate();
try {
Thread.sleep(16);
} catch (InterruptedException e) {
Debug.e("UpdateThread interrupted from sleep.", e);
}
}
}
public void onDrawFrame(final GL10 pGL) {
this.mThreadLocker.waitUntilCanDraw();
this.mTextureManager.ensureTexturesLoadedToHardware(pGL);
this.mFontManager.ensureFontsLoadedToHardware(pGL);
if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) {
BufferObjectManager.ensureBufferObjectsLoadedToHardware((GL11)pGL);
}
this.onDrawScene(pGL);
this.mThreadLocker.notifyCanUpdate();
}
protected void onUpdateScene(final float secondsElapsed) {
this.mScene.onUpdate(secondsElapsed);
}
protected void onUpdateScenePostFrameHandlers(final float secondsElapsed) {
this.mScene.updatePostFrameHandlers(secondsElapsed);
}
protected void onUpdateScenePreFrameHandlers(final float secondsElapsed) {
this.mScene.updatePreFrameHandlers(secondsElapsed);
}
protected void updatePreFrameHandlers(final float pSecondsElapsed) {
this.getCamera().onUpdate(pSecondsElapsed);
this.mPreFrameHandlers.onUpdate(pSecondsElapsed);
}
protected void updatePostFrameHandlers(final float pSecondsElapsed) {
this.mPostFrameHandlers.onUpdate(pSecondsElapsed);
}
protected void onDrawScene(final GL10 pGL) {
final Camera camera = this.getCamera();
camera.onApplyMatrix(pGL);
GLHelper.setModelViewIdentityMatrix(pGL);
this.mScene.onDraw(pGL);
camera.onDrawHUD(pGL);
}
private float getSecondsElapsed() {
final long now = System.nanoTime();
final float secondsElapsed = (float)(now - this.mLastTick) / TimeConstants.NANOSECONDSPERSECOND;
this.mLastTick = now;
this.mSecondsElapsedTotal += secondsElapsed;
return secondsElapsed;
}
public boolean enableVibrator(final Context pContext) {
this.mVibrator = (Vibrator)pContext.getSystemService(Context.VIBRATOR_SERVICE);
return this.mVibrator != null;
}
public void vibrate(final long pMilliseconds) throws IllegalStateException {
if(this.mVibrator != null) {
this.mVibrator.vibrate(pMilliseconds);
} else {
throw new IllegalStateException("You need to enable the Vibrator before you can use it!");
}
}
public boolean enableAccelerometerSensor(final Context pContext, final IAccelerometerListener pAccelerometerListener) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if (this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) {
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER);
this.mAccelerometerListener = pAccelerometerListener;
if(this.mAccelerometerData == null) {
this.mAccelerometerData = new AccelerometerData();
}
return true;
} else {
return false;
}
}
public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if (this.isSensorSupported(sensorManager, Sensor.TYPE_ORIENTATION)) {
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ORIENTATION);
this.mOrientationListener = pOrientationListener;
if(this.mOrientationData == null) {
this.mOrientationData = new OrientationData();
}
return true;
} else {
return false;
}
}
private void registerSelfAsSensorListener(final SensorManager pSensorManager, final int pType) {
final Sensor accelerometer = pSensorManager.getSensorList(pType).get(0);
pSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
}
private boolean isSensorSupported(final SensorManager pSensorManager, final int pType) {
return pSensorManager.getSensorList(pType).size() > 0;
}
// Inner and Anonymous Classes
private static class State {
private boolean mDrawing = false;
public synchronized void notifyCanDraw() {
// Debug.d(">>> notifyCanDraw");
this.mDrawing = true;
this.notifyAll();
// Debug.d("<<< notifyCanDraw");
}
public synchronized void notifyCanUpdate() {
// Debug.d(">>> notifyCanUpdate");
this.mDrawing = false;
this.notifyAll();
// Debug.d("<<< notifyCanUpdate");
}
public synchronized void waitUntilCanDraw() {
// Debug.d(">>> waitUntilCanDraw");
while (this.mDrawing == false) {
try {
this.wait();
} catch (final InterruptedException e) { }
}
// Debug.d("<<< waitUntilCanDraw");
}
public synchronized void waitUntilCanUpdate() {
// Debug.d(">>> waitUntilCanUpdate");
while (this.mDrawing == true) {
try {
this.wait();
} catch (final InterruptedException e) { }
}
// Debug.d("<<< waitUntilCanUpdate");
}
}
}
|
package org.basex.gui.view.xpath;
import static org.basex.gui.GUIConstants.*;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import javax.swing.JComboBox;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.JCheckBox;
import org.basex.core.Commands;
import org.basex.core.Context;
import org.basex.core.proc.Optimize;
import org.basex.data.Data;
import org.basex.gui.GUI;
import org.basex.gui.GUIConstants;
import org.basex.gui.GUIConstants.FILL;
import org.basex.gui.layout.BaseXBack;
import org.basex.gui.layout.BaseXLabel;
import org.basex.gui.layout.BaseXTextField;
import org.basex.gui.view.View;
import org.basex.util.StringList;
import org.basex.util.Token;
public final class XPathView extends View {
/** Database Context. */
public static Context context = new Context();
/** Input field for XPath queries. */
protected final BaseXTextField input;
/** Header string. */
protected final BaseXLabel header;
/** Button box. */
protected final BaseXBack back;
/** BasicComboPopup Menu. */
public BasicComboPopup pop;
/** StringList with all entries. */
public StringList all = new StringList();
/** JComboBox. */
public JComboBox box;
/** String for temporary input. */
public String tmpIn;
/** Int value to count slashes. */
public int slashC = 0;
/** Boolean value if BasicComboPopup is initialized. */
public boolean popInit = false;
/** Checkbox if popup will be shown. */
public JCheckBox checkPop = new JCheckBox("Helpmode", false);
/**
* Default Constructor.
*/
public XPathView() {
super(null);
back = new BaseXBack(FILL.NONE);
back.setLayout(new BorderLayout());
header = new BaseXLabel(GUIConstants.XPATHVIEW, 10);
back.add(header, BorderLayout.NORTH);
input = new BaseXTextField(null);
input.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(final KeyEvent e) {
int c = e.getKeyCode();
if(checkPop.isSelected()) {
if(all.size == 0) {
String[] test = keys(GUI.context.data());
for(int i = 1; i < test.length; i++) {
all.add(test[i]);
}
String[] cmdList = { "ancestor-or-self::", "ancestor::",
"attribute::", "child::", "comment()", "descendant-or-self::",
"following-sibling::", "following::", "namespace::", "node()",
"parent::", "preceding-sibling::", "preceding::",
"processing-instruction()", "self::", "text()" };
for(int j = 0; j < test.length; j++) {
all.add(cmdList[j]);
}
}
if(c == KeyEvent.VK_SLASH) {
slashC++;
showPopAll();
} else if(c == KeyEvent.VK_DELETE || c == KeyEvent.VK_BACK_SPACE) {
if(input.getText().length() == 0) {
slashC = 0;
tmpIn = "";
pop.hide();
}
} else if(c == KeyEvent.VK_UP || c == KeyEvent.VK_DOWN
|| c == KeyEvent.VK_RIGHT || c == KeyEvent.VK_LEFT) return;
else {
if(popInit) {
if(tmpIn.length() == 0) {
pop.hide();
} else {
slashC = 0;
showSpecPop();
}
}
}
}
if(c == KeyEvent.VK_ESCAPE || c == KeyEvent.VK_ENTER) return;
final String query = input.getText();
GUI.get().execute(Commands.XPATH, query);
}
});
setBorder(10, 10, 10, 10);
setLayout(new BorderLayout(0, 4));
checkPop.setContentAreaFilled(false);
back.add(checkPop, BorderLayout.CENTER);
back.add(input, BorderLayout.SOUTH);
add(back, BorderLayout.NORTH);
refreshLayout();
}
/**
* Shows the BasicComboPopup with all Entries.
*/
public void showPopAll() {
tmpIn = input.getText();
box = new JComboBox(all.finish());
popInit = true;
box.setSelectedItem(null);
box.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if(e.getModifiers() == 16) {
input.setText(tmpIn + box.getSelectedItem());
pop.hide();
}
}
});
if(slashC <= 2) {
pop = new BasicComboPopup(box);
pop.show(input, 0, input.getHeight());
} else {
pop.hide();
}
}
/**
* Shows the special BasicComboPopup with correct entries only.
*/
public void showSpecPop() {
pop.hide();
box.removeAllItems();
String tmp = input.getText().substring(tmpIn.length());
for(int i = 0; i < all.finish().length; i++) {
if(all.finish()[i].startsWith(tmp)) {
box.addItem(all.finish()[i]);
}
}
if(box.getComponentCount() != 0) {
pop = new BasicComboPopup(box);
pop.show(input, 0, input.getHeight());
}
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
}
@Override
protected void refreshContext(final boolean more, final boolean quick) {
// TODO Auto-generated method stub
}
@Override
protected void refreshFocus() {
repaint();
// TODO Auto-generated method stub
}
@Override
protected void refreshInit() {
// TODO Auto-generated method stub
}
@Override
protected void refreshLayout() {
header.setFont(GUIConstants.lfont);
header.setForeground(COLORS[16]);
}
@Override
protected void refreshMark() {
// TODO Auto-generated method stub
}
@Override
protected void refreshUpdate() {
// TODO Auto-generated method stub
}
/**
* Returns a string array with all distinct keys
* and the keys of the specified set.
* @param data data reference
* @return key array
*/
String[] keys(final Data data) {
if(!data.tags.stats()) Optimize.stats(data);
final StringList sl = new StringList();
sl.add("");
for(int i = 1; i <= data.tags.size(); i++) {
if(data.tags.counter(i) == 0) continue;
sl.add(Token.string(data.tags.key(i)));
}
for(int i = 1; i <= data.atts.size(); i++) {
if(data.atts.counter(i) == 0) continue;
sl.add("@" + Token.string(data.atts.key(i)));
}
final String[] vals = sl.finish();
Arrays.sort(vals);
vals[0] = "(" + (vals.length - 1) + " entries)";
return vals;
}
}
|
package org.bdgp.OpenHiCAMM;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.imageio.ImageIO;
import org.bdgp.OpenHiCAMM.DB.Acquisition;
import org.bdgp.OpenHiCAMM.DB.Config;
import org.bdgp.OpenHiCAMM.DB.Image;
import org.bdgp.OpenHiCAMM.DB.ModuleConfig;
import org.bdgp.OpenHiCAMM.DB.Pool;
import org.bdgp.OpenHiCAMM.DB.PoolSlide;
import org.bdgp.OpenHiCAMM.DB.ROI;
import org.bdgp.OpenHiCAMM.DB.Slide;
import org.bdgp.OpenHiCAMM.DB.Task;
import org.bdgp.OpenHiCAMM.DB.TaskConfig;
import org.bdgp.OpenHiCAMM.DB.TaskDispatch;
import org.bdgp.OpenHiCAMM.DB.WorkflowModule;
import org.bdgp.OpenHiCAMM.DB.Task.Status;
import org.bdgp.OpenHiCAMM.Modules.ROIFinderDialog;
import org.bdgp.OpenHiCAMM.Modules.SlideImagerDialog;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Report;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.PositionList;
import org.micromanager.utils.ImageLabelComparator;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMSerializationException;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.NewImage;
import ij.gui.Roi;
import ij.process.Blitter;
import ij.process.ImageProcessor;
import static org.bdgp.OpenHiCAMM.Util.where;
import static org.bdgp.OpenHiCAMM.Tag.T.*;
public class WorkflowReport implements Report {
public static final int SLIDE_PREVIEW_WIDTH = 1280;
public static final int ROI_GRID_PREVIEW_WIDTH = 425;
public static final boolean DEBUG=true;
private WorkflowRunner workflowRunner;
public void jsLog(String message) {
IJ.log(String.format("[WorkflowReport:js] %s", message));
}
public void log(String message, Object... args) {
if (DEBUG) {
IJ.log(String.format("[WorkflowReport] %s", String.format(message, args)));
}
}
@Override public void initialize(WorkflowRunner workflowRunner) {
this.workflowRunner = workflowRunner;
}
@Override
public String runReport() {
Dao<Pool> poolDao = this.workflowRunner.getInstanceDb().table(Pool.class);
Dao<PoolSlide> psDao = this.workflowRunner.getInstanceDb().table(PoolSlide.class);
// Find SlideImager modules where there is no associated posListModuleId module config
// This is the starting SlideImager module.
return Html().indent().with(()->{
Head().with(()->{
// use bootstrap with the default theme
Link().attr("rel", "stylesheet").
attr("href", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");
Link().attr("rel", "stylesheet").
attr("href", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css");
Script().attr("src", "https://code.jquery.com/jquery-2.1.4.min.js");
Script().attr("src", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js");
try {
Script().raw(Resources.toString(Resources.getResource("jquery.maphilight.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("WorkflowReport.js"), Charsets.UTF_8));
}
catch (Exception e) {throw new RuntimeException(e);}
});
Body().with(()->{
List<Runnable> runnables = new ArrayList<Runnable>();
for (Config canImageSlides : this.workflowRunner.getModuleConfig().select(
where("key","canImageSlides").
and("value", "yes")))
{
WorkflowModule slideImager = this.workflowRunner.getWorkflow().selectOneOrDie(
where("id", canImageSlides.getId()));
log("Working on slideImager: %s", slideImager);
if (workflowRunner.getModuleConfig().selectOne(
where("id", slideImager.getId()).
and("key", "posListModuleId")) == null)
{
// get the loader module
if (slideImager.getParentId() != null) {
WorkflowModule loaderModule = this.workflowRunner.getWorkflow().selectOneOrDie(
where("id", slideImager.getParentId()));
if (this.workflowRunner.getModuleConfig().selectOne(
where("id", loaderModule.getId()).
and("key", "canLoadSlides").
and("value", "yes")) != null)
{
log("Using loaderModule: %s", loaderModule);
ModuleConfig poolIdConf = this.workflowRunner.getModuleConfig().selectOne(
where("id", loaderModule.getId()).
and("key", "poolId"));
if (poolIdConf != null) {
Pool pool = poolDao.selectOneOrDie(where("id", poolIdConf.getValue()));
List<PoolSlide> pss = psDao.select(where("poolId", pool.getId()));
if (!pss.isEmpty()) {
for (PoolSlide ps : pss) {
P().with(()->{
A(String.format("Module %s, Slide %s", slideImager, ps)).
attr("href", String.format("#report-%s-PS%s", slideImager.getId(), ps.getId()));
});
runnables.add(()->{
log("Calling runReport(startModule=%s, poolSlide=%s)", slideImager, ps);
runReport(slideImager, ps);
});
}
continue;
}
}
}
}
P().with(()->{
A(String.format("Module %s", slideImager)).
attr("href", String.format("#report-%s", slideImager.getId()));
});
runnables.add(()->{
log("Calling runReport(startModule=%s, poolSlide=null)", slideImager);
runReport(slideImager, null);
});
}
}
Hr();
for (Runnable runnable : runnables) {
runnable.run();
}
});
}).toString();
}
private void runReport(WorkflowModule startModule, PoolSlide poolSlide) {
log("Called runReport(startModule=%s, poolSlide=%s)", startModule, poolSlide);
Dao<Slide> slideDao = this.workflowRunner.getInstanceDb().table(Slide.class);
Dao<Image> imageDao = this.workflowRunner.getInstanceDb().table(Image.class);
Dao<Acquisition> acqDao = this.workflowRunner.getInstanceDb().table(Acquisition.class);
Dao<ROI> roiDao = this.workflowRunner.getInstanceDb().table(ROI.class);
// get the ROIFinder module(s)
List<WorkflowModule> roiFinderModules = new ArrayList<WorkflowModule>();
for (WorkflowModule wm : this.workflowRunner.getWorkflow().select(where("parentId", startModule.getId()))) {
if (this.workflowRunner.getModuleConfig().selectOne(
where("id", wm.getId()).
and("key", "canProduceROIs").
and("value", "yes")) != null)
{
roiFinderModules.add(wm);
}
}
log("roiFinderModules = %s", roiFinderModules);
// get the associated hi res ROI slide imager modules for each ROI finder module
Map<WorkflowModule,List<WorkflowModule>> roiImagers = new HashMap<WorkflowModule,List<WorkflowModule>>();
for (WorkflowModule roiFinderModule : roiFinderModules) {
for (Config canImageSlides : this.workflowRunner.getModuleConfig().select(
where("key","canImageSlides").
and("value", "yes")))
{
WorkflowModule slideImager = this.workflowRunner.getWorkflow().selectOneOrDie(
where("id", canImageSlides.getId()));
if (!workflowRunner.getModuleConfig().select(
where("id", slideImager.getId()).
and("key", "posListModuleId").
and("value", roiFinderModule.getId())).isEmpty())
{
if (!roiImagers.containsKey(roiFinderModule)) {
roiImagers.put(roiFinderModule, new ArrayList<WorkflowModule>());
}
roiImagers.get(roiFinderModule).add(slideImager);
}
}
}
log("roiImagers = %s", roiImagers);
// display the title
Slide slide;
String slideId;
if (poolSlide != null) {
slide = slideDao.selectOneOrDie(where("id", poolSlide.getSlideId()));
slideId = slide.getName();
String title = String.format("SlideImager %s, Slide %s, Pool %d, Cartridge %d, Slide Position %d",
startModule.getId(),
slide.getName(),
poolSlide.getPoolId(),
poolSlide.getCartridgePosition(),
poolSlide.getSlidePosition());
A().attr("name", String.format("report-%s-PS%s", startModule.getId(), poolSlide.getId()));
H1().text(title);
log("title = %s", title);
}
else {
slide = null;
slideId = "slide";
String title = String.format("SlideImager %s", startModule.getId());
A().attr("name", String.format("report-%s", startModule.getId()));
H1().text(title);
log("title = %s", title);
}
// get the pixel size of this slide imager config
Config pixelSizeConf = this.workflowRunner.getModuleConfig().selectOne(where("id", startModule.getId()).and("key","pixelSize"));
Double pixelSize = pixelSizeConf != null? new Double(pixelSizeConf.getValue()) : SlideImagerDialog.DEFAULT_PIXEL_SIZE_UM;
log("pixelSize = %f", pixelSize);
// get invertXAxis and invertYAxis conf values
Config invertXAxisConf = this.workflowRunner.getModuleConfig().selectOne(where("id", startModule.getId()).and("key","invertXAxis"));
boolean invertXAxis = invertXAxisConf == null || invertXAxisConf.getValue().equals("yes");
log("invertXAxis = %b", invertXAxis);
Config invertYAxisConf = this.workflowRunner.getModuleConfig().selectOne(where("id", startModule.getId()).and("key","invertYAxis"));
boolean invertYAxis = invertYAxisConf == null || invertYAxisConf.getValue().equals("yes");
log("invertYAxis = %b", invertYAxis);
// sort imageTasks by image position
List<Task> imageTasks = this.workflowRunner.getTaskStatus().select(
where("moduleId", startModule.getId()));
Map<String,Task> imageTaskPosIdx = new TreeMap<String,Task>(new ImageLabelComparator());
for (Task imageTask : imageTasks) {
Config slideIdConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", imageTask.getId()).and("key", "slideId"));
if (poolSlide == null || new Integer(slideIdConf.getValue()).equals(poolSlide.getSlideId())) {
Config imageLabelConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", imageTask.getId()).and("key", "imageLabel"));
if (imageLabelConf != null) {
imageTaskPosIdx.put(imageLabelConf.getValue(), imageTask);
}
}
}
imageTasks.clear();
imageTasks.addAll(imageTaskPosIdx.values());
log("imageTasks = %s", imageTasks);
// determine the bounds of the stage coordinates
Double minX_ = null, minY_ = null, maxX = null, maxY = null;
Integer imageWidth = null, imageHeight = null;
for (Task task : imageTasks) {
MultiStagePosition msp = getMsp(task);
if (minX_ == null || msp.getX() < minX_) minX_ = msp.getX();
if (maxX == null || msp.getX() > maxX) maxX = msp.getX();
if (minY_ == null || msp.getY() < minY_) minY_ = msp.getY();
if (maxY == null || msp.getY() > maxY) maxY = msp.getY();
if (imageWidth == null || imageHeight == null) {
Config imageIdConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", task.getId()).and("key", "imageId"));
if (imageIdConf != null) {
Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue())));
log("Getting image size for image %s", image);
ImagePlus imp = null;
try { imp = image.getImagePlus(acqDao); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image, sw);
}
if (imp != null) {
imageWidth = imp.getWidth();
imageHeight = imp.getHeight();
}
}
}
}
Double minX = minX_, minY = minY_;
log("minX = %f, minY = %f, maxX = %f, maxY = %f, imageWidth = %d, imageHeight = %d",
minX, minY, maxX, maxY, imageWidth, imageHeight);
int slideWidthPx = (int)Math.floor(((maxX - minX) / pixelSize) + (double)imageWidth);
int slideHeightPx = (int)Math.floor(((maxY - minY) / pixelSize) + (double)imageHeight);
log("slideWidthPx = %d, slideHeightPx = %d", slideWidthPx, slideHeightPx);
// this is the scale factor for creating the thumbnail images
double scaleFactor = (double)SLIDE_PREVIEW_WIDTH / (double)slideWidthPx;
log("scaleFactor = %f", scaleFactor);
int slidePreviewHeight = (int)Math.floor(scaleFactor * slideHeightPx);
log("slidePreviewHeight = %d", slidePreviewHeight);
ImagePlus slideThumb = NewImage.createRGBImage("slideThumb", SLIDE_PREVIEW_WIDTH, slidePreviewHeight, 1, NewImage.FILL_WHITE);
Map<Integer,Roi> imageRois = new LinkedHashMap<Integer,Roi>();
List<Roi> roiRois = new ArrayList<Roi>();
Map().attr("name",String.format("map-%s-%s", startModule.getId(), slideId)).with(()->{
for (Task task : imageTasks) {
Config imageIdConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", new Integer(task.getId()).toString()).and("key", "imageId"));
if (imageIdConf != null) {
MultiStagePosition msp = getMsp(task);
// Get a thumbnail of the image
Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue())));
log("Working on image; %s", image);
ImagePlus imp = null;
try { imp = image.getImagePlus(acqDao); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image, sw);
}
if (imp != null) {
int width = imp.getWidth(), height = imp.getHeight();
log("Image width: %d, height: %d", width, height);
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
(int)Math.floor(imp.getWidth() * scaleFactor),
(int)Math.floor(imp.getHeight() * scaleFactor)));
log("Resized image width: %d, height: %d", imp.getWidth(), imp.getHeight());
int xloc = (int)Math.floor(((msp.getX() - minX) / pixelSize));
int xlocInvert = invertXAxis? slideWidthPx - (xloc + width) : xloc;
int xlocScale = (int)Math.floor(xlocInvert * scaleFactor);
log("xloc = %d, xlocInvert = %d, xlocScale = %d", xloc, xlocInvert, xlocScale);
int yloc = (int)Math.floor(((msp.getY() - minY) / pixelSize));
int ylocInvert = invertYAxis? slideHeightPx - (yloc + height) : yloc;
int ylocScale = (int)Math.floor(ylocInvert * scaleFactor);
log("yloc = %d, ylocInvert = %d, ylocScale = %d", yloc, ylocInvert, ylocScale);
// draw the thumbnail image
slideThumb.getProcessor().copyBits(imp.getProcessor(), xlocScale, ylocScale, Blitter.COPY);
// save the image ROI for the image map
Roi imageRoi = new Roi(xlocScale, ylocScale, imp.getWidth(), imp.getHeight());
imageRoi.setName(image.getName());
imageRoi.setProperty("id", new Integer(image.getId()).toString());
imageRois.put(image.getId(), imageRoi);
log("imageRoi = %s", imageRoi);
for (ROI roi : roiDao.select(where("imageId", image.getId()))) {
int roiX = (int)Math.floor(xlocScale + (roi.getX1() * scaleFactor));
int roiY = (int)Math.floor(ylocScale + (roi.getY1() * scaleFactor));
int roiWidth = (int)Math.floor((roi.getX2()-roi.getX1()+1) * scaleFactor);
int roiHeight = (int)Math.floor((roi.getY2()-roi.getY1()+1) * scaleFactor);
Roi r = new Roi(roiX, roiY, roiWidth, roiHeight);
r.setName(roi.toString());
r.setProperty("id", new Integer(roi.getId()).toString());
r.setStrokeColor(new Color(1f, 0f, 0f, 0.4f));
r.setStrokeWidth(0.4);
roiRois.add(r);
log("roiRoi = %s", r);
}
}
}
}
// write the ROI areas first so they take precedence
for (Roi roi : roiRois) {
Area().attr("shape","rect").
attr("coords", String.format("%d,%d,%d,%d",
(int)Math.floor(roi.getXBase()),
(int)Math.floor(roi.getYBase()),
(int)Math.floor(roi.getXBase()+roi.getFloatWidth()),
(int)Math.floor(roi.getYBase()+roi.getFloatHeight()))).
attr("href", String.format("#area-ROI-%s", roi.getProperty("id"))).
attr("title", roi.getName());
}
// next write the image ROIs
for (Roi roi : imageRois.values()) {
Area().attr("shape", "rect").
attr("coords", String.format("%d,%d,%d,%d",
(int)Math.floor(roi.getXBase()),
(int)Math.floor(roi.getYBase()),
(int)Math.floor(roi.getXBase()+roi.getFloatWidth()),
(int)Math.floor(roi.getYBase()+roi.getFloatHeight()))).
attr("title", roi.getName()).
attr("onclick", String.format("report.showImage(%d)", new Integer(roi.getProperty("id"))));
}
// now draw the ROI rois in red
for (Roi roiRoi : roiRois) {
slideThumb.getProcessor().setColor(roiRoi.getStrokeColor());
slideThumb.getProcessor().draw(roiRoi);
}
});
// write the slide thumbnail as an embedded HTML image.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try { ImageIO.write(slideThumb.getBufferedImage(), "jpg", baos); }
catch (IOException e) {throw new RuntimeException(e);}
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos.toByteArray()))).
attr("width", slideThumb.getWidth()).
attr("height", slideThumb.getHeight()).
attr("usemap", String.format("#map-%s-%s", startModule.getId(), slideId)).
attr("class","map").
attr("style", "border: 1px solid black");
// now render the individual ROI sections
for (Task task : imageTasks) {
Config imageIdConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", new Integer(task.getId()).toString()).and("key", "imageId"));
if (imageIdConf != null) {
Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue())));
// make sure this image was included in the slide thumbnail image
if (!imageRois.containsKey(image.getId())) continue;
List<ROI> rois = roiDao.select(where("imageId", image.getId()));
Collections.sort(rois, (a,b)->a.getId()-b.getId());
for (ROI roi : rois) {
log("Working on ROI: %s", roi);
Hr();
A().attr("name", String.format("area-ROI-%s", roi.getId())).with(()->{
H2().text(String.format("Image %s, ROI %s", image, roi));
});
// go through each attached SlideImager and look for MSP's with an ROI property
// that matches this ROI's ID.
for (Map.Entry<WorkflowModule, List<WorkflowModule>> entry : roiImagers.entrySet()) {
for (WorkflowModule imager : entry.getValue()) {
// get the hires pixel size for this imager
Config hiResPixelSizeConf = this.workflowRunner.getModuleConfig().selectOne(where("id", imager.getId()).and("key","pixelSize"));
Double hiResPixelSize = hiResPixelSizeConf != null? new Double(hiResPixelSizeConf.getValue()) : ROIFinderDialog.DEFAULT_HIRES_PIXEL_SIZE_UM;
log("hiResPixelSize = %f", hiResPixelSize);
// determine the stage coordinate bounds of this ROI tile grid.
// also get the image width and height of the acqusition.
Double minX2_=null, minY2_=null, maxX2=null, maxY2=null;
Integer imageWidth2 = null, imageHeight2 = null;
Map<String,List<Task>> imagerTasks = new TreeMap<String,List<Task>>(new ImageLabelComparator());
for (Task imagerTask : this.workflowRunner.getTaskStatus().select(where("moduleId", imager.getId()))) {
MultiStagePosition msp = getMsp(imagerTask);
if (msp.hasProperty("ROI") && msp.getProperty("ROI").equals(new Integer(roi.getId()).toString()))
{
TaskConfig imageLabelConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", imagerTask.getId()).
and("key", "imageLabel"));
int[] indices = MDUtils.getIndices(imageLabelConf.getValue());
if (indices != null && indices.length >= 4) {
String imageLabel = MDUtils.generateLabel(indices[0], indices[1], indices[2], 0);
if (!imagerTasks.containsKey(imageLabel)) {
imagerTasks.put(imageLabel, new ArrayList<Task>());
}
imagerTasks.get(imageLabel).add(imagerTask);
if (minX2_ == null || msp.getX() < minX2_) minX2_ = msp.getX();
if (minY2_ == null || msp.getY() < minY2_) minY2_ = msp.getY();
if (maxX2 == null || msp.getX() > maxX2) maxX2 = msp.getX();
if (maxY2 == null || msp.getY() > maxY2) maxY2 = msp.getY();
if (imageWidth2 == null || imageHeight2 == null) {
Config imageIdConf2 = this.workflowRunner.getTaskConfig().selectOne(
where("id", imagerTask.getId()).
and("key", "imageId"));
if (imageIdConf2 != null) {
Image image2 = imageDao.selectOneOrDie(
where("id", new Integer(imageIdConf2.getValue())));
log("Getting image size for image %s", image2);
ImagePlus imp = null;
try { imp = image2.getImagePlus(acqDao); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image2, sw);
}
if (imp != null) {
imageWidth2 = imp.getWidth();
imageHeight2 = imp.getHeight();
}
}
}
}
}
}
Double minX2 = minX2_, minY2 = minY2_;
log("minX2 = %f, minY2 = %f, maxX2 = %f, maxY2 = %f, imageWidth2 = %d, imageHeight2 = %d",
minX2, minY2, maxX2, maxY2, imageWidth2, imageHeight2);
if (!imagerTasks.isEmpty()) {
int gridWidthPx = (int)Math.floor(((maxX2 - minX2_) / hiResPixelSize) + (double)imageWidth2);
int gridHeightPx = (int)Math.floor(((maxY2 - minY2_) / hiResPixelSize) + (double)imageHeight2);
log("gridWidthPx = %d, gridHeightPx = %d", gridWidthPx, gridHeightPx);
// this is the scale factor for creating the thumbnail images
double gridScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)gridWidthPx;
int gridPreviewHeight = (int)Math.floor(gridScaleFactor * gridHeightPx);
log("gridScaleFactor = %f, gridPreviewHeight = %d", gridScaleFactor, gridPreviewHeight);
ImagePlus roiGridThumb = NewImage.createRGBImage(
String.format("roiGridThumb-%s-ROI%d", imager.getId(), roi.getId()),
ROI_GRID_PREVIEW_WIDTH,
gridPreviewHeight,
1,
NewImage.FILL_WHITE);
log("roiGridThumb: width=%d, height=%d", roiGridThumb.getWidth(), roiGridThumb.getHeight());
Table().attr("class","table table-bordered table-hover table-striped").
with(()->{
Thead().with(()->{
Tr().with(()->{
Th().text("Channel, Slice, Frame");
Th().text("Source ROI Cutout");
Th().text("Tiled ROI Images");
Th().text("Stitched ROI Image");
});
});
Tbody().with(()->{
for (Map.Entry<String,List<Task>> imagerTaskEntry : imagerTasks.entrySet()) {
String imageLabel = imagerTaskEntry.getKey();
int[] indices = MDUtils.getIndices(imageLabel);
int channel = indices[0], slice = indices[1], frame = indices[2];
log("Working on channel %d, slice %d, frame %d", channel, slice, frame);
Tr().with(()->{
Th().text(String.format("Channel %d, Slice %d, Frame %d", channel, slice, frame));
Td().with(()->{
ImagePlus imp = null;
try { imp = image.getImagePlus(acqDao); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image, sw);
}
if (imp != null) {
imp.setRoi(new Roi(roi.getX1(), roi.getY1(), roi.getX2()-roi.getX1()+1, roi.getY2()-roi.getY1()+1));
double roiScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)imp.getWidth();
int roiPreviewHeight = (int)Math.floor(imp.getHeight() * roiScaleFactor);
imp.setProcessor(imp.getTitle(), imp.getProcessor().crop().resize(
ROI_GRID_PREVIEW_WIDTH,
roiPreviewHeight));
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
try { ImageIO.write(imp.getBufferedImage(), "jpg", baos2); }
catch (IOException e) {throw new RuntimeException(e);}
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))).
attr("width", imp.getWidth()).
attr("height", imp.getHeight()).
attr("title", roi.toString()).
attr("onclick", String.format("report.showImage(%d)", image.getId()));
}
});
Td().with(()->{
Map().attr("name", String.format("map-roi-%s-ROI%d", imager.getId(), roi.getId())).with(()->{
for (Task imagerTask : imagerTaskEntry.getValue()) {
Config imageIdConf2 = this.workflowRunner.getTaskConfig().selectOne(
where("id", new Integer(imagerTask.getId()).toString()).and("key", "imageId"));
if (imageIdConf2 != null) {
MultiStagePosition msp = getMsp(imagerTask);
// Get a thumbnail of the image
Image image2 = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf2.getValue())));
ImagePlus imp = null;
try { imp = image2.getImagePlus(acqDao); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image2, sw);
}
if (imp != null) {
int width = imp.getWidth(), height = imp.getHeight();
log("imp: width=%d, height=%d", width, height);
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
(int)Math.floor(imp.getWidth() * gridScaleFactor),
(int)Math.floor(imp.getHeight() * gridScaleFactor)));
log("imp: resized width=%d, height=%d", imp.getWidth(), imp.getHeight());
int xloc = (int)Math.floor((msp.getX() - minX2) / hiResPixelSize);
int xlocInvert = invertXAxis? gridWidthPx - (xloc + width) : xloc;
int xlocScale = (int)Math.floor(xlocInvert * gridScaleFactor);
log("xloc=%d, xlocInvert=%d, xlocScale=%d", xloc, xlocInvert, xlocScale);
int yloc = (int)Math.floor((msp.getY() - minY2) / hiResPixelSize);
int ylocInvert = invertYAxis? gridHeightPx - (yloc + height) : yloc;
int ylocScale = (int)Math.floor(ylocInvert * gridScaleFactor);
log("yloc=%d, ylocInvert=%d, ylocScale=%d", yloc, ylocInvert, ylocScale);
roiGridThumb.getProcessor().copyBits(imp.getProcessor(), xlocScale, ylocScale, Blitter.COPY);
Roi tileRoi = new Roi(xlocScale, ylocScale, imp.getWidth(), imp.getHeight());
// make the tile image clickable
Area().attr("shape", "rect").
attr("coords", String.format("%d,%d,%d,%d",
(int)Math.floor(tileRoi.getXBase()),
(int)Math.floor(tileRoi.getYBase()),
(int)Math.floor(tileRoi.getXBase()+tileRoi.getFloatWidth()),
(int)Math.floor(tileRoi.getYBase()+tileRoi.getFloatHeight()))).
attr("title", image2.getName()).
attr("onclick", String.format("report.showImage(%d)", image2.getId()));
}
}
}
});
// write the grid thumbnail as an embedded HTML image.
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
try { ImageIO.write(roiGridThumb.getBufferedImage(), "jpg", baos2); }
catch (IOException e) {throw new RuntimeException(e);}
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))).
attr("width", roiGridThumb.getWidth()).
attr("height", roiGridThumb.getHeight()).
attr("class", "map").
attr("usemap", String.format("#map-%s-ROI%d", imager.getId(), roi.getId()));
});
Td().with(()->{
// get the downstream stitcher tasks
Set<Task> stitcherTasks = new HashSet<Task>();
for (Task imagerTask : imagerTaskEntry.getValue()) {
for (TaskDispatch td : this.workflowRunner.getTaskDispatch().select(where("parentTaskId", imagerTask.getId()))) {
Task stitcherTask = this.workflowRunner.getTaskStatus().selectOneOrDie(
where("id", td.getTaskId()));
if (!this.workflowRunner.getModuleConfig().select(
where("id", stitcherTask.getModuleId()).
and("key", "canStitchImages").
and("value", "yes")).isEmpty() &&
stitcherTask.getStatus().equals(Status.SUCCESS))
{
stitcherTasks.add(stitcherTask);
}
}
}
for (Task stitcherTask : stitcherTasks) {
log("Working on stitcher task: %s", stitcherTask);
Config stitchedImageFile = this.workflowRunner.getTaskConfig().selectOne(
where("id", new Integer(stitcherTask.getId()).toString()).and("key", "stitchedImageFile"));
log("stitchedImageFile = %s", stitchedImageFile.getValue());
if (stitchedImageFile != null && new File(stitchedImageFile.getValue()).exists()) {
// Get a thumbnail of the image
ImagePlus imp = new ImagePlus(stitchedImageFile.getValue());
log("stitchedImage width = %d, height = %d", imp.getWidth(), imp.getHeight());
double stitchScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)imp.getWidth();
log("stitchScaleFactor = %f", stitchScaleFactor);
int stitchPreviewHeight = (int)Math.floor(imp.getHeight() * stitchScaleFactor);
log("stitchPreviewHeight = %d", stitchPreviewHeight);
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
ROI_GRID_PREVIEW_WIDTH,
stitchPreviewHeight));
log("resized stitched image width=%d, height=%d", imp.getWidth(), imp.getHeight());
// write the stitched thumbnail as an embedded HTML image.
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
try { ImageIO.write(imp.getBufferedImage(), "jpg", baos2); }
catch (IOException e) {throw new RuntimeException(e);}
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))).
attr("width", imp.getWidth()).
attr("height", imp.getHeight()).
attr("title", stitchedImageFile.getValue()).
attr("onclick", String.format("report.showImageFile(\"%s\")",
Util.escapeJavaStyleString(stitchedImageFile.getValue())));
}
}
});
});
}
});
});
}
}
}
}
}
}
}
public void showImage(int imageId) {
//log("called showImage(imageId=%d)", imageId);
Dao<Image> imageDao = this.workflowRunner.getInstanceDb().table(Image.class);
Dao<Acquisition> acqDao = this.workflowRunner.getInstanceDb().table(Acquisition.class);
Image image = imageDao.selectOneOrDie(where("id", imageId));
ImagePlus imp = image.getImagePlus(acqDao);
imp.show();
}
public void showImageFile(String imagePath) {
//log("called showImageFile(imagePath=%s)", imagePath);
ImagePlus imp = new ImagePlus(imagePath);
imp.show();
}
private MultiStagePosition getMsp(Task task) {
// get the MSP from the task config
PositionList posList = new PositionList();
try {
Config mspConf = this.workflowRunner.getTaskConfig().selectOneOrDie(where("id", task.getId()).and("key","MSP"));
JSONObject posListJson = new JSONObject().
put("POSITIONS", new JSONArray().put(new JSONObject(mspConf.getValue()))).
put("VERSION", 3).
put("ID","Micro-Manager XY-position list");
posList.restore(posListJson.toString());
}
catch (JSONException | MMSerializationException e) {throw new RuntimeException(e);}
MultiStagePosition msp = posList.getPosition(0);
return msp;
}
}
|
package org.bouncycastle.openssl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Reader;
import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.EncryptionScheme;
import org.bouncycastle.asn1.pkcs.KeyDerivationFunc;
import org.bouncycastle.asn1.pkcs.PBEParameter;
import org.bouncycastle.asn1.pkcs.PBES2Parameters;
import org.bouncycastle.asn1.pkcs.PBKDF2Params;
import org.bouncycastle.asn1.pkcs.PKCS12PBEParams;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.sec.ECPrivateKeyStructure;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.RSAPublicKeyStructure;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.io.pem.PemHeader;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemObjectParser;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.x509.X509V2AttributeCertificate;
/**
* Class for reading OpenSSL PEM encoded streams containing
* X509 certificates, PKCS8 encoded keys and PKCS7 objects.
* <p>
* In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Keys and
* Certificates will be returned using the appropriate java.security type (KeyPair, PublicKey, X509Certificate,
* or X509CRL). In the case of a Certificate Request a PKCS10CertificationRequest will be returned.
* </p>
*/
public class PEMReader
extends PemReader
{
private final Map parsers = new HashMap();
private PasswordFinder pFinder;
/**
* Create a new PEMReader
*
* @param reader the Reader
*/
public PEMReader(
Reader reader)
{
this(reader, null, "BC");
}
/**
* Create a new PEMReader with a password finder
*
* @param reader the Reader
* @param pFinder the password finder
*/
public PEMReader(
Reader reader,
PasswordFinder pFinder)
{
this(reader, pFinder, "BC");
}
/**
* Create a new PEMReader with a password finder
*
* @param reader the Reader
* @param pFinder the password finder
* @param provider the cryptography provider to use
*/
public PEMReader(
Reader reader,
PasswordFinder pFinder,
String provider)
{
this(reader, pFinder, provider, provider);
}
/**
* Create a new PEMReader with a password finder and differing providers for secret and public key
* operations.
*
* @param reader the Reader
* @param pFinder the password finder
* @param symProvider provider to use for symmetric operations
* @param asymProvider provider to use for asymmetric (public/private key) operations
*/
public PEMReader(
Reader reader,
PasswordFinder pFinder,
String symProvider,
String asymProvider)
{
super(reader);
this.pFinder = pFinder;
parsers.put("CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
parsers.put("NEW CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
parsers.put("CERTIFICATE", new X509CertificateParser(asymProvider));
parsers.put("X509 CERTIFICATE", new X509CertificateParser(asymProvider));
parsers.put("X509 CRL", new X509CRLParser(asymProvider));
parsers.put("PKCS7", new PKCS7Parser());
parsers.put("ATTRIBUTE CERTIFICATE", new X509AttributeCertificateParser());
parsers.put("EC PARAMETERS", new ECNamedCurveSpecParser());
parsers.put("PUBLIC KEY", new PublicKeyParser(asymProvider));
parsers.put("RSA PUBLIC KEY", new RSAPublicKeyParser(asymProvider));
parsers.put("RSA PRIVATE KEY", new RSAKeyPairParser(asymProvider));
parsers.put("DSA PRIVATE KEY", new DSAKeyPairParser(asymProvider));
parsers.put("EC PRIVATE KEY", new ECDSAKeyPairParser(asymProvider));
parsers.put("ENCRYPTED PRIVATE KEY", new EncryptedPrivateKeyParser(symProvider, asymProvider));
parsers.put("PRIVATE KEY", new PrivateKeyParser(asymProvider));
}
public Object readObject()
throws IOException
{
PemObject obj = readPemObject();
if (obj != null)
{
String type = obj.getType();
if (parsers.containsKey(type))
{
return ((PemObjectParser)parsers.get(type)).parseObject(obj);
}
else
{
throw new IOException("unrecognised object: " + type);
}
}
return null;
}
private abstract class KeyPairParser
implements PemObjectParser
{
protected String provider;
public KeyPairParser(String provider)
{
this.provider = provider;
}
/**
* Read a Key Pair
*/
protected ASN1Sequence readKeyPair(
PemObject obj)
throws IOException
{
boolean isEncrypted = false;
String dekInfo = null;
List headers = obj.getHeaders();
for (Iterator it = headers.iterator(); it.hasNext();)
{
PemHeader hdr = (PemHeader)it.next();
if (hdr.getName().equals("Proc-Type") && hdr.getValue().equals("4,ENCRYPTED"))
{
isEncrypted = true;
}
else if (hdr.getName().equals("DEK-Info"))
{
dekInfo = hdr.getValue();
}
}
// extract the key
byte[] keyBytes = obj.getContent();
if (isEncrypted)
{
if (pFinder == null)
{
throw new PasswordException("No password finder specified, but a password is required");
}
char[] password = pFinder.getPassword();
if (password == null)
{
throw new PasswordException("Password is null, but a password is required");
}
StringTokenizer tknz = new StringTokenizer(dekInfo, ",");
String dekAlgName = tknz.nextToken();
byte[] iv = Hex.decode(tknz.nextToken());
keyBytes = PEMUtilities.crypt(false, provider, keyBytes, password, dekAlgName, iv);
}
try
{
return (ASN1Sequence)ASN1Object.fromByteArray(keyBytes);
}
catch (IOException e)
{
if (isEncrypted)
{
throw new PEMException("exception decoding - please check password and data.", e);
}
else
{
throw new PEMException(e.getMessage(), e);
}
}
catch (ClassCastException e)
{
if (isEncrypted)
{
throw new PEMException("exception decoding - please check password and data.", e);
}
else
{
throw new PEMException(e.getMessage(), e);
}
}
}
}
private class DSAKeyPairParser
extends KeyPairParser
{
public DSAKeyPairParser(String provider)
{
super(provider);
}
public Object parseObject(PemObject obj)
throws IOException
{
try
{
ASN1Sequence seq = readKeyPair(obj);
if (seq.size() != 6)
{
throw new PEMException("malformed sequence in DSA private key");
}
// DERInteger v = (DERInteger)seq.getObjectAt(0);
DERInteger p = (DERInteger)seq.getObjectAt(1);
DERInteger q = (DERInteger)seq.getObjectAt(2);
DERInteger g = (DERInteger)seq.getObjectAt(3);
DERInteger y = (DERInteger)seq.getObjectAt(4);
DERInteger x = (DERInteger)seq.getObjectAt(5);
DSAPrivateKeySpec privSpec = new DSAPrivateKeySpec(
x.getValue(), p.getValue(),
q.getValue(), g.getValue());
DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(
y.getValue(), p.getValue(),
q.getValue(), g.getValue());
KeyFactory fact = KeyFactory.getInstance("DSA", provider);
return new KeyPair(
fact.generatePublic(pubSpec),
fact.generatePrivate(privSpec));
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException(
"problem creating DSA private key: " + e.toString(), e);
}
}
}
private class ECDSAKeyPairParser
extends KeyPairParser
{
public ECDSAKeyPairParser(String provider)
{
super(provider);
}
public Object parseObject(PemObject obj)
throws IOException
{
try
{
ASN1Sequence seq = readKeyPair(obj);
ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.getDERObject());
SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pKey.getPublicKey().getBytes());
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privInfo.getEncoded());
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubInfo.getEncoded());
KeyFactory fact = KeyFactory.getInstance("ECDSA", provider);
return new KeyPair(
fact.generatePublic(pubSpec),
fact.generatePrivate(privSpec));
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException(
"problem creating EC private key: " + e.toString(), e);
}
}
}
private class RSAKeyPairParser
extends KeyPairParser
{
public RSAKeyPairParser(String provider)
{
super(provider);
}
public Object parseObject(PemObject obj)
throws IOException
{
try
{
ASN1Sequence seq = readKeyPair(obj);
if (seq.size() != 9)
{
throw new PEMException("malformed sequence in RSA private key");
}
// DERInteger v = (DERInteger)seq.getObjectAt(0);
DERInteger mod = (DERInteger)seq.getObjectAt(1);
DERInteger pubExp = (DERInteger)seq.getObjectAt(2);
DERInteger privExp = (DERInteger)seq.getObjectAt(3);
DERInteger p1 = (DERInteger)seq.getObjectAt(4);
DERInteger p2 = (DERInteger)seq.getObjectAt(5);
DERInteger exp1 = (DERInteger)seq.getObjectAt(6);
DERInteger exp2 = (DERInteger)seq.getObjectAt(7);
DERInteger crtCoef = (DERInteger)seq.getObjectAt(8);
RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(
mod.getValue(), pubExp.getValue());
RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(
mod.getValue(), pubExp.getValue(), privExp.getValue(),
p1.getValue(), p2.getValue(),
exp1.getValue(), exp2.getValue(),
crtCoef.getValue());
KeyFactory fact = KeyFactory.getInstance("RSA", provider);
return new KeyPair(
fact.generatePublic(pubSpec),
fact.generatePrivate(privSpec));
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException(
"problem creating RSA private key: " + e.toString(), e);
}
}
}
private class PublicKeyParser
implements PemObjectParser
{
private String provider;
public PublicKeyParser(String provider)
{
this.provider = provider;
}
public Object parseObject(PemObject obj)
throws IOException
{
KeySpec keySpec = new X509EncodedKeySpec(obj.getContent());
String[] algorithms = {"DSA", "RSA"};
for (int i = 0; i < algorithms.length; i++)
{
try
{
KeyFactory keyFact = KeyFactory.getInstance(algorithms[i], provider);
PublicKey pubKey = keyFact.generatePublic(keySpec);
return pubKey;
}
catch (NoSuchAlgorithmException e)
{
// ignore
}
catch (InvalidKeySpecException e)
{
// ignore
}
catch (NoSuchProviderException e)
{
throw new RuntimeException("can't find provider " + provider);
}
}
return null;
}
}
private class RSAPublicKeyParser
implements PemObjectParser
{
private String provider;
public RSAPublicKeyParser(String provider)
{
this.provider = provider;
}
public Object parseObject(PemObject obj)
throws IOException
{
try
{
ASN1InputStream ais = new ASN1InputStream(obj.getContent());
Object asnObject = ais.readObject();
ASN1Sequence sequence = (ASN1Sequence)asnObject;
RSAPublicKeyStructure rsaPubStructure = new RSAPublicKeyStructure(sequence);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(
rsaPubStructure.getModulus(),
rsaPubStructure.getPublicExponent());
KeyFactory keyFact = KeyFactory.getInstance("RSA", provider);
return keyFact.generatePublic(keySpec);
}
catch (IOException e)
{
throw e;
}
catch (NoSuchProviderException e)
{
throw new IOException("can't find provider " + provider);
}
catch (Exception e)
{
throw new PEMException("problem extracting key: " + e.toString(), e);
}
}
}
private class X509CertificateParser
implements PemObjectParser
{
private String provider;
public X509CertificateParser(String provider)
{
this.provider = provider;
}
/**
* Reads in a X509Certificate.
*
* @return the X509Certificate
* @throws IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(obj.getContent());
try
{
CertificateFactory certFact
= CertificateFactory.getInstance("X.509", provider);
return certFact.generateCertificate(bIn);
}
catch (Exception e)
{
throw new PEMException("problem parsing cert: " + e.toString(), e);
}
}
}
private class X509CRLParser
implements PemObjectParser
{
private String provider;
public X509CRLParser(String provider)
{
this.provider = provider;
}
/**
* Reads in a X509CRL.
*
* @return the X509Certificate
* @throws IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(obj.getContent());
try
{
CertificateFactory certFact
= CertificateFactory.getInstance("X.509", provider);
return certFact.generateCRL(bIn);
}
catch (Exception e)
{
throw new PEMException("problem parsing cert: " + e.toString(), e);
}
}
}
private class PKCS10CertificationRequestParser
implements PemObjectParser
{
/**
* Reads in a PKCS10 certification request.
*
* @return the certificate request.
* @throws IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
return new PKCS10CertificationRequest(obj.getContent());
}
catch (Exception e)
{
throw new PEMException("problem parsing certrequest: " + e.toString(), e);
}
}
}
private class PKCS7Parser
implements PemObjectParser
{
/**
* Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
* API.
*
* @return the X509Certificate
* @throws IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
ASN1InputStream aIn = new ASN1InputStream(obj.getContent());
return ContentInfo.getInstance(aIn.readObject());
}
catch (Exception e)
{
throw new PEMException("problem parsing PKCS7 object: " + e.toString(), e);
}
}
}
private class X509AttributeCertificateParser
implements PemObjectParser
{
public Object parseObject(PemObject obj)
throws IOException
{
return new X509V2AttributeCertificate(obj.getContent());
}
}
private class ECNamedCurveSpecParser
implements PemObjectParser
{
public Object parseObject(PemObject obj)
throws IOException
{
try
{
DERObjectIdentifier oid = (DERObjectIdentifier)ASN1Object.fromByteArray(obj.getContent());
Object params = ECNamedCurveTable.getParameterSpec(oid.getId());
if (params == null)
{
throw new IOException("object ID not found in EC curve table");
}
return params;
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException("exception extracting EC named curve: " + e.toString());
}
}
}
private class EncryptedPrivateKeyParser
implements PemObjectParser
{
private String symProvider;
private String asymProvider;
public EncryptedPrivateKeyParser(String symProvider, String asymProvider)
{
this.symProvider = symProvider;
this.asymProvider = asymProvider;
}
/**
* Reads in a X509CRL.
*
* @return the X509Certificate
* @throws IOException if an I/O error occured
*/
public Object parseObject(PemObject obj)
throws IOException
{
try
{
EncryptedPrivateKeyInfo info = EncryptedPrivateKeyInfo.getInstance(ASN1Object.fromByteArray(obj.getContent()));
AlgorithmIdentifier algId = info.getEncryptionAlgorithm();
if (pFinder == null)
{
throw new PEMException("no PasswordFinder specified");
}
if (PEMUtilities.isPKCS5Scheme2(algId.getAlgorithm()))
{
PBES2Parameters params = PBES2Parameters.getInstance(algId.getParameters());
KeyDerivationFunc func = params.getKeyDerivationFunc();
EncryptionScheme scheme = params.getEncryptionScheme();
PBKDF2Params defParams = (PBKDF2Params)func.getParameters();
int iterationCount = defParams.getIterationCount().intValue();
byte[] salt = defParams.getSalt();
String algorithm = scheme.getAlgorithm().getId();
SecretKey key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(algorithm, pFinder.getPassword(), salt, iterationCount);
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
AlgorithmParameters algParams = AlgorithmParameters.getInstance(algorithm, symProvider);
algParams.init(scheme.getParameters().getDERObject().getEncoded());
cipher.init(Cipher.DECRYPT_MODE, key, algParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
}
else if (PEMUtilities.isPKCS12(algId.getAlgorithm()))
{
PKCS12PBEParams params = PKCS12PBEParams.getInstance(algId.getParameters());
String algorithm = algId.getAlgorithm().getId();
PBEKeySpec pbeSpec = new PBEKeySpec(pFinder.getPassword());
SecretKeyFactory secKeyFact = SecretKeyFactory.getInstance(algorithm, symProvider);
PBEParameterSpec defParams = new PBEParameterSpec(params.getIV(), params.getIterations().intValue());
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
}
else if (PEMUtilities.isPKCS5Scheme1(algId.getAlgorithm()))
{
PBEParameter params = PBEParameter.getInstance(algId.getParameters());
String algorithm = algId.getAlgorithm().getId();
PBEKeySpec pbeSpec = new PBEKeySpec(pFinder.getPassword());
SecretKeyFactory secKeyFact = SecretKeyFactory.getInstance(algorithm, symProvider);
PBEParameterSpec defParams = new PBEParameterSpec(params.getSalt(), params.getIterationCount().intValue());
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
}
else
{
throw new PEMException("Unknown algorithm: " + algId.getAlgorithm());
}
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PEMException("problem parsing ENCRYPTED PRIVATE KEY: " + e.toString(), e);
}
}
}
private class PrivateKeyParser
implements PemObjectParser
{
private String provider;
public PrivateKeyParser(String provider)
{
this.provider = provider;
}
public Object parseObject(PemObject obj)
throws IOException
{
try
{
PrivateKeyInfo info = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(obj.getContent()));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(obj.getContent());
KeyFactory keyFact = KeyFactory.getInstance(info.getAlgorithmId().getAlgorithm().getId(), provider);
return keyFact.generatePrivate(keySpec);
}
catch (Exception e)
{
throw new PEMException("problem parsing PRIVATE KEY: " + e.toString(), e);
}
}
}
}
|
package org.encog.nlp.lexicon;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.encog.nlp.lexicon.data.Fix;
import org.encog.nlp.lexicon.data.Lemma;
import org.encog.nlp.lexicon.data.Word;
import org.encog.nlp.lexicon.data.WordType;
import org.encog.nlp.lexicon.data.WordTypePossibility;
import org.encog.util.orm.ORMSession;
import org.hibernate.Query;
public class EncogLexicon {
public static final String WORD_TYPE_NODE = "node";
public static final String WORD_TYPE_ACTION = "action";
public static final String WORD_TYPE_DESCRIPTION = "description";
public static final String WORD_TYPE_SPLIT = "split";
public static final String WORD_TYPE_QUESTION_SIMPLE = "question-s";
public static final String WORD_TYPE_QUESTION_EMBED = "question-e";
private ORMSession session;
private Map<String,Fix> prefixes = new HashMap<String,Fix>();
private Map<String,Fix> suffixes = new HashMap<String,Fix>();
private Map<String,WordType> wordTypes = new HashMap<String,WordType>();
public EncogLexicon(ORMSession session)
{
this.session = session;
}
public void loadCache()
{
Query q = session.createQuery("from org.encog.nlp.lexicon.data.Fix");
List<Fix> list = q.list();
for(Fix fix: list)
{
if( fix.isPre())
this.prefixes.put(fix.getText(), fix);
else
this.suffixes.put(fix.getText(), fix);
}
q = session.createQuery("from org.encog.nlp.lexicon.data.WordType");
List<WordType> typeList = q.list();
for(WordType type: typeList)
{
wordTypes.put(type.getCode(), type);
}
}
public Word findWord(String word)
{
String scanWord = word.toLowerCase();
Query q = session.createQuery("from org.encog.nlp.lexicon.data.Word where text = :w");
q.setString("w", scanWord);
return (Word)q.uniqueResult();
}
public Lemma findLemma(String str)
{
Word word = this.findWord(str);
return this.findLemma(word);
}
public Lemma findLemma(Word word)
{
Query q = session.createQuery("from org.encog.nlp.lexicon.data.Lemma where root = :w");
q.setEntity("w", word);
return (Lemma)q.uniqueResult();
}
public Lemma obtainLemmaForRoot(Word root)
{
Lemma lemma = findLemma(root);
if( lemma==null )
{
lemma = new Lemma();
lemma.setRoot(root);
lemma.addWordUse(root);
this.session.save(lemma);
}
return lemma;
}
public Word obtainWord(String word)
{
Word w = findWord(word);
if( w==null )
{
w = new Word();
w.setText(word);
session.save(w);
}
return w;
}
public void addFix(String value,boolean pre, WordType type)
{
Fix fix = new Fix();
fix.setText(value);
fix.setPre(pre);
fix.setWordType(type);
session.save(fix);
}
public Iterator<Word> iterateWordList()
{
Query q = session.createQuery("from org.encog.nlp.lexicon.data.Word");
return q.iterate();
}
public Map<String, Fix> getPrefixes() {
return prefixes;
}
public Map<String, Fix> getSuffixes() {
return suffixes;
}
public Word removeFix(Word word, Fix fix)
{
String str = word.getText();
if( fix.isPost() )
{
if( str.endsWith(fix.getText()) && word.length()>fix.length() )
{
Word result;
String removed = str.substring(0,str.length()-fix.length());
result = this.findWord(removed);
if( result==null )
{
result = this.findWord(removed+"e");
}
if( result!=null )
return result;
}
}
else if( fix.isPre() )
{
if( str.startsWith(fix.getText()) && word.length()>fix.length() )
{
Word temp = findWord(str.substring(fix.length()));
if( temp!=null )
return temp;
}
}
return word;
}
public Collection<Fix> determineWordFixes(Word word)
{
Collection<Fix> result = new ArrayList<Fix>();
// determine prefixes
for(Fix fix: this.prefixes.values() )
{
if( word.length()>fix.getText().length() && word.startsWith(fix.getText()) )
{
if( removeFix(word,fix)!=null)
result.add(fix);
}
}
// determine suffixes
for(Fix fix: this.suffixes.values() )
{
if( word.length()>fix.getText().length() && word.endsWith(fix.getText()) )
{
if( removeFix(word,fix)!=null)
result.add(fix);
}
}
return result;
}
public void setupWord(Word word)
{
// determine all prefixes and suffixes that this word has
Collection<Fix> fixes = determineWordFixes(word);
word.getFixes().addAll(fixes);
// determine the root word and setup word types by fix
Word rootWord = word;
for(Fix fix: fixes)
{
rootWord = removeFix(rootWord, fix);
addType(word,fix.getWordType());
}
// associate with the lemma
Lemma lemma = this.obtainLemmaForRoot(rootWord);
lemma.addWordUse(word);
}
public void addType(Word word, WordType type)
{
if( type!=null && !word.isWordOfType(type))
{
WordTypePossibility pos = new WordTypePossibility();
pos.setWord(word);
pos.setType(type);
word.getTypes().add(pos);
session.save(pos);
}
}
public Lemma obtainLemma(String str) {
Word word = obtainWord(str);
return obtainLemmaForRoot(word);
}
public Iterator<Lemma> iterateLemmaList() {
Query q = session.createQuery("from org.encog.nlp.lexicon.data.Lemma");
return q.iterate();
}
public void addWordType(String str) {
WordType wordType = new WordType();
wordType.setCode(str);
session.save(wordType);
}
public WordType getWordType(String code)
{
return this.wordTypes.get(code);
}
public void addType(String word, WordType wordType) {
addType(findWord(word),wordType);
}
public void registerGutenbergCount(String word, int count)
{
Word w = obtainWord(word);
w.setGutenbergCount(w.getGutenbergCount()+count);
session.save(w);
}
public boolean hasWordType(Word usedWord,Lemma lemma, WordType wordType) {
for(Word pos: lemma.getUses())
{
if( usedWord.equals(pos) && pos.hasType(wordType))
{
return true;
}
}
return false;
}
}
|
package org.exist.xquery.functions;
import java.util.Iterator;
import org.apache.oro.text.GlobCompiler;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Matcher;
import org.exist.EXistException;
import org.exist.dom.ExtArrayNodeSet;
import org.exist.dom.NodeProxy;
import org.exist.dom.NodeSet;
import org.exist.storage.NativeTextEngine;
import org.exist.storage.analysis.TextToken;
import org.exist.storage.analysis.Tokenizer;
import org.exist.xquery.Constants;
import org.exist.xquery.Expression;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.IntegerValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
/**
* near() function.
*
*@author Wolfgang Meier <wolfgang@exist-db.org>
*@created July 31, 2002
*/
public class ExtNear extends ExtFulltext {
private int max_distance = 1;
private PatternCompiler globCompiler = new GlobCompiler();
private Expression distance = null;
public ExtNear(XQueryContext context) {
super(context, Constants.FULLTEXT_AND);
}
/* (non-Javadoc)
* @see org.exist.xquery.functions.ExtFulltext#analyze(org.exist.xquery.Expression)
*/
public void analyze(Expression parent, int flags) throws XPathException {
super.analyze(parent, flags);
if(distance != null)
distance.analyze(this, flags);
}
public Sequence evalQuery(
String searchArg,
NodeSet nodes)
throws XPathException {
if(distance != null)
max_distance = ((IntegerValue)distance.eval(nodes).convertTo(Type.INTEGER)).getInt();
try {
getSearchTerms(context, searchArg);
} catch (EXistException e) {
throw new XPathException(e.getMessage(), e);
}
NodeSet hits = processQuery(nodes);
if (hits == null)
return Sequence.EMPTY_SEQUENCE;
boolean hasWildcards = false;
for(int i = 0; i < terms.length; i++) {
hasWildcards |=
NativeTextEngine.containsWildcards(terms[i]);
}
return hasWildcards
? patternMatch(context, hits)
: exactMatch(context, hits);
}
private Sequence exactMatch(XQueryContext context, NodeSet result) {
// walk through hits and calculate term-distances
String value;
String term;
String word;
TextToken token;
NodeProxy current;
NodeSet r = new ExtArrayNodeSet();
Tokenizer tok = context.getBroker().getTextEngine().getTokenizer();
int j;
int distance;
for (Iterator i = result.iterator(); i.hasNext();) {
current = (NodeProxy) i.next();
value = current.getNodeValueSeparated();
tok.setText(value);
j = 0;
if (j < terms.length)
term = terms[j];
else
break;
distance = -1;
while ((token = tok.nextToken()) != null) {
word = token.getText().toLowerCase();
if (distance > max_distance) {
// reset
j = 0;
term = terms[j];
distance = -1;
} // that else would cause some words to be ignored in the matching
if (word.equalsIgnoreCase(term)) {
distance = 0;
j++;
if (j == terms.length) {
// all terms found
r.add(current);
break;
} else
term = terms[j];
} else if (j > 0 && word.equalsIgnoreCase(terms[0])) {
// first search term found: start again
j = 1;
term = terms[j];
distance = 0 ;
continue;
} // that else MAY cause the distance count to be off by one but i'm not sure
if (-1 < distance)
++distance;
}
}
// LOG.debug("found " + r.getLength());
return r;
}
private Sequence patternMatch(XQueryContext context, NodeSet result) {
// generate list of search term patterns
Pattern patterns[] = new Pattern[terms.length];
for (int i = 0; i < patterns.length; i++)
try {
patterns[i] =
globCompiler.compile(
terms[i],
GlobCompiler.CASE_INSENSITIVE_MASK
| GlobCompiler.QUESTION_MATCHES_ZERO_OR_ONE_MASK);
} catch (MalformedPatternException e) {
LOG.warn("malformed pattern", e);
return Sequence.EMPTY_SEQUENCE;
}
// walk through hits and calculate term-distances
String value;
Pattern term;
String word;
TextToken token;
NodeProxy current;
ExtArrayNodeSet r = new ExtArrayNodeSet(100);
PatternMatcher matcher = new Perl5Matcher();
Tokenizer tok = context.getBroker().getTextEngine().getTokenizer();
int j;
int distance;
for (Iterator i = result.iterator(); i.hasNext();) {
current = (NodeProxy) i.next();
value = current.getNodeValueSeparated();
tok.setText(value);
j = 0;
if (j < patterns.length)
term = patterns[j];
else
break;
distance = -1;
while ((token = tok.nextToken()) != null) {
word = token.getText().toLowerCase();
if (distance > max_distance) {
// reset
j = 0;
term = patterns[j];
distance = -1;
continue;
}
if (matcher.matches(word, term)) {
distance = 0;
j++;
if (j == patterns.length) {
// all terms found
r.add(current);
break;
} else
term = patterns[j];
} else if (j > 0 && matcher.matches(word, patterns[0])) {
// first search term found: start again
j = 1;
term = patterns[j];
distance = 0;
continue;
} else if (-1 < distance)
++distance;
}
}
return r;
}
/* (non-Javadoc)
* @see org.exist.xquery.functions.ExtFulltext#dump(org.exist.xquery.util.ExpressionDumper)
*/
public void dump(ExpressionDumper dumper) {
dumper.display("near(");
path.dump(dumper);
dumper.display(", ");
searchTerm.dump(dumper);
dumper.display(")");
}
public void setDistance(Expression expr) {
distance = expr;
}
}
|
package org.javarosa.clforms.util;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.microedition.lcdui.ChoiceGroup;
import org.javarosa.clforms.api.Constants;
import org.javarosa.clforms.api.Prompt;
import de.enough.polish.util.TextUtil;
public class J2MEUtil {
public J2MEUtil() {
super();
// TODO Auto-generated constructor stub
}
/**
* Converts the value object into a String based on the returnType
*
* @return
*/
public static String getStringValue(Object val, int returnType) {
String stringValue = "";
if (val == null){
//LOG
System.out.println("string value null");
return stringValue;
}
switch (returnType) {
case Constants.RETURN_DATE:
System.out.println("test1");
if(val instanceof Date){
Date d = (Date) val;
Calendar cd = Calendar.getInstance();
cd.setTime(d);
String year = "" + cd.get(Calendar.YEAR);
String month = "" + (cd.get(Calendar.MONTH)+1);
String day = "" + cd.get(Calendar.DAY_OF_MONTH);
if (month.length() < 2)
month = "0" + month;
if (day.length() < 2)
day = "0" + day;
stringValue = day + "/" + month + "/" + year;
}else
stringValue = val.toString();
System.out.println("test1"+stringValue);
break;
default:
stringValue = val.toString();
}
return stringValue;
}
public static Object setSelected(Prompt prompt, ChoiceGroup collection) {
switch (prompt.getReturnType()) {
case Constants.RETURN_SELECT1:
String key = null;
String value = (String)prompt.getValue();
for(int i=0; i<prompt.getSelectMap().size();i++){
if(TextUtil.equalsIgnoreCase(value,(String)prompt.getSelectMap().elementAt(i))){
key = (String)prompt.getSelectMap().keyAt(i);
}
}
System.out.println(value+"-Key-"+key);
for(int i=0; i<collection.size(); i++){
if(TextUtil.equalsIgnoreCase(collection.getString(i),key))
collection.setSelectedIndex(i,true);
}
break;
case Constants.RETURN_SELECT_MULTI:
Vector valuesVector = new Vector();
String values = (String)prompt.getValue();
// remove any []
values = values.substring(values.indexOf('[')+1, values.indexOf(']'));
System.out.println("VAL:"+values);
// tokenize to vector
valuesVector = tokenize(values,',');
// 2D search through values
// TODO can we improve this efficiency?
Vector keys = new Vector();
for (int i = 0; i < valuesVector.size(); i++) {
System.out.println((String)valuesVector.elementAt(i));
value = (String)valuesVector.elementAt(i);
for(int j=0; j<prompt.getSelectMap().size();j++){
if(TextUtil.equalsIgnoreCase(value,(String)prompt.getSelectMap().elementAt(j))){
keys.addElement((String)prompt.getSelectMap().keyAt(j));
}
}
}
for(int i=0; i<collection.size(); i++){
if(keys.contains(collection.getString(i)))
collection.setSelectedIndex(i,true);
}
break;
}
return collection ;
}
private static Vector tokenize(String values, char c) {
Vector temp = new Vector();
int pos = 0;
int index = values.indexOf(c);
while(index != -1){
String tempp = values.substring(pos, index).trim();
//System.out.println(tempp+pos+index);
temp.addElement(tempp);
pos = index+1;
index = values.indexOf(c,pos);
}
temp.addElement(values.substring(pos).trim());
return temp;
}
public static boolean getBoolean(String attributeValue) throws Exception {
if (TextUtil.equalsIgnoreCase(attributeValue,"true()"))
return true;
else if (TextUtil.equalsIgnoreCase(attributeValue,"false()"))
return false;
else
//TODO throw parse exception
return false;
}
public static Date getDateFromString(String value) {
Date result = new Date();
Vector digits = tokenize(value, '/');
int day = Integer.valueOf((String)digits.elementAt(0)).intValue();
int month = Integer.valueOf((String)digits.elementAt(1)).intValue();
month
int year = Integer.valueOf((String)digits.elementAt(2)).intValue();
Calendar cd = Calendar.getInstance();
cd.set(Calendar.DAY_OF_MONTH, day);
cd.set(Calendar.MONTH, month);
cd.set(Calendar.YEAR, year);
result = cd.getTime();
return result;
}
}
|
package org.jgroups.protocols.pbcast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import java.util.concurrent.locks.ReentrantLock;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Header;
import org.jgroups.Message;
import org.jgroups.TimeoutException;
import org.jgroups.View;
import org.jgroups.ViewId;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Promise;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
/**
* Flush, as it name implies, forces group members to flush their pending messages
* while blocking them to send any additional messages. The process of flushing
* acquiesces the group so that state transfer or a join can be done. It is also
* called stop-the-world model as nobody will be able to send messages while a
* flush is in process.
*
* <p>
* Flush is needed for:
* <p>
* (1) State transfer. When a member requests state transfer, the coordinator
* tells everyone to stop sending messages and waits for everyone's ack. Then it asks
* the application for its state and ships it back to the requester. After the
* requester has received and set the state successfully, the coordinator tells
* everyone to resume sending messages.
* <p>
* (2) View changes (e.g.a join). Before installing a new view V2, flushing would
* ensure that all messages *sent* in the current view V1 are indeed *delivered*
* in V1, rather than in V2 (in all non-faulty members). This is essentially
* Virtual Synchrony.
*
*
*
* @author Vladimir Blagojevic
* @version $Id$
* @since 2.4
*/
public class FLUSH extends Protocol
{
public static final String NAME = "FLUSH";
// GuardedBy ("sharedLock")
private View currentView;
private Address localAddress;
/**
* Group member that requested FLUSH.
* For view intallations flush coordinator is the group coordinator
* For state transfer flush coordinator is the state requesting member
*/
// GuardedBy ("sharedLock")
private Address flushCoordinator;
// GuardedBy ("sharedLock")
private final Collection flushMembers;
// GuardedBy ("sharedLock")
private final Set flushOkSet;
// GuardedBy ("sharedLock")
private final Set flushCompletedSet;
// GuardedBy ("sharedLock")
private final Set stopFlushOkSet;
// GuardedBy ("sharedLock")
private final Set suspected;
private final Object sharedLock = new Object();
private final Object blockMutex = new Object();
/**
* Indicates if FLUSH.down() is currently blocking threads
* Condition predicate associated with blockMutex
*/
//GuardedBy ("blockMutex")
private boolean isBlockingFlushDown = true;
/**
* Default timeout for a group member to be in <code>isBlockingFlushDown</code>
*/
private long timeout = 8000;
/**
* Default timeout started when <code>Event.BLOCK</code> is passed to
* application. Response <code>Event.BLOCK_OK</code> should be received by
* application within timeout.
*/
private long block_timeout = 10000;
// GuardedBy ("sharedLock")
private boolean receivedFirstView = false;
// GuardedBy ("sharedLock")
private boolean receivedMoreThanOneView = false;
private long startFlushTime;
private long totalTimeInFlush;
private int numberOfFlushes;
private double averageFlushDuration;
private final Promise flush_promise = new Promise();
private final Promise blockok_promise = new Promise();
private final FlushPhase flushPhase = new FlushPhase();
/**
* If true configures timeout in GMS and STATE_TRANFER using FLUSH timeout value
*/
private boolean auto_flush_conf = true;
public FLUSH()
{
super();
currentView = new View(new ViewId(), new Vector());
flushOkSet = new TreeSet();
flushCompletedSet = new TreeSet();
stopFlushOkSet = new TreeSet();
flushMembers = new ArrayList();
suspected = new TreeSet();
}
public String getName()
{
return NAME;
}
public boolean setProperties(Properties props)
{
super.setProperties(props);
timeout = Util.parseLong(props, "timeout", timeout);
block_timeout = Util.parseLong(props, "block_timeout", block_timeout);
auto_flush_conf = Util.parseBoolean(props, "auto_flush_conf", auto_flush_conf);
if (!props.isEmpty())
{
log.error("the following properties are not recognized: " + props);
return false;
}
return true;
}
public void init() throws Exception
{
if(auto_flush_conf)
{
Map map = new HashMap();
map.put("flush_timeout", new Long(timeout));
up_prot.up(new Event(Event.CONFIG, map));
down_prot.down(new Event(Event.CONFIG, map));
}
}
public void start() throws Exception
{
Map map = new HashMap();
map.put("flush_supported", Boolean.TRUE);
up_prot.up(new Event(Event.CONFIG, map));
down_prot.down(new Event(Event.CONFIG, map));
synchronized(sharedLock)
{
receivedFirstView = false;
receivedMoreThanOneView = false;
}
synchronized(blockMutex)
{
isBlockingFlushDown = true;
}
}
public void stop()
{
synchronized (sharedLock)
{
currentView = new View(new ViewId(), new Vector());
flushCompletedSet.clear();
flushOkSet.clear();
stopFlushOkSet.clear();
flushMembers.clear();
suspected.clear();
flushCoordinator = null;
}
}
public double getAverageFlushDuration()
{
return averageFlushDuration;
}
public long getTotalTimeInFlush()
{
return totalTimeInFlush;
}
public int getNumberOfFlushes()
{
return numberOfFlushes;
}
public boolean startFlush(long timeout)
{
boolean successfulFlush = false;
down(new Event(Event.SUSPEND));
flush_promise.reset();
try
{
flush_promise.getResultWithTimeout(timeout);
successfulFlush = true;
}
catch (TimeoutException e)
{
}
return successfulFlush;
}
public void stopFlush()
{
down(new Event(Event.RESUME));
}
public Object down(Event evt)
{
switch (evt.getType())
{
case Event.MSG :
Message msg = (Message) evt.getArg();
FlushHeader fh = (FlushHeader) msg.getHeader(getName());
if (fh != null && fh.type == FlushHeader.FLUSH_BYPASS)
{
break;
}
else
{
blockMessageDuringFlush();
break;
}
case Event.GET_STATE:
blockMessageDuringFlush();
break;
case Event.CONNECT:
boolean successfulBlock = sendBlockUpToChannel(block_timeout);
if (successfulBlock && log.isDebugEnabled())
{
log.debug("Blocking of channel " + localAddress + " completed successfully");
}
break;
case Event.SUSPEND :
attemptSuspend(evt);
return null;
case Event.RESUME :
onResume();
return null;
case Event.BLOCK_OK:
blockok_promise.setResult(Boolean.TRUE);
return null;
}
return down_prot.down(evt);
}
private void blockMessageDuringFlush()
{
boolean shouldSuspendByItself = false;
long start=0, stop=0;
synchronized (blockMutex)
{
while (isBlockingFlushDown)
{
if (log.isDebugEnabled())
log.debug("FLUSH block at " + localAddress + " for " + (timeout <= 0? "ever" : timeout + "ms"));
try
{
start=System.currentTimeMillis();
if(timeout <= 0)
blockMutex.wait();
else
blockMutex.wait(timeout);
stop=System.currentTimeMillis();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // set interrupt flag again
}
if (isBlockingFlushDown)
{
isBlockingFlushDown = false;
shouldSuspendByItself = true;
blockMutex.notifyAll();
}
}
}
if(shouldSuspendByItself)
{
log.warn("unblocking FLUSH.down() at " + localAddress + " after timeout of " + (stop-start) + "ms");
up_prot.up(new Event(Event.SUSPEND_OK));
down_prot.down(new Event(Event.SUSPEND_OK));
}
}
public Object up(Event evt)
{
switch (evt.getType())
{
case Event.MSG :
Message msg = (Message) evt.getArg();
FlushHeader fh = (FlushHeader) msg.getHeader(getName());
if (fh != null)
{
if(fh.type == FlushHeader.FLUSH_BYPASS)
{
break;
//propel this msg up
}
flushPhase.lock();
if (fh.type == FlushHeader.START_FLUSH)
{
if (!flushPhase.isFlushInProgress())
{
flushPhase.setFirstPhase(true);
flushPhase.release();
boolean successfulBlock = sendBlockUpToChannel(block_timeout);
if (successfulBlock && log.isDebugEnabled())
{
log.debug("Blocking of channel " + localAddress + " completed successfully");
}
onStartFlush(msg.getSrc(), fh);
}
else if (flushPhase.isInFirstPhase())
{
flushPhase.release();
Address flushRequester = msg.getSrc();
Address coordinator = null;
synchronized(sharedLock)
{
coordinator = flushCoordinator;
}
if(flushRequester.compareTo(coordinator)<0)
{
rejectFlush(fh.viewID, coordinator);
if(log.isDebugEnabled())
{
log.debug("Rejecting flush at " + localAddress + " to current flush coordinator " + coordinator + " and switching flush coordinator to " + flushRequester);
}
synchronized(sharedLock)
{
flushCoordinator = flushRequester;
}
}
else
{
rejectFlush(fh.viewID, flushRequester);
if(log.isDebugEnabled())
{
log.debug("Rejecting flush at " + localAddress + " to flush requester " + flushRequester);
}
}
}
else if (flushPhase.isInSecondPhase())
{
flushPhase.release();
Address flushRequester = msg.getSrc();
rejectFlush(fh.viewID, flushRequester);
if(log.isDebugEnabled())
{
log.debug("Rejecting flush in second phase at " + localAddress + " to flush requester " + flushRequester);
}
}
}
else if (fh.type == FlushHeader.STOP_FLUSH)
{
flushPhase.setPhases(false, true);
flushPhase.release();
onStopFlush();
}
else if (fh.type == FlushHeader.ABORT_FLUSH)
{
//abort current flush
flushPhase.release();
up_prot.up(new Event(Event.SUSPEND_FAILED));
down_prot.down(new Event(Event.SUSPEND_FAILED));
}
else if (isCurrentFlushMessage(fh))
{
flushPhase.release();
if (fh.type == FlushHeader.FLUSH_OK)
{
onFlushOk(msg.getSrc(), fh.viewID);
}
else if (fh.type == FlushHeader.STOP_FLUSH_OK)
{
onStopFlushOk(msg.getSrc());
}
else if (fh.type == FlushHeader.FLUSH_COMPLETED)
{
onFlushCompleted(msg.getSrc());
}
}
else
{
flushPhase.release();
if (log.isDebugEnabled())
log.debug(localAddress + " received outdated FLUSH message " + fh + ",ignoring it.");
}
return null; //do not pass FLUSH msg up
}
break;
case Event.VIEW_CHANGE :
//if this is channel's first view and its the only member of the group then the
//goal is to pass BLOCK,VIEW,UNBLOCK to application space on the same thread as VIEW.
View newView = (View) evt.getArg();
boolean firstView = onViewChange(newView);
boolean singletonMember = newView.size()==1 && newView.containsMember(localAddress);
if(firstView && singletonMember){
up_prot.up(evt);
synchronized (blockMutex)
{
isBlockingFlushDown = false;
blockMutex.notifyAll();
}
if (log.isDebugEnabled())
log.debug("At " + localAddress + " unblocking FLUSH.down() and sending UNBLOCK up");
up_prot.up(new Event(Event.UNBLOCK));
return null;
}
break;
case Event.SET_LOCAL_ADDRESS :
localAddress = (Address) evt.getArg();
break;
case Event.SUSPECT :
onSuspect((Address) evt.getArg());
break;
case Event.SUSPEND :
attemptSuspend(evt);
return null;
case Event.RESUME :
onResume();
return null;
}
return up_prot.up(evt);
}
public Vector providedDownServices()
{
Vector retval = new Vector(2);
retval.addElement(new Integer(Event.SUSPEND));
retval.addElement(new Integer(Event.RESUME));
return retval;
}
private void attemptSuspend(Event evt)
{
View v = (View) evt.getArg();
if(log.isDebugEnabled())
log.debug("Received SUSPEND at " + localAddress + ", view is " + v);
flushPhase.lock();
if (!flushPhase.isFlushInProgress())
{
flushPhase.release();
onSuspend(v);
}
else
{
flushPhase.release();
up_prot.up(new Event(Event.SUSPEND_FAILED));
down_prot.down(new Event(Event.SUSPEND_FAILED));
}
}
private void rejectFlush(long viewId, Address flushRequester)
{
Message reject = new Message(flushRequester, localAddress, null);
reject.putHeader(getName(), new FlushHeader(FlushHeader.ABORT_FLUSH, viewId));
down_prot.down(new Event(Event.MSG, reject));
}
private boolean sendBlockUpToChannel(long btimeout)
{
boolean successfulBlock = false;
blockok_promise.reset();
new Thread(Util.getGlobalThreadGroup(), new Runnable()
{
public void run()
{
up_prot.up(new Event(Event.BLOCK));
}
}, "FLUSH block").start();
try
{
blockok_promise.getResultWithTimeout(btimeout);
successfulBlock = true;
}
catch (TimeoutException e)
{
log.warn("Blocking of channel using BLOCK event timed out after " + btimeout + " msec.");
}
return successfulBlock;
}
private boolean isCurrentFlushMessage(FlushHeader fh)
{
return fh.viewID == currentViewId();
}
private long currentViewId()
{
long viewId = -1;
synchronized (sharedLock)
{
ViewId view = currentView.getVid();
if (view != null)
{
viewId = view.getId();
}
}
return viewId;
}
private boolean onViewChange(View view)
{
boolean amINewCoordinator = false;
boolean isThisOurFirstView = false;
synchronized (sharedLock)
{
if (receivedFirstView)
{
receivedMoreThanOneView = true;
}
if (!receivedFirstView)
{
receivedFirstView = true;
}
isThisOurFirstView = receivedFirstView && !receivedMoreThanOneView;
suspected.retainAll(view.getMembers());
currentView = view;
amINewCoordinator = flushCoordinator != null && !view.getMembers().contains(flushCoordinator)
&& localAddress.equals(view.getMembers().get(0));
}
//If coordinator leaves, its STOP FLUSH message will be discarded by
//other members at NAKACK layer. Remaining members will be hung, waiting
//for STOP_FLUSH message. If I am new coordinator I will complete the
//FLUSH and send STOP_FLUSH on flush callers behalf.
if (amINewCoordinator)
{
if (log.isDebugEnabled())
log.debug("Coordinator left, " + localAddress + " will complete flush");
onResume();
}
if (log.isDebugEnabled())
log.debug("Installing view at " + localAddress + " view is " + view);
return isThisOurFirstView;
}
private void onStopFlush()
{
if (stats)
{
long stopFlushTime = System.currentTimeMillis();
totalTimeInFlush += (stopFlushTime - startFlushTime);
if (numberOfFlushes > 0)
{
averageFlushDuration = totalTimeInFlush / (double)numberOfFlushes;
}
}
//ack this STOP_FLUSH
Message msg = new Message(null, localAddress, null);
msg.putHeader(getName(), new FlushHeader(FlushHeader.STOP_FLUSH_OK,currentViewId()));
down_prot.down(new Event(Event.MSG, msg));
if (log.isDebugEnabled())
log.debug("Received STOP_FLUSH and sent STOP_FLUSH_OK from " + localAddress);
}
private void onSuspend(View view)
{
Message msg = null;
Collection participantsInFlush = null;
synchronized (sharedLock)
{
//start FLUSH only on group members that we need to flush
if (view != null)
{
participantsInFlush = new ArrayList(view.getMembers());
participantsInFlush.retainAll(currentView.getMembers());
}
else
{
participantsInFlush = new ArrayList(currentView.getMembers());
}
msg = new Message(null, localAddress, null);
msg.putHeader(getName(), new FlushHeader(FlushHeader.START_FLUSH, currentViewId(), participantsInFlush));
}
if (participantsInFlush.isEmpty())
{
up_prot.up(new Event(Event.SUSPEND_OK));
down_prot.down(new Event(Event.SUSPEND_OK));
}
else
{
down_prot.down(new Event(Event.MSG, msg));
if (log.isDebugEnabled())
log.debug("Received SUSPEND at " + localAddress + ", sent START_FLUSH to " + participantsInFlush);
}
}
private void onResume()
{
long viewID = currentViewId();
Message msg = new Message(null, localAddress, null);
msg.putHeader(getName(), new FlushHeader(FlushHeader.STOP_FLUSH,viewID));
down_prot.down(new Event(Event.MSG, msg));
if (log.isDebugEnabled())
log.debug("Received RESUME at " + localAddress + ", sent STOP_FLUSH to all");
}
private void onStartFlush(Address flushStarter, FlushHeader fh)
{
if (stats)
{
startFlushTime = System.currentTimeMillis();
numberOfFlushes += 1;
}
synchronized (sharedLock)
{
flushCoordinator = flushStarter;
flushMembers.clear();
if(fh.flushParticipants!=null)
{
flushMembers.addAll(fh.flushParticipants);
}
flushMembers.removeAll(suspected);
}
Message msg = new Message(null, localAddress, null);
msg.putHeader(getName(), new FlushHeader(FlushHeader.FLUSH_OK, fh.viewID));
down_prot.down(new Event(Event.MSG, msg));
if (log.isDebugEnabled())
log.debug("Received START_FLUSH at " + localAddress + " responded with FLUSH_OK");
}
private void onFlushOk(Address address, long viewID)
{
boolean flushOkCompleted = false;
Message m = null;
synchronized (sharedLock)
{
flushOkSet.add(address);
flushOkCompleted = flushOkSet.containsAll(flushMembers);
if (flushOkCompleted)
{
m = new Message(flushCoordinator, localAddress, null);
}
}
if (log.isDebugEnabled())
log.debug("At " + localAddress + " FLUSH_OK from " + address + ",completed "
+ flushOkCompleted + ", flushOkSet " + flushOkSet.toString());
if (flushOkCompleted)
{
synchronized(blockMutex)
{
isBlockingFlushDown = true;
}
m.putHeader(getName(), new FlushHeader(FlushHeader.FLUSH_COMPLETED, viewID));
down_prot.down(new Event(Event.MSG, m));
if (log.isDebugEnabled())
log.debug(localAddress + " is blocking FLUSH.down(). Sent FLUSH_COMPLETED message to " + flushCoordinator);
}
}
private void onStopFlushOk(Address address)
{
boolean stopFlushOkCompleted = false;
synchronized (sharedLock)
{
stopFlushOkSet.add(address);
TreeSet membersCopy = new TreeSet(currentView.getMembers());
membersCopy.removeAll(suspected);
stopFlushOkCompleted = stopFlushOkSet.containsAll(membersCopy);
}
if (log.isDebugEnabled())
log.debug("At " + localAddress + " STOP_FLUSH_OK from " + address + ",completed " + stopFlushOkCompleted
+ ", stopFlushOkSet " + stopFlushOkSet.toString());
if (stopFlushOkCompleted)
{
synchronized (sharedLock)
{
flushCompletedSet.clear();
flushOkSet.clear();
stopFlushOkSet.clear();
flushMembers.clear();
suspected.clear();
flushCoordinator = null;
}
flushPhase.lock();
flushPhase.setSecondPhase(false);
flushPhase.release();
if (log.isDebugEnabled())
log.debug("At " + localAddress + " unblocking FLUSH.down() and sending UNBLOCK up");
synchronized (blockMutex)
{
isBlockingFlushDown = false;
blockMutex.notifyAll();
}
up_prot.up(new Event(Event.UNBLOCK));
}
}
private void onFlushCompleted(Address address)
{
boolean flushCompleted = false;
synchronized (sharedLock)
{
flushCompletedSet.add(address);
flushCompleted = flushCompletedSet.containsAll(flushMembers);
}
if (log.isDebugEnabled())
log.debug("At " + localAddress + " FLUSH_COMPLETED from " + address
+ ",completed " + flushCompleted + ",flushCompleted "
+ flushCompletedSet.toString());
if (flushCompleted)
{
//needed for jmx operation startFlush(timeout);
flush_promise.setResult(Boolean.TRUE);
up_prot.up(new Event(Event.SUSPEND_OK));
down_prot.down(new Event(Event.SUSPEND_OK));
if (log.isDebugEnabled())
log.debug("All FLUSH_COMPLETED received at " + localAddress + " sent SUSPEND_OK down/up");
}
}
private void onSuspect(Address address)
{
boolean flushOkCompleted = false;
Message m = null;
long viewID = 0;
synchronized (sharedLock)
{
suspected.add(address);
flushMembers.removeAll(suspected);
viewID = currentViewId();
flushOkCompleted = !flushOkSet.isEmpty() && flushOkSet.containsAll(flushMembers);
if (flushOkCompleted)
{
m = new Message(flushCoordinator, localAddress, null);
}
}
if (flushOkCompleted)
{
m.putHeader(getName(), new FlushHeader(FlushHeader.FLUSH_COMPLETED, viewID));
down_prot.down(new Event(Event.MSG, m));
if (log.isDebugEnabled())
log.debug(localAddress + " sent FLUSH_COMPLETED message to " + flushCoordinator);
}
if (log.isDebugEnabled())
log.debug("Suspect is " + address + ",completed " + flushOkCompleted + ", flushOkSet " + flushOkSet
+ " flushMembers " + flushMembers);
}
private static class FlushPhase
{
private boolean inFirstFlushPhase = false;
private boolean inSecondFlushPhase = false;
private final ReentrantLock lock = new ReentrantLock();
public FlushPhase(){}
public void lock()
{
lock.lock();
}
public void release()
{
lock.unlock();
}
public void setFirstPhase(boolean inFirstPhase)
{
inFirstFlushPhase = inFirstPhase;
}
public void setSecondPhase(boolean inSecondPhase)
{
inSecondFlushPhase = inSecondPhase;
}
public void setPhases(boolean inFirstPhase,boolean inSecondPhase)
{
inFirstFlushPhase = inFirstPhase;
inSecondFlushPhase = inSecondPhase;
}
public boolean isInFirstPhase()
{
return inFirstFlushPhase;
}
public boolean isInSecondPhase()
{
return inSecondFlushPhase;
}
public boolean isFlushInProgress()
{
return inFirstFlushPhase || inSecondFlushPhase;
}
}
public static class FlushHeader extends Header implements Streamable
{
public static final byte START_FLUSH = 0;
public static final byte FLUSH_OK = 1;
public static final byte STOP_FLUSH = 2;
public static final byte FLUSH_COMPLETED = 3;
public static final byte STOP_FLUSH_OK = 4;
public static final byte ABORT_FLUSH = 5;
public static final byte FLUSH_BYPASS = 6;
byte type;
long viewID;
Collection flushParticipants;
public FlushHeader()
{
this(START_FLUSH,0);
} // used for externalization
public FlushHeader(byte type)
{
this(type,0);
}
public FlushHeader(byte type, long viewID)
{
this(type, viewID, null);
}
public FlushHeader(byte type, long viewID, Collection flushView)
{
this.type = type;
this.viewID = viewID;
this.flushParticipants = flushView;
}
public String toString()
{
switch (type)
{
case START_FLUSH :
return "FLUSH[type=START_FLUSH,viewId=" + viewID + ",members=" + flushParticipants + "]";
case FLUSH_OK :
return "FLUSH[type=FLUSH_OK,viewId=" + viewID + "]";
case STOP_FLUSH :
return "FLUSH[type=STOP_FLUSH,viewId=" + viewID + "]";
case STOP_FLUSH_OK :
return "FLUSH[type=STOP_FLUSH_OK,viewId=" + viewID + "]";
case ABORT_FLUSH :
return "FLUSH[type=ABORT_FLUSH,viewId=" + viewID + "]";
case FLUSH_COMPLETED :
return "FLUSH[type=FLUSH_COMPLETED,viewId=" + viewID + "]";
case FLUSH_BYPASS :
return "FLUSH[type=FLUSH_BYPASS,viewId=" + viewID + "]";
default :
return "[FLUSH: unknown type (" + type + ")]";
}
}
public void writeExternal(ObjectOutput out) throws IOException
{
out.writeByte(type);
out.writeLong(viewID);
out.writeObject(flushParticipants);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
type = in.readByte();
viewID = in.readLong();
flushParticipants = (Collection) in.readObject();
}
public void writeTo(DataOutputStream out) throws IOException
{
out.writeByte(type);
out.writeLong(viewID);
if (flushParticipants != null && !flushParticipants.isEmpty())
{
out.writeShort(flushParticipants.size());
for (Iterator iter = flushParticipants.iterator(); iter.hasNext();)
{
Address address = (Address) iter.next();
Util.writeAddress(address, out);
}
}
else
{
out.writeShort(0);
}
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException
{
type = in.readByte();
viewID = in.readLong();
int flushParticipantsSize = in.readShort();
if (flushParticipantsSize > 0)
{
flushParticipants = new ArrayList(flushParticipantsSize);
for (int i = 0; i < flushParticipantsSize; i++)
{
flushParticipants.add(Util.readAddress(in));
}
}
}
}
}
|
/*
* $Id: LeafNodeImpl.java,v 1.3 2002-11-02 01:01:00 aalto Exp $
*/
package org.lockss.repository;
import java.io.*;
import java.util.*;
/**
* LeafNodeImpl is a leaf-specific subclass of RepositoryNodeImpl.
*/
public class LeafNodeImpl extends RepositoryNodeImpl implements LeafNode {
/**
* The name of the file created in leaf cache directories.
*/
public static final String LEAF_FILE_NAME = "isLeaf";
private static final String CURRENT_SUFFIX = ".current";
private static final String PROPS_SUFFIX = ".props";
private static final String TEMP_SUFFIX = ".temp";
private boolean newVersionOpen = false;
private OutputStream newVersionOutput;
private InputStream curInput;
private Properties curProps;
private String versionName;
private int currentVersion = -1;
private StringBuffer buffer;
public LeafNodeImpl(String url, String cacheLocation, LockssRepositoryImpl repository) {
super(url, cacheLocation, repository);
}
public int getCurrentVersion() {
ensureCurrentVersionLoaded();
return currentVersion;
}
public boolean isLeaf() {
return true;
}
public boolean exists() {
ensureCurrentVersionLoaded();
return (currentVersion > 0);
}
public void makeNewVersion() {
if (newVersionOpen) {
throw new UnsupportedOperationException("New version already"+
" initialized.");
}
ensureCurrentVersionLoaded();
if (currentVersion == 0) {
File cacheDir = getCacheLocation();
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
File leafFile = new File(cacheDir, LEAF_FILE_NAME);
try {
leafFile.createNewFile();
} catch (IOException ioe) {
logger.error("Couldn't create leaf file for " +
cacheDir.getAbsolutePath()+".");
}
}
newVersionOpen = true;
}
public void sealNewVersion() {
if (!newVersionOpen) {
throw new UnsupportedOperationException("New version not initialized.");
}
synchronized (this) {
File curContent = getCurrentCacheFile();
File curProps = getCurrentPropertiesFile();
File newContent = getTempCacheFile();
File newProps = getTempPropertiesFile();
// rename current
curContent.renameTo(getVersionedCacheFile(currentVersion));
curProps.renameTo(getVersionedPropertiesFile(currentVersion));
// rename new
newContent.renameTo(getCurrentCacheFile());
newProps.renameTo(getCurrentCacheFile());
currentVersion++;
newVersionOutput = null;
curInput = null;
curProps = null;
newVersionOpen = false;
}
}
public InputStream getInputStream() {
ensureCurrentVersionLoaded();
ensureReadInfoLoaded();
return curInput;
}
public Properties getProperties() {
ensureCurrentVersionLoaded();
ensureReadInfoLoaded();
return curProps;
}
public OutputStream getNewOutputStream() {
if (!newVersionOpen) {
throw new UnsupportedOperationException("New version not initialized.");
}
if (newVersionOutput!=null) {
return newVersionOutput;
}
File file = getTempCacheFile();
try {
newVersionOutput = new FileOutputStream(file);
return newVersionOutput;
} catch (FileNotFoundException fnfe) {
logger.error("No new version file for "+file.getAbsolutePath()+".");
return null;
}
}
public void setNewProperties(Properties newProps) {
if (!newVersionOpen) {
throw new UnsupportedOperationException("New version not initialized.");
}
if (newProps!=null) {
File file = getTempPropertiesFile();
try {
OutputStream os = new FileOutputStream(file);
newProps.setProperty("version_number", ""+(currentVersion+1));
newProps.store(os, "HTTP headers for " + url);
os.close();
} catch (IOException ioe) {
logger.error("Couldn't write properties for " +
file.getAbsolutePath()+".");
}
}
}
private void ensureReadInfoLoaded() {
if ((curInput==null) || (curProps==null)) {
synchronized (this) {
File file = null;
if (curInput==null) {
file = getCurrentCacheFile();
try {
curInput = new FileInputStream(file);
} catch (FileNotFoundException fnfe) {
logger.error("No inputstream for "+file.getAbsolutePath()+".");
}
}
if (curProps==null) {
file = getCurrentPropertiesFile();
try {
InputStream is = new FileInputStream(file);
curProps = new Properties();
curProps.load(is);
is.close();
} catch (IOException e) {
logger.error("No properties file for "+file.getAbsolutePath()+".");
curProps = new Properties();
}
}
}
}
}
private void ensureCurrentVersionLoaded() {
if (currentVersion!=-1) return;
File cacheDir = getCacheLocation();
versionName = cacheDir.getName();
if (!cacheDir.exists()) {
currentVersion = 0;
return;
}
//XXX getting version from props probably a mistake
if (curProps==null) {
synchronized (this) {
File curPropsFile = getCurrentPropertiesFile();
if (curPropsFile.exists()) {
try {
InputStream is = new FileInputStream(curPropsFile);
curProps = new Properties();
curProps.load(is);
is.close();
} catch (Exception e) {
logger.error("Error loading version from "+
curPropsFile.getAbsolutePath()+".");
curProps = new Properties();
}
} else {
curProps = new Properties();
}
}
}
currentVersion = Integer.parseInt(
curProps.getProperty("version_number", "0"));
}
private File getCurrentCacheFile() {
buffer = new StringBuffer(cacheLocation);
buffer.append(File.separator);
buffer.append(versionName);
buffer.append(CURRENT_SUFFIX);
return new File(buffer.toString());
}
private File getCurrentPropertiesFile() {
buffer = new StringBuffer(cacheLocation);
buffer.append(File.separator);
buffer.append(versionName);
buffer.append(PROPS_SUFFIX);
buffer.append(CURRENT_SUFFIX);
return new File(buffer.toString());
}
private File getTempCacheFile() {
buffer = new StringBuffer(cacheLocation);
buffer.append(File.separator);
buffer.append(versionName);
buffer.append(TEMP_SUFFIX);
return new File(buffer.toString());
}
private File getTempPropertiesFile() {
buffer = new StringBuffer(cacheLocation);
buffer.append(File.separator);
buffer.append(versionName);
buffer.append(PROPS_SUFFIX);
buffer.append(TEMP_SUFFIX);
return new File(buffer.toString());
}
private File getVersionedCacheFile(int version) {
buffer = new StringBuffer(cacheLocation);
buffer.append(File.separator);
buffer.append(versionName);
buffer.append(".");
buffer.append(version);
return new File(buffer.toString());
}
private File getVersionedPropertiesFile(int version) {
buffer = new StringBuffer(cacheLocation);
buffer.append(File.separator);
buffer.append(versionName);
buffer.append(PROPS_SUFFIX);
buffer.append(".");
buffer.append(version);
return new File(buffer.toString());
}
private File getCacheLocation() {
return new File(cacheLocation);
}
}
|
// $Id: ProbabilisticTimer.java,v 1.3 2002-09-09 20:31:08 tal Exp $
package org.lockss.util;
import java.util.*;
import java.text.DateFormat;
/** Probabilistic timers measure a duration with randomized jitter.
*/
public class ProbabilisticTimer {
static Random random = null;
Date expiration;
private long duration; // only for testing
Thread thread;
/** Return a timer with the specified duration. */
public ProbabilisticTimer(long duration) {
this(duration, 0.0);
}
/** Return a timer whose duration is a random, normally distrubuted value
* whose mean is <code>meanDuration</code> and standard deviation
* <code>stddev</code>.
*/
public ProbabilisticTimer(long meanDuration, double stddev) {
if (random == null) {
initialize();
}
duration = meanDuration + (long)(stddev * random.nextGaussian());
expiration = new Date(now().getTime() + duration);
}
private static Date now() {
return new Date();
}
private static void initialize() {
random = new Random();
}
/** For testing only. */
long getDuration() {
return duration;
}
/** Return the absolute expiration time, in milliseconds */
long getExpirationTime() {
return expiration.getTime();
}
/** Return the time remaining until expiration, in milliseconds */
public synchronized long getRemainingTime() {
return (expired() ? 0 : expiration.getTime() - now().getTime());
}
/** Cause the timer to expire immediately, and wake up the thread waiting
on it, if any. */
public synchronized void expire() {
expiration.setTime(0);
if (thread != null)
thread.interrupt();
}
/** Return true iff the timer has expired */
public synchronized boolean expired() {
return (!now().before(expiration));
}
/** Add <code>delta</code> to the timer's expiration time. */
public synchronized void slower(long delta) {
expiration.setTime(expiration.getTime() + delta);
}
/** Subtract <code>delta</code> from the timer's expiration time, and
wake up the waiting thread, if any, so it can recalculate the time
to wait. */
public synchronized void faster(long delta) {
expiration.setTime(expiration.getTime() - delta);
if (thread != null)
thread.interrupt();
}
/** Set the thread to be interrupted to the current thread. */
void setThread() {
thread = Thread.currentThread();
}
/** Set the thread to be interrupted to null. */
void clearThread() {
thread = null;
}
/** Return true iff this is shorter in duration than <code>other</code>. */
public boolean shorterThan(ProbabilisticTimer other) {
return (this.getRemainingTime() < other.getRemainingTime());
}
// This needs fixing.
private void sleep() {
long nap = getRemainingTime();
// XXX make these parameters
long minimumSleep = 1000;
long maximumSleep = 60000;
// make sure we always sleep if there's
if (nap > 0) {
if (nap < minimumSleep)
nap = minimumSleep;
try {
thread = Thread.currentThread();
thread.sleep(nap > maximumSleep ? maximumSleep : nap);
} catch (InterruptedException e) {
// XXX check that it's harmless
}
}
}
/** Sleep until the timer expires. */
public void sleepUntil() {
long nap = getRemainingTime();
while (nap > 0) {
try {
thread = Thread.currentThread();
thread.sleep(nap);
} catch (InterruptedException e) {
// Just wake up and see if it's time to expire
}
nap = getRemainingTime();
}
}
public String toString() {
DateFormat df = DateFormat.getTimeInstance();
return "[Timeout " + duration + " at " + df.format(expiration) + "]";
}
}
|
import java.util.*;
import java.io.*;
public class Verifier
{
public static final String EXAMPLE1_FILE = "example1.txt";
public static final int TOTAL_ORE_1 = 31;
public static final String EXAMPLE2_FILE = "example2.txt";
public static final int TOTAL_ORE_2 = 165;
public static final String EXAMPLE3_FILE = "example3.txt";
public static final int TOTAL_ORE_3 = 13312;
public static final String EXAMPLE4_FILE = "example4.txt";
public static final int TOTAL_ORE_4 = 180697;
public static final String EXAMPLE5_FILE = "example5.txt";
public static final int TOTAL_ORE_5 = 2210736;
public Verifier (boolean debug)
{
_debug = debug;
_theParser = new Parser(debug);
}
/*
* 10 ORE => 10 A
* 1 ORE => 1 B
* 7 A, 1 B => 1 C
* 7 A, 1 C => 1 D
* 7 A, 1 D => 1 E
* 7 A, 1 E => 1 FUEL
*/
public final boolean verify ()
{
Vector<Reaction> reactions = _theParser.loadData(EXAMPLE2_FILE);
NanoFactory factory = new NanoFactory(reactions, _debug);
int oreNeeded = factory.oreNeeded();
boolean verified = false;
if (oreNeeded == TOTAL_ORE_1)
{
reactions = _theParser.loadData(EXAMPLE2_FILE);
factory = new NanoFactory(reactions, _debug);
oreNeeded = factory.oreNeeded();
return (oreNeeded == TOTAL_ORE_2);
}
else
System.out.println("Failed on "+EXAMPLE1_FILE);
return verified;
}
private boolean _debug;
private Parser _theParser;
}
|
public class Verifier
{
public static final String EXAMPLE_1 = "example1.txt";
public static final Integer[] EXAMPLE_1_RESULT = {0, 3, 6, 9, 2, 5, 8, 1, 4, 7};
public static final String EXAMPLE_2 = "example2.txt";
public static final Integer[] EXAMPLE_2_RESULT = {3, 0, 7, 4, 1, 8, 5, 2, 9, 6};
public static final String EXAMPLE_3 = "example3.txt";
public static final Integer[] EXAMPLE_3_RESULT = {6, 3, 0, 7, 4, 1, 8, 5, 2, 9};
public static final Integer[] DEALT_INTO_RESULT = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
public static final Integer[] POSITIVE_CUT_RESULT = {3, 4, 5, 6, 7, 8, 9, 0, 1, 2};
public static final Integer[] NEGATIVE_CUT_RESULT = {6, 7, 8, 9, 0, 1, 2, 3, 4, 5};
public static final Integer[] DEAL_WITH_INCREMENT = {0, 7, 4, 1, 8, 5, 2, 9, 6, 3};
public Verifier (boolean debug)
{
_debug = debug;
}
public boolean verify ()
{
if (verifyBasic())
{
Dealer theDealer = new Dealer(EXAMPLE_1, _debug);
Deck theDeck = theDealer.dealCards(10);
Deck theResult = new Deck(EXAMPLE_1_RESULT, _debug);
if (_debug)
System.out.println("\nResult of "+EXAMPLE_1+" is "+theDeck+"\n");
if (theDeck.equals(theResult))
{
theDealer = new Dealer(EXAMPLE_2, _debug);
theDeck = theDealer.dealCards(10);
theResult = new Deck(EXAMPLE_2_RESULT, _debug);
if (_debug)
System.out.println("\nResult of "+EXAMPLE_2+" is "+theDeck+"\n");
if (theDeck.equals(theResult))
{
theDealer = new Dealer(EXAMPLE_3, _debug);
theDeck = theDealer.dealCards(10);
theResult = new Deck(EXAMPLE_3_RESULT, _debug);
if (_debug)
System.out.println("\nResult of "+EXAMPLE_3+" is "+theDeck+"\n");
if (theDeck.equals(theResult))
return true;
}
}
}
return false;
}
private boolean verifyBasic ()
{
Deck theDeck = new Deck(10, _debug);
//theDeck.populateWithCards();
System.out.println("Initial:\n"+theDeck);
Deck copy = new Deck(10, _debug);
if (!theDeck.dealInto(copy))
System.out.println("Dealing failed!");
System.out.println("\nDealt into:\n"+copy);
Deck dealtInto = new Deck(DEALT_INTO_RESULT, _debug);
if (copy.equals(dealtInto))
System.out.println("Dealt into worked!");
else
{
System.out.println("Dealt into did not work!");
return false;
}
theDeck.cut(3);
System.out.println("\nDeck after cut 3:\n"+theDeck);
Deck cutDeck = new Deck(POSITIVE_CUT_RESULT, _debug);
if (theDeck.equals(cutDeck))
System.out.println("Cut with positive worked!");
else
{
System.out.println("Cut with positive did not work!");
return false;
}
theDeck.populateWithCards();
theDeck.cut(-4);
System.out.println("\nDeck after cut -4:\n"+theDeck);
cutDeck = new Deck(NEGATIVE_CUT_RESULT, _debug);
if (theDeck.equals(cutDeck))
System.out.println("Cut with negative worked!");
else
{
System.out.println("Cut with negative did not work!");
return false;
}
theDeck.populateWithCards();
Table theTable = new Table(_debug);
theTable.deal(theDeck, 3);
theDeck = theTable.collectCards();
System.out.println("\nDeck after deal with increment 3:\n"+theDeck);
Deck dealtDeck = new Deck(DEAL_WITH_INCREMENT, _debug);
if (theDeck.equals(dealtDeck))
System.out.println("Deal with increment worked!");
else
{
System.out.println("Deal with increment did not work!");
return false;
}
return true;
}
private boolean _debug;
}
|
package org.nativescript.widgets;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.Drawable;
/**
* @author hhristov
*
*/
public class ImageView extends android.widget.ImageView {
private float cornerRadius = 0;
private float borderWidth = 0;
private Path path = new Path();
private RectF rect = new RectF();
private double scaleW = 1;
private double scaleH = 1;
public ImageView(Context context) {
super(context);
this.setScaleType(ScaleType.FIT_CENTER);
}
public float getCornerRadius() {
return this.cornerRadius;
}
public void setCornerRadius(float radius) {
if (radius != this.cornerRadius) {
this.cornerRadius = radius;
this.invalidate();
}
}
public float getBorderWidth() {
return this.borderWidth;
}
public void setBorderWidth(float radius) {
if (radius != this.borderWidth) {
this.borderWidth = radius;
this.invalidate();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Drawable drawable = this.getDrawable();
int measureWidth;
int measureHeight;
if (drawable != null) {
measureWidth = drawable.getIntrinsicWidth();
measureHeight = drawable.getIntrinsicHeight();
} else {
measureWidth = 0;
measureHeight = 0;
}
boolean finiteWidth = widthMode != MeasureSpec.UNSPECIFIED;
boolean finiteHeight = heightMode != MeasureSpec.UNSPECIFIED;
if (measureWidth != 0 && measureHeight != 0 && (finiteWidth || finiteHeight)) {
this.computeScaleFactor(width, height, finiteWidth, finiteHeight, measureWidth, measureHeight);
int resultW = (int) Math.floor(measureWidth * this.scaleW);
int resultH = (int) Math.floor(measureHeight * this.scaleH);
measureWidth = finiteWidth ? Math.min(resultW, width) : resultW;
measureHeight = finiteHeight ? Math.min(resultH, height) : resultH;
}
measureWidth += this.getPaddingLeft() + this.getPaddingRight();
measureHeight += this.getPaddingTop() + this.getPaddingBottom();
measureWidth = Math.max(measureWidth, getSuggestedMinimumWidth());
measureHeight = Math.max(measureHeight, getSuggestedMinimumHeight());
if (CommonLayoutParams.debuggable > 0) {
StringBuilder sb = CommonLayoutParams.getStringBuilder();
sb.append("ImageView onMeasure: ");
sb.append(MeasureSpec.toString(widthMeasureSpec));
sb.append(", ");
sb.append(MeasureSpec.toString(heightMeasureSpec));
sb.append(", stretch: ");
sb.append(this.getScaleType());
sb.append(", measureWidth: ");
sb.append(measureWidth);
sb.append(", measureHeight: ");
sb.append(measureHeight);
CommonLayoutParams.log(CommonLayoutParams.tag, sb.toString());
}
int widthSizeAndState = resolveSizeAndState(measureWidth, widthMeasureSpec, 0);
int heightSizeAndState = resolveSizeAndState(measureHeight, heightMeasureSpec, 0);
this.setMeasuredDimension(widthSizeAndState, heightSizeAndState);
}
private void computeScaleFactor(int measureWidth, int measureHeight, boolean widthIsFinite, boolean heightIsFinite, double nativeWidth, double nativeHeight) {
this.scaleW = 1;
this.scaleH = 1;
ScaleType scale = this.getScaleType();
if ((scale == ScaleType.CENTER_CROP || scale == ScaleType.FIT_CENTER || scale == ScaleType.FIT_XY) &&
(widthIsFinite || heightIsFinite)) {
this.scaleW = (nativeWidth > 0) ? measureWidth / nativeWidth : 0d;
this.scaleH = (nativeHeight > 0) ? measureHeight / nativeHeight : 0d;
if (!widthIsFinite) {
this.scaleW = scaleH;
} else if (!heightIsFinite) {
this.scaleH = scaleW;
} else {
// No infinite dimensions.
switch (scale) {
case FIT_CENTER:
this.scaleH = this.scaleW < this.scaleH ? this.scaleW : this.scaleH;
this.scaleW = this.scaleH;
break;
case CENTER_CROP:
this.scaleH = this.scaleW > this.scaleH ? this.scaleW : this.scaleH;
this.scaleW = this.scaleH;
break;
default:
break;
}
}
}
}
@Override
protected void onDraw(Canvas canvas) {
// floor the border width to avoid gaps between the border and the image
float roundedBorderWidth = (float) Math.floor(this.borderWidth);
float innerRadius = Math.max(0, this.cornerRadius - roundedBorderWidth);
// The border width is included in the padding so there is no need for
// clip if there is no inner border radius.
if (innerRadius != 0) {
this.rect.set(
roundedBorderWidth,
roundedBorderWidth,
this.getWidth() - roundedBorderWidth,
this.getHeight() - roundedBorderWidth);
this.path.reset();
this.path.addRoundRect(rect, innerRadius, innerRadius, android.graphics.Path.Direction.CW);
canvas.clipPath(this.path);
}
super.onDraw(canvas);
}
}
|
package org.nutz.dao.impl.entity;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.nutz.dao.DaoException;
import org.nutz.dao.FieldMatcher;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.EntityIndex;
import org.nutz.dao.entity.LinkField;
import org.nutz.dao.entity.LinkVisitor;
import org.nutz.dao.entity.MappingField;
import org.nutz.dao.entity.PkType;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Pojo;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.born.BornContext;
import org.nutz.lang.born.Borning;
import org.nutz.lang.born.Borns;
import org.nutz.lang.reflect.FastClass;
import org.nutz.lang.reflect.FastClassFactory;
import org.nutz.lang.util.Context;
import org.nutz.log.Log;
import org.nutz.log.Logs;
/**
*
*
* @author zozoh(zozohtnt@gmail.com)
*/
public class NutEntity<T> implements Entity<T> {
private static final Log log = Logs.get();
private static final Object[] EMTRY_ARG = new Object[]{};
/**
* Java
*/
private Map<String, MappingField> byJava;
private Map<String, MappingField> byDB;
private List<MappingField> fields;
private List<EntityIndex> indexes;
private Map<String, EntityIndex> indexMap;
private List<MappingField> theComposites;
private List<Pojo> beforeInsertMacroes;
private List<Pojo> afterInsertMacroes;
protected LinkFieldSet ones;
protected LinkFieldSet manys;
protected LinkFieldSet manymanys;
private MappingField theId;
private MappingField theName;
/**
* Java
*/
protected Class<T> type;
/**
* Java Mirror
*/
private Mirror<T> mirror;
/**
* ResultSet
*/
protected Borning<T> bornByRS;
protected Borning<T> bornByDefault;
private EntityName tableName;
private String tableComment;
private Map<String, String> columnComments;
private boolean hasTableComment;
private boolean hasColumnComment;
private EntityName viewName;
private Map<String, Object> metas;
private PkType pkType;
private boolean complete;
public NutEntity(final Class<T> type) {
this.type = type;
this.mirror = Mirror.me(type);
this.byJava = new HashMap<String, MappingField>();
this.byDB = new HashMap<String, MappingField>();
this.indexMap = new HashMap<String, EntityIndex>();
this.fields = new ArrayList<MappingField>(5);
this.indexes = new ArrayList<EntityIndex>(3);
this.theComposites = new ArrayList<MappingField>(3);
this.metas = new HashMap<String, Object>();
this.columnComments = new HashMap<String, String>();
this.pkType = PkType.UNKNOWN;
beforeInsertMacroes = new ArrayList<Pojo>(3);
afterInsertMacroes = new ArrayList<Pojo>(3);
try {
bornByDefault = mirror.getBorningByArgTypes();
try {
type.getConstructor();
final FastClass fast = FastClassFactory.get(type);
bornByDefault = new Borning<T>() {
@SuppressWarnings("unchecked")
public T born(Object... args) {
return (T)fast.born();
}
};
}
catch (Throwable e) {
// pls report issues
log.debugf("create FastClass for type=%s, but it is ok: %s", type, e.getMessage(), e);
}
}
catch (Exception e) {}
BornContext<T> bc = Borns.evalByArgTypes(type, ResultSet.class);
if (null != bc)
this.bornByRS = bc.getBorning();
else if (null == bornByDefault)
throw new DaoException("Need non-arg constructor : " + type);
this.ones = new LinkFieldSet();
this.manys = new LinkFieldSet();
this.manymanys = new LinkFieldSet();
}
public T getObject(ResultSet rs, FieldMatcher matcher) {
return getObject(rs, matcher, null);
}
public T getObject(ResultSet rs, FieldMatcher matcher, String prefix) {
if (null != bornByRS)
return bornByRS.born(rs);
T re = bornByDefault.born(EMTRY_ARG);
if (null == matcher)
for (MappingField fld : fields)
fld.injectValue(re, rs, prefix);
else
for (MappingField fld : fields)
if (matcher.match(fld.getName()))
fld.injectValue(re, rs, prefix);
return re;
}
public T getObject(Record rec) {
return getObject(rec, null);
}
public T getObject(Record rec, String prefix) {
T obj = bornByDefault.born(EMTRY_ARG);
for (MappingField fld : fields)
fld.injectValue(obj, rec, prefix);
return obj;
}
/**
*
*
* @param names
* Java
*/
public void checkCompositeFields(String[] names) {
if (!Lang.isEmptyArray(names) && names.length > 1) {
for (String name : names) {
if (byJava.containsKey(name) && byJava.get(name).isCompositePk())
theComposites.add(byJava.get(name));
else
throw Lang.makeThrow("Fail to find comosite field '%s' in class '%s'!",
name,
type.getName());
}
this.pkType = PkType.COMPOSITE;
} else if (null != this.theId) {
this.pkType = PkType.ID;
} else if (null != this.theName) {
this.pkType = PkType.NAME;
}
}
/**
*
*
* @param field
*
*/
public void addMappingField(MappingField field) {
if (field.isId())
theId = field;
else if (field.isName())
theName = field;
byJava.put(field.getName(), field);
byDB.put(field.getColumnName(), field);
fields.add(field);
columnComments.put(field.getName(), field.getColumnComment());
}
/**
*
* @param lnk
*/
public void addLinkField(LinkField lnk) {
switch (lnk.getLinkType()) {
case ONE:
ones.add(lnk);
break;
case MANY:
manys.add(lnk);
break;
case MANYMANY:
manymanys.add(lnk);
break;
default:
throw Lang.makeThrow("It is a miracle in Link field: '%s'(%s)",
lnk.getName(),
lnk.getEntity().getType().getName());
}
}
/**
*
*
* @param index
*
*/
public void addIndex(EntityIndex index) {
indexes.add(index);
indexMap.put(index.getName(), index);
}
public Context wrapAsContext(Object obj) {
return new EntityObjectContext(this, obj);
}
public List<LinkField> visitOne(Object obj, String regex, LinkVisitor visitor) {
return ones.visit(obj, regex, visitor);
}
public List<LinkField> visitMany(Object obj, String regex, LinkVisitor visitor) {
return manys.visit(obj, regex, visitor);
}
public List<LinkField> visitManyMany(Object obj, String regex, LinkVisitor visitor) {
return manymanys.visit(obj, regex, visitor);
}
public void setTableName(String namep) {
this.tableName = EntityName.create(namep);
}
public void setTableComment(String tComment) {
this.tableComment = tComment;
}
public void setHasTableComment(boolean hasTableComment) {
this.hasTableComment = hasTableComment;
}
public void setHasColumnComment(boolean hasColumnComment) {
this.hasColumnComment = hasColumnComment;
}
public void setBeforeInsertMacroes(List<Pojo> beforeInsertMacroes) {
this.beforeInsertMacroes = beforeInsertMacroes;
}
public void setAfterInsertMacroes(List<Pojo> afterInsertMacroes) {
this.afterInsertMacroes = afterInsertMacroes;
}
public void setViewName(String namep) {
this.viewName = EntityName.create(namep);
}
public MappingField getField(String name) {
return byJava.get(name);
}
public MappingField getColumn(String name) {
return byDB.get(name);
}
public List<MappingField> getMappingFields() {
return fields;
}
public List<LinkField> getLinkFields(String regex) {
List<LinkField> reOnes = ones.getList(regex);
List<LinkField> reManys = manys.getList(regex);
List<LinkField> reManymanys = manymanys.getList(regex);
List<LinkField> re = new ArrayList<LinkField>(reOnes.size()
+ reManys.size()
+ reManymanys.size());
re.addAll(reOnes);
re.addAll(reManys);
re.addAll(reManymanys);
return re;
}
public List<MappingField> getCompositePKFields() {
return this.theComposites;
}
public MappingField getNameField() {
return this.theName;
}
public MappingField getIdField() {
return this.theId;
}
public List<MappingField> getPks() {
if (null != theId)
return Lang.list(theId);
if (null != theName)
return Lang.list(theName);
return theComposites;
}
public Class<T> getType() {
return this.type;
}
public Mirror<T> getMirror() {
return this.mirror;
}
public List<EntityIndex> getIndexes() {
return this.indexes;
}
public EntityIndex getIndex(String name) {
return this.indexMap.get(name);
}
public String getTableName() {
return this.tableName.value();
}
public String getViewName() {
return this.viewName.value();
}
public boolean addBeforeInsertMacro(Pojo pojo) {
if (null != pojo) {
beforeInsertMacroes.add(pojo);
return true;
}
return false;
}
public boolean addAfterInsertMacro(Pojo pojo) {
if (null != pojo) {
afterInsertMacroes.add(pojo);
return true;
}
return false;
}
public List<Pojo> cloneBeforeInsertMacroes() {
List<Pojo> re = new ArrayList<Pojo>(beforeInsertMacroes.size());
for (Pojo pojo : beforeInsertMacroes)
re.add(pojo.duplicate());
return re;
}
public List<Pojo> cloneAfterInsertMacroes() {
List<Pojo> re = new ArrayList<Pojo>(afterInsertMacroes.size());
for (Pojo pojo : afterInsertMacroes)
re.add(pojo.duplicate());
return re;
}
public PkType getPkType() {
return pkType;
}
public Object getMeta(String key) {
return metas.get(key);
}
public boolean hasMeta(String key) {
return metas.containsKey(key);
}
public Map<String, Object> getMetas() {
return metas;
}
public String toString() {
return String.format("Entity<%s:%s>", getType().getName(), getTableName());
}
public boolean hasTableComment() {
return hasTableComment;
}
public String getTableComment() {
return tableComment;
}
public boolean hasColumnComment() {
return hasColumnComment;
}
public String getColumnComent(String columnName) {
return columnComments.get(columnName);
}
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public T born(ResultSet rs) {
if (null != bornByRS)
return bornByRS.born(rs);
return bornByDefault.born(EMTRY_ARG);
}
}
|
package org.nutz.dao.impl.sql;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.util.List;
import org.nutz.castor.Castors;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.sql.DaoStatement;
import org.nutz.dao.sql.SqlContext;
import org.nutz.dao.sql.SqlType;
import org.nutz.lang.Strings;
public abstract class NutStatement implements DaoStatement {
private Entity<?> entity;
private SqlContext context;
private SqlType sqlType;
public NutStatement() {
this.context = new SqlContext();
}
public boolean isSelect() {
return SqlType.SELECT == sqlType;
}
public boolean isUpdate() {
return SqlType.UPDATE == sqlType;
}
public boolean isDelete() {
return SqlType.DELETE == sqlType;
}
public boolean isInsert() {
return SqlType.INSERT == sqlType;
}
public boolean isCreate() {
return SqlType.CREATE == sqlType;
}
public boolean isDrop() {
return SqlType.DROP == sqlType;
}
public boolean isRun() {
return SqlType.RUN == sqlType;
}
public boolean isAlter() {
return SqlType.ALTER == sqlType;
}
public boolean isExec() {
return SqlType.EXEC == sqlType;
}
public boolean isCall() {
return SqlType.CALL == sqlType;
}
public boolean isOther() {
return SqlType.OTHER == sqlType;
}
public Entity<?> getEntity() {
return entity;
}
public DaoStatement setEntity(Entity<?> entity) {
this.entity = entity;
return this;
}
public SqlContext getContext() {
return context;
}
public void setContext(SqlContext context) {
this.context = context;
}
public SqlType getSqlType() {
return sqlType;
}
public DaoStatement setSqlType(SqlType sqlType) {
this.sqlType = sqlType;
return this;
}
public Object getResult() {
return context.getResult();
}
// TODO ~~~ --> !!
@SuppressWarnings("unchecked")
public <T> List<T> getList(Class<T> classOfT) {
return (List<T>) getResult();// TODO
}
public <T> T getObject(Class<T> classOfT) {
return Castors.me().castTo(getResult(), classOfT);
}
public int getInt() {
return getObject(Integer.class);
}
public String getString() {
return getObject(String.class);
}
public boolean getBoolean() {
return getObject(Boolean.class);
}
public int getUpdateCount() {
return context.getUpdateCount();
}
public String toString() {
String sql = this.toPreparedStatement();
StringBuilder sb = new StringBuilder(sql);
Object[][] mtrx = this.getParamMatrix();
if (null != mtrx && mtrx.length > 0 && mtrx[0].length > 0) {
int[] maxes = new int[mtrx[0].length];
String[][] sss = new String[mtrx.length][mtrx[0].length];
for (int row = 0; row < mtrx.length; row++)
for (int col = 0; col < mtrx[0].length; col++) {
String s = param2String(mtrx[row][col]);
maxes[col] = Math.max(maxes[col], s.length());
sss[row][col] = s;
}
sb.append("\n |");
for (int i = 0; i < mtrx[0].length; i++) {
sb.append(' ');
sb.append(Strings.alignRight("" + (i + 1), maxes[i], ' '));
sb.append(" |");
}
sb.append("\n |");
for (int i = 0; i < mtrx[0].length; i++) {
sb.append('-');
sb.append(Strings.dup('-', maxes[i]));
sb.append("-|");
}
// XXX 50
int maxRow = mtrx.length > 50 ? 50 : mtrx.length;
for (int row = 0; row < maxRow; row++) {
sb.append("\n |");
for (int col = 0; col < mtrx[0].length; col++) {
sb.append(' ');
sb.append(Strings.alignLeft(sss[row][col], maxes[col], ' '));
sb.append(" |");
}
}
if (maxRow != mtrx.length)
sb.append("\n .............................................")
.append("\n !!!Too many data . Only display 50 lines , don't show the remaining record")
.append("\n .............................................");
// SQL , TODO !!SQL,!!!
sb.append("\n For example:> \"");
sb.append(toExampleStatement(mtrx, sql));
sb.append('"');
}
return sb.toString();
}
protected String toExampleStatement(Object[][] mtrx, String sql) {
StringBuilder sb = new StringBuilder();
String[] ss = sql.split("[?]");
int i = 0;
if (mtrx.length > 0) {
for (; i < mtrx[0].length; i++) {
sb.append(ss[i]);
Object obj = mtrx[0][i];
if (obj != null) {
if (obj instanceof Blob) {
Blob blob = (Blob) obj;
obj = "Blob(" + blob.hashCode() + ")";
} else if (obj instanceof Clob) {
Clob clob = (Clob) obj;
obj = "Clob(" + clob.hashCode() + ")";
} else if (obj instanceof byte[] || obj instanceof char[]) {
if (Array.getLength(obj) > 10240)
obj = "*BigData[len=" + Array.getLength(obj) + "]";
} else if (obj instanceof InputStream) {
try {
obj = "*InputStream[len=" + ((InputStream) obj).available() + "]";
}
catch (IOException e) {}
} else if (obj instanceof Reader) {
obj = "*Reader@" + obj.hashCode();
}
}
sb.append(Sqls.formatFieldValue(obj));
}
}
if (i < ss.length)
sb.append(ss[i]);
return sb.toString();
}
protected String toStatement(Object[][] mtrx, String sql) {
StringBuilder sb = new StringBuilder();
String[] ss = sql.split("[?]");
int i = 0;
if (mtrx.length > 0) {
for (; i < mtrx[0].length; i++) {
sb.append(ss[i]);
sb.append(Sqls.formatFieldValue(mtrx[0][i]));
}
}
for (; i < ss.length; i++) {
sb.append(ss[i]);
}
return sb.toString();
}
protected String param2String(Object obj) {
if (obj == null)
return "NULL";
else {
if (obj instanceof Blob) {
Blob blob = (Blob) obj;
return "Blob(" + blob.hashCode() + ")";
} else if (obj instanceof Clob) {
Clob clob = (Clob) obj;
return "Clob(" + clob.hashCode() + ")";
} else if (obj instanceof byte[] || obj instanceof char[]) {
if (Array.getLength(obj) > 10240)
return "*BigData[len=" + Array.getLength(obj) + "]";
} else if (obj instanceof InputStream) {
try {
obj = "*InputStream[len=" + ((InputStream) obj).available() + "]";
}
catch (IOException e) {}
} else if (obj instanceof Reader) {
obj = "*Reader@" + obj.hashCode();
}
return Castors.me().castToString(obj); // TODO ,
}
}
}
|
package org.opencms.file;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsRuntimeException;
import org.opencms.security.CmsOrganizationalUnit;
import org.opencms.util.CmsResourceTranslator;
import org.opencms.workplace.CmsWorkplace;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
/**
* Stores the information about the current users OpenCms context,
* for example the requested URI, the current project, the selected site and more.<p>
*
* @author Alexander Kandzior
* @author Michael Emmerich
*
* @version $Revision: 1.32 $
*
* @since 6.0.0
*/
public final class CmsRequestContext {
/** Request context attribute for indicating that an editor is currently open. */
public static final String ATTRIBUTE_EDITOR = "org.opencms.file.CmsRequestContext.ATTRIBUTE_EDITOR";
/** Request context attribute for indicating the model file for a create resource operation. */
public static final String ATTRIBUTE_MODEL = "org.opencms.file.CmsRequestContext.ATTRIBUTE_MODEL";
/** A map for storing (optional) request context attributes. */
private Map m_attributeMap;
/** The current project. */
private CmsProject m_currentProject;
/** Directory name translator. */
private CmsResourceTranslator m_directoryTranslator;
/** Current encoding. */
private String m_encoding;
/** File name translator. */
private CmsResourceTranslator m_fileTranslator;
/** The locale for this request. */
private Locale m_locale;
/** The fully qualified name of the organizational unit for this request. */
private String m_ouFqn;
/** The remote ip address. */
private String m_remoteAddr;
/** The current request time. */
private long m_requestTime;
/** Used to save / restore a site root .*/
private String m_savedSiteRoot;
/** The name of the root, e.g. /site_a/vfs. */
private String m_siteRoot;
/** Flag to indicate that this context should not update the user session. */
private boolean m_updateSession;
/** The URI for getUri() in case it is "overwritten". */
private String m_uri;
/** The current user. */
private CmsUser m_user;
/**
* Constructs a new request context.<p>
*
* @param user the current user
* @param project the current project
* @param requestedUri the requested OpenCms VFS URI
* @param siteRoot the users current site root
* @param locale the users current locale
* @param encoding the encoding to use for this request
* @param remoteAddr the remote IP address of the user
* @param requestTime the time of the request (used for resource publication / expiration date)
* @param directoryTranslator the directory translator
* @param fileTranslator the file translator
* @param ouFqn the fully qualified name of the organizational unit
*/
public CmsRequestContext(
CmsUser user,
CmsProject project,
String requestedUri,
String siteRoot,
Locale locale,
String encoding,
String remoteAddr,
long requestTime,
CmsResourceTranslator directoryTranslator,
CmsResourceTranslator fileTranslator,
String ouFqn) {
m_updateSession = true;
m_user = user;
m_currentProject = project;
m_uri = requestedUri;
setSiteRoot(siteRoot);
m_locale = locale;
m_encoding = encoding;
m_remoteAddr = remoteAddr;
m_requestTime = requestTime;
m_directoryTranslator = directoryTranslator;
m_fileTranslator = fileTranslator;
setOuFqn(ouFqn);
}
/**
* Returns the adjusted site root for a resoure using the provided site root as a base.<p>
*
* Usually, this would be the site root for the current site.
* However, if a resource from the <code>/system/</code> folder is requested,
* this will be the empty String.<p>
*
* @param siteRoot the site root of the current site
* @param resourcename the resource name to get the adjusted site root for
*
* @return the adjusted site root for the resoure
*/
public static String getAdjustedSiteRoot(String siteRoot, String resourcename) {
if (resourcename.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) {
return "";
} else {
return siteRoot;
}
}
/**
* Adds the current site root of this context to the given resource name,
* and also translates the resource name with the configured the directory translator.<p>
*
* @param resourcename the resource name
* @return the translated resource name including site root
* @see #addSiteRoot(String, String)
*/
public String addSiteRoot(String resourcename) {
return addSiteRoot(m_siteRoot, resourcename);
}
/**
* Adds the given site root of this context to the given resource name,
* taking into account special folders like "/system" where no site root must be added,
* and also translates the resource name with the configured the directory translator.<p>
*
* @param siteRoot the site root to add
* @param resourcename the resource name
* @return the translated resource name including site root
*/
public String addSiteRoot(String siteRoot, String resourcename) {
if ((resourcename == null) || (siteRoot == null)) {
return null;
}
siteRoot = getAdjustedSiteRoot(siteRoot, resourcename);
StringBuffer result = new StringBuffer(128);
result.append(siteRoot);
if (((siteRoot.length() == 0) || (siteRoot.charAt(siteRoot.length() - 1) != '/'))
&& ((resourcename.length() == 0) || (resourcename.charAt(0) != '/'))) {
// add slash between site root and resource if required
result.append('/');
}
result.append(resourcename);
return m_directoryTranslator.translateResource(result.toString());
}
/**
* Returns the current project of the current user.
*
* @return the current project of the current user
*/
public CmsProject currentProject() {
return m_currentProject;
}
/**
* Returns the current user object.<p>
*
* @return the current user object
*/
public CmsUser currentUser() {
return m_user;
}
/**
* Returns the adjusted site root for a resoure this context current site root.<p>
*
* @param resourcename the resource name to get the adjusted site root for
* @return the adjusted site root for the resoure
* @see #getAdjustedSiteRoot(String, String)
*/
public String getAdjustedSiteRoot(String resourcename) {
return getAdjustedSiteRoot(m_siteRoot, resourcename);
}
/**
* Gets the value of an attribute from the OpenCms request context attribute list.<p>
*
* @param attributeName the attribute name
* @return Object the attribute value, or <code>null</code> if the attribute was not found
*/
public Object getAttribute(String attributeName) {
if (m_attributeMap == null) {
return null;
}
return m_attributeMap.get(attributeName);
}
/**
* Returns the directory name translator this context was initialized with.<p>
*
* The directory translator is used to translate old VFS path information
* to a new location. Example: <code>/bodys/index.html --> /system/bodies/</code>.<p>
*
* @return the directory name translator this context was initialized with
*/
public CmsResourceTranslator getDirectoryTranslator() {
return m_directoryTranslator;
}
/**
* Returns the current content encoding to be used in HTTP response.<p>
*
* @return the encoding
*/
public String getEncoding() {
return m_encoding;
}
/**
* Returns the file name translator this context was initialized with.<p>
*
* The file name translator is used to translate filenames from uploaded files
* to valid OpenCms filenames. Example: <code>Wste Wrter.doc --> Wueste_Woerter.doc</code>.<p>
*
* @return the file name translator this context was initialized with
*/
public CmsResourceTranslator getFileTranslator() {
return m_fileTranslator;
}
/**
* Gets the name of the parent folder of the requested file.<p>
*
* @return the name of the parent folder of the requested file
*/
public String getFolderUri() {
return CmsResource.getFolderPath(m_uri);
}
/**
* Returns the name of the requested locale within this context.<p>
*
* @return the name of the locale
*/
public Locale getLocale() {
return m_locale;
}
/**
* Returns the fully qualified name of the organizational unit.<p>
*
* @return the fully qualified name of the organizational unit
*/
public String getOuFqn() {
return m_ouFqn;
}
/**
* Returns the remote ip address.<p>
*
* @return the remote ip address as string
*/
public String getRemoteAddress() {
return m_remoteAddr;
}
/**
* Returns the current request time.<p>
*
* @return the current request time
*/
public long getRequestTime() {
return m_requestTime;
}
/**
* Adjusts the absolute resource root path for the current site.<p>
*
* The full root path of a resource is always available using
* <code>{@link CmsResource#getRootPath()}</code>. From this name this method cuts
* of the current site root using
* <code>{@link CmsRequestContext#removeSiteRoot(String)}</code>.<p>
*
* If the resource root path does not start with the current site root,
* it is left untouched.<p>
*
* @param resource the resource to get the adjusted site root path for
*
* @return the absolute resource path adjusted for the current site
*
* @see #removeSiteRoot(String)
* @see CmsResource#getRootPath()
* @see CmsObject#getSitePath(CmsResource)
*/
public String getSitePath(CmsResource resource) {
return removeSiteRoot(resource.getRootPath());
}
/**
* Returns the current root directory in the virtual file system.<p>
*
* @return the current root directory in the virtual file system
*/
public String getSiteRoot() {
return m_siteRoot;
}
/**
* Returns the OpenCms VFS URI of the requested resource.<p>
*
* @return the OpenCms VFS URI of the requested resource
*/
public String getUri() {
return m_uri;
}
/**
* Check if this request context will update the session.<p>
*
* This is used mainly for CmsReports that continue to use the
* users context, even after the http request is already finished.<p>
*
* @return true if this request context will update the session, false otherwise
*/
public boolean isUpdateSessionEnabled() {
return m_updateSession;
}
/**
* Removes the current site root prefix from the absolute path in the resource name,
* that is adjusts the resource name for the current site root.<p>
*
* If the resource name does not start with the current site root,
* it is left untouched.<p>
*
* @param resourcename the resource name
*
* @return the resource name adjusted for the current site root
*
* @see #getSitePath(CmsResource)
*/
public String removeSiteRoot(String resourcename) {
String siteRoot = getAdjustedSiteRoot(m_siteRoot, resourcename);
if ((siteRoot == m_siteRoot)
&& resourcename.startsWith(siteRoot)
&& ((resourcename.length() == siteRoot.length()) || resourcename.charAt(siteRoot.length()) == '/')) {
resourcename = resourcename.substring(siteRoot.length());
}
return resourcename;
}
/**
* Restores the saved site root.<p>
*
* @throws RuntimeException in case there is no site root saved
*
* @deprecated store the current site root locally before switching
* to another site, and set it back again at the end, like:
* <pre>
* String storedSite = context.getSiteRoot();
* try {
* context.setSiteRoot("");
* // do something with the context
* } finally {
* context.setSiteRoot(storedSite);
* }
* </pre>
*/
public void restoreSiteRoot() throws RuntimeException {
if (m_savedSiteRoot == null) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_EMPTY_SITEROOT_0));
}
m_siteRoot = m_savedSiteRoot;
m_savedSiteRoot = null;
}
/**
* Saves the current site root.<p>
*
* @throws RuntimeException in case there is already a site root saved
*
* @deprecated store the current site root locally before switching
* to another site, and set it back again at the end, like:
* <pre>
* String storedSite = context.getSiteRoot();
* try {
* context.setSiteRoot("");
* // do something with the context
* } finally {
* context.setSiteRoot(storedSite);
* }
* </pre>
*/
public void saveSiteRoot() throws RuntimeException {
if (m_savedSiteRoot != null) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_NONEMPTY_SITEROOT_1, m_savedSiteRoot));
}
m_savedSiteRoot = m_siteRoot;
}
/**
* Sets an attribute in the request context.<p>
*
* @param key the attribute name
* @param value the attribute value
*/
public void setAttribute(String key, Object value) {
if (m_attributeMap == null) {
// Hash table is still the most efficient form of a synchronized Map
m_attributeMap = new Hashtable();
}
m_attributeMap.put(key, value);
}
/**
* Sets the current project for the user.<p>
*
* @param project the project to be set as current project
*
* @return the CmsProject instance
*/
public CmsProject setCurrentProject(CmsProject project) {
if (project != null) {
m_currentProject = project;
}
return m_currentProject;
}
/**
* Sets the current content encoding to be used in HTTP response.<p>
*
* @param encoding the encoding
*/
public void setEncoding(String encoding) {
m_encoding = encoding;
}
/**
* Sets the current request time.<p>
*
* @param time the request time
*/
public void setRequestTime(long time) {
m_requestTime = time;
}
/**
* Sets the current root directory in the virtual file system.<p>
*
* @param root the name of the new root directory
*/
public void setSiteRoot(String root) {
// site roots must never end with a "/"
if (root.endsWith("/")) {
m_siteRoot = root.substring(0, root.length() - 1);
} else {
m_siteRoot = root;
}
}
/**
* Mark this request context to update the session or not.<p>
*
* @param value true if this request context will update the session, false otherwise
*/
public void setUpdateSessionEnabled(boolean value) {
m_updateSession = value;
}
/**
* Set the requested resource OpenCms VFS URI, that is the value returned by {@link #getUri()}.<p>
*
* Use this with caution! Many things (caches etc.) depend on this value.
* If you change this value, better make sure that you change it only temporarily
* and reset it in a <code>try { // do something // } finally { // reset URI // }</code> statement.<p>
*
* @param value the value to set the Uri to, must be a complete OpenCms path name like /system/workplace/style.css
*/
public void setUri(String value) {
m_uri = value;
}
/**
* Switches the user in the context, required after a login.<p>
*
* @param user the new user to use
* @param project the new users current project
* @param ouFqn the organizational unit
*/
protected void switchUser(CmsUser user, CmsProject project, String ouFqn) {
m_user = user;
m_currentProject = project;
setOuFqn(ouFqn);
}
/**
* Sets the organizational unit fully qualified name.<p>
*
* @param ouFqn the organizational unit fully qualified name
*/
private void setOuFqn(String ouFqn) {
String userOu = CmsOrganizationalUnit.getParentFqn(m_user.getName());
if (ouFqn != null) {
if (!ouFqn.startsWith(userOu) && !ouFqn.substring(1).startsWith(userOu)) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_BAD_ORGUNIT_2,
ouFqn,
userOu));
}
m_ouFqn = ouFqn;
} else {
m_ouFqn = userOu;
}
m_ouFqn = CmsOrganizationalUnit.removeLeadingSeparator(m_ouFqn);
}
}
|
package org.opencms.jsp;
import org.opencms.ade.containerpage.CmsContainerpageActionElement;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.history.CmsHistoryResourceHandler;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsGwtActionElement;
import org.opencms.gwt.shared.CmsGwtConstants;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.editors.directedit.CmsAdvancedDirectEditProvider;
import org.opencms.workplace.editors.directedit.CmsDirectEditMode;
import org.opencms.workplace.editors.directedit.I_CmsDirectEditProvider;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
* Implementation of the <code><enable-ade/></code> tag.<p>
*
* @since 7.6
*/
public class CmsJspTagEnableAde extends BodyTagSupport {
/** The preview mode JavaScript include. */
private static final String PREVIEW_INCLUDE_SCRIPT = "<script type=\"text/javascript\"> "
+ "function openEditor(){ "
+ "var target=window.location.href; "
+ "if (target.indexOf(\""
+ CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT
+ "\")>0){ "
+ "target=target.replace(\""
+ CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT
+ "=true\",\""
+ CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT
+ "=false\"); "
+ "} else { "
+ "if (target.indexOf(\"?\")>0) { "
+ "target+=\"&\"; "
+ "} else { "
+ "target+=\"?\"; "
+ "} "
+ "target+=\""
+ CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT
+ "=false\"; "
+ "} "
+ "window.location.href=target; "
+ "} "
+ "function injectButton(){ "
+ "if (self === top){ "
+ "var injectElement=document.createElement(\"div\"); "
+ "injectElement.innerHTML=\"<button id='opencms-leave-preview' class='opencms-icon opencms-icon-edit-point cmsState-up' onClick='openEditor()'></button>\"; "
+ "document.body.appendChild(injectElement); "
+ "}"
+ "} "
+ "document.addEventListener(\"DOMContentLoaded\",injectButton); "
+ "</script>\n";
/** The preview mode CSS include. */
private static final String PREVIEW_INCLUDE_STYLE = "<style type=\"text/css\"> "
+ "button#opencms-leave-preview{"
+ "font-size:32px; "
+ "color:#474747; "
+ "border:none; "
+ "background:transparent; "
+ "position:fixed; "
+ "top:5px; "
+ "left:%s; "
+ "z-index:1000000; "
+ "padding:4px;"
+ "} "
+ "button#opencms-leave-preview:hover{"
+ "color:#356EE1;"
+ "} "
+ "button#opencms-leave-preview:after{"
+ "content:\"\"; "
+ "position:absolute; "
+ "z-index:-1; "
+ "background:#fff; "
+ "top:0; "
+ "left:0; "
+ "right:0; "
+ "bottom:0; "
+ "opacity:0.7; "
+ "border-radius:4px;"
+ "} "
+ "</style>\n";
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = 8447599916548975733L;
/**
* Enable-ade action method.<p>
*
* @param context the current JSP page context
*
* @throws JspException in case something goes wrong
*/
public static void enableAdeTagAction(PageContext context) throws JspException {
ServletRequest req = context.getRequest();
if (CmsHistoryResourceHandler.isHistoryRequest(req)) {
// don't display advanced direct edit buttons on an historical resource
return;
}
CmsFlexController controller = CmsFlexController.getController(req);
CmsObject cms = controller.getCmsObject();
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// advanced direct edit is never enabled in the online project
return;
}
if (CmsResource.isTemporaryFileName(cms.getRequestContext().getUri())) {
// don't display advanced direct edit buttons if a temporary file is displayed
return;
}
updateDirectEditFlagInSession(req);
if (isDirectEditDisabled(req)) {
try {
String buttonLeft = null;
Integer left = (Integer)((HttpServletRequest)req).getSession().getAttribute(
CmsGwtConstants.PARAM_BUTTON_LEFT);
if (left != null) {
buttonLeft = left.toString() + "px";
} else {
buttonLeft = "20%";
}
context.getOut().print(getPreviewInclude(buttonLeft));
} catch (IOException e) {
throw new JspException(e);
}
} else {
I_CmsDirectEditProvider eb = new CmsAdvancedDirectEditProvider();
eb.init(cms, CmsDirectEditMode.TRUE, "");
CmsJspTagEditable.setDirectEditProvider(context, eb);
try {
CmsContainerpageActionElement actionEl = new CmsContainerpageActionElement(
context,
(HttpServletRequest)req,
(HttpServletResponse)context.getResponse());
context.getOut().print(actionEl.exportAll());
} catch (Exception e) {
throw new JspException(e);
}
}
}
/**
* Returns if direct edit is disabled for the current request.<p>
*
* @param request the servlet request
*
* @return <code>true</code> if direct edit is disabled for the current request
*/
public static boolean isDirectEditDisabled(ServletRequest request) {
String disabledParam = request.getParameter(CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(disabledParam)) {
return Boolean.parseBoolean(disabledParam);
} else {
HttpSession session = ((HttpServletRequest)request).getSession(false);
Boolean disabledAttr = null == session
? null
: (Boolean)session.getAttribute(CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT);
return (disabledAttr != null) && disabledAttr.booleanValue();
}
}
/**
* Removes the direct edit flag from session, turning the preview mode off.<p>
*
* @param session the session
*/
public static void removeDirectEditFlagFromSession(HttpSession session) {
session.removeAttribute(CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT);
}
/**
* Updates the direct edit flag in the session and also storing the button left info if available.<p>
*
* @param request the request
*/
public static void updateDirectEditFlagInSession(ServletRequest request) {
String disabledParam = request.getParameter(CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(disabledParam)) {
if (Boolean.parseBoolean(disabledParam)) {
((HttpServletRequest)request).getSession().setAttribute(
CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT,
Boolean.TRUE);
String buttonLeft = request.getParameter(CmsGwtConstants.PARAM_BUTTON_LEFT);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(buttonLeft)) {
Integer left = null;
try {
left = Integer.valueOf(buttonLeft);
if (left.intValue() > 0) {
((HttpServletRequest)request).getSession().setAttribute(
CmsGwtConstants.PARAM_BUTTON_LEFT,
left);
}
} catch (NumberFormatException e) {
// malformed parameter, ignore
}
}
} else {
((HttpServletRequest)request).getSession().removeAttribute(CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT);
}
}
}
/**
* Returns the preview mode include.<p>
*
* @param buttonLeft the button left parameter
*
* @return the preview mode include
*/
private static String getPreviewInclude(String buttonLeft) {
StringBuffer buffer = new StringBuffer();
buffer.append("<style type=\"text/css\"> @import url(\"").append(
CmsGwtActionElement.getFontIconCssLink()).append("\"); </style>\n");
buffer.append(String.format(PREVIEW_INCLUDE_STYLE, buttonLeft));
buffer.append(PREVIEW_INCLUDE_SCRIPT);
return buffer.toString();
}
/**
* Close the direct edit tag, also prints the direct edit HTML to the current page.<p>
*
* @return {@link #EVAL_PAGE}
*
* @throws JspException in case something goes wrong
*/
@Override
public int doEndTag() throws JspException {
// only execute action for the first "ade" tag on the page (include file)
enableAdeTagAction(pageContext);
if (OpenCms.getSystemInfo().getServletContainerSettings().isReleaseTagsAfterEnd()) {
// need to release manually, JSP container may not call release as required (happens with Tomcat)
release();
}
return EVAL_PAGE;
}
/**
* Opens the direct edit tag, if manual mode is set then the next
* start HTML for the direct edit buttons is printed to the page.<p>
*
* @return {@link #EVAL_BODY_INCLUDE}
*/
@Override
public int doStartTag() {
return EVAL_BODY_INCLUDE;
}
}
|
package org.ratson.pentagrid.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.ratson.pentagrid.Clusterizer;
import org.ratson.pentagrid.DayNightRule;
import org.ratson.pentagrid.Field;
import org.ratson.pentagrid.OrientedPath;
import org.ratson.pentagrid.Path;
import org.ratson.pentagrid.PathNavigation;
import org.ratson.pentagrid.Rule;
import org.ratson.pentagrid.RuleSyntaxException;
import org.ratson.pentagrid.TotalisticRule;
import org.ratson.pentagrid.Util;
import org.ratson.pentagrid.fields.SimpleMapField;
import org.ratson.pentagrid.gui.poincare_panel.PoincarePanelEvent;
import org.ratson.pentagrid.gui.poincare_panel.PoincarePanelListener;
import org.ratson.util.Pair;
public class MainFrame extends JFrame implements NotificationReceiver {
private SimpleMapField world = new SimpleMapField();
private TotalisticRule rule = new Rule(new int[]{3}, new int[]{2,3});
private FarPoincarePanel panel;
private EvaluationRunner evaluationThread=null;
private Settings settings = new Settings();
private JLabel lblFieldInfo, lblLocationInfo;
private WaypointNavigator waypointNavigator=new WaypointNavigator();
class WaypointNavigator{
ArrayList<Path> waypoints = new ArrayList<Path>();
int currentPosition = 0;
public void clear(){
waypoints.clear();
currentPosition = 0;
}
public void add( Path p ){
waypoints.add( p );
}
private void navigateBy( int offset ){
if (waypoints.size()==0) return;
currentPosition = org.ratson.util.Util.mod(currentPosition+offset, waypoints.size());
goToCell( waypoints.get(currentPosition));
System.out.println("Showing waypoint "+currentPosition+" of "+waypoints.size());
}
public void next(){ navigateBy(1); };
public void previous(){ navigateBy(-1); }
public void current() { navigateBy(0); };
}
private void createUI(){
Box topBox = Box.createVerticalBox();
panel = new FarPoincarePanel( world );
lblFieldInfo = new JLabel();
lblLocationInfo = new JLabel();
topBox.add( lblFieldInfo );
topBox.add( lblLocationInfo );
getContentPane().add( panel );
getContentPane().add( topBox, BorderLayout.NORTH );
}
/**Show a cell in the view*/
public void goToCell(Path path) {
panel.setOrigin( new OrientedPath(path, 0));
}
private void updateFieldInfo(){
String infoStr = String.format("Population:%d State:%d Rule:%s", world.population(), world.getFieldState(), rule);
lblFieldInfo.setText( infoStr );
}
private void updateLocationInfo(){
String locStr = "Location: "+panel.getOrigin().path;
lblLocationInfo.setText( locStr );
}
private void addHandlers(){
addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar() ){
case ' ':
if ( evaluationThread == null){
world.evaluate( rule );
updateFieldInfo();
panel.update();
}
break;
case 'r':
setCells( Util.randomField( settings.randomFieldRadius, settings.randomFillPercent ) );
break;
case 'd':
setCells( new Path[0] );
break;
case 'x':
doChangeRule();
break;
case 'e':
doSaveImage();
break;
case 's':
doSaveField();
break;
case 'l':
doLoadField();
break;
case 't':
doEditSettings();
break;
case 'u':
panel.update();
break;
case 'z':
doClusterize();
break;
case 'o':
waypointNavigator.next();
break;
case 'p':
waypointNavigator.previous();
break;
}
}
@Override
public void keyPressed(KeyEvent e) {
switch( e.getKeyCode()){
case KeyEvent.VK_UP : panel.offsetView(0, -0.1); break;
case KeyEvent.VK_DOWN : panel.offsetView(0, 0.1); break;
case KeyEvent.VK_LEFT : panel.offsetView(0.1, 0); break;
case KeyEvent.VK_RIGHT : panel.offsetView(-0.1, 0); break;
case KeyEvent.VK_OPEN_BRACKET : panel.rotateView( -0.06); break;
case KeyEvent.VK_CLOSE_BRACKET : panel.rotateView( 0.06); break;
case KeyEvent.VK_C : { panel.centerView(); break;}
case KeyEvent.VK_A : panel.antiAlias = ! panel.antiAlias; panel.repaint(); break;
case KeyEvent.VK_G : panel.showGrid = ! panel.showGrid; panel.repaint(); break;
case KeyEvent.VK_ENTER: toggleRunning(); break;
}
}
});
panel.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent arg0) {
try{
if( arg0.getButton() == MouseEvent.BUTTON1 ){
Path point = panel.mouse2cellPath(arg0.getX(), arg0.getY());
if (point != null){
world.setCell( point, 1 ^ world.getCell( point ) );
panel.update();
}else{
System.err.println("Non-point");
}
}
}catch( Exception err ){
System.err.println("Error:"+err.getMessage());
}
}});
panel.AddPoincarePanelListener( new PoincarePanelListener(){
public void originChanged(PoincarePanelEvent e) {
updateLocationInfo();
}});
}
/**Find clusters in the field, and set waypoints to them*/
protected void doClusterize() {
waypointNavigator.clear();
System.out.println("Clusterizing...");
Clusterizer c = null;
synchronized( world ){
c = new Clusterizer( world );
}
System.out.println("Done. Found "+c.clusters.size()+" clusters");
for( Clusterizer.Cluster cl: c.clusters ){
waypointNavigator.add( cl.cells.get(0) );
}
waypointNavigator.current();
}
protected void doEditSettings() {
Settings settingsCopy = (Settings)(settings.clone());
SettingsDialog sd = new SettingsDialog(settingsCopy);
if ( sd.showDialog() ){
settings = settingsCopy;
}
}
protected void toggleRunning() {
if( evaluationThread == null )
startEvaluation();
else
stopEvaluation();
}
protected void doChangeRule() {
String sRule = JOptionPane.showInputDialog(this, "Enter the rule in format B3/S23", rule.getCode());
if ( sRule != null ){
try{
setRule( sRule );
}catch( RuleSyntaxException err ){
JOptionPane.showMessageDialog(this, err.getMessage(), "Error parsing rule", JOptionPane.ERROR_MESSAGE);
}
}
}
public void setRule( TotalisticRule r){
rule = r;
updateFieldInfo();
System.out.println( "Rule set to "+rule);
}
public void setRule( String sRule ) throws RuleSyntaxException{
stopEvaluation();
Rule parsed = Rule.parseRule(sRule);
if (parsed.isVacuumStable() ){
//normal rule
setRule( parsed );
}else{
if ( parsed.isValidDayNight() ){
DayNightRule converted = new DayNightRule(parsed);
System.out.println( "Converting Day/Night rule "+parsed+" to the pair of stable rules:"+ converted);
assert( converted.isValidRule() );
setRule(converted);
}else
throw new RuleSyntaxException("Rule "+parsed+" is not supported: it has B0 and SA. Try inverted rule:"+parsed.invertBoth());
}
}
public void setCells( Path[] cells ){
boolean wasRunning = false;
if( evaluationThread != null ) {
stopEvaluation();
wasRunning = true;
}
world.setCells( cells );
world.setFieldState(0);
panel.update();
updateFieldInfo();
if (wasRunning) startEvaluation();
}
public MainFrame() {
super("Hyperbolic CA simulator");
createUI();
addHandlers();
}
public static void main(String[] args) {
MainFrame frm = new MainFrame();
Path root = Path.getRoot();
Path[] cells = PathNavigation.neigh10( root );
frm.setCells( cells );
frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frm.setSize( 600, 600 );
frm.setVisible( true );
}
public void startEvaluationFast(){
if( evaluationThread != null ) return;
evaluationThread = new EvaluationRunner(world, rule, this);
evaluationThread.setDelayMs(0);
evaluationThread.start();
}
public void startEvaluation(){
if( evaluationThread != null ) return;
evaluationThread = new EvaluationRunner(world, rule, this);
evaluationThread.start();
}
public void stopEvaluation(){
if (evaluationThread != null){
evaluationThread.requestStop();
try {
evaluationThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
evaluationThread = null;
}
}
@Override
public void notifyUpdate( Object w ) {
//Receive results from the evaluator
//This code is called from the evaluator thread
if (w == world){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
panel.update();
updateFieldInfo();
}
});
}else{
System.err.println("Unknown notification");
}
}
private JFileChooser fieldFileChooser = null;
private JFileChooser imageFileChooser = null;
private void doSaveImage() {
if ( imageFileChooser == null ){
imageFileChooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("PNG image (*.png)", "png");
imageFileChooser.addChoosableFileFilter( filter );
imageFileChooser.setFileFilter( filter );
}
if (imageFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = imageFileChooser.getSelectedFile();
if ( ! file.getName().contains("."))
file = new File( file.getParentFile(), file.getName()+".png");
try {
int s = settings.exportImageSize;
ImageIO.write( panel.exportImage(new Dimension(s, s), settings.exportAntiAlias ),
"PNG", file);
} catch (IOException err) {
JOptionPane.showMessageDialog(this, err.getMessage(), "Can not save file", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveFieldData( File f, Field fld ) throws FileNotFoundException, IOException{
ObjectOutputStream oos = new ObjectOutputStream( new GZIPOutputStream( new FileOutputStream( f )));
oos.writeObject( fld );
oos.writeObject( rule);
oos.close();
}
private Pair<SimpleMapField, TotalisticRule> loadFieldData( File f ) throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream(new GZIPInputStream(new FileInputStream( f )));
Object o = ois.readObject();
Object rule = ois.readObject();
ois.close();
try{
return new Pair<SimpleMapField, TotalisticRule>( (SimpleMapField)o, (TotalisticRule) rule );
}catch(ClassCastException e){
throw new IOException("File has wrong format");
}
}
private void ensureSaveFileChooser(){
if (fieldFileChooser != null ) return;
fieldFileChooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("Gzipped serialized Java object (*.sgz)", "sgz");
fieldFileChooser.addChoosableFileFilter(filter);
fieldFileChooser.setFileFilter( filter );
}
private void doSaveField(){
ensureSaveFileChooser();
if (fieldFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fieldFileChooser.getSelectedFile();
if ( ! file.getName().contains("."))
file = new File( file.getParentFile(), file.getName()+".sgz");
try {
saveFieldData(file, world);
} catch (Exception err) {
JOptionPane.showMessageDialog(this, err.getMessage(), "Error writing file", JOptionPane.ERROR_MESSAGE);
}
}
}
private void doLoadField(){
ensureSaveFileChooser();
if ( fieldFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fieldFileChooser.getSelectedFile();
try {
Pair<SimpleMapField, TotalisticRule> world_rule= loadFieldData(file);
setWorld( world_rule.left );
setRule( world_rule.right );
} catch (Exception err) {
JOptionPane.showMessageDialog(this, err.getMessage(), "Can not load file", JOptionPane.ERROR_MESSAGE);
}
}
}
private void setWorld(SimpleMapField newWorld) {
assert newWorld != null;
stopEvaluation();
world = newWorld;
panel.setField( newWorld );
updateFieldInfo();
}
}
|
package org.snow.window.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.snow.util.Displays;
public class AboutDialog extends Dialog {
public static final int WIDTH = 450;
public static final int HEIGHT = 250;
private final Display display;
private final String title;
private final Image image;
private final String version;
private String website = null;;
private String text = null;
private boolean showCloseButton = false;
private Color color = null;
public AboutDialog( final Shell shell, final String title, final String image, final String version ) {
super( shell );
this.display = shell.getDisplay();
this.title = title;
this.image = new Image( display, image );
this.version = version;
}
public void setWebsite( final String website ) {
this.website = website;
}
public void setText( final String text ) {
this.text = text;
}
public void showCloseButton() {
showCloseButton = true;
}
public void setTextColor( final Color color ) {
this.color = color;
}
public void open() {
final Shell shell = new Shell( getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL );
shell.setText( title );
shell.setSize( WIDTH, HEIGHT );
//shell.setSize( image.getImageData().width, image.getImageData().height );
shell.setBackgroundImage(image);
shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
shell.setLayout( new FormLayout() );
final Label aboutVersion = new Label( shell, SWT.NONE );
final Font font = Displays.getSystemFontBold( display );
aboutVersion.setFont( font );
aboutVersion.setText( version );
if( color != null )
aboutVersion.setForeground( color );
final FormData versionData = new FormData();
versionData.top = new FormAttachment( 0, 70 );
versionData.left = new FormAttachment( 0, 133 );
aboutVersion.setLayoutData( versionData );
if( website != null && ! website.equals( "" ) ) {
final Label aboutWebsite = new Label( shell, SWT.NONE );
aboutWebsite.setText( website );
if( color != null )
aboutWebsite.setForeground( color );
final FormData websiteData = new FormData();
websiteData.top = new FormAttachment( 0, 92 );
websiteData.left = new FormAttachment( 0, 133 );
aboutWebsite.setLayoutData( websiteData );
}
if( text != null && ! text.equals( "" ) ) {
final Label aboutText = new Label( shell, SWT.NONE );
aboutText.setText( text );
if( color != null )
aboutText.setForeground( color );
final FormData textData = new FormData();
textData.top = new FormAttachment( 100, -75 );
textData.bottom = new FormAttachment( 100, -10 );
textData.left = new FormAttachment( 0, 12 );
textData.right = new FormAttachment( showCloseButton ? 76 : 100, -12 );
aboutText.setLayoutData( textData );
}
if( showCloseButton ) {
final Button button = new Button( shell, SWT.PUSH );
button.setText( "Close" );
button.setSize( 60, 25 );
final FormData buttonData = new FormData();
buttonData.left = new FormAttachment( 76, 0 );
buttonData.right = new FormAttachment( 100, -5 );
buttonData.bottom = new FormAttachment( 100, -5 );
button.setLayoutData( buttonData );
button.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
shell.close();
}
} );
}
/** add dispose listener */
shell.addDisposeListener( new DisposeListener() {
public void widgetDisposed( DisposeEvent e ) {
if( image != null && !image.isDisposed() )
image.dispose();
if( font != null && !font.isDisposed() )
font.dispose();
}
} );
/** open shell */
shell.setLocation( Displays.getDisplayCenter( display, shell.getBounds() ) );
shell.open();
while( ! shell.isDisposed() )
if( !display.readAndDispatch() )
display.sleep();
}
}
|
package pitt.search.semanticvectors;
import java.io.IOException;
import java.lang.IllegalArgumentException;
import java.util.LinkedList;
/**
* Command line term vector search utility.
*/
public class Search {
/**
* List of different types of searches that can be performed. Most
* involve processing combinations of vectors in different ways, in
* building a query expression, scoring candidates against these
* query expressions, or both. Most options here correspond directly
* to a particular subclass of <code>VectorSearcher</code>
* @see VectorSearcher
*/
public enum SearchType {
/**
* Default option - build a query by adding together (weighted)
* vectors for each of the query terms, and search using cosine
* similarity.
* @see VectorSearcher.VectorSearcherCosine
*/
SUM,
/**
* Build a query as with <code>SUM</code> option, but quantize to
* sparse vectors before taking scalar product at search time.
* This can be used to give a guide to how much smilarities are
* changed by only using the most significant coordinates of a
* vector.
* @see VectorSearcher.VectorSearcherCosineSparse
*/
SPARSESUM,
/**
* "Quantum disjunction" - get vectors for each query term, create a
* representation for the subspace spanned by these vectors, and
* score by measuring cosine similarity with this subspace.
* @see VectorSearcher.VectorSearcherSubspaceSim
*/
SUBSPACE,
/**
* "Closest disjunction" - get vectors for each query term, score
* by measuring distance to each term and taking the minimum.
* @see VectorSearcher.VectorSearcherMaxSim
*/
MAXSIM,
/**
* A product similarity that trains by taking ordered pairs of
* terms, a target query term, and searches for the term whose tensor
* product with the target term gives the largest similarity with training tensor.
* @see VectorSearcher.VectorSearcherTensorSim
*/
TENSOR,
/**
* Similar to <code>TENSOR</code>, product similarity that trains
* by taking ordered pairs of terms, a target query term, and
* searches for the term whose convolution product with the target
* term gives the largest similarity with training convolution.
* @see VectorSearcher.VectorSearcherConvolutionSim
*/
CONVOLUTION,
/**
* Based on Sahlgren (2008). Searches for the term that best matches
* the position of a "?" in a sequence of terms. For example
* 'martin ? king' should retrieve luther as the top ranked match
* requires the index queried to contain unpermuted vectors, either
* random vectors (or term vectors if these were used to build permuted
* vectors - not yet implemented), and the index searched must contain
* permuted vectors
**/
PERMUTATION,
/**
* Build an additive query vector (as with <code>SUM</code> and
* print out the query vector for debugging.
*/
PRINTQUERY }
// Experimenting with class-level static variables to enable several
// methods to use this state. Initialize each with default values.
static String queryFile = "termvectors.bin";
static String searchFile = "";
static String lucenePath = null;
static VectorStore queryVecReader, searchVecReader;
static boolean textIndex = false;
static LuceneUtils lUtils = null;
static int numResults;
static SearchType searchType = SearchType.SUM;
/**
* Prints the following usage message:
* <code>
* <br> Search class in package pitt.search.semanticvectors
* <br> Usage: java pitt.search.semanticvectors.Search [-q query_vector_file]
* <br> [-s search_vector_file]
* <br> [-l path_to_lucene_index]
* <br> [-searchtype TYPE]
* <br> [-results num_results]
* <br> <QUERYTERMS>
* <br> If no query or search file is given, default will be
* <br> termvectors.bin in local directory.
* <br> -l argument my be used to get term weights from
* <br> term frequency, doc frequency, etc. in lucene index.
* <br> -searchtype can be one of SUM, SPARSESUM, SUBSPACE, MAXSIM,
* <br> TENSOR, CONVOLUTION, PRINTQUERY
* <br> <QUERYTERMS> should be a list of words, separated by spaces.
* <br> If the term NOT is used, terms after that will be negated.
* </code>
*/
public static void usage() {
String usageMessage = "\nSearch class in package pitt.search.semanticvectors"
+ "\nUsage: java pitt.search.semanticvectors.Search [-q query_vector_file]"
+ "\n [-s search_vector_file]"
+ "\n [-l path_to_lucene_index]"
+ "\n [-searchtype TYPE]"
+ "\n [-results num_results]"
+ "\n <QUERYTERMS>"
+ "\n-q argument must precede -s argument if they differ;"
+ "\n otherwise -s will default to -q."
+ "\nIf no query or search file is given, default will be"
+ "\n termvectors.bin in local directory."
+ "\n-l argument is needed if to get term weights from"
+ "\n term frequency, doc frequency, etc. in lucene index."
+ "\n-searchtype can be one of SUM, SPARSESUM, SUBSPACE, MAXSIM,"
+ "\n TENSOR, CONVOLUTION, PRINTQUERY"
+ "\n<QUERYTERMS> should be a list of words, separated by spaces."
+ "\n If the term NOT is used, terms after that will be negated.";
System.out.println(usageMessage);
}
/**
* Takes a user's query, creates a query vector, and searches a vector store.
* @param args See usage();
* @param numResults Number of search results to be returned in a ranked list.
* @return Linked list containing <code>numResults</code> search results.
*/
public static LinkedList<SearchResult> RunSearch (String[] args, int numResults)
throws IllegalArgumentException, ZeroVectorException {
/**
* The RunSearch function has four main stages:
* i. Parse command line arguments.
* ii. Open corresponding vector and lucene indexes.
* iii. Based on search type, build query vector and perform search.
* iv. Return LinkedList of results, usually for main() to print out.
*
* Stage iii. is a large switch statement, that depends on the searchType.
*
* The code would be nicer if we combined stages i. and ii., but
* this would be hard to implement without forcing the user to use
* command line arguments in a fixed order, which would definitely
* lead to errors. So the trade-off is to make the code more
* complex and the usage simpler.
*/
// This will become overwritten if -results is passed in as a command line argument!
numResults = numResults;
if (args.length == 0) {
usage();
}
int argc = 0;
// Lower case all arguments: this is standard policy for
// now. Please don't write internal code that depends on this
// assumption, in case we want to change this. Fixes issue 4,
// though there could be better solutions. DW, version 1.7.
if (true) { // Wanted this to be easily removed.
for (int i = 0; i < args.length; ++i) {
if (!args[i].equals(args[i].toLowerCase())) {
System.err.println("Lowercasing term: " + args[i]);
args[i] = args[i].toLowerCase();
}
}
}
// Stage i. Parse all the command-line arguments.
while (args[argc].substring(0, 1).equals("-")) {
// If the args list is now too short, this is an error.
if (args.length - argc <= 2) {
usage();
throw new IllegalArgumentException();
}
if (args[argc].equals("-q")) {
queryFile = args[argc + 1];
argc += 2;
}
else if (args[argc].equals("-s")) {
searchFile = args[argc + 1];
argc += 2;
}
else if (args[argc].equals("-l")) {
lucenePath = args[argc + 1];
argc += 2;
}
else if (args[argc].equals("-results")) {
numResults = Integer.parseInt(args[argc + 1]);
argc += 2;
}
else if (args[argc].equals("-textindex")) {
textIndex = true;
argc += 1;
}
// The most complicated option is the search type: this will
// lead to the most complex implementational differences later.
// It would be nice if this behavior could be generated
// automatically from the entries in the enum.
else if (args[argc].equals("-searchtype")) {
String searchTypeString = args[argc + 1];
searchTypeString = searchTypeString.toLowerCase();
if (searchTypeString.equals("sum")) {
searchType = SearchType.SUM;
}
else if (searchTypeString.equals("sparsesum")) {
searchType = SearchType.SPARSESUM;
}
else if (searchTypeString.equals("subspace")) {
searchType = SearchType.SUBSPACE;
}
else if (searchTypeString.equals("maxsim")) {
searchType = SearchType.MAXSIM;
}
else if (searchTypeString.equals("subspace")) {
searchType = SearchType.SUBSPACE;
}
else if (searchTypeString.equals("tensor")) {
searchType = SearchType.TENSOR;
}
else if (searchTypeString.equals("convolution")) {
searchType = SearchType.CONVOLUTION;
}else if (searchTypeString.equals("permutation")) {
searchType = SearchType.PERMUTATION;
}
else if (searchTypeString.equals("printquery")) {
searchType = SearchType.PRINTQUERY;
}
// Unrecognized search type.
else {
System.err.println("Unrecognized -searchtype: " + args[argc + 1]);
System.err.print("Options are: ");
for (SearchType option : SearchType.values()) {
System.out.print(option + ", ");
}
System.out.println();
usage();
throw new IllegalArgumentException();
}
argc += 2;
}
// Unrecognized command line option.
else {
System.err.println("The following option is not recognized: " + args[argc]);
usage();
throw new IllegalArgumentException("Failed to recognize command line arguments.");
}
}
// If searchFile wasn't set, it defaults to queryFile.
if (searchFile.equals("")) {
searchFile = queryFile;
}
// Stage ii. Open vector stores, and Lucene utils.
try {
// Default VectorStore implementation is (Lucene) VectorStoreReader.
System.err.println("Opening query vector store from file: " + queryFile);
if (textIndex) { queryVecReader = new VectorStoreReaderText(queryFile); }
else { queryVecReader = new VectorStoreReader(queryFile); }
// Open second vector store if search vectors are different from query vectors.
if (queryFile == searchFile) {
searchVecReader = queryVecReader;
} else {
System.err.println("Opening search vector store from file: " + searchFile);
if (textIndex) { searchVecReader = new VectorStoreReaderText(searchFile); }
else { searchVecReader = new VectorStoreReader(searchFile); }
}
if (lucenePath != null) {
try { lUtils = new LuceneUtils(lucenePath); }
catch (IOException e) {
System.err.println("Couldn't open Lucene index at " + lucenePath);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
// This takes the slice of args from argc to end.
String queryTerms[] = new String[args.length - argc];
for (int j = 0; j < args.length - argc; ++j) {
queryTerms[j] = args[j + argc];
}
VectorSearcher vecSearcher;
LinkedList<SearchResult> results = new LinkedList();
// Stage iii. Perform search according to which searchType was selected.
// Most options have corresponding dedicated VectorSearcher subclasses.
switch(searchType) {
// Simplest option, vector sum for composition, with possible negation.
case SUM:
// Create VectorSearcher and search for nearest neighbors.
try {
vecSearcher =
new VectorSearcher.VectorSearcherCosine(queryVecReader,
searchVecReader,
lUtils,
queryTerms);
System.err.print("Searching term vectors, searchtype SUM ... ");
results = vecSearcher.getNearestNeighbors(numResults);
} catch (ZeroVectorException zve) {
System.err.println(zve.getMessage());
results = new LinkedList<SearchResult>();
}
break;
// Option for quantizing to sparse vectors before
// comparing. This is for experimental purposes to see how much
// we lose by compressing to a sparse bit vector.
case SPARSESUM:
// Create VectorSearcher and search for nearest neighbors.
try {
vecSearcher =
new VectorSearcher.VectorSearcherCosineSparse(queryVecReader,
searchVecReader,
lUtils,
queryTerms);
System.err.print("Searching term vectors, searchtype SPARSESUM ... ");
results = vecSearcher.getNearestNeighbors(numResults);
} catch (ZeroVectorException zve) {
System.err.println(zve.getMessage());
results = new LinkedList<SearchResult>();
}
break;
// Tensor product.
case TENSOR:
// Create VectorSearcher and search for nearest neighbors.
try {
vecSearcher =
new VectorSearcher.VectorSearcherTensorSim(queryVecReader,
searchVecReader,
lUtils,
queryTerms);
System.err.print("Searching term vectors, searchtype TENSOR ... ");
results = vecSearcher.getNearestNeighbors(numResults);
} catch (ZeroVectorException zve) {
System.err.println(zve.getMessage());
results = new LinkedList<SearchResult>();
}
break;
// Convolution product.
case CONVOLUTION:
// Create VectorSearcher and search for nearest neighbors.
try {
vecSearcher =
new VectorSearcher.VectorSearcherConvolutionSim(queryVecReader,
searchVecReader,
lUtils,
queryTerms);
System.err.print("Searching term vectors, searchtype CONVOLUTION ... ");
results = vecSearcher.getNearestNeighbors(numResults);
} catch (ZeroVectorException zve) {
System.err.println(zve.getMessage());
results = new LinkedList<SearchResult>();
}
break;
// Quantum disjunction / subspace similarity.
case SUBSPACE:
// Create VectorSearcher and search for nearest neighbors.
vecSearcher =
new VectorSearcher.VectorSearcherSubspaceSim(queryVecReader,
searchVecReader,
lUtils,
queryTerms);
System.err.print("Searching term vectors, searchtype SUBSPACE ... ");
results = vecSearcher.getNearestNeighbors(numResults);
break;
// Ranks by maximum similarity with any of the query terms.
case MAXSIM:
// Create VectorSearcher and search for nearest neighbors.
vecSearcher =
new VectorSearcher.VectorSearcherMaxSim(queryVecReader,
searchVecReader,
lUtils,
queryTerms);
System.err.print("Searching term vectors, searchtype MAXSIM ... ");
results = vecSearcher.getNearestNeighbors(numResults);
break;
// Permutes query vectors such that the most likely term in the position
// of the "?" is retrieved
case PERMUTATION:
try {
// Create VectorSearcher and search for nearest neighbors.
vecSearcher =
new VectorSearcher.VectorSearcherPerm(queryVecReader,searchVecReader,lUtils,queryTerms);
System.err.print("Searching term vectors, searchtype PERMUTATION ... ");
results = vecSearcher.getNearestNeighbors(numResults);
break;
} catch (IllegalArgumentException e) {
throw e;
}
// Simply prints out the query vector: doesn't do any searching.
case PRINTQUERY:
float[] queryVector = CompoundVectorBuilder.getQueryVector(queryVecReader,
lUtils,
queryTerms);
VectorUtils.printVector(queryVector);
return null;
default:
System.err.println("Search type unrecognized ...");
results = new LinkedList();
}
return results;
}
/**
* Search wrapper that returns the list of ObjectVectors.
*/
public static ObjectVector[] getSearchResultVectors(String[] args, int numResults)
throws IllegalArgumentException, ZeroVectorException {
LinkedList<SearchResult> results = Search.RunSearch(args, numResults);
ObjectVector[] resultsList = new ObjectVector[results.size()];
for (int i = 0; i < results.size(); ++i) {
String term = ((ObjectVector)results.get(i).getObject()).getObject().toString();
float[] tmpVector = searchVecReader.getVector(term);
resultsList[i] = new ObjectVector(term, tmpVector);
}
return resultsList;
}
/**
* Takes a user's query, creates a query vector, and searches a vector store.
* @param args See usage();
*/
public static void main (String[] args)
throws IllegalArgumentException, ZeroVectorException {
int defaultNumResults = 20;
LinkedList<SearchResult> results = RunSearch(args, defaultNumResults);
// Print out results.
System.err.println("Search output follows ...");
for (SearchResult result: results) {
System.out.println(result.getScore() + ":" +
((ObjectVector)result.getObject()).getObject().toString());
}
}
}
|
package pl.ijestfajnie.circles;
import javax.swing.JFrame;
public class CirclesUnit extends JFrame {
private int currentPointer = 0;
private final String[] cartridge;
private byte[] memory;
private byte[] screenmemory;
public CirclesUnit(String[] cartridge) {
memory = new byte[16];
for (byte bt: memory) {
bt = 0;
}
screenmemory = new byte[16];
for (byte bt: screenmemory) {
bt = 0;
}
this.cartridge = cartridge;
for (; currentPointer < cartridge.length; currentPointer++) {
parse();
}
}
public void parse() {
switch (cartridge[currentPointer]) {
case CircleCommands.CMD_ADD:
int toadd = Integer.parseInt("0b" + cartridge[++currentPointer]);
int pointer1 = Integer.parseInt("0b" + ++currentPointer);
memory[pointer1] += toadd;
break;
case CircleCommands.CMD_SUB:
int tosub = Integer.parseInt("0b" + cartridge[++currentPointer]);
int pointer2 = Integer.parseInt("0b" + ++currentPointer);
memory[pointer2] -= tosub;
break;
case CircleCommands.CMD_SET:
int toset = Integer.parseInt("0b" + cartridge[++currentPointer]);
int pointer3 = Integer.parseInt("0b" + ++currentPointer);
memory[pointer3] = (byte) toset;
break;
case CircleCommands.CMD_SAD:
int tosad = Integer.parseInt("0b" + cartridge[++currentPointer]);
int pointer4 = Integer.parseInt("0b" + ++currentPointer);
memory[pointer4] += tosad;
break;
case CircleCommands.CMD_SSU:
int tossu = Integer.parseInt("0b" + cartridge[++currentPointer]);
int pointer5 = Integer.parseInt("0b" + ++currentPointer);
memory[pointer5] -= tossu;
break;
case CircleCommands.CMD_SST:
int tosst = Integer.parseInt("0b" + cartridge[++currentPointer]);
int pointer6 = Integer.parseInt("0b" + ++currentPointer);
memory[pointer6] = (byte) tosst;
break;
case CircleCommands.CMD_FWD:
int tofwd = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer += tofwd;
break;
case CircleCommands.CMD_BCK:
int tobck = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer -= tobck;
break;
case CircleCommands.CMD_CHK:
int chktype = Integer.parseInt("0b" + cartridge[++currentPointer]);
int onecell = Integer.parseInt("0b" + cartridge[++currentPointer]);
int onevalu = memory[onecell];
int twocell = Integer.parseInt("0b" + cartridge[++currentPointer]);
int twovalu = memory[twocell];
if (chktype == Integer.parseInt("0b" + CircleCommands.ConditionType.CND_EQL)) {
if (onevalu == twovalu) {
currentPointer++;
} else {
int toskip = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer += toskip;
}
} else if (chktype == Integer.parseInt("0b" + CircleCommands.ConditionType.CND_MOR)) {
if (onevalu > twovalu) {
currentPointer++;
} else {
int toskip = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer += toskip;
}
} else if (chktype == Integer.parseInt("0b" + CircleCommands.ConditionType.CND_LES)) {
if (onevalu < twovalu) {
currentPointer++;
} else {
int toskip = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer += toskip;
}
} else if (chktype == Integer.parseInt("0b" + CircleCommands.ConditionType.CND_MOE)) {
if (onevalu >= twovalu) {
currentPointer++;
} else {
int toskip = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer += toskip;
}
} else if (chktype == Integer.parseInt("0b" + CircleCommands.ConditionType.CND_LOE)) {
if (onevalu <= twovalu) {
currentPointer++;
} else {
int toskip = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer += toskip;
}
} else if (chktype == Integer.parseInt("0b" + CircleCommands.ConditionType.CND_NOT)) {
if (onevalu != twovalu) {
currentPointer++;
} else {
int toskip = Integer.parseInt("0b" + cartridge[++currentPointer]);
currentPointer += toskip;
}
}
break;
default:
System.exit(4);
break;
}
}
}
|
package rapanui.dsl;
import java.io.StringReader;
import javax.inject.Inject;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.parser.IParser;
import rapanui.dsl.services.DslGrammarAccess;
public class Parser {
private static final Parser instance = new Parser();
public static Parser getInstance() {
return instance;
}
@Inject
private IParser internalParser;
@Inject
private DslGrammarAccess grammar;
private Parser() {
new DslStandaloneSetup()
.createInjectorAndDoEMFRegistration()
.injectMembers(this);
}
public RuleSystem parseRuleSystem(String input) {
return (RuleSystem)parse(input, grammar.getRuleSystemRule());
}
public Formula parseFormula(String input) {
return (Formula)parse(input, grammar.getFormulaRule());
}
public Term parseTerm(String input) {
return (Term)parse(input, grammar.getTermRule());
}
private EObject parse(String input, ParserRule rule) {
IParseResult result = internalParser.parse(rule, new StringReader(input));
if (result.hasSyntaxErrors()) {
for (INode node : result.getSyntaxErrors())
throw new IllegalArgumentException("Parsing error: "
+ node.getSyntaxErrorMessage().getMessage());
}
return result.getRootASTElement();
}
public boolean canParseRuleSystem(String input) {
return canParse(input, grammar.getRuleSystemRule());
}
public boolean canParseFormula(String input) {
return canParse(input, grammar.getFormulaRule());
}
public boolean canParseTerm(String input) {
return canParse(input, grammar.getTermRule());
}
private boolean canParse(String input, ParserRule rule) {
IParseResult result = internalParser.parse(rule, new StringReader(input));
return !result.hasSyntaxErrors();
}
}
|
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.scene.control.Button;
import javafx.geometry.Pos;
public class SudokuGUI extends BorderPane {
public SudokuGUI() {
drawGUI();
}
private void drawGUI() {
Text tMessage = new Text();
SudokuPane sPane = new SudokuPane();
Button btSolve = new Button("Solve");
Button btClear = new Button("Clear");
btSolve.setOnAction(e -> solve(sPane, tMessage, btSolve));
btClear.setOnAction(e -> clear(sPane, tMessage, btSolve));
HBox hbControl = new HBox(10);
hbControl.getChildren().addAll(btSolve, btClear);
hbControl.setAlignment(Pos.CENTER);
setTop(tMessage);
setCenter(sPane);
setBottom(hbControl);
setAlignment(tMessage, Pos.CENTER);
}
private void solve(SudokuPane sPane, Text tMessage, Button btSolve) {
try {
if (!sPane.solve()) {
tMessage.setText("Only 1-9 or empty spaces allowed");
} else {
btSolve.setDisable(true);
}
} catch (IllegalArgumentException ex) {
tMessage.setText("Invalid Sudoku Grid");
}
}
private void clear(SudokuPane sPane, Text tMessage, Button btSolve) {
sPane.clear();
tMessage.setText("");
btSolve.setDisable(false);
}
}
|
package protocolsupport.utils.netty;
import java.util.Arrays;
import java.util.zip.Deflater;
import io.netty.util.Recycler;
import io.netty.util.Recycler.Handle;
import protocolsupport.ProtocolSupport;
import protocolsupport.utils.Utils;
import protocolsupport.utils.Utils.Converter;
public class Compressor {
public static void init() {
ProtocolSupport.logInfo("Compression level: "+compressionLevel);
}
private static final int compressionLevel = Utils.getJavaPropertyValue("protocolsupport.compressionlevel", 3, Converter.STRING_TO_INT);
private static final Recycler<Compressor> recycler = new Recycler<Compressor>() {
@Override
protected Compressor newObject(Handle handle) {
return new Compressor(handle);
}
};
public static Compressor create() {
return recycler.get();
}
private final Deflater deflater = new Deflater(compressionLevel);
private final Handle handle;
protected Compressor(Handle handle) {
this.handle = handle;
}
public byte[] compress(byte[] input) {
deflater.setInput(input);
deflater.finish();
byte[] compressedBuf = new byte[input.length * 11 / 10 + 6];
int size = deflater.deflate(compressedBuf);
deflater.reset();
return Arrays.copyOf(compressedBuf, size);
}
public void recycle() {
recycler.recycle(this, handle);
}
public static byte[] compressStatic(byte[] input) {
Compressor compressor = create();
try {
return compressor.compress(input);
} finally {
compressor.recycle();
}
}
}
|
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import org.apache.commons.math3.analysis.MultivariateFunction;
import org.apache.commons.math3.optim.InitialGuess;
import org.apache.commons.math3.optim.MaxEval;
import org.apache.commons.math3.optim.PointValuePair;
import org.apache.commons.math3.optim.nonlinear.scalar.GoalType;
import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction;
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.MultiDirectionalSimplex;
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
public class ZigDetector {
public static void main(String[] args) throws Exception {
// declare which scenario we're running
final String SCENARIO = "Scen2";
// load the data
Track ownshipTrack = new Track("data/" + SCENARIO +"_Ownship.csv");
Track targetTrack = new Track("data/" + SCENARIO +"_Target.csv");
Sensor sensor = new Sensor("data/" + SCENARIO +"_Sensor.csv");
// create a holder for the data
final JFrame frame = createFrame();
// Now, we have to slice the data into ownship legs
List<LegOfData> ownshipLegs = calculateLegs(ownshipTrack);
// create the combined plot - where we show all our data
CombinedDomainXYPlot combinedPlot = Plotting.createPlot();
// ok create the plots of ownship & target tracks
Plotting.addOwnshipData(combinedPlot, "O/S ", ownshipTrack, ownshipLegs, null);
// capture the start time (used for time elapsed at the end)
long startTime = System.currentTimeMillis();
// get ready to store the results runs
TimeSeriesCollection legResults = new TimeSeriesCollection();
List<Long> valueMarkers = new ArrayList<Long>();
// ok, work through the legs. In the absence of a Discrete Optimisation algorithm we're taking a brue force approach.
// Hopefully Craig can find an optimised alternative to this.
for (Iterator<LegOfData> iterator = ownshipLegs.iterator(); iterator.hasNext();) {
LegOfData thisLeg = (LegOfData) iterator.next();
// ok, slice the data for this leg
List<Double> bearings = sensor.extractBearings(thisLeg.getStart(), thisLeg.getEnd());
List<Long> times = sensor.extractTimes(thisLeg.getStart(), thisLeg.getEnd());
// find the error score for the overall leg
MultivariateFunction wholeLeg = new ArcTanSolver(times, bearings);
SimplexOptimizer wholeOptimizer = new SimplexOptimizer(1e-3, 1e-6);
int MAX_ITERATIONS = Integer.MAX_VALUE;
// calculate the overall score for this leg
PointValuePair wholeLegOptimiser = wholeOptimizer.optimize(
new MaxEval(MAX_ITERATIONS),
new ObjectiveFunction(wholeLeg),
GoalType.MINIMIZE,
new InitialGuess(new double[] {bearings.get(0), 1, 1} ),//beforeBearings.get(0)
new MultiDirectionalSimplex(3));
// look at the individual scores (though they're not of interest)
// double[] key = wholeLegOptimiser.getKey();
// System.out.println("B:" + key[0] + " P:" + key[1] + " Q:" + key[2]);
// we will try to beat this score, so set as very high number
double bestScore = Double.MAX_VALUE;
int bestIndex = -1;
Double overallScore = wholeLegOptimiser.getValue();
final int BUFFER_REGION = 4; // the number of measurements to ignore whilst the target is turning
// how many points in this leg?
int thisLegSize = times.size();
int startIndex = 1 + BUFFER_REGION / 2;
int endIndex = thisLegSize -1 - BUFFER_REGION / 2;
// create a placeholder for the overall score for this leg
TimeSeries straightBar = new TimeSeries("Whole " + thisLeg.getName(), FixedMillisecond.class);
legResults.addSeries(straightBar);
// create a placeholder for the individual time slice experiments
TimeSeries thisSeries = new TimeSeries(thisLeg.getName(), FixedMillisecond.class);
legResults.addSeries(thisSeries);
// loop through the values in this leg
// NOTE: this is a brute force algorithm - maybe we can find a Discrete Optimisation equivalent
for(int index=startIndex;index<endIndex;index++)
{
// what's the total score for slicing at this index?
double sum = sliceLeg(index, bearings, times, MAX_ITERATIONS,
BUFFER_REGION);
thisSeries.add(new FixedMillisecond(times.get(index)), sum);
straightBar.add(new FixedMillisecond(times.get(index)), overallScore);
// is this better?
if(sum < bestScore)
{
// yes - store it.
bestScore = sum;
bestIndex = index;
}
}
valueMarkers.add(times.get(bestIndex));
}
// ok, also plot the leg attempts
Plotting.addLegResults(combinedPlot, legResults, valueMarkers);
// show the target track (it contains the results)
Plotting.addOwnshipData(combinedPlot, "Tgt ", targetTrack, null, valueMarkers);
// wrap the combined chart
ChartPanel cp = new ChartPanel(new JFreeChart("Results for " + SCENARIO,
JFreeChart.DEFAULT_TITLE_FONT, combinedPlot, true)){
private static final long serialVersionUID = 1L;
@Override
@Transient
public Dimension getPreferredSize() {
return new Dimension(1000,800);
}
};
frame.add(cp);
frame.pack();
long elapsed = System.currentTimeMillis() - startTime;
System.out.println("Elapsed:" + elapsed / 1000 + " secs");
}
/**
* @return a frame to contain the results
*/
private static JFrame createFrame() {
JFrame frame = new JFrame("Results");
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
}
});
return frame;
}
/**
* @param trialIndex
* @param bearings
* @param times
* @param MAX_ITERATIONS
* @param overallScore the overall score for this leg
* @param BUFFER_REGION
* @param straightBar
* @param thisSeries
* @return
*/
private static double sliceLeg(int trialIndex, List<Double> bearings,
List<Long> times, int MAX_ITERATIONS,
final int BUFFER_REGION) {
List<Long> theseTimes = times;
List<Double> theseBearings = bearings;
// first the times
List<Long> beforeTimes = theseTimes.subList(0, trialIndex - BUFFER_REGION / 2);
List<Long> afterTimes = theseTimes.subList(trialIndex + BUFFER_REGION / 2, theseTimes.size()-1);
// now the bearings
List<Double> beforeBearings = theseBearings.subList(0, trialIndex);
List<Double> afterBearings = theseBearings.subList(trialIndex, theseBearings.size()-1);
MultivariateFunction beforeF = new ArcTanSolver(beforeTimes, beforeBearings);
MultivariateFunction afterF = new ArcTanSolver(afterTimes, afterBearings);
SimplexOptimizer optimizerMult = new SimplexOptimizer(1e-3, 1e-6);
// fit a curve to the period before the turn
PointValuePair beforeOptimiser = optimizerMult.optimize(
new MaxEval(MAX_ITERATIONS),
new ObjectiveFunction(beforeF),
GoalType.MINIMIZE,
new InitialGuess(new double[] {beforeBearings.get(0), 1, 1} ),//beforeBearings.get(0)
new MultiDirectionalSimplex(3));
// fit a curve to the period after the turn
PointValuePair afterOptimiser = optimizerMult.optimize(
new MaxEval(MAX_ITERATIONS),
new ObjectiveFunction(afterF),
GoalType.MINIMIZE,
new InitialGuess(new double[] {afterBearings.get(0), 1, 1} ),//afterBearings.get(0)
new MultiDirectionalSimplex(3));
// find the total error sum
double sum = beforeOptimiser.getValue() + afterOptimiser.getValue();
return sum;
}
/** slice this data into ownship legs, where the course and speed are relatively steady
*
* @param course_degs
* @param speed
* @param bearings
* @param elapsedTimes
* @return
*/
private static List<LegOfData> calculateLegs(Track track) {
final double COURSE_TOLERANCE = 0.1; // degs / sec (just a guess!!)
final double SPEED_TOLERANCE = 2; // knots / sec (just a guess!!)
double lastCourse = 0;
double lastSpeed = 0;
long lastTime = 0;
List<LegOfData> legs = new ArrayList<LegOfData>();
legs.add(new LegOfData("Leg-1"));
long[] times = track.getDates();
double[] speeds = track.getSpeeds();
double[] courses = track.getCourses();
for (int i = 0; i < times.length; i++) {
long thisTime = times[i];
double thisSpeed = speeds[i];
double thisCourse = courses[i];
if(i > 0)
{
// ok, check out the course change rate
double timeStepSecs = (thisTime - lastTime)/1000;
double courseRate = Math.abs(thisCourse - lastCourse) / timeStepSecs;
double speedRate = Math.abs(thisSpeed - lastSpeed) / timeStepSecs;
// are they out of range
if((courseRate < COURSE_TOLERANCE) && (speedRate < SPEED_TOLERANCE))
{
// ok, we're on a new leg - drop the current one
legs.get(legs.size()-1).add(thisTime);
}
else
{
// we may be in a turn. create a new leg, if we haven't done so already
if(legs.get(legs.size()-1).size() != 0)
{
legs.add(new LegOfData("Leg-" + (legs.size()+1)));
}
}
}
// ok, store the values
lastTime = thisTime;
lastCourse = thisCourse;
lastSpeed = thisSpeed;
}
return legs;
}
/** function to generate sum of squares of errors for a single permutation of B,P,Q
*
*/
private static class ArcTanSolver implements MultivariateFunction
{
final private List<Long> _times;
final private List<Double> _bearings;
public ArcTanSolver(List<Long> beforeTimes, List<Double> beforeBearings)
{
_times = beforeTimes;
_bearings = beforeBearings;
}
@Override
public double value(double[] point) {
double B = point[0];
double P = point[1];
double Q = point[2];
double runningSum = 0;
// ok, loop through the data
for (int i = 0; i < _times.size(); i++) {
Long elapsedSecs = _times.get(i);
double thisForecast = calcForecast(B, P, Q, elapsedSecs / 1000d);
Double thisMeasured = _bearings.get(i);
double thisError = Math.pow(thisForecast - thisMeasured, 2);
runningSum += thisError;
}
// System.out.println("B:" + (int)B + " P:" + (int)P + " Q:" + (int)Q + " sum:" + runningSum);
return runningSum;
}
private double calcForecast(double B, double P, double Q,
Double elapsedSecs) {
// return Math.toDegrees(Math.atan2(Math.sin(Math.toRadians(B))+P*elapsedSecs,Math.cos(Math.toRadians(B))+Q*elapsedSecs));
return Math.toDegrees(Math.atan2(Math.cos(Math.toRadians(B))+Q*elapsedSecs, Math.sin(Math.toRadians(B))+P*elapsedSecs));
}
}
}
|
package com.opentok.test;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.opentok.*;
import com.opentok.Archive.OutputMode;
import com.opentok.exception.InvalidArgumentException;
import com.opentok.exception.OpenTokException;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.*;
public class OpenTokTest {
private final String SESSION_CREATE = "/session/create";
private int apiKey = 123456;
private String archivePath = "/v2/project/" + apiKey + "/archive";
private String apiSecret = "1234567890abcdef1234567890abcdef1234567890";
private String apiUrl = "http://localhost:8080";
private OpenTok sdk;
@Rule
public WireMockRule wireMockRule = new WireMockRule(8080);
@Before
public void setUp() throws OpenTokException {
// read system properties for integration testing
int anApiKey = 0;
boolean useMockKey = false;
String anApiKeyProp = System.getProperty("apiKey");
String anApiSecret = System.getProperty("apiSecret");
try {
anApiKey = Integer.parseInt(anApiKeyProp);
} catch (NumberFormatException e) {
useMockKey = true;
}
if (!useMockKey && anApiSecret != null && !anApiSecret.isEmpty()) {
// TODO: figure out when to turn mocking off based on this
apiKey = anApiKey;
apiSecret = anApiSecret;
archivePath = "/v2/project/" + apiKey + "/archive";
}
sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(apiUrl).build();
}
@Test
public void testCreateDefaultSession() throws OpenTokException {
String sessionId = "SESSIONID";
stubFor(post(urlEqualTo(SESSION_CREATE))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," +
"\"partner_id\":\"123456\"," +
"\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," +
"\"media_server_url\":\"\"}]")));
Session session = sdk.createSession();
assertNotNull(session);
assertEquals(apiKey, session.getApiKey());
assertEquals(sessionId, session.getSessionId());
assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode());
assertEquals(ArchiveMode.MANUAL, session.getProperties().archiveMode());
assertNull(session.getProperties().getLocation());
verify(postRequestedFor(urlMatching(SESSION_CREATE))
.withRequestBody(matching(".*p2p.preference=enabled.*"))
.withRequestBody(matching(".*archiveMode=manual.*")));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(SESSION_CREATE)))));
Helpers.verifyUserAgent();
}
@Test
public void testCreateRoutedSession() throws OpenTokException {
String sessionId = "SESSIONID";
stubFor(post(urlEqualTo(SESSION_CREATE))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," +
"\"partner_id\":\"123456\"," +
"\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," +
"\"media_server_url\":\"\"}]")));
SessionProperties properties = new SessionProperties.Builder()
.mediaMode(MediaMode.ROUTED)
.build();
Session session = sdk.createSession(properties);
assertNotNull(session);
assertEquals(apiKey, session.getApiKey());
assertEquals(sessionId, session.getSessionId());
assertEquals(MediaMode.ROUTED, session.getProperties().mediaMode());
assertNull(session.getProperties().getLocation());
verify(postRequestedFor(urlMatching(SESSION_CREATE))
// NOTE: this is a pretty bad way to verify, ideally we can decode the body and then query the object
.withRequestBody(matching(".*p2p.preference=disabled.*")));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(SESSION_CREATE)))));
Helpers.verifyUserAgent();
}
@Test
public void testCreateLocationHintSession() throws OpenTokException {
String sessionId = "SESSIONID";
String locationHint = "12.34.56.78";
stubFor(post(urlEqualTo(SESSION_CREATE))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," +
"\"partner_id\":\"123456\"," +
"\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," +
"\"media_server_url\":\"\"}]")));
SessionProperties properties = new SessionProperties.Builder()
.location(locationHint)
.build();
Session session = sdk.createSession(properties);
assertNotNull(session);
assertEquals(apiKey, session.getApiKey());
assertEquals(sessionId, session.getSessionId());
assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode());
assertEquals(locationHint, session.getProperties().getLocation());
verify(postRequestedFor(urlMatching(SESSION_CREATE))
// TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object
.withRequestBody(matching(".*location="+locationHint+".*")));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(SESSION_CREATE)))));
Helpers.verifyUserAgent();
}
@Test
public void testCreateAlwaysArchivedSession() throws OpenTokException {
String sessionId = "SESSIONID";
String locationHint = "12.34.56.78";
stubFor(post(urlEqualTo(SESSION_CREATE))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," +
"\"partner_id\":\"123456\"," +
"\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," +
"\"media_server_url\":\"\"}]")));
SessionProperties properties = new SessionProperties.Builder()
.archiveMode(ArchiveMode.ALWAYS)
.build();
Session session = sdk.createSession(properties);
assertNotNull(session);
assertEquals(apiKey, session.getApiKey());
assertEquals(sessionId, session.getSessionId());
assertEquals(ArchiveMode.ALWAYS, session.getProperties().archiveMode());
verify(postRequestedFor(urlMatching(SESSION_CREATE))
// TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object
.withRequestBody(matching(".*archiveMode=always.*")));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(SESSION_CREATE)))));
Helpers.verifyUserAgent();
}
@Test(expected = InvalidArgumentException.class)
public void testCreateBadSession() throws OpenTokException {
SessionProperties properties = new SessionProperties.Builder()
.location("NOT A VALID IP")
.build();
}
// This is not part of the API because it would introduce a backwards incompatible change.
// @Test(expected = InvalidArgumentException.class)
// public void testCreateInvalidAlwaysArchivedAndRelayedSession() throws OpenTokException {
// SessionProperties properties = new SessionProperties.Builder()
// .mediaMode(MediaMode.RELAYED)
// .archiveMode(ArchiveMode.ALWAYS)
// .build();
// TODO: test session creation conditions that result in errors
@Test
public void testTokenDefault() throws
OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException,
SignatureException, InvalidKeyException {
int apiKey = 123456;
String apiSecret = "1234567890abcdef1234567890abcdef1234567890";
OpenTok opentok = new OpenTok(apiKey, apiSecret);
String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4";
String token = opentok.generateToken(sessionId);
assertNotNull(token);
assertTrue(Helpers.verifyTokenSignature(token, apiSecret));
Map<String, String> tokenData = Helpers.decodeToken(token);
assertEquals(Integer.toString(apiKey), tokenData.get("partner_id"));
assertNotNull(tokenData.get("create_time"));
assertNotNull(tokenData.get("nonce"));
}
@Test
public void testTokenLayoutClass() throws
OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException,
SignatureException, InvalidKeyException {
int apiKey = 123456;
String apiSecret = "1234567890abcdef1234567890abcdef1234567890";
OpenTok opentok = new OpenTok(apiKey, apiSecret);
String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4";
String token = sdk.generateToken(sessionId, new TokenOptions.Builder()
.initialLayoutClassList(Arrays.asList("full", "focus"))
.build());
assertNotNull(token);
assertTrue(Helpers.verifyTokenSignature(token, apiSecret));
Map<String, String> tokenData = Helpers.decodeToken(token);
assertEquals("full focus", tokenData.get("initial_layout_class_list"));
}
@Test
public void testTokenRoles() throws
OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException,
SignatureException, InvalidKeyException {
int apiKey = 123456;
String apiSecret = "1234567890abcdef1234567890abcdef1234567890";
OpenTok opentok = new OpenTok(apiKey, apiSecret);
String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4";
Role role = Role.SUBSCRIBER;
String defaultToken = opentok.generateToken(sessionId);
String roleToken = sdk.generateToken(sessionId, new TokenOptions.Builder()
.role(role)
.build());
assertNotNull(defaultToken);
assertNotNull(roleToken);
assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret));
assertTrue(Helpers.verifyTokenSignature(roleToken, apiSecret));
Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken);
assertEquals("publisher", defaultTokenData.get("role"));
Map<String, String> roleTokenData = Helpers.decodeToken(roleToken);
assertEquals(role.toString(), roleTokenData.get("role"));
}
@Test
public void testTokenExpireTime() throws
OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException,
UnsupportedEncodingException {
int apiKey = 123456;
String apiSecret = "1234567890abcdef1234567890abcdef1234567890";
String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4";
OpenTok opentok = new OpenTok(apiKey, apiSecret);
long now = System.currentTimeMillis() / 1000L;
long inOneHour = now + (60 * 60);
long inOneDay = now + (60 * 60 * 24);
long inThirtyDays = now + (60 * 60 * 24 * 30);
ArrayList<Exception> exceptions = new ArrayList<Exception>();
String defaultToken = opentok.generateToken(sessionId);
String oneHourToken = opentok.generateToken(sessionId, new TokenOptions.Builder()
.expireTime(inOneHour)
.build());
try {
String earlyExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder()
.expireTime(now - 10)
.build());
} catch (Exception exception) {
exceptions.add(exception);
}
try {
String lateExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder()
.expireTime(inThirtyDays + (60 * 60 * 24) /* 31 days */)
.build());
} catch (Exception exception) {
exceptions.add(exception);
}
assertNotNull(defaultToken);
assertNotNull(oneHourToken);
assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret));
assertTrue(Helpers.verifyTokenSignature(oneHourToken, apiSecret));
Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken);
assertEquals(Long.toString(inOneDay), defaultTokenData.get("expire_time"));
Map<String, String> oneHourTokenData = Helpers.decodeToken(oneHourToken);
assertEquals(Long.toString(inOneHour), oneHourTokenData.get("expire_time"));
assertEquals(2, exceptions.size());
for (Exception e : exceptions) {
assertEquals(InvalidArgumentException.class, e.getClass());
}
}
@Test
public void testTokenConnectionData() throws
OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException,
UnsupportedEncodingException {
int apiKey = 123456;
String apiSecret = "1234567890abcdef1234567890abcdef1234567890";
String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4";
OpenTok opentok = new OpenTok(apiKey, apiSecret);
// purposely contains some exotic characters
String actualData = "{\"name\":\"%foo ç &\"}";
Exception tooLongException = null;
String defaultToken = opentok.generateToken(sessionId);
String dataBearingToken = opentok.generateToken(sessionId, new TokenOptions.Builder()
.data(actualData)
.build());
try {
String dataTooLongToken = opentok.generateToken(sessionId, new TokenOptions.Builder()
.data(StringUtils.repeat("x", 1001))
.build());
} catch (InvalidArgumentException e) {
tooLongException = e;
}
assertNotNull(defaultToken);
assertNotNull(dataBearingToken);
assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret));
assertTrue(Helpers.verifyTokenSignature(dataBearingToken, apiSecret));
Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken);
assertNull(defaultTokenData.get("connection_data"));
Map<String, String> dataBearingTokenData = Helpers.decodeToken(dataBearingToken);
assertEquals(actualData, dataBearingTokenData.get("connection_data"));
assertEquals(InvalidArgumentException.class, tooLongException.getClass());
}
@Test
public void testTokenBadSessionId() throws OpenTokException {
int apiKey = 123456;
String apiSecret = "1234567890abcdef1234567890abcdef1234567890";
OpenTok opentok = new OpenTok(apiKey, apiSecret);
ArrayList<Exception> exceptions = new ArrayList<Exception>();
try {
String nullSessionToken = opentok.generateToken(null);
} catch (Exception e) {
exceptions.add(e);
}
try {
String emptySessionToken = opentok.generateToken("");
} catch (Exception e) {
exceptions.add(e);
}
try {
String invalidSessionToken = opentok.generateToken("NOT A VALID SESSION ID");
} catch (Exception e) {
exceptions.add(e);
}
assertEquals(3, exceptions.size());
for (Exception e : exceptions) {
assertEquals(InvalidArgumentException.class, e.getClass());
}
}
@Test
public void testGetArchive() throws OpenTokException {
String archiveId = "ARCHIVEID";
stubFor(get(urlEqualTo(archivePath + "/" + archiveId))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395187836000,\n" +
" \"duration\" : 62,\n" +
" \"id\" : \"" + archiveId + "\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 8347554,\n" +
" \"status\" : \"available\",\n" +
" \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F" +
archiveId + "%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Si" +
"gnature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" +
" }")));
Archive archive = sdk.getArchive(archiveId);
assertNotNull(archive);
assertEquals(apiKey, archive.getPartnerId());
assertEquals(archiveId, archive.getId());
assertEquals(1395187836000L, archive.getCreatedAt());
assertEquals(62, archive.getDuration());
assertEquals("", archive.getName());
assertEquals("SESSIONID", archive.getSessionId());
assertEquals(8347554, archive.getSize());
assertEquals(Archive.Status.AVAILABLE, archive.getStatus());
assertEquals("http://tokbox.com.archive2.s3.amazonaws.com/123456%2F"+archiveId +"%2Farchive.mp4?Expires=13951" +
"94362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", archive.getUrl());
verify(getRequestedFor(urlMatching(archivePath + "/" + archiveId)));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(getRequestedFor(urlMatching(archivePath + "/" + archiveId)))));
Helpers.verifyUserAgent();
}
// TODO: test get archive failure scenarios
@Test
public void testListArchives() throws OpenTokException {
stubFor(get(urlEqualTo(archivePath))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"count\" : 60,\n" +
" \"items\" : [ {\n" +
" \"createdAt\" : 1395187930000,\n" +
" \"duration\" : 22,\n" +
" \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 2909274,\n" +
" \"status\" : \"available\",\n" +
" \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" +
"a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" +
"LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" +
" }, {\n" +
" \"createdAt\" : 1395187910000,\n" +
" \"duration\" : 14,\n" +
" \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 1952651,\n" +
" \"status\" : \"available\",\n" +
" \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" +
"f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" +
"LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" +
" }, {\n" +
" \"createdAt\" : 1395187836000,\n" +
" \"duration\" : 62,\n" +
" \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 8347554,\n" +
" \"status\" : \"available\",\n" +
" \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" +
"8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" +
"LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" +
" }, {\n" +
" \"createdAt\" : 1395183243000,\n" +
" \"duration\" : 544,\n" +
" \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 78499758,\n" +
" \"status\" : \"available\",\n" +
" \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" +
"1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" +
"LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" +
" }, {\n" +
" \"createdAt\" : 1394396753000,\n" +
" \"duration\" : 24,\n" +
" \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" +
" \"name\" : \"showtime again\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 2227849,\n" +
" \"status\" : \"available\",\n" +
" \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" +
"1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" +
"LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" +
" }, {\n" +
" \"createdAt\" : 1394321113000,\n" +
" \"duration\" : 1294,\n" +
" \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" +
" \"name\" : \"showtime\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 42165242,\n" +
" \"status\" : \"available\",\n" +
" \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" +
"f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" +
"LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" +
" } ]\n" +
" }")));
ArchiveList archives = sdk.listArchives();
assertNotNull(archives);
assertEquals(6, archives.size());
assertEquals(60, archives.getTotalCount());
assertThat(archives.get(0), instanceOf(Archive.class));
assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId());
verify(getRequestedFor(urlMatching(archivePath)));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(getRequestedFor(urlMatching(archivePath)))));
Helpers.verifyUserAgent();
}
// TODO: test list archives with count and offset
// TODO: test list archives failure scenarios
@Test
public void testStartArchive() throws OpenTokException {
String sessionId = "SESSIONID";
stubFor(post(urlEqualTo(archivePath))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395183243556,\n" +
" \"duration\" : 0,\n" +
" \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 0,\n" +
" \"status\" : \"started\",\n" +
" \"url\" : null\n" +
" }")));
ArchiveProperties properties = new ArchiveProperties.Builder().name(null).build();
Archive archive = sdk.startArchive(sessionId, properties);
assertNotNull(archive);
assertEquals(sessionId, archive.getSessionId());
assertNotNull(archive.getId());
verify(postRequestedFor(urlMatching(archivePath)));
// TODO: find a way to match JSON without caring about spacing
//.withRequestBody(matching(".*"+".*"))
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(archivePath)))));
Helpers.verifyUserAgent();
}
@Test
public void testStartArchiveWithName() throws OpenTokException {
String sessionId = "SESSIONID";
String name = "archive_name";
stubFor(post(urlEqualTo(archivePath))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395183243556,\n" +
" \"duration\" : 0,\n" +
" \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" +
" \"name\" : \"archive_name\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 0,\n" +
" \"status\" : \"started\",\n" +
" \"url\" : null\n" +
" }")));
Archive archive = sdk.startArchive(sessionId, name);
assertNotNull(archive);
assertEquals(sessionId, archive.getSessionId());
assertEquals(name, archive.getName());
assertNotNull(archive.getId());
verify(postRequestedFor(urlMatching(archivePath)));
// TODO: find a way to match JSON without caring about spacing
//.withRequestBody(matching(".*"+".*"))
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(archivePath)))));
Helpers.verifyUserAgent();
}
@Test
public void testStartVoiceOnlyArchive() throws OpenTokException {
String sessionId = "SESSIONID";
stubFor(post(urlEqualTo(archivePath))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395183243556,\n" +
" \"duration\" : 0,\n" +
" \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 0,\n" +
" \"status\" : \"started\",\n" +
" \"url\" : null,\n" +
" \"hasVideo\" : false,\n" +
" \"hasAudio\" : true\n" +
" }")));
ArchiveProperties properties = new ArchiveProperties.Builder().hasVideo(false).build();
Archive archive = sdk.startArchive(sessionId, properties);
assertNotNull(archive);
assertEquals(sessionId, archive.getSessionId());
assertNotNull(archive.getId());
verify(postRequestedFor(urlMatching(archivePath)));
// TODO: find a way to match JSON without caring about spacing
//.withRequestBody(matching(".*"+".*"))
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(archivePath)))));
Helpers.verifyUserAgent();
}
@Test
public void testStartComposedArchive() throws OpenTokException {
String sessionId = "SESSIONID";
stubFor(post(urlEqualTo(archivePath))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395183243556,\n" +
" \"duration\" : 0,\n" +
" \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 0,\n" +
" \"status\" : \"started\",\n" +
" \"url\" : null,\n" +
" \"outputMode\" : \"composed\"\n" +
" }")));
ArchiveProperties properties = new ArchiveProperties.Builder()
.outputMode(OutputMode.COMPOSED)
.build();
Archive archive = sdk.startArchive(sessionId, properties);
assertNotNull(archive);
assertEquals(sessionId, archive.getSessionId());
assertNotNull(archive.getId());
assertEquals(OutputMode.COMPOSED, archive.getOutputMode());
verify(postRequestedFor(urlMatching(archivePath)));
// TODO: find a way to match JSON without caring about spacing
//.withRequestBody(matching(".*"+".*"))
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(archivePath)))));
Helpers.verifyUserAgent();
}
@Test
public void testStartComposedArchiveWithLayout() throws OpenTokException {
String sessionId = "SESSIONID";
stubFor(post(urlEqualTo(archivePath))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395183243556,\n" +
" \"duration\" : 0,\n" +
" \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 0,\n" +
" \"status\" : \"started\",\n" +
" \"url\" : null,\n" +
" \"outputMode\" : \"composed\"\n" +
" }")));
ArchiveProperties properties = new ArchiveProperties.Builder()
.outputMode(OutputMode.COMPOSED)
.layout(new ArchiveLayout(ArchiveLayout.Type.CUSTOM, "stream { position: absolute; }"))
.build();
Archive archive = sdk.startArchive(sessionId, properties);
assertNotNull(archive);
assertEquals(sessionId, archive.getSessionId());
assertNotNull(archive.getId());
assertEquals(OutputMode.COMPOSED, archive.getOutputMode());
verify(postRequestedFor(urlMatching(archivePath)));
// TODO: find a way to match JSON without caring about spacing
//.withRequestBody(matching(".*"+".*"))
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(archivePath)))));
Helpers.verifyUserAgent();
}
@Test
public void testStartIndividualArchive() throws OpenTokException {
String sessionId = "SESSIONID";
stubFor(post(urlEqualTo(archivePath))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395183243556,\n" +
" \"duration\" : 0,\n" +
" \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 0,\n" +
" \"status\" : \"started\",\n" +
" \"url\" : null,\n" +
" \"outputMode\" : \"individual\"\n" +
" }")));
ArchiveProperties properties = new ArchiveProperties.Builder().outputMode(OutputMode.INDIVIDUAL).build();
Archive archive = sdk.startArchive(sessionId, properties);
assertNotNull(archive);
assertEquals(sessionId, archive.getSessionId());
assertNotNull(archive.getId());
assertEquals(OutputMode.INDIVIDUAL, archive.getOutputMode());
verify(postRequestedFor(urlMatching(archivePath)));
// TODO: find a way to match JSON without caring about spacing
//.withRequestBody(matching(".*"+".*"))
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(archivePath)))));
Helpers.verifyUserAgent();
}
// TODO: test start archive with name
// TODO: test start archive failure scenarios
@Test
public void testStopArchive() throws OpenTokException {
String archiveId = "ARCHIVEID";
stubFor(post(urlEqualTo(archivePath + "/" + archiveId + "/stop"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395183243000,\n" +
" \"duration\" : 0,\n" +
" \"id\" : \"ARCHIVEID\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 0,\n" +
" \"status\" : \"stopped\",\n" +
" \"url\" : null\n" +
" }")));
Archive archive = sdk.stopArchive(archiveId);
assertNotNull(archive);
assertEquals("SESSIONID", archive.getSessionId());
assertEquals(archiveId, archive.getId());
verify(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop")));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop")))));
Helpers.verifyUserAgent();
}
// TODO: test stop archive failure scenarios
@Test
public void testDeleteArchive() throws OpenTokException {
String archiveId = "ARCHIVEID";
stubFor(delete(urlEqualTo(archivePath + "/" + archiveId))
.willReturn(aResponse()
.withStatus(204)
.withHeader("Content-Type", "application/json")));
sdk.deleteArchive(archiveId);
verify(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId)));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId)))));
Helpers.verifyUserAgent();
}
// TODO: test delete archive failure scenarios
// NOTE: this test is pretty sloppy
@Test public void testGetExpiredArchive() throws OpenTokException {
String archiveId = "ARCHIVEID";
stubFor(get(urlEqualTo(archivePath + "/" + archiveId))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395187836000,\n" +
" \"duration\" : 62,\n" +
" \"id\" : \"" + archiveId + "\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 8347554,\n" +
" \"status\" : \"expired\",\n" +
" \"url\" : null\n" +
" }")));
Archive archive = sdk.getArchive(archiveId);
assertNotNull(archive);
assertEquals(Archive.Status.EXPIRED, archive.getStatus());
}
// NOTE: this test is pretty sloppy
@Test public void testGetPausedArchive() throws OpenTokException {
String archiveId = "ARCHIVEID";
stubFor(get(urlEqualTo(archivePath + "/" + archiveId))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395187836000,\n" +
" \"duration\" : 62,\n" +
" \"id\" : \"" + archiveId + "\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 8347554,\n" +
" \"status\" : \"paused\",\n" +
" \"url\" : null\n" +
" }")));
Archive archive = sdk.getArchive(archiveId);
assertNotNull(archive);
assertEquals(Archive.Status.PAUSED, archive.getStatus());
}
@Test public void testGetArchiveWithUnknownProperties() throws OpenTokException {
String archiveId = "ARCHIVEID";
stubFor(get(urlEqualTo(archivePath + "/" + archiveId))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"createdAt\" : 1395187836000,\n" +
" \"duration\" : 62,\n" +
" \"id\" : \"" + archiveId + "\",\n" +
" \"name\" : \"\",\n" +
" \"partnerId\" : 123456,\n" +
" \"reason\" : \"\",\n" +
" \"sessionId\" : \"SESSIONID\",\n" +
" \"size\" : 8347554,\n" +
" \"status\" : \"expired\",\n" +
" \"url\" : null,\n" +
" \"thisisnotaproperty\" : null\n" +
" }")));
Archive archive = sdk.getArchive(archiveId);
assertNotNull(archive);
}
@Test
public void testGetStreamWithId() {
String sessionID = "SESSIONID";
String streamID = "STREAMID";
Boolean exceptionThrown = false;
String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream/" + streamID;
stubFor(get(urlEqualTo(url))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"id\" : \"" + streamID + "\",\n" +
" \"name\" : \"\",\n" +
" \"videoType\" : \"camera\",\n" +
" \"layoutClassList\" : [] \n" +
" }")));
try {
Stream stream = sdk.getStream(sessionID, streamID);
assertNotNull(stream);
assertEquals(streamID, stream.getId());
assertEquals("", stream.getName());
assertEquals("camera", stream.getVideoType());
verify(getRequestedFor(urlMatching(url)));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(getRequestedFor(urlMatching(url)))));
Helpers.verifyUserAgent();
} catch (Exception e) {
exceptionThrown = true;
}
assertFalse(exceptionThrown);
}
@Test
public void testGetStreams() {
String sessionID = "SESSIONID";
Boolean exceptionThrown = false;
String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream";
stubFor(get(urlEqualTo(url))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"count\" : 2,\n" +
" \"items\" : [ {\n" +
" \"id\" : \"" + 1234 + "\",\n" +
" \"name\" : \"\",\n" +
" \"videoType\" : \"camera\",\n" +
" \"layoutClassList\" : [] \n" +
" }, {\n" +
" \"id\" : \"" + 5678 + "\",\n" +
" \"name\" : \"\",\n" +
" \"videoType\" : \"screen\",\n" +
" \"layoutClassList\" : [] \n" +
" } ]\n" +
" }")));
try {
StreamList streams = sdk.listStreams(sessionID);
assertNotNull(streams);
assertEquals(2,streams.getTotalCount());
Stream stream1 = streams.get(0);
Stream stream2 = streams.get(1);
assertEquals("1234", stream1.getId());
assertEquals("", stream1.getName());
assertEquals("camera", stream1.getVideoType());
assertEquals("5678", stream2.getId());
assertEquals("", stream2.getName());
assertEquals("screen", stream2.getVideoType());
verify(getRequestedFor(urlMatching(url)));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(getRequestedFor(urlMatching(url)))));
Helpers.verifyUserAgent();
} catch (Exception e) {
exceptionThrown = true;
}
assertFalse(exceptionThrown);
}
@Test
public void testCreateSessionWithProxy() throws OpenTokException, UnknownHostException {
WireMockConfiguration proxyConfig = WireMockConfiguration.wireMockConfig();
proxyConfig.dynamicPort();
WireMockServer proxyingService = new WireMockServer(proxyConfig);
proxyingService.start();
WireMock proxyingServiceAdmin = new WireMock(proxyingService.port());
String targetServiceBaseUrl = "http://localhost:" + wireMockRule.port();
proxyingServiceAdmin.register(any(urlMatching(".*")).atPriority(10)
.willReturn(aResponse()
.proxiedFrom(targetServiceBaseUrl)));
String sessionId = "SESSIONID";
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getLocalHost(), proxyingService.port()));
sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(targetServiceBaseUrl).proxy(proxy).build();
stubFor(post(urlEqualTo("/session/create"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," +
"\"partner_id\":\"123456\"," +
"\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," +
"\"media_server_url\":\"\"}]")));
Session session = sdk.createSession();
assertNotNull(session);
assertEquals(apiKey, session.getApiKey());
assertEquals(sessionId, session.getSessionId());
verify(postRequestedFor(urlMatching(SESSION_CREATE)));
assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret,
findAll(postRequestedFor(urlMatching(SESSION_CREATE)))));
Helpers.verifyUserAgent();
}
}
|
package com.pump.text.html;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.text.html.HTMLEditorKit;
import org.junit.Test;
import com.pump.geom.ShapeUtils;
import com.pump.graphics.vector.FillOperation;
import com.pump.graphics.vector.ImageOperation;
import com.pump.graphics.vector.Operation;
import com.pump.graphics.vector.StringOperation;
import com.pump.graphics.vector.VectorGraphics2D;
import com.pump.graphics.vector.VectorImage;
import com.pump.text.html.css.CssColorParser;
import com.pump.text.html.css.CssLineHeightValue;
import junit.framework.TestCase;
/**
* This renders a series of HTML and makes sure misc visual features are
* painted. Most tests check to see that the QHTMLEditorKit produces certain
* results AND that the default HTMLEditorKit fails to produce those same
* results. In the unlikely event that the HTMLEditorKit is ever enhanced and
* some of its shortcomings are addressed: we should remove some of the extra
* work the QHTMLEditorKit is doing.
*/
public class QHtmlTest extends TestCase {
static Dimension batDataSize = new Dimension(79, 80);
static String batDataURL = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE8AAABQCAYAAABYtCjIAAAAAXNSR0IArs4c6QAAAPJlWElmTU0AKgAAAAgABgESAAMAAAABAAEAAAEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgExAAIAAAARAAAAZoKYAAIAAABPAAAAeIdpAAQAAAABAAAAyAAAAAAAAAC5AAAAAQAAALkAAAABd3d3Lmlua3NjYXBlLm9yZwAAQ0MwIFB1YmxpYyBEb21haW4gRGVkaWNhdGlvbiBodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9wdWJsaWNkb21haW4vemVyby8xLjAvAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAT6ADAAQAAAABAAAAUAAAAACxoqkGAAAACXBIWXMAABxzAAAccwHWg+9QAAADgGlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyIKICAgICAgICAgICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgICAgICAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICAgICA8ZGM6dGl0bGU+CiAgICAgICAgICAgIDxyZGY6QWx0PgogICAgICAgICAgICAgICA8cmRmOmxpIHhtbDpsYW5nPSJ4LWRlZmF1bHQiPlZpbnRhZ2UgSGFsbG93ZWVuIGJhdDwvcmRmOmxpPgogICAgICAgICAgICA8L3JkZjpBbHQ+CiAgICAgICAgIDwvZGM6dGl0bGU+CiAgICAgICAgIDxkYzpyaWdodHM+CiAgICAgICAgICAgIDxyZGY6QWx0PgogICAgICAgICAgICAgICA8cmRmOmxpIHhtbDpsYW5nPSJ4LWRlZmF1bHQiPkNDMCBQdWJsaWMgRG9tYWluIERlZGljYXRpb24gaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvcHVibGljZG9tYWluL3plcm8vMS4wLzwvcmRmOmxpPgogICAgICAgICAgICA8L3JkZjpBbHQ+CiAgICAgICAgIDwvZGM6cmlnaHRzPgogICAgICAgICA8eG1wOkNyZWF0b3JUb29sPnd3dy5pbmtzY2FwZS5vcmc8L3htcDpDcmVhdG9yVG9vbD4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CoKd9cYAAA8xSURBVHgB7Zp70KZjHcfpIOQUWrRZu61FDlFKSu1uWHKMUSmpVZtRDaPRH0yDmgwzmsYYpoTFMs5hUJShhhwaRHJcFrvLrnU+rVOEPp/nub77Xu6e59131/vuLo/vzPe+ftf5ur737zo89/suvdTiwfvp9nX4c3gkfBneCu+FD5VwKuEDcC4US8MPwtfgm7BnoRBiGBwPfw8VpMmHSTsTbgUD6y6TSK+GETDzH41xEYyA8bDELydvhxQmtL4e3LNw8h+CLsdgAsZdUNH+A18odkS8nvguMHgfxgcS6cVQL1IAhRDaJ8MI5p6oJ75Rpf0de1MYuJSb3py8nglrL9ydWb8IFfGVEirif4vtoXMWHAGFnpwX0EroxYcCRMSNsB+FtYC1B5r+DJwIg55exhFh2WKsQehVRqFeKuHNhDcV23R5GoxwPX8io0XrQDFcHkZAPe856Ol7EIx4hgq6JhTv7YOIkCXsyXw7jFh64cfgBnBalf409nZQuA/2/EGSZbgWYjwBI+CD2MHZGEk3/HHJeE9AhMge+KUikvdARTodBr/BMC2HyoElQ+/teQ906YoDoCLlCvNdEwuOIDQvV5p9S3qWf4n2XqD35C53IbYiyTlwFRgcgmF6PDDi9ryA7mFiNejhEAGPNRFkeR+FXQs43kzQ8wJGgMMQQ4Fehf76GANFlvep2BFXoT9uJkj9dqzHnlm6LtX7YQQ6seiwXKXHLVX+lSW9Xv5V0d4x4107V+J4eR5RJPhwCdcnzC8TRZ5U0t/zviJE7V1+oRb+VIvAChbv9DOXl2uR/bMd67FnxNmLeUec2dgeJsLlHYEuw06ZKdgiee1Yjz2z963AvB+DEWe/ooPiRKBPYPttMGXGlTL5mFCivRVk7zq+EsbP9iLipkxOZwW8qlWir0yJ9lYQz9qKacernsf2U5bwZE2ZFbFnQsu9Dj8HRX47t2M99FQc4fXkARgBtzMRZFlGoANIS5ljWiXeu/e1ZDilEua4hjARUZHzCcvQ/VIkvx3roWcmvgdzjlfdg509L2FO58Orct8sOmVfLNGFC1wG3bhwLQ59rYjnh1F/qimg+95IKJKfcDRp+bPmSa0SbaGzBZSkgQVuqCpv43lLdU0bNb0up92pbF1vUdmORfi5fiqM921jIsh+p52yl2Bbzq/T1hOZk/PqxlaZZNqwJ89r0G9gfsZpwk5Mr8tpm279vFHMxQLH4Qv2Z5jLNRhZjNqjIt4VJW8Twi2LrSa2lfk65yZb83bCZujm2rq8R/cWcBRcGdqpF8vHoV8lHob/hHdCP4cruPWFg5I2LhclnKwTt99ZVccji22+K8v56CDiZLgNXBV6wRbOZyB4M97yU0pPguvCfAubXwMK+QicDv8ML4CKGdHi1Yk7+KGE7efFPVB1tHGxHUfGYtIIuB78C3TeP4N+SFAT2wmdh3ZCnc1DR4da6jpox036BlwCbqoW9O8Fr8Bsxs3yCvdHeBDcCNawcwdVL5063/SUMewPKdupLbcPsSt0fL7gb0Bh3lbwSPgP6B/Km3NYkPhVDuBS6L1Hl3bT1Ha5DoeqLWxUMTO47AGmi7yVdqz9/CvBZHg5fL6dNE9A2+oPCp2llXKO1TE2PajO1yN8wcJ9zPF5h9sZeoVxW+oE5xPhdA7nU6/AZ4m7rB+GM6BzOxf+H6yo+24GdeVrYRrW+xx84gnt3HQnrDBJN5wNj4Xrw0ARFKP2nh8Q3w+uAoUCBpZzXN1Ql7XMZ6B9uk/XY3GMjs9xatdOYHq9qmYQ/x3cBY6EtZhE27BjB1ZPpGTNC3bEugFmIHUnSWuGlqnLKfwxcA0Y6CnCky71Z2Jn2StyLdr2xKdAD6sJUNST+h7x62DaMlQo+zas02MrYD3Oe4j7IleETaiRq89xzYOJ0oFK9x0LZZlitqAnugTtuOlhGUwzdGAupaRbfzJ0OdmnOBSaP7eELo+InDEcX/LSzkHEg7UxrobJM7RPx6g4dXpt632J34a9E1wJBjqWL1ix1CTjxRwYFLNWehjxS6Gd1m8sg+gWOpFa8POIB9/CSHsR8IRkEu5d8vUeDzHLjoVic+jBkPqOyXLdxpH0LFvjv4Tu876gzaBw7x80qHqWmY3+CWbAGdBAQicW0f3/O7EqnAWtHy99CvtQ+CN4NzQvwuqZvlBf7AxoXkQdyBgsE69zDHp3+vg0tojHt2OD9IyAvqkZ0IEM5E3Xk8rA9Zh1odgeRtTaQ1Mvec9S7qtWAAdD818uYcrOL3QPtMzZUFwMjfsCPg/FkIhnwxHQk8hOF1Q860QM3/hHoBgPzQstk4mmn6+QJkbDLNf+9rW0lTDtTaO+e5qIeJYZ10rpm2OJDl6QjdMT6VFopwsjYCbyIPW3hV8rbT1EuBuMOHtinwv1DLEpnA3tt5OXmt6JKetLiYdhvuW/8MebAOIg7ViHZ5TvkDWgJPccBykiqF4QTzDdMuYZNuHSUPRR8EpoPfEiHAFzXViv2G7iU6AirwIVoz7MiHaFbWe+X8e+Edq/QnqvFS5/91qRsbRjg/j02BafhHaigA4idqe3bpqTrU+5lFPAeG72w+TV8dq2v5RJaP+Wkdr1eOJ1J5Mulm0HrRd7M7ZtuBI8vcV897y8iXbxgT/jZe5VseMBvrmp0PvcStCDxXLDYfpzciIvwdDBO9l4s2VMN+7EDY0rmmH6w5x3ctp+xmO67flSrGuebR4LRcr5k1QvFpa3L+F4hgQRYSyt24nXi19D95HVYA0H6XLzU5f3qDnQOtKBxm6GTqSZ1oxbJleb5BnPXpq0tHULeUHEX58E91LL+uLXgiJzbMcG8ZmO96ZNO/1Co20F823n7dbZKxI5EGbZ9SdgJt8ptJ6eZJ7iTIZbwzWh4xkP94MXwJS7ElvEE7UnwLR/D3ZEs8yQIKKsQeublB7cIxQ1eSW5FZjmoOp9xL3lSejAM7lMYn5hLfj51Pf0FfZxBrwNngqDL2PMhrabS3D2vEkl3Twv/sJtYUhRixRPHEiHDsx9RvitzUHXYgxUOO+HW8MaRxNJ/XhZxuZ2cgIcWyrkKuIemDqHlbz6JZekwQ9q91+Q1hVeWv8OWAvoBu+e5bKWChvPjMizSFMMEW93wtNhhPA6I8yPgK0EHvYbXIuROruUxGb5lF1iwiyNs8vg3egjTiZThwqpsKZNgsKlFw+aiJ3yM7E96UWEyovOizPPg2wGtJ5bSA6L1CFpycb1DM/Bv1xCrzh3QTfvB+GjMKIYzoUjoYhw2rfClDvKBOAeqFhN5MVtTUbqXFMKvSOEywROqyZwEvbq0CWoMN78ja8Lz4JOVA/9LBT5ZbA9dkTwJXh5F92Wn6KK02HqHdJK6TttS3TJDCLet8sELp7PMF2iM0tZrzoi4lyNHRHOMwPYfievi2cNIz+nvfe89aFIfjvWz3PABftpY2GzMjH3MeHeJ/Q480LHqBB6nPuecG8UhnvBcdC7ngJmyVrPeBMRfAcycujcgH1vKdipTrONxR6P5+3PSNzXXJqi0wuN0LuR7y+ZfMLyyjMDOmF5OhQRqB3re9ZtK1jq5YqSMfXVWMKtlRmf3iYiUjvW/RkRjqSIAui97nUjoEh+O9b3XKaYuxNGOMPsod1E72thCbJqsWq72xAVJRfsrbGduMvZ8GAochi0Y31P208f7q8R7299RbqKXhVZskwn1M1TmiON5/j7eA6MAFdXBbu1FVE9iev75K6lbtqumnr3mJm8M7oMRjjvhWubCPpbdhH1HMql7p2tWu1HvLJKeneYtXCnMiUn7084Q09NkX2zHXvrM6LuTLJ14nn5OVa3/9aa7/BYvZzOKJPP97dcbOsyzenG4zxJZ5T6Cng6FO+4E7Y97Pk/402KcyV00i+W8LeEQnG6LTnT41UnYltf1r9j33XiOel4k78E/lUm7f7m5M+CQTwr8TqM+PuSaD0v2Yb1Fxei7x64P0WQDbGnQycc4S7EDuJVidehP+fEVrAW7vxWavePBiX7nRUoWDzFkcdbnHjuciebUdCfcGlnNGVfgLYhH4F6suivfrvEAJ950wMsPujFskRteBQ8AzrZfL/Tzk8ozH43+bTl9eVBGOGewh4Dhd49qFDARbV5uqfVm3kmorflJPXnlhPXc/xNKxxjtxdd75P+3HoaRjgPmY2hiLjt2Nt82ulaVRu6s29msIW0H9u0/WbbbuD/hk72DRiP86fTOlA4pm7CpV3LbQtzj7M9PzqsB0WWczs2CM81aONZeBxcvdGeA7ZD31a3gTeqzIsqlnWsaxvN+qb5OekWGA/JpPWU/WDgOGyvE2pPmkSBtGU4G44plexv0OGgroF2NgceBXX7TvANOxEH3B8t0xSLpFbdCYTe0abBTPT1ynYsWWK20fRSklpw3DlRTTgJ2l5+edyH/VEoaoHbKYP49HP21TCTMbwJHg2/AzeHC3M6OUGvGz+E58A7Yd1Hbf+BvHEw6DZh26zHMoK4y9u2sl/eg50Pnd3aocjbQwbiHqO3TIEupU6YSqLe8hicCWfDFaB/pXoVWt8rxUi4InQfHQ5Hw+VgJ9jWufAUeEdVwLZeq+KaeqCemHQF3B/+Ctpf4D1uX+i9UOEc25CifpMH0JN7jm/SJZBTr/aSt2M7qSvgPrCetC9S0erlrq0ApgeOdSKcDutxPEd8EgzqOkkbstCBZuDrYV8CMzjfnkLqob750PSU6RZ6GN0Hp8B94BhYQzHSr+kRsbnclidvb+iSbPZ1JmnDoYiHtmND+HSgTdSuvhOZh8MtSiHFs44DdALa98NZUAH0Uj3rITgdzoBO1uWpNwd6hW3YXtoxLweHdvBFDK8ye8DRSSzhNMKfwKtKvB57SVr0gZOrvcHB3w7rN67XOdl74S9g06NIWiisTK0t4ZHQA+YNWPer/SQ8BGYv9UU45kWKTp6XASieg3KJCst+H06EY2ETL5AwE94G4216pMtWjwwV3Ul77/LAGQE3gKOg24VcC3aC7Z4GJ8NnSgFFiweXpCUnUDT3pRou4yOgXtf0imZcz1EwT+K50J9NLm2XcZZps04dt+xlcE/oWALHVMeTvsjCBe3cPUVPdHJCD/oU3B7uCDeCetPbgaK6R94I9eKL4P0wcAx6mi9lsWJBxXOw1nGpKGCWNGYLo3i67FyGG8Jh0Hug4TpQb1Gcp+Ac+ARUKO3H4d3wkWK/RBikzyVCtAzqfxltLlAWEUDiAAAAAElFTkSuQmCC')";
static Dimension htmlPaneSize = new Dimension(1000, 1000);
/**
* Test that "darkorchid" is resolved correctly.
*/
public void test_named_color_h3_inline() throws Exception {
//@formatter:off
String html = "<html>\n" +
" <h3 style=\"color: darkorchid;font-size: 150%;\">Lorem Ipsum</h3>\n" +
"</html>";
//@formatter:on
Color darkorchid = CssColorParser.getNamedColor("darkorchid");
List<Operation> ops1 = getOperations(true, html);
assertEquals(darkorchid, ops1.get(1).getContext().getPaint());
List<Operation> ops2 = getOperations(false, html);
assertEquals(Color.black, ops2.get(1).getContext().getPaint());
}
/**
* Test that "darkorchid" is resolved correctly.
*/
public void test_named_color_h1_internalSheet() throws Exception {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" h1 {color: darkorchid;}\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1 style=\"font-size: 150%;\">Lorem Ipsum</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
Color darkorchid = CssColorParser.getNamedColor("darkorchid");
List<Operation> ops1 = getOperations(true, html);
assertEquals(darkorchid, ops1.get(1).getContext().getPaint());
List<Operation> ops2 = getOperations(false, html);
assertEquals(Color.black, ops2.get(1).getContext().getPaint());
}
/**
* Test that a 4-digit hex code with an alpha component is rendered
* correctly.
*/
public void test_hex_alpha_h3_inline() throws Exception {
//@formatter:off
String html = "<html>\n" +
" <h3 style=\"color: #321C;font-size: 150%;\">Lorem Ipsum</h3>\n" +
"</html>";
//@formatter:on
List<Operation> ops1 = getOperations(true, html);
assertEquals(204, ops1.get(1).getContext().getColor().getAlpha());
List<Operation> ops2 = getOperations(false, html);
assertEquals(255, ops2.get(1).getContext().getColor().getAlpha());
}
/**
* Test that a 8-digit hex code with an alpha component is rendered
* correctly.
*/
public void test_hex_alpha_h1_internalSheet() throws Exception {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" h1 {color: #00331199;}\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1 style=\"font-size: 150%;\">Lorem Ipsum</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
List<Operation> ops1 = getOperations(true, html);
assertEquals(153, ops1.get(1).getContext().getColor().getAlpha());
List<Operation> ops2 = getOperations(false, html);
assertEquals(255, ops2.get(1).getContext().getColor().getAlpha());
}
/**
* Test a text-shadow for an h1 tag.
*/
public void test_text_shadow_h1_internalSheet() throws Exception {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" h1 {color:darkorchid; text-shadow: 2px 2px 4px plum;}\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1 style=\"font-size: 150%;\">Lorem Ipsum</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
testTextShadow(html);
}
/**
* Test a text-shadow for an h3 tag.
*/
public void test_text_shadow_h3_inline() throws Exception {
//@formatter:off
String html = "<html>\n" +
" <h3 style=\"color:darkorchid; text-shadow: 2px 2px 4px plum;font-size: 150%;\">Lorem Ipsum</h3>\n" +
"</html>";
//@formatter:on
testTextShadow(html);
}
/**
* Test a text-shadow for a span tag.
*/
public void test_text_shadow_span_inline() throws Exception {
//@formatter:off
String html = "<html>\n" +
" <span style=\"color:darkorchid; text-shadow: 2px 2px 4px plum;font-size: 150%;\">Lorem Ipsum</span>\n" +
"</html>";
//@formatter:on
testTextShadow(html);
}
/**
* This asserts that HTML produces exactly 3 layers: a background, an image
* (the shadow), and text
*/
private void testTextShadow(String html) {
List<Operation> ops1 = getOperations(true, html);
assertEquals(3, ops1.size());
// background:
assertEquals(FillOperation.class, ops1.get(0).getClass());
// shadow:
assertEquals(ImageOperation.class, ops1.get(1).getClass());
// text:
assertEquals(StringOperation.class, ops1.get(2).getClass());
List<Operation> ops2 = getOperations(false, html);
assertEquals(2, ops2.size());
// background:
assertEquals(FillOperation.class, ops2.get(0).getClass());
// text:
assertEquals(StringOperation.class, ops2.get(1).getClass());
}
interface TextPaneFormatter {
JComponent format(JEditorPane p);
}
/**
* Return the visible Operations used to render certain HTML.
* <p>
* If an Operation would not be visible (because of clipping) then it is not
* included in the returned list.
*
* @param useQHTMLKit
* @param html
* @return
*/
private List<Operation> getOperations(boolean useQHTMLKit, String html) {
return getOperations(useQHTMLKit, html, null);
}
private List<Operation> getOperations(boolean useQHTMLKit, String html,
TextPaneFormatter textPaneFormatter) {
HTMLEditorKit kit = useQHTMLKit ? new QHTMLEditorKit()
: new HTMLEditorKit();
JEditorPane p = new JEditorPane();
p.setEditorKit(kit);
p.setText(html);
p.setPreferredSize(htmlPaneSize);
p.setSize(htmlPaneSize);
JComponent jc = textPaneFormatter == null ? p
: textPaneFormatter.format(p);
VectorImage vi = new VectorImage();
VectorGraphics2D vig = vi.createGraphics();
jc.paint(vig);
vig.dispose();
List<Operation> returnValue = vi.getOperations();
Iterator<Operation> iter = returnValue.iterator();
while (iter.hasNext()) {
Operation op = iter.next();
if (op.getBounds() == null)
iter.remove();
}
return returnValue;
}
public void testBackgroundRepeat_base64img_no_repeat() {
//@formatter:off
// the same layout, but test a single "no-repeat" argument vs two consecutive "no-repeat" arguments.
String html1 = "<html>\n" +
" <head>\n" +
" <style>\n" +
" body {\n"+
"background-repeat:no-repeat;\n" +
"background-image: "+batDataURL+"\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1>LOREM IPSUM</h1>\n" +
" </body>\n" +
"</html>";
String html2 = "<html>\n" +
" <head>\n" +
" <style>\n" +
" body {\n"+
"background-repeat:no-repeat no-repeat;\n" +
"background-image: "+batDataURL+"\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1>LOREM IPSUM</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
for (String html : new String[] { html1, html2 }) {
List<Operation> ops1 = getOperations(true, html);
assertEquals(3, ops1.size());
assertEquals(FillOperation.class, ops1.get(0).getClass());
// image:
assertEquals(ImageOperation.class, ops1.get(1).getClass());
ImageOperation io = (ImageOperation) ops1.get(1);
assertEquals(batDataSize.width, io.getDestRect().width);
assertEquals(batDataSize.height, io.getDestRect().height);
// text:
assertEquals(StringOperation.class, ops1.get(2).getClass());
// Swing's default renderer should support no-repeat, but not with a
// base64-encoded image
List<Operation> ops2 = getOperations(false, html);
assertEquals(2, ops2.size());
assertEquals(FillOperation.class, ops2.get(0).getClass());
assertEquals(StringOperation.class, ops2.get(1).getClass());
}
}
public void testBackgroundRepeat_base64img_repeat_x() {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" body {\n"+
"background-repeat:repeat-x;\n" +
"background-image: "+batDataURL+"\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1>LOREM IPSUM</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
List<Operation> ops1 = getOperations(true, html);
ops1.remove(0); // background color
ops1.remove(ops1.size() - 1); // text
assertEquals(13, ops1.size());
for (int a = 0; a < ops1.size(); a++) {
assertEquals(ImageOperation.class, ops1.get(a).getClass());
ImageOperation first = (ImageOperation) ops1.get(0);
ImageOperation c = (ImageOperation) ops1.get(a);
assertEquals(first.getDestRect().y, c.getDestRect().y);
}
// Swing's default renderer should support repeat-x, but not with a
// base64-encoded image
List<Operation> ops2 = getOperations(false, html);
assertEquals(2, ops2.size());
assertEquals(FillOperation.class, ops2.get(0).getClass());
assertEquals(StringOperation.class, ops2.get(1).getClass());
}
public void testBackgroundRepeat_base64img_repeat_y() {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" body {\n"+
"background-repeat:repeat-y;\n" +
"background-image: "+batDataURL+"\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1>LOREM IPSUM</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
List<Operation> ops1 = getOperations(true, html);
ops1.remove(0); // background color
ops1.remove(ops1.size() - 1); // text
assertEquals(13, ops1.size());
for (int a = 0; a < ops1.size(); a++) {
assertEquals(ImageOperation.class, ops1.get(a).getClass());
ImageOperation first = (ImageOperation) ops1.get(0);
ImageOperation c = (ImageOperation) ops1.get(a);
assertEquals(first.getDestRect().x, c.getDestRect().x);
}
// Swing's default renderer should support repeat-x, but not with a
// base64-encoded image
List<Operation> ops2 = getOperations(false, html);
assertEquals(2, ops2.size());
assertEquals(FillOperation.class, ops2.get(0).getClass());
assertEquals(StringOperation.class, ops2.get(1).getClass());
}
public void testBackgroundRepeat_base64img_repeat() {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" body {\n"+
"background-repeat:repeat;\n" +
"background-image: "+batDataURL+"\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1>LOREM IPSUM</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
List<Operation> ops1 = getOperations(true, html);
ops1.remove(0); // background color
ops1.remove(ops1.size() - 1); // text
Area sum = new Area();
for (int a = 0; a < ops1.size(); a++) {
assertEquals(ImageOperation.class, ops1.get(a).getClass());
ImageOperation c = (ImageOperation) ops1.get(a);
sum.add(new Area(c.getBounds()));
}
// did our tiles cover everything:
assertTrue(sum.contains(new Rectangle(1, 1, htmlPaneSize.width - 2,
htmlPaneSize.height - 2)));
// Swing's default renderer should support repeat-x, but not with a
// base64-encoded image
List<Operation> ops2 = getOperations(false, html);
assertEquals(2, ops2.size());
assertEquals(FillOperation.class, ops2.get(0).getClass());
assertEquals(StringOperation.class, ops2.get(1).getClass());
}
/**
* Make sure when no position is specified that the image is in the
* top-left. This test was added as a result of an observed failure.
*/
public void testBackgroundPosition_base64img_none() {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" body {\n" +
"background-repeat: no-repeat;\n"+
"background-image: "+batDataURL+"\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" </body>\n" +
"</html>";
//@formatter:on
List<Operation> ops = getOperations(true, html);
assertEquals(2, ops.size());
// page background:
assertEquals(FillOperation.class, ops.get(0).getClass());
// h1 background:
assertEquals(ImageOperation.class, ops.get(1).getClass());
ImageOperation io = (ImageOperation) ops.get(1);
assertEquals(0, io.getDestRect().x);
assertEquals(0, io.getDestRect().y);
// we can't test the Swing renderer using a base64 image
}
/**
* Test that h1 tags support background-colors. This test was added as a
* result of an observed failure.
*/
public void testBackground_color_h1() {
//@formatter:off
String html = "<html>\n" +
" <body> \n" +
" <h1 style=\"background-color:#F0F;font-size: 30pt;\">LOREM IPSUM</h1>\n" +
" </body> \n" +
"</html> ";
//@formatter:on
for (boolean useNewKit : new boolean[] { true, false }) {
List<Operation> ops = getOperations(useNewKit, html);
assertEquals(3, ops.size());
// page background:
assertEquals(FillOperation.class, ops.get(0).getClass());
// h1 background:
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(StringOperation.class, ops.get(2).getClass());
assertEquals(new Color(255, 0, 255),
ops.get(1).getContext().getPaint());
}
}
/**
* Test that an overflowing div clips its contents as expected when
* "overflow:hidden" is used.
*/
public void testOverflow_hidden_div() {
//@formatter:off
String html = "<html>\n" +
" <body> \n" +
" <div style=\"overflow:hidden;font-size: 30pt;height:30px;width:40px;background-color:#6FF;\">little baby buggy bumpers</div>\n" +
" </body> \n" +
"</html> ";
//@formatter:on
List<Operation> ops1 = getOperations(true, html);
assertEquals(3, ops1.size());
// page background:
assertEquals(FillOperation.class, ops1.get(0).getClass());
// div background:
assertEquals(FillOperation.class, ops1.get(1).getClass());
assertEquals(StringOperation.class, ops1.get(2).getClass());
FillOperation f = (FillOperation) ops1.get(1);
Rectangle r = f.getBounds().getBounds();
assertEquals(40, r.width);
assertEquals(30, r.height);
r = ops1.get(2).getBounds().getBounds();
assertTrue(r.getWidth() <= 40);
assertTrue(r.getHeight() <= 30);
// the old Swing should ignore "hidden":
List<Operation> ops2 = getOperations(false, html);
// we have multiple lines of text
assertEquals(3, ops2.size());
assertEquals(FillOperation.class, ops2.get(0).getClass());
assertEquals(FillOperation.class, ops2.get(1).getClass());
assertEquals(StringOperation.class, ops2.get(2).getClass());
f = (FillOperation) ops2.get(1);
r = f.getBounds().getBounds();
assertFalse(r.width == 40);
assertFalse(r.height == 30);
r = ops2.get(2).getBounds().getBounds();
assertTrue(r.getWidth() > 40);
}
/**
* This is derived from testOverflow_hidden_div, except when we use spans we
* should NOT successfully clip anything. (When testing in chrome: spans
* don't clip but divs do.)
*/
public void testOverflow_hidden_span() {
//@formatter:off
String html = "<html>\n" +
" <body> \n" +
" <span style=\"overflow:hidden;font-size: 30pt;height:30px;width:40px;background-color:#6FF;\">little baby buggy bumpers</span>\n" +
" </body> \n" +
"</html> ";
//@formatter:on
for (boolean useNewKit : new boolean[] { true, false }) {
List<Operation> ops = getOperations(useNewKit, html);
assertEquals(3, ops.size());
// page background:
assertEquals(FillOperation.class, ops.get(0).getClass());
// div background:
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(StringOperation.class, ops.get(2).getClass());
FillOperation f = (FillOperation) ops.get(1);
Rectangle r = f.getBounds().getBounds();
assertTrue(r.getWidth() > 40);
r = ops.get(2).getBounds().getBounds();
assertTrue(r.getWidth() > 40);
}
}
/**
* Test that using "background-attachment:fixed" vs
* "background-attachment:scroll" positions a background image in a
* JScrollPane appropriately. (When the property is "fixed" the image should
* render in the location, and when it is "scroll" the background image
* should move.)
*/
public void testBackgroundAttachment_base64img() {
class ScrollPaneFormatter implements TextPaneFormatter {
int xOffset, yOffset;
public ScrollPaneFormatter(int xOffset, int yOffset) {
this.xOffset = xOffset;
this.yOffset = yOffset;
}
@Override
public JComponent format(JEditorPane p) {
JScrollPane scrollPane = new JScrollPane(p,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.getViewport()
.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
Dimension d = new Dimension(400, 200);
scrollPane.setSize(d);
scrollPane.setBorder(null);
scrollPane.getViewport().setBorder(null);
scrollPane.doLayout();
scrollPane.getViewport()
.setViewPosition(new Point(xOffset, yOffset));
return scrollPane;
}
}
for (String attachmentProperty : new String[] { "fixed", "scroll" }) {
//@formatter:off
String html = "<html>\n" +
" <head>\n" +
" <style>\n" +
" body { background-color: #387;\n" +
" background-repeat:no-repeat;\n" +
" background-attachment:"+attachmentProperty+";\n" +
" background-image:"+batDataURL+"; \n" +
"}\n" +
" h1 { color: rgba(0,240,0,1); font-weight: bold;}\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <h1 style=\"font-size: 100pt;\">LOREM IPSUM</h1>\n" +
" </body>\n" +
"</html>";
//@formatter:on
Collection<Integer> imageYs = new HashSet<>();
Collection<Double> string1Ys = new HashSet<>();
for (int y = 0; y < 500; y += 50) {
ScrollPaneFormatter formatter = new ScrollPaneFormatter(0, y);
List<Operation> ops = getOperations(true, html, formatter);
// there may be 4 or 5 lines of text, depending on clipping
assertTrue(ops.size() >= 3);
// scrollpane/page background:
assertEquals(FillOperation.class, ops.get(0).getClass());
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(ImageOperation.class, ops.get(2).getClass());
// two lines of text (sometimes true):
// assertEquals(StringOperation.class, ops.get(3).getClass());
// assertEquals(StringOperation.class, ops.get(4).getClass());
ImageOperation io = (ImageOperation) ops.get(2);
Rectangle imageRect = io.getContext().getTransform()
.createTransformedShape(io.getDestRect()).getBounds()
.getBounds();
imageYs.add(imageRect.y);
if (ops.size() > 3) {
StringOperation so = (StringOperation) ops.get(3);
Point2D stringPos = so.getContext().getTransform()
.transform(new Point2D.Float(so.getX(), so.getY()),
null);
string1Ys.add(stringPos.getY());
}
}
// this is the main event: did our image always paint at the same
// position
if ("fixed".equals(attachmentProperty)) {
assertEquals(1, imageYs.size());
} else {
assertEquals(10, imageYs.size());
}
// make sure the text is scrolling; this proves our viewport was
// changing each iteration.
assertEquals(6, string1Ys.size());
}
}
/**
* This identifies a bug related line wrapping.
* <p>
* The QInlineView is cloned as line wrapping is calculated. In earlier
* versions of the QViewHelper class we kept a reference to the original
* (uncloned) QInlineView. So painting the newly wrapped QInlineView
* actually invoked the old unwrapped QInlineView. The end result for the
* user is the text was printed twice.
*/
public void testLineWrapping() {
//@formatter:off
String html = "<html>\n"
+ " <body>\n"
+ " <h1 style=\"font-size: 100pt;\">LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
TextPaneFormatter formatter = new TextPaneFormatter() {
@Override
public JComponent format(JEditorPane p) {
p.setSize(new Dimension(540, 540));
return p;
}
};
List<Operation> ops = getOperations(true, html, formatter);
int charCtr = 0;
for (Operation op : ops) {
if (op instanceof StringOperation) {
StringOperation strOp = (StringOperation) op;
charCtr += strOp.getString().length();
}
}
assertEquals("LOREM IPSUM".length(), charCtr);
}
/**
* Text shadows should always render as if the text was 100% opaque.
* <p>
* This one surprised me. (I assumed the shadow's alpha should be multiplied
* by the text's alpha?) But if we assume "correct behavior" is defined as
* "what existing browsers already do", then this test checks for the
* correct behavior
*/
public void testTextShadowWithTransparentText() throws Exception {
// render text in purple (no shadow)
String plainHtml = "<html>\n" + " <body>\n"
+ " <h1 style=\"font-size: 100pt; color: #F0F;\">LOREM IPSUM</h1>\n"
+ " </body>\n" + "</html>";
// render text transparently, but apply a purple (unblurred) shadow:
String transparentHtml = "<html>\n" + " <body>\n"
+ " <h1 style=\"font-size: 100pt; color: transparent; text-shadow: 0px 0px 0px rgba(255,0,255,1);\">LOREM IPSUM</h1>\n"
+ " </body>\n" + "</html>";
// these two snippets of HTML should visually be the same
BufferedImage bi1 = getImage(transparentHtml);
BufferedImage bi2 = getImage(plainHtml);
assertImageEquals(bi1, bi2, 0);
List<Operation> ops1 = getOperations(true, plainHtml);
List<Operation> ops2 = getOperations(true, transparentHtml);
assertEquals(2, ops1.size());
assertEquals(2, ops2.size());
// paint using a shadow (BufferedImage)
assertEquals(FillOperation.class, ops2.get(0).getClass());
assertEquals(ImageOperation.class, ops2.get(1).getClass());
// don't paint using a shadow:
assertEquals(FillOperation.class, ops1.get(0).getClass());
assertFalse(ops1.get(1) instanceof ImageOperation);
}
/**
* At one point a bug made an inner view inherit the border of its parent.
* The correct behavior is for views to NOT inherit their parent's border.
*/
public void testSingleBorder() {
String html = "<html>\n" + " <body> \n"
+ " <p style=\"border: solid red 7px;\">Lorem Ipsum</div>\n"
+ " </body>\n" + "</html>";
List<Operation> ops = getOperations(true, html);
assertEquals(3, ops.size());
assertEquals(Color.red,
((FillOperation) ops.get(1)).getContext().getPaint());
}
/**
* Test that when giving a nested div both the outer and inner div show the
* appropriate CSS border.
*/
public void testSelector_nestedDiv() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " div { border: 10px solid #ff0000; }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div>\n"
+ " <div style=\"font-size: 10pt;\">LOREM IPSUM</div>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, html);
assertEquals(4, ops.size());
// the white background:
assertEquals(FillOperation.class, ops.get(0).getClass());
assertEquals(Color.white, ops.get(0).getContext().getPaint());
// the outer div border:
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(Color.red, ops.get(1).getContext().getPaint());
// the inner div border:
assertEquals(FillOperation.class, ops.get(2).getClass());
assertEquals(Color.red, ops.get(2).getContext().getPaint());
// the inner div border:
assertEquals(StringOperation.class, ops.get(3).getClass());
}
public void testSelector_nestedList() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " li { list-style-type: none;}\n"
+ " li div { color: red; border: 10px solid red; }\n"
+ " ul li div { border: 10px solid green; }\n"
+ " ul li div { border: 10px solid blue; }\n"
+ " div { border: 10px solid gray; }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div>div</div>\n"
+ " <ul>\n"
+ " <li>\n"
+ " <div>li div</div>\n"
+ " </li>\n"
+ " <li>\n"
+ " <ul>\n"
+ " <li>\n"
+ " <div>li li div</div>\n"
+ " </li>\n"
+ " </ul>\n"
+ " </li>\n"
+ " </ul>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, html);
assertEquals(7, ops.size());
// the white background:
assertEquals(FillOperation.class, ops.get(0).getClass());
assertEquals(Color.white, ops.get(0).getContext().getPaint());
// the outer div border:
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(Color.gray, ops.get(1).getContext().getPaint());
assertEquals(StringOperation.class, ops.get(2).getClass());
// the first (simple) list
assertEquals(FillOperation.class, ops.get(3).getClass());
assertEquals(Color.blue, ops.get(3).getContext().getPaint());
assertEquals(StringOperation.class, ops.get(4).getClass());
// the list-within-the-list
assertEquals(FillOperation.class, ops.get(5).getClass());
assertEquals(Color.blue, ops.get(5).getContext().getPaint());
assertEquals(StringOperation.class, ops.get(6).getClass());
}
/**
* Test a basic unordered list.
* <p>
* At one point any reference to a list tag failed (with a NPE) because
* antialiasing hints were undefined.
*/
public void testList() {
//@formatter:off
String html = "<html>\n"
+ " <body>\n"
+ " Outside\n"
+ " <ul>\n"
+ " <li>Item 1</li>\n"
+ " <li>Item 2</li>\n"
+ " <li>Item 3</li>\n"
+ " </ul>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, html);
assertEquals(8, ops.size());
// the white background:
assertEquals(FillOperation.class, ops.get(0).getClass());
assertEquals(Color.white, ops.get(0).getContext().getPaint());
assertEquals(StringOperation.class, ops.get(1).getClass());
assertEquals("Outside", ((StringOperation) (ops.get(1))).getString());
float outerX = ((StringOperation) (ops.get(1))).getX();
// ops.get(2) is a bullet shape
assertEquals(StringOperation.class, ops.get(3).getClass());
StringOperation li1 = (StringOperation) (ops.get(3));
assertEquals("Item 1", li1.getString());
assertTrue(li1.getX() > outerX);
// ops.get(4) is a bullet shape
assertEquals(StringOperation.class, ops.get(5).getClass());
StringOperation li2 = (StringOperation) (ops.get(5));
assertEquals("Item 2", li2.getString());
assertTrue(li2.getX() > outerX);
// ops.get(6) is a bullet shape
assertEquals(StringOperation.class, ops.get(7).getClass());
StringOperation li3 = (StringOperation) (ops.get(7));
assertEquals("Item 3", li3.getString());
assertTrue(li3.getX() > outerX);
}
/**
* Confirm that the background of 200x200 div with a border radius of 50%
* resembles a circle.
*/
@Test
public BufferedImage testBorderRadius() {
//@formatter:off
String html = "<html>\n"
+ "<body>\n"
+ "<div style=\"border-radius: 50%; width: 200px; height: 200px; background-color: #F0B;\"></div>\n"
+ "</body>\n"
+ "</html>";
//@formatter:on
BufferedImage bi1 = getImage(html);
BufferedImage bi2 = new BufferedImage(1000, 1000,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi2.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.white);
g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
g.setColor(new Color(0xff00bb));
g.fill(new Ellipse2D.Float(0, 0, 200, 200));
g.dispose();
assertImageEquals(bi1, bi2, 0);
return bi1;
}
/**
* This tests an ID selector (in this case "myDIV"). The actual style here
* is just another way of writing testBorderRadius().
*/
public void testSelector_plainID() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " #myDIV { \n"
+ " border-radius: 50%;\n"
+ " width: 200px;\n"
+ " height: 200px;\n"
+ " background-color: #F0B;\n"
+ " }\n"
+ " </style> \n"
+ " </head>\n"
+ " <body>\n"
+ " <div id=\"myDIV\"></div>\n"
+ " </body>\n"
+ "</html>\n";
//@formatter:on
BufferedImage bi1 = getImage(html);
BufferedImage bi2 = testBorderRadius();
assertImageEquals(bi1, bi2, 0);
}
/**
* When there are competing constituent attributes to define a border: make
* sure we use the last one.
*/
public void testBorderConstituentOrder_border() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " body { \n"
+ " border-color: #00ff22;\n"
+ " border-top-color: #ffff02;\n"
+ " border: solid red;\n"
+ " }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div>LOREM IPSUM</div>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, html);
assertEquals(3, ops.size());
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(0xffff0000, ops.get(1).getContext().getColor().getRGB());
}
/**
* When there are competing constituent attributes to define a border: make
* sure we use the last one.
*/
public void testBorderConstituentOrder_border_color() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " body { \n"
+ " border: solid red;\n"
+ " border-top-color: #ffff02;\n"
+ " border-color: #00ff22;\n"
+ " }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div>LOREM IPSUM</div>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, html);
assertEquals(3, ops.size());
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(0xff00ff22, ops.get(1).getContext().getColor().getRGB());
}
/**
* When there are competing constituent attributes to define a border: make
* sure we use the last ones.
*/
public void testBorderConstituentOrder_border_top_color() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " body { \n"
+ " border: solid red;\n"
+ " border-color: #00ff22;\n"
+ " border-top-color: #ffff02;\n"
+ " }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div>LOREM IPSUM</div>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, html);
assertEquals(4, ops.size());
assertEquals(FillOperation.class, ops.get(1).getClass());
assertEquals(FillOperation.class, ops.get(2).getClass());
// the exact order they're painted in might not match the css above,
// but just the fact that we have two colors indicates the css was
// parsed correctly
Collection<Integer> rgbs = new HashSet<>();
rgbs.add(ops.get(1).getContext().getColor().getRGB());
rgbs.add(ops.get(2).getContext().getColor().getRGB());
assertTrue(rgbs.contains(0xff00ff22));
assertTrue(rgbs.contains(0xffffff02));
}
/**
* This tests "width: max-content" and "width: min-content".
*/
public void testWidth() {
//@formatter:off
String maxContent = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " h1 { width: max-content; background-color: red; }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
// first test the orig Swing implementation:
{
List<Operation> ops = getOperations(false, maxContent);
assertEquals(3, ops.size());
FillOperation bodyBackground = (FillOperation) ops.get(0);
FillOperation h1Background = (FillOperation) ops.get(1);
assertEquals(1000, bodyBackground.getBounds().getBounds().width);
// it didn't recognize "max-content":
assertTrue(h1Background.getBounds().getBounds().width > 900);
}
// our new implementation should use smaller width:
{
List<Operation> maxContentOps = getOperations(true, maxContent);
{
assertEquals(3, maxContentOps.size());
FillOperation bodyBackground = (FillOperation) maxContentOps
.get(0);
FillOperation h1Background = (FillOperation) maxContentOps
.get(1);
assertEquals(1000,
bodyBackground.getBounds().getBounds().width);
// ... we should support "max-content":
assertTrue(h1Background.getBounds().getBounds().width < 200);
}
// and now a little extra test: let's compare the min-content
// against the max-content. Since we're using two words ("LOREM
// IPSUM") the min-content should produce two wrapping lines of
// text.
//@formatter:off
String minContent = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " h1 { width: min-content; background-color: red; }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> minContentOps = getOperations(true, minContent);
// 2 lines of text now (before we had 1)
assertEquals(4, minContentOps.size());
FillOperation h1BackgroundMin = (FillOperation) minContentOps
.get(1);
FillOperation h1BackgroundMax = (FillOperation) maxContentOps
.get(1);
// is our "min-content" narrower than our max-content
assertTrue(h1BackgroundMin.getBounds()
.getBounds().width < h1BackgroundMax.getBounds()
.getBounds().width);
}
}
/**
* This tests that margins of "auto" can be used to left-align, right-align
* or center-align h1 views.
*/
public void testMargin_auto() {
{
//@formatter:off
String maxContent = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " h1 { width: max-content; background-color: red; margin-right:auto;}\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, maxContent);
assertEquals(3, ops.size());
Rectangle h1Background = ops.get(1).getBounds().getBounds();
assertTrue(h1Background.getMaxX() < 200);
}
{
//@formatter:off
String maxContent = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " h1 { width: max-content; background-color: red; margin-left:auto;}\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, maxContent);
assertEquals(3, ops.size());
Rectangle h1Background = ops.get(1).getBounds().getBounds();
assertTrue(h1Background.getMinX() > htmlPaneSize.width - 200);
}
{
//@formatter:off
String maxContent = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " h1 { width: max-content; background-color: red; margin-left:auto; margin-right:auto}\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, maxContent);
assertEquals(3, ops.size());
Rectangle h1Background = ops.get(1).getBounds().getBounds();
assertTrue(Math.abs(
h1Background.getCenterX() - htmlPaneSize.width / 2) < 5);
}
}
/**
* This checks that if there are competing instructions for "margin" and
* "margin-right" that we respect the last instruction.
*/
public void testMarginConstituentOrder() {
// this should be left-aligned:
{
//@formatter:off
String maxContent = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " h1 { width: max-content; background-color: red; "
+ " margin: 0; "
+ " margin-right:auto;}\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, maxContent);
assertEquals(3, ops.size());
Rectangle h1Background = ops.get(1).getBounds().getBounds();
assertTrue(h1Background.getMaxX() < 200);
}
// this should be centered
{
//@formatter:off
String maxContent = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " h1 { width: max-content; background-color: red; "
+ " margin-right:auto;\n"
+ " margin: 0 }"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>LOREM IPSUM</h1>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> ops = getOperations(true, maxContent);
assertEquals(3, ops.size());
Rectangle h1Background = ops.get(1).getBounds().getBounds();
assertTrue(Math.abs(
h1Background.getCenterX() - htmlPaneSize.width / 2) < 5);
}
}
/**
* This makes sure a line height of three is spread out to take 3x as much
* space as usual.
*/
public void testLineHeight() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " body { line-height: 3; }"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam"
+ " </body>\n"
+ "</html>";
//@formatter:on
TextPaneFormatter smallText = new TextPaneFormatter() {
@Override
public JComponent format(JEditorPane p) {
p.setSize(new Dimension(100, 1000));
return p;
}
};
List<Operation> opsQ = getOperations(true, html, smallText);
List<Operation> opsOrig = getOperations(false, html, smallText);
int indexQ = 1;
int indexOrig = 2;
while (indexOrig < 10) {
StringOperation opOrig = (StringOperation) opsOrig.get(indexOrig);
StringOperation opQ = (StringOperation) opsQ.get(indexQ);
assertEquals(opOrig.getY(), opQ.getY());
indexOrig += 3;
indexQ++;
}
}
/**
* This makes sure the keyword "normal" makes taller lines in the QHtml
* renderer.
*/
public void testLineHeight_normalDefault() {
//@formatter:off
String html = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " body { line-height: normal; }"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam"
+ " </body>\n"
+ "</html>";
//@formatter:on
TextPaneFormatter smallText = new TextPaneFormatter() {
@Override
public JComponent format(JEditorPane p) {
p.setSize(new Dimension(100, 1000));
return p;
}
};
List<Operation> opsQ = getOperations(true, html, smallText);
List<Operation> opsOrig = getOperations(false, html, smallText);
assertTrue(opsOrig.get(opsOrig.size() - 1).getBounds().getMaxY() > 150);
assertTrue(opsQ.get(opsQ.size() - 1).getBounds().getMaxY() > 150
* CssLineHeightValue.VALUE_NORMAL);
}
/**
* When we have a background image with a border radius: we need to render
* the background with the appropriate Shape.
* <p>
* This covers issue #80 where we were ignoring the shape and rendering the
* background as a Rectangle.
*/
public void testRoundedCornerBackgroundImage() {
//@formatter:off
// this one does NOT have a 'border-radius', so it uses a rectangular background
String rectHtml = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " body { background-color: white; }\n"
+ " h2 { padding: 4px 10px 4px 10px; \n"
+ " background-image:\n"
+ " repeating-linear-gradient(190deg, rgba(255, 0, 0, 0.5) 40px,\n"
+ " rgba(255, 153, 0, 0.5) 80px, rgba(255, 255, 0, 0.5) 120px,\n"
+ " rgba(0, 255, 0, 0.5) 160px, rgba(0, 0, 255, 0.5) 200px,\n"
+ " rgba(75, 0, 130, 0.5) 240px, rgba(238, 130, 238, 0.5) 280px,\n"
+ " rgba(255, 0, 0, 0.5) 300px);\n"
+ " font: bold 130% sans-serif; \n"
+ " color: white; \n"
+ " width: max-content; \n"
+ " background-clip: border-box; \n"
+ " border: transparent;}\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h2>Header 2</h2>\n"
+ " </body>\n"
+ "</html>";
// this one has a 'border-radius', so it uses a rounded rectangle background:
String roundRectHtml = "<html>\n"
+ " <head>\n"
+ " <style>\n"
+ " body { background-color: white; }\n"
+ " h2 { padding: 4px 10px 4px 10px; \n"
+ " background-image:\n"
+ " repeating-linear-gradient(190deg, rgba(255, 0, 0, 0.5) 40px,\n"
+ " rgba(255, 153, 0, 0.5) 80px, rgba(255, 255, 0, 0.5) 120px,\n"
+ " rgba(0, 255, 0, 0.5) 160px, rgba(0, 0, 255, 0.5) 200px,\n"
+ " rgba(75, 0, 130, 0.5) 240px, rgba(238, 130, 238, 0.5) 280px,\n"
+ " rgba(255, 0, 0, 0.5) 300px);\n"
+ " font: bold 130% sans-serif; \n"
+ " color: white; \n"
+ " width: max-content; \n"
+ " background-clip: border-box; \n"
+ " border: transparent; \n"
+ " border-radius:10px;}\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h2>Header 2</h2>\n"
+ " </body>\n"
+ "</html>";
//@formatter:on
List<Operation> rectOps = getOperations(true, rectHtml);
List<Operation> roundRectOps = getOperations(true, roundRectHtml);
Rectangle2D rectHeaderBackgroundAsRect = ShapeUtils
.getRectangle2D(((FillOperation) rectOps.get(2)).getShape());
Rectangle2D roundRectHeaderBkgndAsRect = ShapeUtils.getRectangle2D(
((FillOperation) roundRectOps.get(2)).getShape());
// the aliased one (with no rounded corners) should be a Rectangle2D:
assertNotNull(rectHeaderBackgroundAsRect);
// the antialiased one (with rounded corners) should not be a
// Rectangle2D:
assertNull(roundRectHeaderBkgndAsRect);
}
private static void assertImageEquals(BufferedImage bi1, BufferedImage bi2,
int tolerance) {
assertEquals(bi1.getWidth(), bi2.getWidth());
assertEquals(bi1.getHeight(), bi2.getHeight());
assertEquals(bi1.getType(), BufferedImage.TYPE_INT_ARGB);
assertEquals(bi2.getType(), BufferedImage.TYPE_INT_ARGB);
int[] row1 = new int[bi1.getWidth()];
int[] row2 = new int[bi1.getWidth()];
for (int y = 0; y < bi1.getHeight(); y++) {
bi1.getRaster().getDataElements(0, y, row1.length, 1, row1);
bi2.getRaster().getDataElements(0, y, row1.length, 1, row2);
for (int x = 0; x < bi1.getWidth(); x++) {
int red1 = (row1[x] >> 16) & 0xff;
int green1 = (row1[x] >> 8) & 0xff;
int blue1 = (row1[x] >> 0) & 0xff;
int alpha1 = (row1[x] >> 24) & 0xff;
int red2 = (row2[x] >> 16) & 0xff;
int green2 = (row2[x] >> 8) & 0xff;
int blue2 = (row2[x] >> 0) & 0xff;
int alpha2 = (row2[x] >> 24) & 0xff;
assertTrue(
"red1 = " + red1 + ", red2 = " + red2 + " at (" + x
+ "," + y + ")",
Math.abs(red1 - red2) <= tolerance);
assertTrue(
"green1 = " + green1 + ", green2 = " + green2 + " at ("
+ x + "," + y + ")",
Math.abs(green1 - green2) <= tolerance);
assertTrue(
"blue1 = " + blue1 + ", blue2 = " + blue2 + " at (" + x
+ "," + y + ")",
Math.abs(blue1 - blue2) <= tolerance);
assertTrue(
"alpha1 = " + alpha1 + ", alpha2 = " + alpha2 + " at ("
+ x + "," + y + ")",
Math.abs(alpha1 - alpha2) <= tolerance);
}
}
}
private BufferedImage getImage(String html) {
HTMLEditorKit kit = new QHTMLEditorKit();
JEditorPane p = new JEditorPane();
p.setEditorKit(kit);
p.setText(html);
p.setPreferredSize(htmlPaneSize);
p.setSize(htmlPaneSize);
BufferedImage bi = new BufferedImage(htmlPaneSize.width,
htmlPaneSize.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
p.paint(g);
g.dispose();
return bi;
}
}
|
package com.kyloth.serleenacloud.datamodel.auth;
import static org.junit.Assert.*;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
public class TempTokenTest {
/**
* Testa la correttezza del costruttore e dei metodi
* "getter" della classe.
*/
@Test
public void testConstructor() {
String deviceId = "id";
String s = deviceId + new SimpleDateFormat("yyyyMMddHH").format(new Date(121542));
String token = deviceId + "::" + Util.sha256(s);
TempToken tt = new TempToken(deviceId, new Date(121542));
assertTrue(tt.getDeviceId().equals(deviceId));
assertTrue(tt.getToken().equals(token));
}
}
|
package me.coley.recaf;
import me.coley.recaf.graph.SearchResult;
import me.coley.recaf.graph.impl.*;
import me.coley.recaf.workspace.JarResource;
import me.coley.recaf.workspace.Workspace;
import org.junit.jupiter.api.*;
import org.objectweb.asm.ClassReader;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for class hierarchy graph.
*
* @author Matt
*/
public class HierarchyTest extends Base {
private Hierarchy graph;
@BeforeEach
public void setup() throws IOException {
File file = getClasspathFile("inherit.jar");
Workspace workspace = new Workspace(new JarResource(file));
graph = workspace.getHierarchy();
}
@Test
public void testDescendants() {
String actualParent = "test/Greetings";
Set<String> expectedChildren = new HashSet<>(Arrays.asList(
"test/Person", "test/Jedi", "test/Sith", "test/Yoda"));
Set<String> descendants = graph.getAllDescendants(actualParent).collect(Collectors.toSet());
expectedChildren.forEach(child -> assertTrue(descendants.contains(child)));
}
@Test
public void testParents() {
String actualChild = "test/Yoda";
Set<String> expectedParents = new HashSet<>(Arrays.asList(
"test/Jedi", "test/Person", "test/Greetings", "java/lang/Object"));
Set<String> parents = graph.getAllParents(actualChild).collect(Collectors.toSet());
expectedParents.forEach(parent -> assertTrue(parents.contains(parent)));
}
@Test
public void testParentToChildSearch() {
ClassVertex root = graph.getRoot("test/Person");
ClassVertex target = graph.getRoot("test/Yoda");
SearchResult<ClassReader> result = new ClassDfsSearch(ClassDfsSearch.Type.CHILDREN).find(root, target);
if (result != null) {
String[] expectedPath = new String[] {"test/Person", "test/Jedi", "test/Yoda"};
String[] actualPath = result.getPath().stream()
.map(v -> v.getData().getClassName()).toArray(String[]::new);
assertArrayEquals(expectedPath, actualPath);
} else {
fail("no path");
}
}
@Test
public void testChildToParentSearch() {
ClassVertex root = graph.getRoot("test/Yoda");
ClassVertex target = graph.getRoot("test/Person");
SearchResult<ClassReader> result = new ClassDfsSearch(ClassDfsSearch.Type.PARENTS).find(root, target);
if (result != null) {
String[] expectedPath = new String[] {"test/Yoda", "test/Jedi", "test/Person"};
String[] actualPath = result.getPath().stream()
.map(v -> v.getData().getClassName()).toArray(String[]::new);
assertArrayEquals(expectedPath, actualPath);
} else {
fail("no path");
}
}
@Test
public void testHierarchyBuilder() {
// Replicated in Hierarchy#getHierarchy(root)
ClassVertex root = graph.getRoot("test/Yoda");
ClassHierarchyBuilder builder = new ClassHierarchyBuilder();
Set<ClassVertex> hierarchy = builder.build(root);
// Almost all names should be discovered in the hierarchy for this test case.
// Sith and Jedi for example, share the same parent "Person".
Set<String> expected = new HashSet<>(Arrays.asList(
"test/Deal", "test/Absolutes",
"test/Person", "test/Greetings",
"test/Jedi", "test/Sith",
"test/Yoda", "java/lang/Object"));
assertEquals(expected.size(), hierarchy.stream()
.filter(v -> expected.contains(v.getData().getClassName()))
.count());
// Only two classes that should NOT be in there.
// Never used
assertFalse(hierarchy.stream().anyMatch(v -> v.getData().getClassName().equals("test/Speech")));
// Referenced as field, never inherited
assertFalse(hierarchy.stream().anyMatch(v -> v.getData().getClassName().equals("test/Ability")));
}
@Test
public void testIsLibrary() {
// The "say" method is defined only by classes in the input.
// - It is not a "library" method.
assertFalse(graph.isLibrary("test/Yoda", "say", "()V"));
// The "toString" method belongs to "java/lang/Object" which is not in the input.
// - It is a "library" method.
assertTrue(graph.isLibrary("test/Yoda", "toString", "()Ljava/lang/String;"));
}
@Test
public void testAreLinked() {
// Yoda -> Person -> Greetings
assertTrue(graph.areLinked("test/Yoda", "say", "()V", "test/Greetings", "say", "()V"));
// No path between Yoda and Speech
assertFalse(graph.areLinked("test/Yoda", "say", "()V", "test/Speech", "say", "()V"));
}
}
|
package me.kahlil.scene;
import me.kahlil.geometry.Ray3D;
import me.kahlil.geometry.RayHit;
import me.kahlil.geometry.Sphere3D;
import me.kahlil.geometry.Vector;
import me.kahlil.graphics.Color;
import org.junit.Test;
import java.util.Optional;
import java.util.Random;
import static me.kahlil.graphics.Color.RED;
import static org.junit.Assert.*;
/**
* Unit tests for {@link Sphere3D}.
*/
public class Sphere3DTest {
private static final double DELTA = .000001;
private static final Material material = ImmutableMaterial.builder()
.setColor(RED)
.setHardness(10)
.setSpecularIntensity(1.0)
.build();
private static final Sphere3D unitSphere = new Sphere3D(
new Vector(0, 0, 0),
1,
material,
material);
@Test
public void testInsiderMaterial() {
assertEquals(unitSphere.getInsideMaterial().getColor(), RED);
assertEquals(unitSphere.getInsideMaterial().getHardness(), 10);
}
@Test
public void testOutsideMaterial() {
assertEquals(unitSphere.getOutsideMaterial().getColor(), RED);
assertEquals(unitSphere.getOutsideMaterial().getHardness(), 10);
}
@Test
public void testRayIntersectFromInside() {
Ray3D r = new Ray3D(new Vector(0, 0, 0), new Vector(1, 1, 1));
Optional<RayHit> rayHit = unitSphere.intersectWith(r);
assertTrue(rayHit.isPresent());
assertEquals(rayHit.get().getDistance(), 1, DELTA);
assertEquals(rayHit.get().getIntersection(), new Vector(1, 1, 1).normalize());
}
@Test
public void testRayIntersectOnceFromOutside() {
Ray3D r = new Ray3D(new Vector(-1, 1, 0), new Vector(1, 0, 0));
Optional<RayHit> rayHit = unitSphere.intersectWith(r);
assertTrue(rayHit.isPresent());
assertEquals(rayHit.get().getDistance(), 1, DELTA);
assertEquals(rayHit.get().getIntersection(), new Vector(0, 1, 0));
}
@Test
public void testRayIntersectTwiceFromOutside() {
for (int i = 0; i < 100; ++i) {
Vector p = getRandPointBiggerThan(1);
Ray3D ray = new Ray3D(p, p.scale(-1));
Optional<RayHit> rh = unitSphere.intersectWith(ray);
assertTrue(rh.isPresent());
assertTrue(rh.get().getDistance() < p.magnitude());
}
}
@Test
public void testRayDoesNotIntersectSphere() {
Ray3D r = new Ray3D(new Vector(0, -2, 0), new Vector(0, -1, 0));
Optional<RayHit> rh = unitSphere.intersectWith(r);
assertFalse(rh.isPresent());
}
private static Vector getRandPointBiggerThan(int i) {
Random rand = new Random();
return new Vector(rand.nextInt(100) + i, rand.nextInt(100) + i, rand.nextInt(100) + i);
}
}
|
package utask.logic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static utask.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static utask.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
import static utask.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.google.common.eventbus.Subscribe;
import utask.commons.core.EventsCenter;
import utask.commons.events.model.UTaskChangedEvent;
import utask.commons.events.ui.JumpToListRequestEvent;
import utask.commons.events.ui.ShowHelpRequestEvent;
import utask.commons.exceptions.IllegalValueException;
import utask.logic.commands.ClearCommand;
import utask.logic.commands.Command;
import utask.logic.commands.CommandResult;
import utask.logic.commands.CreateCommand;
import utask.logic.commands.DeleteCommand;
import utask.logic.commands.DoneCommand;
import utask.logic.commands.EditCommand;
import utask.logic.commands.ExitCommand;
import utask.logic.commands.FindCommand;
import utask.logic.commands.HelpCommand;
import utask.logic.commands.ListCommand;
import utask.logic.commands.SelectCommand;
import utask.logic.commands.SortCommand;
import utask.logic.commands.UndoneCommand;
import utask.logic.commands.exceptions.CommandException;
import utask.model.Model;
import utask.model.ModelManager;
import utask.model.ReadOnlyUTask;
import utask.model.UTask;
import utask.model.tag.Tag;
import utask.model.tag.UniqueTagList;
import utask.model.task.Deadline;
import utask.model.task.DeadlineTask;
import utask.model.task.EventTask;
import utask.model.task.FloatingTask;
import utask.model.task.Frequency;
import utask.model.task.IsCompleted;
import utask.model.task.Name;
import utask.model.task.ReadOnlyTask;
import utask.model.task.Task;
import utask.model.task.Timestamp;
import utask.storage.StorageManager;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
// These are for checking the correctness of the events raised
private ReadOnlyUTask latestSavedAddressBook;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
public void handleLocalModelChangedEvent(UTaskChangedEvent abce) {
latestSavedAddressBook = new UTask(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setUp() {
model = new ModelManager();
String tempAddressBookFile = saveFolder.getRoot().getPath()
+ "TempAddressBook.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath()
+ "TempPreferences.json";
logic = new LogicManager(model,
new StorageManager(tempAddressBookFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedAddressBook = new UTask(model.getUTask()); // last
// saved
// assumed
// date
helpShown = false;
targetedJumpIndex = -1; // non yet
}
@After
public void tearDown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() {
String invalidCommand = " ";
assertCommandFailure(invalidCommand, String.format(
MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command, confirms that a CommandException is not thrown and
* that the result message is correct. Also confirms that both the 'address
* book' and the 'last shown list' are as specified.
*
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyUTask, List)
*/
private void assertCommandSuccess(String inputCommand,
String expectedMessage, ReadOnlyUTask expectedAddressBook,
List<? extends ReadOnlyTask> expectedShownList) {
assertCommandBehavior(false, inputCommand, expectedMessage,
expectedAddressBook, expectedShownList);
}
/**
* Executes the command, confirms that a CommandException is thrown and that
* the result message is correct. Both the 'address book' and the 'last
* shown list' are verified to be unchanged.
*
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyUTask, List)
*/
private void assertCommandFailure(String inputCommand,
String expectedMessage) {
UTask expectedAddressBook = new UTask(model.getUTask());
List<ReadOnlyTask> expectedShownList = new ArrayList<>(
model.getFilteredTaskList());
assertCommandBehavior(true, inputCommand, expectedMessage,
expectedAddressBook, expectedShownList);
}
/**
* Executes the command, confirms that the result message is correct and
* that a CommandException is thrown if expected and also confirms that the
* following three parts of the LogicManager object's state are as
* expected:<br>
* - the internal address book data are same as those in the
* {@code expectedAddressBook} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedAddressBook} was saved to the storage file. <br>
*/
private void assertCommandBehavior(boolean isCommandExceptionExpected,
String inputCommand, String expectedMessage,
ReadOnlyUTask expectedUTask,
List<? extends ReadOnlyTask> expectedShownList) {
try {
CommandResult result = logic.execute(inputCommand);
assertFalse("CommandException expected but was not thrown.",
isCommandExceptionExpected);
assertEquals(expectedMessage, result.feedbackToUser);
} catch (CommandException e) {
assertTrue("CommandException not expected but was thrown.",
isCommandExceptionExpected);
assertEquals(expectedMessage, e.getMessage());
}
// Confirm the ui display elements should contain the right data
assertEquals(expectedShownList, model.getFilteredTaskList());
// Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedUTask, model.getUTask());
assertEquals(expectedUTask, latestSavedAddressBook);
}
@Test
public void execute_unknownCommandWord() {
String unknownCommand = "uicfhmowqewca";
assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() {
assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE,
new UTask(), Collections.emptyList());
assertTrue(helpShown);
}
@Test
public void execute_exit() {
assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT,
new UTask(), Collections.emptyList());
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateEventTaskWithSeed(1));
model.addTask(helper.generateEventTaskWithSeed(2));
model.addTask(helper.generateEventTaskWithSeed(3));
assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new UTask(),
Collections.emptyList());
}
@Test
public void execute_add_invalidTaskData() {
// assertCommandFailure("create []\\[;]",
// Name.MESSAGE_NAME_CONSTRAINTS);
assertCommandFailure(
"create Valid Name /by Aa;a /from 1830 to 2030 /repeat Every Monday /tag urgent",
Deadline.MESSAGE_DEADLINE_CONSTRAINTS);
assertCommandFailure(
"create valid name /by 111111 /from /repeat Every Monday /tag urgent",
Timestamp.MESSAGE_TIMESTAMP_CONSTRAINTS);
assertCommandFailure(
"create valid name /by 111111 /from 0000 to 1200 /repeat Every Monday /tag ;a!!e",
Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.simpleTask();
UTask expectedAB = new UTask();
expectedAB.addTask(toBeAdded);
// execute command and verify result
assertCommandSuccess(helper.generateCreateCommand(toBeAdded),
String.format(CreateCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB, expectedAB.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.simpleTask();
// setup starting state
model.addTask(toBeAdded); // task already in internal address book
// execute command and verify result
assertCommandFailure(helper.generateCreateCommand(toBeAdded),
CreateCommand.MESSAGE_DUPLICATE_TASK);
}
// author A0138423J
@Test
public void execute_updateInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("update", expectedMessage);
}
@Test
public void executeDoneUndoneSuccessFailure() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.generateEventTaskWithSeed(1);
UTask expectedAB = new UTask();
expectedAB.addTask(toBeAdded);
// execute command and verify result
assertCommandSuccess(helper.generateCreateCommand(toBeAdded),
String.format(CreateCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB, expectedAB.getTaskList());
// new task by default is false
// execute command and verify result
assertCommandFailure("undone 1",
String.format(UndoneCommand.MESSAGE_DUPLICATE_STATUS));
// now set it to true for comparison
toBeAdded.setCompleted(new IsCompleted("true"));
// execute incomplete command
assertCommandFailure("done ",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE));
// execute command and verify done is executed properly
assertCommandSuccess("done 1",
String.format(DoneCommand.MESSAGE_DONE_TASK_SUCCESS, toBeAdded),
expectedAB, expectedAB.getTaskList());
// repeated done attempts will fail due to no need to update again
// execute command and verify result
assertCommandFailure("done 1",
String.format(DoneCommand.MESSAGE_DUPLICATE_STATUS));
// now set it to false for comparison
toBeAdded.setCompleted(new IsCompleted("false"));
// execute incomplete command
assertCommandFailure("undone ",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, UndoneCommand.MESSAGE_USAGE));
// execute command and verify result
assertCommandSuccess("undone 1",
String.format(UndoneCommand.MESSAGE_UNDONE_TASK_SUCCESS, toBeAdded),
expectedAB, expectedAB.getTaskList());
}
@Test
public void executeUpdateSuccess() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.generateFloatingTaskWithSeed(1);
// toBeAdded missing new Deadline("010117"), new Timestamp("0000 to 2359")
UTask expectedAB = new UTask();
expectedAB.addTask(toBeAdded);
// execute command and verify result
assertCommandSuccess(helper.generateCreateCommand(toBeAdded),
String.format(CreateCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB, expectedAB.getTaskList());
// create similar tasks with common attributes
// dTask missing (new Timestamp("0000 to 2359"))
DeadlineTask dTask = (DeadlineTask) helper.generateDeadlineTaskWithSeed(1);
EventTask eTask = (EventTask) helper.generateEventTaskWithSeed(1);
// TODO fix tests
/*
// attempt to update fTask into dTask
expectedAB.updateTask(0, dTask);
assertCommandSuccess("update 1 /by 010117",
String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, dTask),
expectedAB, expectedAB.getTaskList());
// attempt to update dTask into eTask
expectedAB.updateTask(1, eTask);
assertCommandSuccess("update 1 /from 0000 to 2359",
String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, eTask),
expectedAB, expectedAB.getTaskList());
// execute test for update name
eTask.setName(new Name("Update Name"));
expectedAB.updateTask(0, eTask);
assertCommandSuccess("update 1 /name Update Name",
String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, eTask),
expectedAB, expectedAB.getTaskList());
// execute test for update frequency
eTask.setFrequency(new Frequency("Every Sunday"));
expectedAB.updateTask(0, eTask);
assertCommandSuccess("update 1 /repeat Every Sunday",
String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, eTask),
expectedAB, expectedAB.getTaskList());
// execute test for update isComplete
eTask.setCompleted(new IsCompleted("true"));
expectedAB.updateTask(0, eTask);
assertCommandSuccess("update 1 /done true",
String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, eTask),
expectedAB, expectedAB.getTaskList());
// execute test for update tags
eTask.setTags(generateTagList("Urgent", "Important"));
expectedAB.updateTask(0, eTask);
assertCommandSuccess("update 1 /tag Urgent /tag Important",
String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, eTask),
expectedAB, expectedAB.getTaskList());
*/
}
@Test
public void executeUpdateFailure() throws Exception {
TestDataHelper helper = new TestDataHelper();
// toBeAdded name is "Task 1"
Task toBeAdded = helper.generateFloatingTaskWithSeed(1);
// toBeAdded name is "Task 2"
Task toBeAdded2 = helper.generateFloatingTaskWithSeed(2);
// toBeAdded missing new Deadline("010117"), new Timestamp("0000 to 2359")
UTask expectedAB = new UTask();
expectedAB.addTask(toBeAdded);
// execute command and verify result add Task 1
assertCommandSuccess(helper.generateCreateCommand(toBeAdded),
String.format(CreateCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB, expectedAB.getTaskList());
// execute incomplete command without index and verify result
assertCommandFailure("update ",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
// execute incomplete command without parameters and verify result
assertCommandFailure("update 1 ",
EditCommand.MESSAGE_NOT_EDITED);
// execute command and verify result add Task 2
expectedAB.addTask(toBeAdded2);
assertCommandSuccess(helper.generateCreateCommand(toBeAdded2),
String.format(CreateCommand.MESSAGE_SUCCESS, toBeAdded2),
expectedAB, expectedAB.getTaskList());
// TODO fix test
// test to change task 1 into task 2 (conflict test)
// assertCommandFailure("update 1 /name Task 2 /repeat Every 2 /tag tag2 /tag tag3",
// EditCommand.MESSAGE_DUPLICATE_TASK);
}
// @author A0138423J
@Test
public void execute_list_showsAllPersons() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
UTask expectedAB = helper.generateAddressBook(2);
List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList();
// prepare address book state
helper.addToModel(model, 2);
assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given
* command targeting a single task in the shown list, using visible index.
*
* @param commandWord
* to test assuming it targets a single task in the last shown
* list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(
String commandWord, String expectedMessage) throws Exception {
assertCommandFailure(commandWord, expectedMessage); // index missing
assertCommandFailure(commandWord + " +1", expectedMessage); // index
// should be
// unsigned
assertCommandFailure(commandWord + " -1", expectedMessage); // index
// should be
// unsigned
assertCommandFailure(commandWord + " 0", expectedMessage); // index
// cannot be
assertCommandFailure(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given
* command targeting a single task in the shown list, using visible index.
*
* @param commandWord
* to test assuming it targets a single task in the last shown
* list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord)
throws Exception {
String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set AB state to 2 tasks
model.resetData(new UTask());
for (Task p : taskList) {
model.addTask(p);
}
assertCommandFailure(commandWord + " 3", expectedMessage);
}
@Test
public void executeSelectInvalidArgsFormatErrorMessageShown()
throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT,
SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void executeSelectIndexNotFoundErrorMessageShown()
throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
// @Test
// public void execute_select_jumpsToCorrectTask() throws Exception {
// TestDataHelper helper = new TestDataHelper();
// List<Task> threeTasks = helper.generateTaskList(3);
// UTask expectedAB = helper.generateUTask(threeTasks);
// helper.addToModel(model, threeTasks);
// assertCommandSuccess("select 2",
// String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2),
// expectedAB, expectedAB.getTaskList());
// assertEquals(1, targetedJumpIndex);
// assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1));
@Test
public void executeDeleteInvalidArgsFormatErrorMessageShown()
throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT,
DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void executeDeleteIndexNotFoundErrorMessageShown()
throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
// @Test
// public void execute_delete_removesCorrectTask() throws Exception {
// TestDataHelper helper = new TestDataHelper();
// List<Task> threePersons = helper.generateTaskList(3);
// UTask expectedAB = helper.generateUTask(threePersons);
// expectedAB.removeTask(threePersons.get(1));
// helper.addToModel(model, threePersons);
// assertCommandSuccess("delete 2",
// String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS,
// threePersons.get(1)),
// expectedAB, expectedAB.getTaskList());
// @@author A0138493W
@Test
public void execute_sort_default() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
List<Task> twoTasks = helper.generateTaskList(2);
UTask expectedAB = helper.generateUTask(twoTasks);
// prepare task list state
helper.addToModel(model, twoTasks);
assertCommandSuccess("sort", SortCommand.MESSAGE_SUCCESS, expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_sort_AToZ_order() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
Task second = helper.generateTaskWithName("beta");
Task first = helper.generateTaskWithName("alpha");
Task fourth = helper.generateTaskWithName("gamma");
Task third = helper.generateTaskWithName("deta");
List<Task> fourTasks = helper.generateTaskList(second, first, fourth,
third);
List<Task> expectedList = helper.generateTaskList(first, second, third,
fourth);
UTask expectedAB = helper.generateUTask(expectedList);
// prepare task list state
helper.addToModel(model, fourTasks);
assertCommandSuccess("sort az", SortCommand.MESSAGE_SUCCESS, expectedAB,
expectedList);
}
@Test
public void execute_sort_ZToA_order() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
Task second = helper.generateTaskWithName("beta");
Task first = helper.generateTaskWithName("alpha");
Task fourth = helper.generateTaskWithName("gamma");
Task third = helper.generateTaskWithName("deta");
List<Task> fourTasks = helper.generateTaskList(second, first, fourth,
third);
List<Task> expectedList = helper.generateTaskList(fourth, third, second,
first);
UTask expectedAB = helper.generateUTask(expectedList);
// prepare task list state
helper.addToModel(model, fourTasks);
assertCommandSuccess("sort za", SortCommand.MESSAGE_SUCCESS, expectedAB,
expectedList);
}
@Test
public void execute_sort_earliest_first_order() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
Task second = helper.generateDeadlineTask("task 1", "160317");
Task first = helper.generateDeadlineTask("task 2", "150317");
Task fourth = helper.generateDeadlineTask("task 3", "180317");
Task third = helper.generateDeadlineTask("task 4", "170317");
List<Task> fourTasks = helper.generateTaskList(second, first, fourth,
third);
List<Task> expectedList = helper.generateTaskList(first, second, third,
fourth);
UTask expectedAB = helper.generateUTask(expectedList);
// prepare task list state
helper.addToModel(model, fourTasks);
assertCommandSuccess("sort", SortCommand.MESSAGE_SUCCESS, expectedAB,
expectedList);
}
@Test
public void execute_sort_latest_first_order() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
Task second = helper.generateDeadlineTask("task 1", "160317");
Task first = helper.generateDeadlineTask("task 2", "150317");
Task fourth = helper.generateDeadlineTask("task 3", "180317");
Task third = helper.generateDeadlineTask("task 4", "170317");
List<Task> fourTasks = helper.generateTaskList(second, first, fourth,
third);
List<Task> expectedList = helper.generateTaskList(fourth, third, second,
first);
UTask expectedAB = helper.generateUTask(expectedList);
// prepare task list state
helper.addToModel(model, fourTasks);
assertCommandSuccess("sort latest", SortCommand.MESSAGE_SUCCESS,
expectedAB, expectedList);
}
@Test
public void execute_sort_tag_order() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
Task second = helper.generateTaskwithTags("task 1",
generateTagList("b", "c"));
Task first = helper.generateTaskwithTags("task 2",
generateTagList("e", "a"));
Task fourth = helper.generateTaskwithTags("task 3",
generateTagList("d", "h"));
Task third = helper.generateTaskwithTags("task 4",
generateTagList("e", "b"));
List<Task> fourTasks = helper.generateTaskList(second, first, fourth,
third);
List<Task> expectedList = helper.generateTaskList(first, second, third,
fourth);
UTask expectedAB = helper.generateUTask(expectedList);
// prepare task list state
helper.addToModel(model, fourTasks);
assertCommandSuccess("sort tag", SortCommand.MESSAGE_SUCCESS,
expectedAB, expectedList);
}
private UniqueTagList generateTagList(String tagNmae1, String tagName2)
throws IllegalValueException {
Tag tag1 = new Tag(tagNmae1);
Tag tag2 = new Tag(tagName2);
return new UniqueTagList(tag1, tag2);
}
// @@author
@Test
public void execute_find_invalidArgsFormat() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE);
assertCommandFailure("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p1 = helper.generateTaskWithName("KE Y");
Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo");
List<Task> fourPersons = helper.generateTaskList(p1, pTarget1, p2,
pTarget2);
UTask expectedAB = helper.generateUTask(fourPersons);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2);
helper.addToModel(model, fourPersons);
assertCommandSuccess("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB, expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithName("bla bla KEY bla");
Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p3 = helper.generateTaskWithName("key key");
Task p4 = helper.generateTaskWithName("KEy sduauo");
List<Task> fourPersons = helper.generateTaskList(p3, p1, p4, p2);
UTask expectedAB = helper.generateUTask(fourPersons);
List<Task> expectedList = fourPersons;
helper.addToModel(model, fourPersons);
assertCommandSuccess("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB, expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia");
Task pTarget3 = helper.generateTaskWithName("key key");
Task p1 = helper.generateTaskWithName("sduauo");
List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2,
pTarget3);
UTask expectedAB = helper.generateUTask(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2,
pTarget3);
helper.addToModel(model, fourTasks);
assertCommandSuccess("find key rAnDoM",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB, expectedList);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper {
private Task simpleTask() throws Exception {
Name name = new Name("My debug task");
Deadline deadline = new Deadline("010117");
Timestamp timestamp = new Timestamp("1830 to 2030");
Frequency frequency = new Frequency("Every Monday");
IsCompleted iscompleted = new IsCompleted("no");
Tag tag1 = new Tag("urgent");
Tag tag2 = new Tag("assignment");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new EventTask(name, deadline, timestamp, frequency, tags,
iscompleted);
}
/**
* Generates a valid task using the given seed. Running this function
* with the same parameter values guarantees the returned task will have
* the same state. Each unique seed will generate a unique Task object.
*
* @param seed
* used to generate the task data field values
*/
// author A0138423J
private Task generateEventTaskWithSeed(int seed) throws Exception {
return new EventTask(new Name("Task " + seed),
new Deadline("010120"), new Timestamp("0000 to 2359"),
new Frequency("Every " + seed),
new UniqueTagList(new Tag("tag" + Math.abs(seed)),
new Tag("tag" + Math.abs(seed + 1))),
new IsCompleted("no"));
}
private Task generateDeadlineTaskWithSeed(int seed) throws Exception {
return new DeadlineTask(new Name("Task " + seed),
new Deadline("010120"),
new Frequency("Every " + seed),
new UniqueTagList(new Tag("tag" + Math.abs(seed)),
new Tag("tag" + Math.abs(seed + 1))),
new IsCompleted("no"));
}
private Task generateFloatingTaskWithSeed(int seed) throws Exception {
return new FloatingTask(new Name("Task " + seed),
new Frequency("Every " + seed),
new UniqueTagList(new Tag("tag" + Math.abs(seed)),
new Tag("tag" + Math.abs(seed + 1))),
new IsCompleted("no"));
}
/** Generates the correct add command based on the task given */
private String generateCreateCommand(Task p) {
StringBuffer cmd = new StringBuffer();
cmd.append("create ");
cmd.append(p.getName().toString());
if (!p.getDeadline().isEmpty()) {
cmd.append(" /by ").append(p.getDeadline());
}
if (!p.getTimestamp().isEmpty()) {
cmd.append(" /from ").append(p.getTimestamp());
}
if (!p.getFrequency().isEmpty()) {
cmd.append(" /repeat ").append(p.getFrequency());
}
if (!p.getIsCompleted().isEmpty()) {
cmd.append(" /done ").append(p.getIsCompleted());
}
UniqueTagList tags = p.getTags();
for (Tag t : tags) {
cmd.append(" /tag ").append(t.tagName);
}
return cmd.toString();
}
/**
* Generates an UTask with auto-generated persons.
*/
private UTask generateAddressBook(int numGenerated) throws Exception {
UTask uTask = new UTask();
addToUTask(uTask, numGenerated);
return uTask;
}
/**
* Generates an UTask based on the list of Tasks given.
*/
private UTask generateUTask(List<Task> tasks) throws Exception {
UTask uTask = new UTask();
addToUTask(uTask, tasks);
return uTask;
}
/**
* Adds auto-generated Task objects to the given UTask
*
* @param uTask
* The UTask to which the Task will be added
*/
private void addToUTask(UTask uTask, int numGenerated)
throws Exception {
addToUTask(uTask, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given UTask
*/
private void addToUTask(UTask uTask, List<Task> tasksToAdd)
throws Exception {
for (Task p : tasksToAdd) {
uTask.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
*
* @param model
* The model to which the Persons will be added
*/
private void addToModel(Model model, int numGenerated)
throws Exception {
addToModel(model, generateTaskList(numGenerated));
}
/**
* Adds the given list of Persons to the given model
*/
private void addToModel(Model model, List<Task> personsToAdd)
throws Exception {
for (Task p : personsToAdd) {
model.addTask(p);
}
}
/**
* Generates a list of Persons based on the flags.
*/
private List<Task> generateTaskList(int numGenerated) throws Exception {
List<Task> persons = new ArrayList<>();
for (int i = 1; i <= numGenerated; i++) {
persons.add(generateEventTaskWithSeed(i));
}
return persons;
}
private List<Task> generateTaskList(Task... tasks) {
return Arrays.asList(tasks);
}
/**
* Generates a Task object with given name. Other fields will have some
* dummy values.
*/
private Task generateTaskWithName(String name) throws Exception {
return new EventTask(new Name(name), new Deadline("010117"),
new Timestamp("0000 to 1300"), new Frequency("-"),
new UniqueTagList(new Tag("tag")), new IsCompleted("no"));
}
// @@author A0138493W
/**
* Generates a Task object with given name and deadline Other fields
* will have some dummy values.
*/
private Task generateDeadlineTask(String name, String deadline)
throws Exception {
return new EventTask(new Name(name), new Deadline(deadline),
new Timestamp("0000 to 1300"), new Frequency("-"),
new UniqueTagList(new Tag("tag")), new IsCompleted("no"));
}
/**
* Generates a Task object with given name and deadline Other fields
* will have some dummy values.
*/
private Task generateTaskwithTags(String name, UniqueTagList tags)
throws Exception {
return new EventTask(new Name(name), new Deadline("150317"),
new Timestamp("0000 to 1300"), new Frequency("-"), tags,
new IsCompleted("no"));
}
}
}
|
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.Collator;
import java.text.FieldPosition;
import java.text.Format;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.LineBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.JXTable.GenericEditor;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.SortKey;
import org.jdesktop.swingx.table.TableColumnExt;
import org.jdesktop.swingx.treetable.FileSystemModel;
import org.jdesktop.swingx.util.AncientSwingTeam;
import org.jdesktop.swingx.util.CellEditorReport;
import org.jdesktop.swingx.util.PropertyChangeReport;
/**
* Test to exposed known issues of <code>JXTable</code>.
*
* Ideally, there would be at least one failing test method per open
* Issue in the issue tracker. Plus additional failing test methods for
* not fully specified or not yet decided upon features/behaviour.
*
* @author Jeanette Winzenburg
*/
public class JXTableIssues extends InteractiveTestCase {
private static final Logger LOG = Logger.getLogger(JXTableIssues.class
.getName());
/**
* Issue 373-swingx: table must unsort column on sortable change.
*
*/
public void testTableUnsortedColumnOnColumnSortableChange() {
JXTable table = new JXTable(10, 2);
TableColumnExt columnExt = table.getColumnExt(0);
table.toggleSortOrder(0);
assertTrue(table.getSortOrder(0).isSorted());
columnExt.setSortable(false);
assertFalse("table must have unsorted column on sortable change",
table.getSortOrder(0).isSorted());
}
/**
* Issue 372-swingx: table must cancel edit if column property
* changes to not editable.
* Here we test if the table is not editing after the change.
*/
public void testTableNotEditingOnColumnEditableChange() {
JXTable table = new JXTable(10, 2);
TableColumnExt columnExt = table.getColumnExt(0);
table.editCellAt(0, 0);
// sanity
assertTrue(table.isEditing());
assertEquals(0, table.getEditingColumn());
columnExt.setEditable(false);
assertFalse(table.isCellEditable(0, 0));
assertFalse("table must have terminated edit",table.isEditing());
}
/**
* Issue 372-swingx: table must cancel edit if column property
* changes to not editable.
* Here we test if the table actually canceled the edit.
*/
public void testTableCanceledEditOnColumnEditableChange() {
JXTable table = new JXTable(10, 2);
TableColumnExt columnExt = table.getColumnExt(0);
table.editCellAt(0, 0);
// sanity
assertTrue(table.isEditing());
assertEquals(0, table.getEditingColumn());
TableCellEditor editor = table.getCellEditor();
CellEditorReport report = new CellEditorReport();
editor.addCellEditorListener(report);
columnExt.setEditable(false);
// sanity
assertFalse(table.isCellEditable(0, 0));
assertEquals("editor must have fired canceled", 1, report.getCanceledEventCount());
assertEquals("editor must not have fired stopped",0, report.getStoppedEventCount());
}
/**
* a quick sanity test: reporting okay?.
* (doesn't belong here, should test the tools
* somewhere else)
*
*/
public void testCellEditorFired() {
JXTable table = new JXTable(10, 2);
table.editCellAt(0, 0);
CellEditorReport report = new CellEditorReport();
TableCellEditor editor = table.getCellEditor();
editor.addCellEditorListener(report);
editor.cancelCellEditing();
assertEquals("total count must be equals to canceled",
report.getCanceledEventCount(), report.getEventCount());
assertEquals("editor must have fired canceled", 1, report.getCanceledEventCount());
assertEquals("editor must not have fired stopped", 0, report.getStoppedEventCount());
report.clear();
assertEquals("canceled cleared", 0, report.getCanceledEventCount());
assertEquals("total cleared", 0, report.getStoppedEventCount());
// same cell, same editor
table.editCellAt(0, 0);
editor.stopCellEditing();
assertEquals("total count must be equals to stopped",
report.getStoppedEventCount(), report.getEventCount());
assertEquals("editor must not have fired canceled", 0, report.getCanceledEventCount());
// JW: surprising... it really fires twice?
assertEquals("editor must have fired stopped", 1, report.getStoppedEventCount());
}
/**
* Issue #359-swing: find suitable rowHeight.
*
* Text selection in textfield has row of metrics.getHeight.
* Suitable rowHeight should should take border into account:
* for a textfield that's the metrics height plus 2.
*/
public void testRowHeightFontMetrics() {
JXTable table = new JXTable(10, 2);
TableCellEditor editor = table.getCellEditor(1, 1);
Component comp = table.prepareEditor(editor, 1, 1);
assertEquals(comp.getPreferredSize().height, table.getRowHeight());
}
/**
* Issue??-swingx: turn off scrollbar doesn't work if the
* table was initially in autoResizeOff mode.
*
* Problem with state management.
*
*/
public void testHorizontalScrollEnabled() {
JXTable table = new JXTable();
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
assertEquals("horizontalScroll must be on", true, table.isHorizontalScrollEnabled());
table.setHorizontalScrollEnabled(false);
assertEquals("horizontalScroll must be off", false, table.isHorizontalScrollEnabled());
}
/**
* we have a slight inconsistency in event values: setting the
* client property to null means "false" but the event fired
* has the newValue null.
*
* The way out is to _not_ set the client prop manually, always go
* through the property setter.
*/
public void testClientPropertyNull() {
JXTable table = new JXTable();
// sanity assert: setting client property set's property
PropertyChangeReport report = new PropertyChangeReport();
table.addPropertyChangeListener(report);
table.putClientProperty("terminateEditOnFocusLost", null);
assertFalse(table.isTerminateEditOnFocusLost());
assertEquals(1, report.getEventCount());
assertEquals(1, report.getEventCount("terminateEditOnFocusLost"));
assertEquals(false, report.getLastNewValue("terminateEditOnFocusLost"));
}
/**
* JXTable has responsibility to guarantee usage of
* TableColumnExt comparator and update the sort if
* the columns comparator changes.
*
*/
public void testComparatorToPipelineDynamic() {
JXTable table = new JXTable(new AncientSwingTeam());
TableColumnExt columnX = table.getColumnExt(0);
table.toggleSortOrder(0);
columnX.setComparator(Collator.getInstance());
// invalid assumption .. only the comparator must be used.
// assertEquals("interactive sorter must be same as sorter in column",
// columnX.getSorter(), table.getFilters().getSorter());
SortKey sortKey = SortKey.getFirstSortKeyForColumn(table.getFilters().getSortController().getSortKeys(), 0);
assertNotNull(sortKey);
assertEquals(columnX.getComparator(), sortKey.getComparator());
}
/**
* Issue #256-swingX: viewport - toggle track height must
* revalidate.
*
* PENDING JW: the visual test looks okay - probably something wrong with the
* test setup ... invoke doesn't help
*
*/
public void testToggleTrackViewportHeight() {
// This test will not work in a headless configuration.
if (GraphicsEnvironment.isHeadless()) {
LOG.info("cannot run trackViewportHeight - headless environment");
return;
}
final JXTable table = new JXTable(10, 2);
table.setFillsViewportHeight(true);
final Dimension tablePrefSize = table.getPreferredSize();
JScrollPane scrollPane = new JScrollPane(table);
JXFrame frame = wrapInFrame(scrollPane, "");
frame.setSize(500, tablePrefSize.height * 2);
frame.setVisible(true);
assertEquals("table height be equal to viewport",
table.getHeight(), scrollPane.getViewport().getHeight());
table.setFillsViewportHeight(false);
assertEquals("table height be equal to table pref height",
tablePrefSize.height, table.getHeight());
}
public void testComponentAdapterCoordinates() {
JXTable table = new JXTable(createAscendingModel(0, 10));
Object originalFirstRowValue = table.getValueAt(0,0);
Object originalLastRowValue = table.getValueAt(table.getRowCount() - 1, 0);
assertEquals("view row coordinate equals model row coordinate",
table.getModel().getValueAt(0, 0), originalFirstRowValue);
// sort first column - actually does not change anything order
table.toggleSortOrder(0);
// sanity asssert
assertEquals("view order must be unchanged ",
table.getValueAt(0, 0), originalFirstRowValue);
// invert sort
table.toggleSortOrder(0);
// sanity assert
assertEquals("view order must be reversed changed ",
table.getValueAt(0, 0), originalLastRowValue);
ComponentAdapter adapter = table.getComponentAdapter();
assertEquals("adapter filteredValue expects view coordinates",
table.getValueAt(0, 0), adapter.getFilteredValueAt(0, 0));
// adapter coordinates are view coordinates
adapter.row = 0;
adapter.column = 0;
assertEquals("adapter filteredValue expects view coordinates",
table.getValueAt(0, 0), adapter.getValue());
}
//-------------------- adapted jesse wilson: #223
/**
* Enhancement: modifying (= filtering by resetting the content) should keep
* selection
*
*/
public void testModifyTableContentAndSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(2, 5);
Object[] selectedObjects = new Object[] { "C", "D", "E", "F" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" });
Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" });
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterModify);
}
/**
* Enhancement: modifying (= filtering by resetting the content) should keep
* selection
*/
public void testModifyXTableContentAndSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.xTable.getSelectionModel().setSelectionInterval(2, 5);
Object[] selectedObjects = new Object[] { "C", "D", "E", "F" };
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" });
Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" });
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterModify);
}
/**
* test: deleting row below selection - should not change
*/
public void testDeleteRowBelowSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(2, 5);
compare.xTable.getSelectionModel().setSelectionInterval(2, 5);
Object[] selectedObjects = new Object[] { "C", "D", "E", "F" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1);
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
}
/**
* test: deleting last row in selection - should remove last item from selection.
*/
public void testDeleteLastRowInSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(7, 8);
compare.xTable.getSelectionModel().setSelectionInterval(7, 8);
Object[] selectedObjects = new Object[] { "H", "I" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects);
compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1);
Object[] selectedObjectsAfterDelete = new Object[] { "H" };
assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterDelete);
assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterDelete);
}
private void assertSelection(TableModel tableModel, ListSelectionModel selectionModel, Object[] expected) {
List selected = new ArrayList();
for(int r = 0; r < tableModel.getRowCount(); r++) {
if(selectionModel.isSelectedIndex(r)) selected.add(tableModel.getValueAt(r, 0));
}
List expectedList = Arrays.asList(expected);
assertEquals("selected Objects must be as expected", expectedList, selected);
}
/**
* Issue #393-swingx: localized NumberEditor.
*
* Playing ... Nearly working ... but not reliably.
*
*/
public void interactiveFloatingPointEditor(){
DefaultTableModel model = new DefaultTableModel(
new String[] {"Double-core", "Double-ext", "Integer-core", "Integer-ext", "Object"}, 10) {
@Override
public Class<?> getColumnClass(int columnIndex) {
if ((columnIndex == 0) || (columnIndex == 1)) {
return Double.class;
}
if ((columnIndex == 2) || (columnIndex == 3)){
return Integer.class;
}
return Object.class;
}
};
JXTable table = new JXTable(model);
table.setSurrendersFocusOnKeystroke(true);
table.setValueAt(10.2, 0, 0);
table.setValueAt(10.2, 0, 1);
table.setValueAt(10, 0, 2);
table.setValueAt(10, 0, 3);
table.getColumn(1).setCellEditor(new NumberEditorExt());
table.getColumn(3).setCellEditor(new NumberEditorExt());
showWithScrollingInFrame(table, "Extended NumberEditors (col 1/3)");
}
/**
*
* Issue #393-swingx: localized NumberEditor.
*
* @author Noel Grandin
*/
public static class NumberEditorExt extends DefaultCellEditor {
private static Class[] argTypes = new Class[]{String.class};
java.lang.reflect.Constructor constructor;
public NumberEditorExt() {
this(null);
}
public NumberEditorExt(NumberFormat formatter) {
super(createFormattedTextField(formatter));
final JFormattedTextField textField = ((JFormattedTextField)getComponent());
textField.setName("Table.editor");
textField.setHorizontalAlignment(JTextField.RIGHT);
// remove action listener added in DefaultCellEditor
textField.removeActionListener(delegate);
// replace the delegate created in DefaultCellEditor
delegate = new EditorDelegate() {
public void setValue(Object value) {
((JFormattedTextField)getComponent()).setValue(value);
}
public Object getCellEditorValue() {
JFormattedTextField textField = ((JFormattedTextField)getComponent());
try {
textField.commitEdit();
return textField.getValue();
} catch (ParseException ex) {
return null;
}
}
};
textField.addActionListener(delegate);
}
@Override
public boolean stopCellEditing() {
return super.stopCellEditing();
}
/** Override and set the border back to normal in case there was an error previously */
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int column) {
((JComponent)getComponent()).setBorder(new LineBorder(Color.black));
try {
final Class type = table.getColumnClass(column);
// Assume that the Number object we are dealing with has a constructor which takes
// a single string parameter.
if (!Number.class.isAssignableFrom(type)) {
throw new IllegalStateException("NumberEditor can only handle subclasses of java.lang.Number");
}
constructor = type.getConstructor(argTypes);
}
catch (Exception ex) {
throw new IllegalStateException("Number subclass must have a constructor which takes a string", ex);
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
@Override
public Object getCellEditorValue() {
Number number = (Number) super.getCellEditorValue();
if (number==null) return null;
// we use a String value as an intermediary between the Number object returned by the
// the NumberFormat and the kind of Object the column wants.
try {
return constructor.newInstance(new Object[]{number.toString()});
} catch (IllegalArgumentException ex) {
throw new RuntimeException("NumberEditor not propertly configured", ex);
} catch (InstantiationException ex) {
throw new RuntimeException("NumberEditor not propertly configured", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("NumberEditor not propertly configured", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("NumberEditor not propertly configured", ex);
}
}
/** Use a static method so that we can do some stuff before calling the superclass. */
private static JFormattedTextField createFormattedTextField(NumberFormat formatter)
{
JFormattedTextField textField = new JFormattedTextField(new NumberEditorNumberFormat(formatter))
{
/** the formatted text field will not call stopCellEditing() until the value is valid.
* So do the red border thing here.
*/
@Override
protected void invalidEdit() {
setBorder(new LineBorder(Color.red));
super.invalidEdit();
}
};
// if the border was red for invalid, clear it as soon as the edit becomes valid.
textField.addPropertyChangeListener("editValid", new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue()==Boolean.TRUE)
{
((JFormattedTextField)evt.getSource()).setBorder(new LineBorder(Color.black));
}
}
});
return textField;
}
}
/**
* A specialised Format for the NumberEditor that returns a null for empty strings.
*/
private static class NumberEditorNumberFormat extends Format
{
private final NumberFormat childFormat;
public NumberEditorNumberFormat(NumberFormat childFormat)
{
if (childFormat == null) {
childFormat = NumberFormat.getInstance();
}
this.childFormat = childFormat;
}
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
if (obj==null) return new AttributedString("").getIterator();
return childFormat.formatToCharacterIterator(obj);
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
if (obj==null) return new StringBuffer("");
return childFormat.format(obj, toAppendTo, pos);
}
@Override
public Object parseObject(String source, ParsePosition pos) {
if (source==null) {
pos.setIndex(1); // otherwise Format thinks parse failed
return null;
}
if (source.trim().equals("")) {
pos.setIndex(1); // otherwise Format thinks parse failed
return null;
}
return childFormat.parseObject(source, pos);
}
}
public void interactiveDeleteRowAboveSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(2, 5);
compare.xTable.getSelectionModel().setSelectionInterval(2, 5);
JComponent box = createContent(compare, createRowDeleteAction(0, compare.tableModel));
JFrame frame = wrapInFrame(box, "delete above selection");
frame.setVisible(true);
}
public void interactiveDeleteRowBelowSelection() {
CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" });
compare.table.getSelectionModel().setSelectionInterval(6, 7);
compare.xTable.getSelectionModel().setSelectionInterval(6, 7);
JComponent box = createContent(compare, createRowDeleteAction(-1, compare.tableModel));
JFrame frame = wrapInFrame(box, "delete below selection");
frame.setVisible(true);
}
/**
* Issue #370-swingx: "jumping" selection while dragging.
*
*/
public void interactiveExtendSelection() {
final UpdatingTableModel model = new UpdatingTableModel();
JXTable table = new JXTable(model);
// Swing Timer - EDT in Timer
ActionListener l = new ActionListener() {
int i = 0;
public void actionPerformed(ActionEvent e) {
model.updateCell(i++ % 10);
}
};
Timer timer = new Timer(1000, l);
timer.start();
JXFrame frame = wrapWithScrollingInFrame(table, "#370 - extend selection by dragging");
frame.setVisible(true);
}
/**
* Simple model for use in continous update tests.
* Issue #370-swingx: jumping selection on dragging.
*/
private class UpdatingTableModel extends AbstractTableModel {
private int[][] data = new int[10][5];
public UpdatingTableModel() {
for (int row = 0; row < data.length; row++) {
fillRow(row);
}
}
public int getRowCount() {
return 10;
}
public int getColumnCount() {
return 5;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
/**
* update first column of row on EDT.
* @param row
*/
public void invokeUpdateCell(final int row) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateCell(row);
}
});
}
/**
* update first column of row. Sorting on any column except the first
* doesn't change row sequence - shouldn't interfere with selection
* extension.
*
* @param row
*/
public void updateCell(final int row) {
updateCell(row, 0);
fireTableCellUpdated(row, 0);
}
public void fillRow(int row) {
for (int col = 0; col < data[row].length; col++) {
updateCell(row, col);
}
}
/**
* Fills the given cell with random value.
* @param row
* @param col
*/
private void updateCell(int row, int col) {
data[row][col] = (int) Math.round(Math.random() * 200);
}
}
/**
* Issue #282-swingx: compare disabled appearance of
* collection views.
*
*/
public void interactiveDisabledCollectionViews() {
final JXTable table = new JXTable(new AncientSwingTeam());
table.setEnabled(false);
final JXList list = new JXList(new String[] {"one", "two", "and something longer"});
list.setEnabled(false);
final JXTree tree = new JXTree(new FileSystemModel());
tree.setEnabled(false);
JComponent box = Box.createHorizontalBox();
box.add(new JScrollPane(table));
box.add(new JScrollPane(list));
box.add(new JScrollPane(tree));
JXFrame frame = wrapInFrame(box, "disabled collection views");
AbstractAction action = new AbstractAction("toggle disabled") {
public void actionPerformed(ActionEvent e) {
table.setEnabled(!table.isEnabled());
list.setEnabled(!list.isEnabled());
tree.setEnabled(!tree.isEnabled());
}
};
addAction(frame, action);
frame.setVisible(true);
}
public void interactiveDataChanged() {
final DefaultTableModel model = createAscendingModel(0, 10, 5, false);
JXTable xtable = new JXTable(model);
xtable.setRowSelectionInterval(0, 0);
JTable table = new JTable(model);
table.setRowSelectionInterval(0, 0);
AbstractAction action = new AbstractAction("fire dataChanged") {
public void actionPerformed(ActionEvent e) {
model.fireTableDataChanged();
}
};
JXFrame frame = wrapWithScrollingInFrame(xtable, table, "selection after data changed");
addAction(frame, action);
frame.setVisible(true);
}
private JComponent createContent(CompareTableBehaviour compare, Action action) {
JComponent box = new JPanel(new BorderLayout());
box.add(new JScrollPane(compare.table), BorderLayout.WEST);
box.add(new JScrollPane(compare.xTable), BorderLayout.EAST);
box.add(new JButton(action), BorderLayout.SOUTH);
return box;
}
private Action createRowDeleteAction(final int row, final ReallySimpleTableModel simpleTableModel) {
Action delete = new AbstractAction("DeleteRow " + ((row < 0) ? "last" : "" + row)) {
public void actionPerformed(ActionEvent e) {
int rowToDelete = row;
if (row < 0) {
rowToDelete = simpleTableModel.getRowCount() - 1;
}
if ((rowToDelete < 0) || (rowToDelete >= simpleTableModel.getRowCount())) {
return;
}
simpleTableModel.removeRow(rowToDelete);
if (simpleTableModel.getRowCount() == 0) {
setEnabled(false);
}
}
};
return delete;
}
public static class CompareTableBehaviour {
public ReallySimpleTableModel tableModel;
public JTable table;
public JXTable xTable;
public CompareTableBehaviour(Object[] model) {
tableModel = new ReallySimpleTableModel();
tableModel.setContents(model);
table = new JTable(tableModel);
xTable = new JXTable(tableModel);
table.getColumnModel().getColumn(0).setHeaderValue("JTable");
xTable.getColumnModel().getColumn(0).setHeaderValue("JXTable");
}
};
/**
* A one column table model where all the data is in an Object[] array.
*/
static class ReallySimpleTableModel extends AbstractTableModel {
private List contents = new ArrayList();
public void setContents(List contents) {
this.contents.clear();
this.contents.addAll(contents);
fireTableDataChanged();
}
public void setContents(Object[] contents) {
setContents(Arrays.asList(contents));
}
public void removeRow(int row) {
contents.remove(row);
fireTableRowsDeleted(row, row);
}
public int getRowCount() {
return contents.size();
}
public int getColumnCount() {
return 1;
}
public Object getValueAt(int row, int column) {
if(column != 0) throw new IllegalArgumentException();
return contents.get(row);
}
}
/**
* returns a tableModel with count rows filled with
* ascending integers in first column
* starting from startRow.
* @param startRow the value of the first row
* @param rowCount the number of rows
* @return
*/
private DefaultTableModel createAscendingModel(int startRow, final int rowCount,
final int columnCount, boolean fillLast) {
DefaultTableModel model = new DefaultTableModel(rowCount, columnCount) {
public Class getColumnClass(int column) {
Object value = rowCount > 0 ? getValueAt(0, column) : null;
return value != null ? value.getClass() : super.getColumnClass(column);
}
};
int filledColumn = fillLast ? columnCount - 1 : 0;
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(new Integer(startRow++), i, filledColumn);
}
return model;
}
private DefaultTableModel createAscendingModel(int startRow, int count) {
DefaultTableModel model = new DefaultTableModel(count, 5);
for (int i = 0; i < model.getRowCount(); i++) {
model.setValueAt(new Integer(startRow++), i, 0);
}
return model;
}
/**
* Issue #??: JXTable pattern search differs from
* PatternHighlighter/Filter.
*
* Fixing the issue (respect the pattern as is by calling
* pattern.matcher().matches instead of the find()) must
* make sure that the search methods taking the string
* include wildcards.
*
* Note: this method passes as long as the issue is not
* fixed!
*
* TODO: check status!
*/
public void testWildCardInSearchByString() {
JXTable table = new JXTable(createAscendingModel(0, 11));
int row = 1;
String lastName = table.getValueAt(row, 0).toString();
int found = table.getSearchable().search(lastName, -1);
assertEquals("found must be equal to row", row, found);
found = table.getSearchable().search(lastName, found);
assertEquals("search must succeed", 10, found);
}
public static void main(String args[]) {
JXTableIssues test = new JXTableIssues();
try {
test.runInteractiveTests();
// test.runInteractiveTests("interactive.*Siz.*");
// test.runInteractiveTests("interactive.*Render.*");
// test.runInteractiveTests("interactive.*Toggle.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
}
|
package org.lwjgl.test.openal;
import org.lwjgl.openal.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* idea from openal-info
*
* @author Brian Matzon <brian@matzon.dk>
*/
public class OpenALInfo {
/**
* Creates an instance of OpenALInfo
*/
public OpenALInfo() {
}
/**
* Runs the actual test, using supplied arguments
*/
protected void execute(String[] args) {
ALContext alContext = null;
try {
alContext = AL.create(null, 44100, 60, false);
checkForErrors(alContext);
} catch (Exception e) {
die("Init", e.getMessage());
}
printALCInfo(alContext);
printALInfo(alContext);
printEFXInfo(alContext);
checkForErrors(alContext);
AL.destroy(alContext);
}
private void printALCInfo(ALContext alContext) {
// we're running 1.1, so really no need to query for the 'ALC_ENUMERATION_EXT' extension
if (ALC.getCapabilities().ALC_ENUMERATION_EXT) {
if (ALC.getCapabilities().ALC_ENUMERATE_ALL_EXT) {
printDevices(alContext, 0, EnumerateAllExt.ALC_ALL_DEVICES_SPECIFIER, "playback");
} else {
printDevices(alContext, 0, ALC10.ALC_DEVICE_SPECIFIER, "playback");
}
printDevices(alContext, 0, ALC11.ALC_CAPTURE_DEVICE_SPECIFIER, "capture");
} else {
System.out.println("No device enumeration available");
}
if (ALC.getCapabilities().ALC_ENUMERATE_ALL_EXT) {
System.out.println("Default playback device: " + ALC10.alcGetString(0, EnumerateAllExt.ALC_DEFAULT_ALL_DEVICES_SPECIFIER));
} else {
System.out.println("Default playback device: " + ALC10.alcGetString(0, ALC10.ALC_DEFAULT_DEVICE_SPECIFIER));
}
System.out.println("Default capture device: " + ALC10.alcGetString(0, ALC11.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
int majorVersion = ALC10.alcGetInteger(0, ALC10.ALC_MAJOR_VERSION);
int minorVersion = ALC10.alcGetInteger(0, ALC10.ALC_MINOR_VERSION);
checkForErrors(alContext);
System.out.println("ALC version: " + majorVersion + "." + minorVersion);
System.out.println("ALC extensions:");
String[] extensions = ALC10.alcGetString(alContext.getDeviceContext().getDevice(), ALC10.ALC_EXTENSIONS).split(" ");
for (String extension : extensions) {
if (extension.trim().length() == 0) {
continue;
}
System.out.println(" " + extension);
}
checkForErrors(alContext);
}
private void printALInfo(ALContext alContext) {
System.out.println("OpenAL vendor string: " + AL10.alGetString(AL10.AL_VENDOR));
System.out.println("OpenAL renderer string: " + AL10.alGetString(AL10.AL_RENDERER));
System.out.println("OpenAL version string: " + AL10.alGetString(AL10.AL_VERSION));
System.out.println("AL extensions:");
String[] extensions = AL10.alGetString(AL10.AL_EXTENSIONS).split(" ");
for (String extension : extensions) {
if (extension.trim().length() == 0) {
continue;
}
System.out.println(" " + extension);
}
checkForErrors(alContext);
}
private void printEFXInfo(ALContext alContext) {
if (!EFXUtil.isEfxSupported()) {
System.out.println("EFX not available");
return;
}
int efxMajor = ALC10.alcGetInteger(alContext.getDeviceContext().getDevice(), EXTEfx.ALC_EFX_MAJOR_VERSION);
int efxMinor = ALC10.alcGetInteger(alContext.getDeviceContext().getDevice(), EXTEfx.ALC_EFX_MINOR_VERSION);
if (ALC10.alcGetError(alContext.getDeviceContext().getDevice()) == ALC10.ALC_NO_ERROR) {
System.out.println("EFX version: " + efxMajor + "." + efxMinor);
}
int auxSends = ALC10.alcGetInteger(alContext.getDeviceContext().getDevice(), EXTEfx.ALC_MAX_AUXILIARY_SENDS);
if (ALC10.alcGetError(alContext.getDeviceContext().getDevice()) == ALC10.ALC_NO_ERROR) {
System.out.println("Max auxiliary sends: " + auxSends);
}
System.out.println("Supported filters: ");
HashMap<String, Integer> filters = new HashMap<String, Integer>();
filters.put("Low-pass", EXTEfx.AL_FILTER_LOWPASS);
filters.put("High-pass", EXTEfx.AL_FILTER_HIGHPASS);
filters.put("Band-pass", EXTEfx.AL_FILTER_BANDPASS);
Set<Entry<String, Integer>> entries = filters.entrySet();
for (final Entry<String, Integer> entry : entries) {
String key = entry.getKey();
if (EFXUtil.isFilterSupported(entry.getValue()))
System.out.println(" " + entry.getKey());
}
System.out.println("Supported effects: ");
HashMap<String, Integer> effects = new HashMap<String, Integer>();
effects.put("EAX Reverb", EXTEfx.AL_EFFECT_EAXREVERB);
effects.put("Reverb", EXTEfx.AL_EFFECT_REVERB);
effects.put("Chorus", EXTEfx.AL_EFFECT_CHORUS);
effects.put("Distortion", EXTEfx.AL_EFFECT_DISTORTION);
effects.put("Echo", EXTEfx.AL_EFFECT_ECHO);
effects.put("Flanger", EXTEfx.AL_EFFECT_FLANGER);
effects.put("Frequency Shifter", EXTEfx.AL_EFFECT_FREQUENCY_SHIFTER);
effects.put("Vocal Morpher", EXTEfx.AL_EFFECT_VOCAL_MORPHER);
effects.put("Pitch Shifter", EXTEfx.AL_EFFECT_PITCH_SHIFTER);
effects.put("Ring Modulator", EXTEfx.AL_EFFECT_RING_MODULATOR);
effects.put("Autowah", EXTEfx.AL_EFFECT_AUTOWAH);
effects.put("Compressor", EXTEfx.AL_EFFECT_COMPRESSOR);
effects.put("Equalizer", EXTEfx.AL_EFFECT_EQUALIZER);
entries = effects.entrySet();
for (final Entry<String, Integer> entry : entries) {
if (EFXUtil.isEffectSupported(entry.getValue()))
System.out.println(" " + entry.getKey());
}
}
private void printDevices(ALContext alContext, long contextDevice, int which, String kind) {
List<String> devices = ALC.getStringList(contextDevice, which);
checkForErrors(alContext);
System.out.println("Available " + kind + " devices: ");
for (String device : devices) {
System.out.println(" " + device);
}
}
private void die(String kind, String description) {
System.out.println(kind + " error " + description + " occured");
}
private void checkForErrors(ALContext alContext) {
{
int error = ALC10.alcGetError(alContext.getDeviceContext().getDevice());
if (error != ALC10.ALC_NO_ERROR) {
die("ALC", ALC10.alcGetString(alContext.getDeviceContext().getDevice(), error));
}
}
{
int error = AL10.alGetError();
if (error != AL10.AL_NO_ERROR) {
die("AL", AL10.alGetString(error));
}
}
}
/**
* main entry point
*
* @param args String array containing arguments
*/
public static void main(String[] args) {
OpenALInfo openalInfo = new OpenALInfo();
openalInfo.execute(args);
System.exit(0);
}
}
|
package uk.ac.kent.dover.fastGraph;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* This class handles all the GUI for the main Launcher.
* It will callback to the launcher when the use requests an algorithm or such like
*
* @author Rob Baker
*
*/
@SuppressWarnings("serial")
public class LauncherGUI extends JFrame {
private final String DEFAULT_STATUS_MESSAGE = "Ready"; //The default message displayed to a user
private Launcher launcher;
private DefaultListModel model = new DefaultListModel();
private double screenWidth; //size of the user's screen
private double screenHeight;
private double textHeight;
/**
* The main builder for the GUI
*
* @param launcher Requires the launcher so it can make callback commands when the user presses buttons etc
*/
public LauncherGUI(Launcher launcher) {
this.launcher = launcher;
try {
//Makes the GUI look like the OS. This has the benefit of scaling the display if the user has zooming or a changed DPI (as Rob does)
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
//find and store the current screen size
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = screenSize.getWidth();
screenHeight = screenSize.getHeight();
textHeight = screenHeight / 100;
JPanel mainPanel = new JPanel(new BorderLayout());
//Builds the graph selection section
JPanel northPanel = new JPanel(new BorderLayout());
JList graphList = buildSourceGraphList();
northPanel.add(graphList, BorderLayout.NORTH);
northPanel.add(new JSeparator(JSeparator.HORIZONTAL), BorderLayout.SOUTH);
Border blackline = BorderFactory.createLineBorder(Color.black);
TitledBorder titled = BorderFactory.createTitledBorder(blackline, "Target Graph");
titled.setTitleJustification(TitledBorder.LEFT);
northPanel.setBorder(titled);
JPanel statusArea = new JPanel(new BorderLayout());
//Displays the progressBar. Not displayed until later, but needed here
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
progressBar.setString("");
//builds the status bar. Again, not used until later;
JPanel statusBar = buildStatusBar();
//adds the two status updates to the statusArea
statusArea.add(progressBar, BorderLayout.NORTH);
statusArea.add(statusBar, BorderLayout.SOUTH);
// Builds the Tabbed area
JTabbedPane tabbedPane = new JTabbedPane();
JPanel motifPanel = buildMotifTab();
tabbedPane.addTab("Motif", motifPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JPanel patternPanel = buildPatternTab();
tabbedPane.addTab("Pattern", patternPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_2);
JPanel convertPanel = buildConvertTab(graphList, progressBar, statusBar);
tabbedPane.addTab("Convert Graph", convertPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_3);
JPanel otherPanel = buildOtherTab(graphList, progressBar, statusBar);
tabbedPane.addTab("Others", otherPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_4);
JPanel gedPanel = buildGedTab(graphList, progressBar, statusBar);
tabbedPane.addTab("GED", gedPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_5);
blackline = BorderFactory.createLineBorder(Color.black);
titled = BorderFactory.createTitledBorder(blackline, "Task");
titled.setTitleJustification(TitledBorder.LEFT);
tabbedPane.setBorder(titled);
//Adds both the upper and lower areas to the main Panel
mainPanel.add(northPanel, BorderLayout.NORTH);
mainPanel.add(tabbedPane, BorderLayout.CENTER);
mainPanel.add(statusArea, BorderLayout.SOUTH);
setJMenuBar(buildMenuBar(mainPanel));
//Builds, Packs and Displays the GUI
this.setContentPane(mainPanel);
setTitle("Dover");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel.setPreferredSize(new Dimension((int) Math.round(screenHeight/2),(int) Math.round(screenHeight/2))); //makes a square window
pack();
setVisible(true);
}
/**
* Builds the menu bar
*
* @param panel The panel which the menu bar is attached to - used for error messages
* @return The menu bar
*/
private JMenuBar buildMenuBar(JPanel panel) {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
exit.getAccessibleContext().setAccessibleDescription("Exit the program");
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
fileMenu.add(exit);
menuBar.add(fileMenu);
JMenu dataMenu = new JMenu("Data");
JMenuItem data = new JMenuItem("Get More Data");
data.getAccessibleContext().setAccessibleDescription("Allows the user to get more data");
data.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
try {
Desktop.getDesktop().browse(new URI(launcher.DATA_URL));
} catch(Exception e) {
JOptionPane.showMessageDialog(panel, "Browser loading is not supported. \nInstead, please visit:\n" + launcher.DATA_URL, "Browser Loading not supported", JOptionPane.WARNING_MESSAGE);
e.printStackTrace();
}
}
});
dataMenu.add(data);
menuBar.add(dataMenu);
return menuBar;
}
/**
* Build the main graph list.
* This allows the user to choose which graph they wish to perform things on
* @return The JList component containing the graphs
*/
private JList buildSourceGraphList() {
File folder = new File(Launcher.startingWorkingDirectory+File.separatorChar+"data");
File[] listOfFiles = folder.listFiles();
ArrayList<String> graphs = new ArrayList<String>();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory() && !listOfFiles[i].getName().equals("snap")) {
graphs.add(listOfFiles[i].getName());
}
}
Collections.sort(graphs, String.CASE_INSENSITIVE_ORDER);
for(String s : graphs) {
model.addElement(s);
}
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(-1);
return list;
}
/**
* Builds the Panel used to house the GUI elements for the Motif Tab
* @return The Motif Tab
*/
private JPanel buildMotifTab() {
JPanel motifPanel = new JPanel(new GridBagLayout());
JLabel infoLabel = new JLabel("Find and export motifs", SwingConstants.CENTER);
JLabel minLabel = new JLabel("Min Size: ");
JLabel maxLabel = new JLabel("Max Size: ");
JTextField minInput = new JTextField(3);
JTextField maxInput = new JTextField(3);
JButton motifBtn = new JButton("Find Motifs");
JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL);
JProgressBar bigProgress = new JProgressBar(0, 100);
bigProgress.setValue(0);
bigProgress.setStringPainted(true);
bigProgress.setString("");
JProgressBar smallProgress = new JProgressBar(0, 100);
smallProgress.setValue(0);
smallProgress.setStringPainted(true);
smallProgress.setString("");
motifBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
int number = checkForPositiveInteger(minInput.getText(),motifPanel);
if (number != -1) {
//replace with actual motif code
System.out.println("Motif search, with number: " + number);
}
}
});
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2,2,2,2);;
c.fill = GridBagConstraints.HORIZONTAL;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
motifPanel.add(infoLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
motifPanel.add(minLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 1;
motifPanel.add(minInput, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
motifPanel.add(maxLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 2;
motifPanel.add(maxInput, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridheight = 2;
c.gridx = 2;
c.gridy = 1;
motifPanel.add(motifBtn, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridheight = 1;
c.gridx = 0;
c.gridy = 3;
motifPanel.add(sep, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridheight = 1;
c.gridx = 0;
c.gridy = 4;
motifPanel.add(bigProgress, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridheight = 1;
c.gridx = 0;
c.gridy = 5;
motifPanel.add(smallProgress, c);
return motifPanel;
}
/**
* Builds the Panel used to house the GUI elements for the Pattern Tab
* @return The Pattern Tab
*/
private JPanel buildPatternTab() {
JPanel patternPanel = new JPanel(new BorderLayout());
patternPanel.add(new JButton("Button"), BorderLayout.WEST);
return patternPanel;
}
/**
* Builds the Panel used to house the GUI elements for the Pattern Tab
* @return The Pattern Tab
*/
private JPanel buildConvertTab(JList graphList, JProgressBar progressBar, JPanel statusBar) {
JLabel status = (JLabel) statusBar.getComponent(0);
JLabel label = new JLabel("Convert from adjacency list to buffers");
JLabel fileLabel = new JLabel("No file selected");
fileLabel.setFont(new Font(fileLabel.getFont().getFontName(), Font.ITALIC, fileLabel.getFont().getSize()));
//Panel used to house the two buttons
JPanel convertPanel = new JPanel(new GridBagLayout());
JFileChooser fileChooser = new JFileChooser();
JButton openBtn = new JButton("Open File...");
//The action for when the user chooses a file
openBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
status.setText("Waiting for user response");
//Handle open button action.
if (evt.getSource() == openBtn) {
int returnVal = fileChooser.showOpenDialog(convertPanel);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
fileLabel.setText(file.getName());
fileLabel.setFont(new Font(fileLabel.getFont().getFontName(), Font.PLAIN, fileLabel.getFont().getSize()));
}
}
status.setText(DEFAULT_STATUS_MESSAGE);
}
});
JLabel nodeLabel = new JLabel("Number of Nodes:");
JTextField nodeField = new JTextField(12);
JLabel edgeLabel = new JLabel("Number of Edges:");
JTextField edgeField = new JTextField(12);
JRadioButton undirected = new JRadioButton("Undirected");
undirected.setSelected(true);
JRadioButton directed = new JRadioButton("Directed");
ButtonGroup group = new ButtonGroup();
group.add(undirected);
group.add(directed);
JButton convertBtn = new JButton("Convert");
//The action for when the user converts a file
convertBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
//check that the numbers of nodes are valid
int nodeNumber = checkForPositiveInteger(nodeField.getText(),convertPanel);
int edgeNumber = checkForPositiveInteger(edgeField.getText(),convertPanel);
if (nodeNumber != -1 && edgeNumber != -1) {
//input numbers are valid
//if the undirected button is selected, then the graph is undirected
boolean directedGraph = directed.isSelected();
File graphFile = fileChooser.getSelectedFile();
String name = graphFile.getName();
String path = fileChooser.getCurrentDirectory().toString();
System.out.println(fileChooser.getSelectedFile());
System.out.println("path: " + fileChooser.getCurrentDirectory());
System.out.println("node: " + nodeNumber);
System.out.println("edge: " + edgeNumber);
System.out.println("directed: " + directedGraph);
//set the Progress Bar to move
progressBar.setIndeterminate(true);
status.setText("Converting...");
// Start converting the Graph, but in a separate thread, to avoid locking up the GUI
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//Display error message to the user if this is unavailable
try {
launcher.convertGraphToBuffers(nodeNumber, edgeNumber, path, name, directedGraph);
status.setText("Conversion Complete");
model.addElement(name);
//stop the Progress Bar
progressBar.setIndeterminate(false);
} catch (Exception e) {
//stop the Progress Bar
progressBar.setIndeterminate(false);
JOptionPane.showMessageDialog(convertPanel, "This buffer could not be built. \n" + e.getMessage(), "Error: Exception", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
});
thread.start();
}
}
});
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2,2,2,2);
c.fill = GridBagConstraints.HORIZONTAL;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
convertPanel.add(label, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
convertPanel.add(openBtn, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
convertPanel.add(fileLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
convertPanel.add(nodeLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
convertPanel.add(nodeField, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
convertPanel.add(edgeLabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 3;
convertPanel.add(edgeField, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 4;
convertPanel.add(undirected, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 4;
convertPanel.add(directed, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 5;
c.gridwidth = 2;
convertPanel.add(convertBtn, c);
return convertPanel;
}
/**
* Builds the Panel used to house the GUI elements for the Pattern Tab
*
* @param graphList The JList element used to select which is the target graph
* @param progressBar The JProgressBar to update when loading a graph
* @return the Other tab
*/
private JPanel buildOtherTab(JList graphList, JProgressBar progressBar, JPanel statusBar) {
JPanel otherPanel = new JPanel(new BorderLayout());
JLabel status = (JLabel) statusBar.getComponent(0);
JButton selectedBtn = new JButton("Node Count");
otherPanel.add(selectedBtn, BorderLayout.WEST);
//The action for when the use selected the
selectedBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
String graph = (String) graphList.getSelectedValue();
if (graph != null) {
System.out.println(graph);
//set the Progress Bar to move
progressBar.setIndeterminate(true);
status.setText("Loading...");
// Start loading the Graph, but in a separate thread, to avoid locking up the GUI
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//Display error message to the user if this is unavailable
try {
FastGraph g = launcher.loadFromBuffers(null,graph);
status.setText("Loading Complete");
System.out.println("Maximum Degree: " + g.maximumDegree());
System.out.println("Degree Counts: " + Arrays.toString(g.countInstancesOfNodeDegrees(5)));
//stop the Progress Bar
progressBar.setIndeterminate(false);
} catch (IOException e) {
//stop the Progress Bar
progressBar.setIndeterminate(false);
JOptionPane.showMessageDialog(otherPanel, "This buffer could not be found. \n" + e.getMessage(), "Error: IOException", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
});
thread.start();
} else {
JOptionPane.showMessageDialog(otherPanel, "Please select a target graph", "No target graph selected", JOptionPane.ERROR_MESSAGE);
}
}
});
otherPanel.add(new JLabel("more text"), BorderLayout.EAST);
return otherPanel;
}
/**
* Builds the Panel used to house the GUI elements for the Graph Edit Distance Tab
*
* @param graphList The JList element used to select which is the target graph
* @param progressBar The JProgressBar to update when loading a graph
* @return the GED tab
*/
private JPanel buildGedTab(JList graphList, JProgressBar progressBar, JPanel statusBar) {
JPanel gedPanel = new JPanel(new GridBagLayout());
// Set the layout
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(2,2,2,2);
JLabel graphOneLabel = new JLabel("Graph one:");
c.gridx = 0;
c.gridy = 0;
gedPanel.add(graphOneLabel, c);
JLabel graphTwoLabel = new JLabel("Graph two:");
c.gridx = 1;
c.gridy = 0;
gedPanel.add(graphTwoLabel, c);
JTextField graphOneTextField = new JTextField();
graphOneTextField.setEditable(false);
c.gridx = 0;
c.gridy = 1;
gedPanel.add(graphOneTextField, c);
JTextField graphTwoTextField = new JTextField();
graphTwoTextField.setEditable(false);
c.gridx = 1;
c.gridy = 1;
gedPanel.add(graphTwoTextField, c);
JButton selectGraphOne = new JButton("Set selected graph as graph one");
c.gridx = 0;
c.gridy = 2;
gedPanel.add(selectGraphOne, c);
JButton selectGraphTwo = new JButton("Set selected graph as graph two");
c.gridx = 1;
c.gridy = 2;
gedPanel.add(selectGraphTwo, c);
JButton getGedBtn = new JButton("Get GED of selected graphs");
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
gedPanel.add(getGedBtn, c);
// Layout finished
// Set behaivour
selectGraphOne.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
String selectedGraph = (String) graphList.getSelectedValue();
graphOneTextField.setText(selectedGraph);
}
});
selectGraphTwo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
String selectedGraph = (String) graphList.getSelectedValue();
graphTwoTextField.setText(selectedGraph);
}
});
getGedBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
// this is the hard bit
}
});
// Behaivour finished
return gedPanel;
}
/**
* Builds the status bar - used for updating the user on small piece of information
* @return The fully built Status Bar
*/
private JPanel buildStatusBar() {
JPanel statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
JLabel statusLabel = new JLabel(DEFAULT_STATUS_MESSAGE);
statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
statusPanel.add(statusLabel);
return statusPanel;
}
/**
* Checks that a String is a positive integer
* @param input The input String to be tested
* @param panel The JPanel to attach the error Popup
* @return The converted integer, or -1 if failed.
*/
private int checkForPositiveInteger(String input, JPanel panel) {
try {
int number = Util.checkForPositiveInteger(input);
return number;
} catch (Exception e) {
JOptionPane.showMessageDialog(panel, "Please enter a positive integer", "Invalid Input", JOptionPane.ERROR_MESSAGE);
return -1;
}
}
}
|
package opendap.auth;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import opendap.PathBuilder;
import opendap.bes.BesDapDispatcher;
import opendap.logging.LogUtil;
import org.jdom.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class UrsIdP extends IdProvider{
public static final String DEFAULT_AUTH_CONTEXT="urs";
public static final String AUTHORIZATION_HEADER_KEY="authorization";
public static final String OAUTH_USER_ID_ENDPOINT_PATH="/oauth/tokens/user";
private Logger log;
private String ursUrl;
private String clientAppId;
private String clientAppAuthCode;
private static final String ERR_PRFX = "ERROR! msg: ";
public UrsIdP(){
super();
log = LoggerFactory.getLogger(this.getClass());
setAuthContext(DEFAULT_AUTH_CONTEXT);
setDescription("The NASA Earthdata Login (formerly known as URS)");
}
@Override
public void init(Element config, String serviceContext) throws ConfigurationException {
super.init(config, serviceContext);
Element e;
e = getConfigElement(config,"UrsUrl");
ursUrl = e.getTextTrim();
e = getConfigElement(config,"UrsClientId");
clientAppId = e.getTextTrim();
e = getConfigElement(config,"UrsClientAuthCode");
clientAppAuthCode = e.getTextTrim();
}
/**
* Just a little worker method.
* @param config
* @param childName
* @return
* @throws ConfigurationException
*/
private Element getConfigElement(Element config, String childName) throws ConfigurationException {
Element e = config.getChild(childName);
if(e == null){
String msg = this.getClass().getSimpleName() + " configuration must contain a <" + childName + "> element.";
log.error("{}",msg);
throw new ConfigurationException(msg);
}
return e;
}
public String getUrsUrl() {
return ursUrl;
}
public void setUrsUrl(String ursUrl) throws ServletException{
if(ursUrl == null){
String msg = "BAD CONFIGURATION - URS IdP Module must be configured with a URS Service URL. (urs_url)";
log.error("{}{}", ERR_PRFX,msg);
throw new ServletException(msg);
}
this.ursUrl = ursUrl;
}
public String getUrsClientAppId() {
return clientAppId;
}
public void setUrsClientAppId(String ursClientApplicationId) throws ServletException{
if(ursClientApplicationId == null){
String msg = "BAD CONFIGURATION - URS IdP Module must be configured with a Client Application ID. (client_id)";
log.error("{}{}", ERR_PRFX,msg);
throw new ServletException(msg);
}
clientAppId = ursClientApplicationId;
}
public String getUrsClientAppAuthCode() {
return clientAppAuthCode;
}
public void setUrsClientAppAuthCode(String ursClientAppAuthCode) throws ServletException {
if(ursClientAppAuthCode == null){
String msg = "BAD CONFIGURATION - URS IdP Module must be configured with a Client Authorization Code. (client_auth_code)";
log.error("{}{}", ERR_PRFX,msg);
throw new ServletException(msg);
}
this.clientAppAuthCode = ursClientAppAuthCode;
}
void getEDLUserProfile(UserProfile userProfile, String endpoint, String tokenType, String accessToken ) throws IOException {
Map<String, String> headers = new HashMap<>();
// Now that we have an access token, we can retrieve the user profile. This
// is returned as a JSON document.
String url = PathBuilder.pathConcat(ursUrl, endpoint) + "?client_id=" + getUrsClientAppId();
String authHeader = tokenType + " " + accessToken;
headers.put("Authorization", authHeader);
log.info("URS User Profile Request URL: {}", url);
log.info("URS User Profile Request Authorization Header: {}", authHeader);
String contents = Util.submitHttpRequest(url, headers, null);
log.info("URS User Profile: {}", contents);
userProfile.ingestJsonProfileString(contents);
}
String getEdlUserId(String accessToken) throws IOException {
Map<String, String> headers = new HashMap<>();
String url = PathBuilder.pathConcat(getUrsUrl(),OAUTH_USER_ID_ENDPOINT_PATH);
StringBuilder post_body= new StringBuilder();
post_body.append("token=").append(accessToken);
String auth_header_value="Basic "+ getUrsClientAppAuthCode();
headers.put("Authorization",auth_header_value);
log.debug("UID request: url: {} post_body: {}",url,post_body.toString());
String contents = Util.submitHttpRequest(url, headers, post_body.toString());
log.debug("url {} returned contents: {}",url,contents);
JsonParser jparse = new JsonParser();
JsonObject profile = jparse.parse(contents).getAsJsonObject();
String uid = profile.get("uid").getAsString();
log.debug("uid: {}",uid);
return uid;
}
/**
* Performs the user login operations.
* This method does not actually generate any output. It performs a series
* of redirects, depending upon the current state.
*
* 1) If the user is already logged in, it just redirects them back to the
* home page.
*
* 2) If no 'code' query parameter is found, it will redirect the user to URS
* to start the authentication process.
*
* 3) If a 'code' query parameter is found, it assumes the call is a redirect
* from a successful URS authentication, and will attempt to perform the
* token exchange.
*
* @param request
* @param response
* @return True if login is complete and user profile has been added to session object. False otherwise.
* @throws IOException
*/
public boolean doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException
{
HttpSession session = request.getSession();
log.debug("BEGIN (session: {})",session.getId());
UserProfile userProfile = new UserProfile();
userProfile.setAuthContext(getAuthContext());
// Add the this instance of UserProfile to the session for retrieval
// down stream on this request.
// We set the state of the instance of userProfile below.
session.setAttribute(IdFilter.USER_PROFILE, userProfile);
Util.debugHttpRequest(request,log);
String authorization_header_value = request.getHeader(AUTHORIZATION_HEADER_KEY);
if(authorization_header_value != null){
if(EarthDataLoginAccessToken.checkAuthorizationHeader(authorization_header_value)){
EarthDataLoginAccessToken edlat = new EarthDataLoginAccessToken(authorization_header_value,getUrsClientAppId());
userProfile.setEDLAccessToken(edlat);
String uid = getEdlUserId(edlat.getAccessToken());
userProfile.setUID(uid);
}
}
else {
// Check to see if we have a code returned from URS. If not, we must
// redirect the user to URS to start the authentication process.
String code = request.getParameter("code");
if (code == null) {
//String url = getUrsUrl() + "/oauth/authorize?client_id=" + getUrsClientAppId() +
// "&response_type=code&redirect_uri=" + request.getRequestURL();
String url;
url = PathBuilder.pathConcat(getUrsUrl(), "/oauth/authorize?");
url += "client_id=" + getUrsClientAppId();
url += "&";
String returnToUrl = request.getRequestURL().toString();
String clientProto = request.getHeader("CloudFront-Forwarded-Proto");
log.debug("CloudFront-Forwarded-Proto: {}",(clientProto==null?"MISSING":clientProto));
if(BesDapDispatcher.forceLinksToHttps() &&
returnToUrl.startsWith(opendap.http.Util.HTTP_PROTOCOL) &&
!returnToUrl.startsWith(opendap.http.Util.HTTP_PROTOCOL+"localhost")
){
returnToUrl = opendap.http.Util.HTTPS_PROTOCOL +
returnToUrl.substring(opendap.http.Util.HTTP_PROTOCOL.length());
}
url += "response_type=code&redirect_uri=" + returnToUrl;
log.info("Redirecting client to URS SSO. URS Code Request URL: {}", LogUtil.scrubEntry(url));
response.sendRedirect(url);
log.debug("END (session: {})", session.getId());
return false;
}
log.info("URS Code: {}", LogUtil.scrubEntry(code));
// If we get here, the the user was redirected by URS back to our application,
// and we have a code. We now exchange the code for a token, which is
// returned as a json document.
String url = getUrsUrl() + "/oauth/token";
String postData = "grant_type=authorization_code&code=" + code +
"&redirect_uri=" + request.getRequestURL();
Map<String, String> headers = new HashMap<>();
String authHeader = "Basic " + getUrsClientAppAuthCode();
headers.put("Authorization", authHeader);
log.info("URS Token Request URL: {}", url);
log.info("URS Token Request POST data: {}", LogUtil.scrubEntry(postData));
log.info("URS Token Request Authorization Header: {}", authHeader);
String contents = Util.submitHttpRequest(url, headers, postData);
log.info("URS Token: {}", contents);
// Parse the json to extract the token.
JsonParser jparse = new JsonParser();
JsonObject json = jparse.parse(contents).getAsJsonObject();
EarthDataLoginAccessToken edlat = new EarthDataLoginAccessToken(json, getUrsClientAppId());
userProfile.setEDLAccessToken(edlat);
getEDLUserProfile(userProfile,edlat.getEndPoint(),edlat.getTokenType(),edlat.getAccessToken());
log.info("URS UID: {}", userProfile.getUID());
}
// Finally, redirect the user back to the their original requested resource.
String redirectUrl = (String) session.getAttribute(IdFilter.RETURN_TO_URL);
log.debug("session.getAttribute(RETURN_TO_URL): {} (session: {})", redirectUrl, session.getId());
if (redirectUrl == null) {
redirectUrl = PathBuilder.normalizePath(serviceContext, true, false);
}
log.info("Authentication Completed. Redirecting client to redirectUrl: {}", redirectUrl);
response.sendRedirect(redirectUrl);
log.debug("END (session: {})", session.getId());
return true;
}
@Override
public String getLoginEndpoint(){
return PathBuilder.pathConcat(AuthenticationControls.getLoginEndpoint(), authContext);
}
@Override
public String getLogoutEndpoint() {
return AuthenticationControls.getLogoutEndpoint();
}
}
|
/**
* Maintains state information during interpretation inside a single procedure block.
* Holds the graphics attributes (color, line styles, transformations, etc.), the
* variables set by the user and connections to external data sources.
*/
import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.util.Hashtable;
import java.io.IOException;
import java.util.Vector;
public class Context
{
/*
* Graphical attributes
*/
private Color mColor;
private double mLineWidth;
/*
* Have graphical attributes been set in this context?
* Have graphical attributes been changed in this context
* since something was last drawn?
*/
private boolean mAttributesSet;
private boolean mAttributesChanged;
/*
* Transformation matrix and cumulative scaling factors and rotation.
*/
private AffineTransform mCtm;
private double mXScaling;
private double mYScaling;
private double mRotation;
/*
* Coordinates making up path.
*/
private GeometricPath mPath;
/*
* Path in context from which this context was created.
* Used when path is not modified in this context to avoid
* needlessly copying paths from one context to another.
*/
private GeometricPath mExistingPath;
/*
* Currently defined variables.
*/
private Hashtable mVars;
/*
* Output device we are drawing to.
*/
private OutputFormat mOutputFormat;
/*
* Flag true if output defined in this context. In this case
* we must close the output file when this context is finished.
*/
private boolean mOutputDefined;
/**
* Create a new context with reasonable default values.
*/
public Context()
{
mColor = Color.GRAY;
mLineWidth = 0.1;
mCtm = new AffineTransform();
mXScaling = mYScaling = 1.0;
mRotation = 0.0;
mVars = null;
mPath = null;
mOutputFormat = null;
mOutputDefined = false;
mAttributesChanged = true;
mAttributesSet = false;
}
/**
* Create a new context, making a copy from an existing context.
* @param existing is context to copy from.
*/
public Context(Context existing)
{
mColor = existing.mColor;
mLineWidth = existing.mLineWidth;
mCtm = new AffineTransform(existing.mCtm);
mXScaling = existing.mXScaling;
mYScaling = existing.mYScaling;
mRotation = existing.mRotation;
/*
* Only create variable lookup table when values defined locally.
*/
mVars = null;
/*
* Don't copy path -- it can be large. Just keep reference to
* existing path.
*
* Create path locally when needed. If it is referenced without
* being created then take path from existing context instead.
*
* This saves unnecessary copying of paths when contexts are created.
*/
mPath = null;
if (existing.mPath != null)
mExistingPath = existing.mPath;
else
mExistingPath = existing.mExistingPath;
mOutputFormat = existing.mOutputFormat;
mOutputDefined = false;
mAttributesChanged = existing.mAttributesChanged;
mAttributesSet = false;
}
/**
* Set graphics attributes (color, line width, etc.) if they
* have changed since the last time we drew something.
*/
private void setGraphicsAttributes()
{
if (mAttributesChanged)
{
mOutputFormat.setAttributes(mColor, mLineWidth);
mAttributesChanged = false;
}
}
/**
* Flag that graphics attributes have been changed.
*/
public void setAttributesChanged()
{
mAttributesChanged = mAttributesSet = true;
}
/**
* Sets output file for drawing to.
* @param filename name of image file output will be saved to
* @param width is the page width (in points).
* @param height is the page height (in points).
* @param extras contains extra settings for this output.
*/
public void setOutputFormat(String filename,
int width, int height, String extras)
throws IOException, MapyrusException
{
mOutputFormat = new OutputFormat(filename, width, height, extras);
mAttributesChanged = true;
mOutputDefined = true;
}
/**
* Closes a context. Any output started in this context is completed,
* memory used for context is released.
* A context cannot be used again after this call.
* @return flag indicating if graphical attributes set in this context.
*/
public boolean closeContext() throws IOException, MapyrusException
{
if (mOutputDefined)
{
mOutputFormat.closeOutputFormat();
mOutputFormat = null;
mOutputDefined = false;
}
mPath = null;
mVars = null;
return(mAttributesSet);
}
/**
* Sets line width.
* @param width is width for lines in millimetres.
*/
public void setLineWidth(double width)
{
/*
* Adjust width by current scaling factor.
*/
mLineWidth = width * Math.min(mXScaling, mYScaling);
mAttributesChanged = mAttributesSet = true;
}
/**
* Sets color.
* @param c is new color for drawing.
*/
public void setColor(Color c)
{
mColor = c;
mAttributesChanged = mAttributesSet = true;
}
/**
* Sets scaling for subsequent coordinates.
* @param x is new scaling in X axis.
* @param y is new scaling in Y axis.
*/
public void setScaling(double x, double y)
{
mCtm.scale(x, y);
mXScaling *= x;
mYScaling *= y;
mAttributesChanged = mAttributesSet = true;
}
/**
* Sets translation for subsequent coordinates.
* @param x is new point for origin on X axis.
* @param y is new point for origin on Y axis.
*/
public void setTranslation(double x, double y)
{
mCtm.translate(x, y);
mAttributesChanged = mAttributesSet = true;
}
/**
* Sets rotation for subsequent coordinates.
* @param angle is rotation angle in radians, going anti-clockwise.
*/
public void setRotation(double angle)
{
mCtm.rotate(angle);
mRotation += angle;
mAttributesChanged = mAttributesSet = true;
}
/**
* Returns X scaling value in current transformation.
* @return m00 element from transformation matrix.
*/
public double getScalingX()
{
return(mXScaling);
}
/**
* Returns X scaling value in current transformation.
* @return m00 element from transformation matrix.
*/
public double getScalingY()
{
return(mYScaling);
}
/**
* Returns X scaling value in current transformation.
* @return m00 element from transformation matrix.
*/
public double getRotation()
{
return(mRotation);
}
/**
* Add point to path.
* @param x X coordinate to add to path.
* @param y Y coordinate to add to path.
*/
public void moveTo(double x, double y)
{
double srcPts[] = {x, y};
float dstPts[] = new float[3];
/*
* Transform point to millimetre position on page.
*/
mCtm.transform(srcPts, 0, dstPts, 0, 1);
if (mPath == null)
mPath = new GeometricPath();
/*
* Set no rotation for point.
*/
dstPts[2] = 0.0f;
mPath.moveTo(dstPts);
}
/**
* Add point to path with straight line segment from last point.
* @param x X coordinate to add to path.
* @param y Y coordinate to add to path.
*/
public void lineTo(double x, double y)
{
double srcPts[] = {x, y};
float dstPts[] = new float[2];
/*
* Transform point to millimetre position on page.
*/
mCtm.transform(srcPts, 0, dstPts, 0, 1);
if (mPath == null)
mPath = new GeometricPath();
mPath.lineTo(dstPts);
}
/**
* Clears currently defined path.
*/
public void clearPath()
{
if (mPath != null)
mPath.reset();
}
/**
* Replace path with regularly spaced points along it.
* @param spacing is distance between points.
* @param offset is starting offset of first point.
*/
public void slicePath(double spacing, double offset)
{
GeometricPath path;
/*
* If path defined in this context then use that,
* else use context defined in previous context.
*/
if (mPath != null)
path = mPath;
else
path = mExistingPath;
if (path != null)
path.slicePath(spacing, offset);
}
/**
* Replace path defining polygon with parallel stripe
* lines covering the polygon.
* @param spacing is distance between stripes.
* @param angle is angle of stripes, in radians, with zero horizontal.
*/
public void stripePath(double spacing, double angle)
{
GeometricPath path;
/*
* If path defined in this context then use that,
* else use context defined in previous context.
*/
if (mPath != null)
path = mPath;
else
path = mExistingPath;
if (path != null)
path.stripePath(spacing, angle);
}
/**
* Draw currently defined path.
*/
public void stroke()
{
GeometricPath path;
/*
* If path defined in this context then use that,
* else use context defined in previous context.
*/
if (mPath != null)
path = mPath;
else
path = mExistingPath;
if (path != null && mOutputFormat != null)
{
setGraphicsAttributes();
mOutputFormat.stroke(path.getShape());
}
}
/**
* Fill currently defined path.
*/
public void fill()
{
GeometricPath path;
/*
* If path defined in this context then use that,
* else use context defined in previous context.
*/
if (mPath != null)
path = mPath;
else
path = mExistingPath;
if (path != null && mOutputFormat != null)
{
setGraphicsAttributes();
mOutputFormat.fill(path.getShape());
}
}
/**
* Returns the number of moveTo's in path defined in this context.
* @return count of moveTo calls made.
*/
public int getMoveToCount()
{
int retval;
if (mPath == null)
retval = 0;
else
retval = mPath.getMoveToCount();
return(retval);
}
/**
* Returns the number of lineTo's in path defined in this context.
* @return count of lineTo calls made for this path.
*/
public int getLineToCount()
{
int retval;
if (mPath == null)
retval = 0;
else
retval = mPath.getLineToCount();
return(retval);
}
/**
* Returns geometric length of current path.
* @return length of current path.
*/
public double getPathLength()
{
double retval;
if (mPath == null)
retval = 0.0;
else
retval = mPath.getLength();
return(retval);
}
/**
* Returns coordinates and rotation angle for each each moveTo point in current path
* @returns list of three element float arrays containing x, y coordinates and
* rotation angles.
*/
public Vector getMoveTos()
{
return(mPath.getMoveTos());
}
/**
* Returns bounding box of this geometry.
* @return bounding box, or null if no path is defined.
*/
public Rectangle2D getBounds2D()
{
Rectangle2D bounds;
GeometricPath path;
/*
* If path defined in this context then use that,
* else use context defined in previous context.
*/
if (mPath != null)
path = mPath;
else
path = mExistingPath;
if (path == null)
bounds = null;
else
bounds = path.getBounds2D();
return(bounds);
}
/**
* Returns value of a variable.
* @param variable name to lookup.
* @return value of variable, or null if it is not defined.
*/
public Argument getVariableValue(String varName)
{
Argument retval;
/*
* Variable is not set if no lookup table is defined.
*/
if (mVars == null)
retval = null;
else
retval = (Argument)mVars.get(varName);
return(retval);
}
/**
* Define variable in current context, replacing any existing
* variable of the same name.
* @param varName name of variable to define.
* @param value is value for this variable
*/
public void defineVariable(String varName, Argument value)
{
/*
* Create new variable.
*/
if (mVars == null)
mVars = new Hashtable();
mVars.put(varName, value);
}
}
|
package butterknife;
import android.app.Activity;
import android.view.View;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.JavaFileObject;
import static javax.lang.model.element.ElementKind.CLASS;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PROTECTED;
import static javax.lang.model.element.Modifier.STATIC;
import static javax.tools.Diagnostic.Kind.ERROR;
public class Views {
private Views() {
// No instances.
}
private static final Map<Class<?>, Method> INJECTORS = new LinkedHashMap<Class<?>, Method>();
/**
* Inject fields annotated with {@link InjectView} in the specified {@link Activity}.
*
* @param target Target activity for field injection.
* @throws UnableToInjectException if injection could not be performed.
*/
public static void inject(Activity target) {
inject(target, Activity.class, target);
}
/**
* Inject fields annotated with {@link InjectView} in the specified {@code source} using {@code
* target} as the view root.
*
* @param target Target class for field injection.
* @param source View tree root on which IDs will be looked up.
* @throws UnableToInjectException if injection could not be performed.
*/
public static void inject(Object target, View source) {
inject(target, View.class, source);
}
private static void inject(Object target, Class<?> sourceType, Object source) {
try {
Class<?> targetClass = target.getClass();
Method inject = INJECTORS.get(targetClass);
if (inject == null) {
Class<?> injector = Class.forName(targetClass.getName() + AnnotationProcessor.SUFFIX);
inject = injector.getMethod("inject", targetClass, sourceType);
INJECTORS.put(targetClass, inject);
}
inject.invoke(null, target, source);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new UnableToInjectException("Unable to inject views for " + target, e);
}
}
/** Simpler version of {@link View#findViewById(int)} which infers the target type. */
@SuppressWarnings({ "unchecked", "UnusedDeclaration" }) // Checked by runtime cast, helper method.
public static <T extends View> T findById(View view, int id) {
return (T) view.findViewById(id);
}
/** Simpler version of {@link Activity#findViewById(int)} which infers the target type. */
@SuppressWarnings({ "unchecked", "UnusedDeclaration" }) // Checked by runtime cast, helper method.
public static <T extends View> T findById(Activity activity, int id) {
return (T) activity.findViewById(id);
}
public static class UnableToInjectException extends RuntimeException {
UnableToInjectException(String message, Throwable cause) {
super(message, cause);
}
}
@SupportedAnnotationTypes("butterknife.InjectView")
public static class AnnotationProcessor extends AbstractProcessor {
static final String SUFFIX = "$$ViewInjector";
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
private void error(String message, Object... args) {
processingEnv.getMessager().printMessage(ERROR, String.format(message, args));
}
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
Map<TypeElement, Set<InjectionPoint>> injectionsByClass =
new LinkedHashMap<TypeElement, Set<InjectionPoint>>();
Set<TypeMirror> injectionTargets = new HashSet<TypeMirror>();
for (Element element : env.getElementsAnnotatedWith(InjectView.class)) {
// Verify containing type.
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
if (enclosingElement.getKind() != CLASS) {
error("Unexpected @InjectView on field in " + element);
continue;
}
// Verify field properties.
Set<Modifier> modifiers = element.getModifiers();
if (modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED) || modifiers.contains(
STATIC)) {
error("@InjectView fields must not be private, protected, or static: "
+ enclosingElement.getQualifiedName()
+ "."
+ element);
continue;
}
// Get and optionally create a set of all injection points for a type.
Set<InjectionPoint> injections = injectionsByClass.get(enclosingElement);
if (injections == null) {
injections = new HashSet<InjectionPoint>();
injectionsByClass.put(enclosingElement, injections);
}
// Assemble information on the injection point.
String variableName = element.getSimpleName().toString();
String type = element.asType().toString();
int value = element.getAnnotation(InjectView.class).value();
injections.add(new InjectionPoint(variableName, type, value));
// Add to the valid injection targets set.
injectionTargets.add(enclosingElement.asType());
}
for (Map.Entry<TypeElement, Set<InjectionPoint>> injection : injectionsByClass.entrySet()) {
TypeElement type = injection.getKey();
Set<InjectionPoint> injectionPoints = injection.getValue();
String targetType = type.getQualifiedName().toString();
String sourceType = resolveSourceType(type);
String packageName = processingEnv.getElementUtils().getPackageOf(type).toString();
String className =
type.getQualifiedName().toString().substring(packageName.length() + 1).replace('.', '$')
+ SUFFIX;
String parentClass = resolveParentType(type, injectionTargets);
StringBuilder injections = new StringBuilder();
if (parentClass != null) {
injections.append(" ")
.append(parentClass)
.append(SUFFIX)
.append(".inject(activity);\n\n");
}
for (InjectionPoint injectionPoint : injectionPoints) {
injections.append(injectionPoint).append("\n");
}
// Write the view injector class.
try {
JavaFileObject jfo =
processingEnv.getFiler().createSourceFile(packageName + "." + className, type);
Writer writer = jfo.openWriter();
writer.write(String.format(INJECTOR, packageName, className, targetType, sourceType,
injections.toString()));
writer.flush();
writer.close();
} catch (IOException e) {
error(e.getMessage());
}
}
return true;
}
/** Returns {@link #TYPE_ACTIVITY} or {@link #TYPE_VIEW} as the injection target type. */
private String resolveSourceType(TypeElement typeElement) {
TypeMirror type;
while (true) {
type = typeElement.getSuperclass();
if (type.getKind() == TypeKind.NONE) {
return TYPE_VIEW;
}
if (type.toString().equals(TYPE_ACTIVITY)) {
return TYPE_ACTIVITY;
}
typeElement = (TypeElement) ((DeclaredType) type).asElement();
}
}
/** Finds the parent injector type in the supplied set, if any. */
private String resolveParentType(TypeElement typeElement, Set<TypeMirror> parents) {
TypeMirror type;
while (true) {
type = typeElement.getSuperclass();
if (type.getKind() == TypeKind.NONE) {
return null;
}
if (parents.contains(type)) {
return type.toString();
}
typeElement = (TypeElement) ((DeclaredType) type).asElement();
}
}
private static class InjectionPoint {
private final String variableName;
private final String type;
private final int value;
InjectionPoint(String variableName, String type, int value) {
this.variableName = variableName;
this.type = type;
this.value = value;
}
@Override public String toString() {
return String.format(INJECTION, variableName, type, value);
}
}
private static final String TYPE_ACTIVITY = "android.app.Activity";
private static final String TYPE_VIEW = "android.view.View";
private static final String INJECTION = " target.%s = (%s) source.findViewById(%s);";
private static final String INJECTOR = ""
+ "package %s;\n\n"
+ "public class %s {\n"
+ " public static void inject(%s target, %s source) {\n"
+ "%s"
+ " }\n"
+ "}\n";
}
}
|
package pkgSwing;
import javax.swing.*;
import java.awt.*;
class ChildFrame extends JFrame {
ChildFrame()
{
final Dimension size = new Dimension(500,500);
final int xcenter = (int)((GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getWidth()-size.getWidth())/2);
final int ycenter = (int)((GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getHeight()-size.getHeight())/2);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setLocation(xcenter,ycenter);
setSize(size);
setTitle("Child Frame fast correct on user demand hotfix!");
setAlwaysOnTop(true);
setVisible(true);
}
}
|
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import services.Chefmate;
import services.EC2OpsGrpc;
import services.Chefmate.CreateVMRequest;
import services.Chefmate.CreateVMResponse;
import services.Chefmate.DestroyVMRequest;
import services.Chefmate.DestroyVMResponse;
import services.Chefmate.VMInstanceId;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
/**
* The ChefMateClient offering connection to the ChefMateServer and its services.
* @author Tobias Freundorfer
*
*/
public class ChefMateClient
{
// TODO: See WebShopClient on how to set up this class!!
private static final Logger logger = Logger.getLogger(ChefMateClient.class.getName());
/**
* Channel for the connection to the server.
*/
private final ManagedChannel channel;
/**
* The blocking Stub (response is synchronous).
*/
private final EC2OpsGrpc.EC2OpsBlockingStub blockingStub;
/**
* Creates a new instance of the ChefMateClient connected to the
* ChefMateServer.
*
* @param host
* The hostname of the ChefMateServer.
* @param port
* The port of the ChefMateServer.
*/
public ChefMateClient(String host, int port)
{
this.channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
this.blockingStub = EC2OpsGrpc.newBlockingStub(this.channel);
}
/**
* Sends the createVM request to the ChefMateServer.
*/
public void sendCreateVMRequest(CreateVMRequest createVMRequest)
{
logger.info("### Sending request for Creating VM.");
CreateVMResponse createVMResponse = null;
try
{
createVMResponse = this.blockingStub.createVM(createVMRequest);
} catch (StatusRuntimeException e)
{
logger.warning("### RPC failed: {0}" + e.getStatus());
return;
}
logger.info("### Received response.");
System.out.println("Created new VM with VmInfo = " + createVMResponse.getInfo());
}
/**
* Sends the destroyVM request to the ChefMateServer.
*/
public void sendDestroyVMRequest(DestroyVMRequest destroyVMRequest)
{
logger.info("### Sending request for Destroying VM.");
DestroyVMResponse destroyVMResponse = null;
try
{
destroyVMResponse = this.blockingStub.destroyVM(destroyVMRequest);
} catch (StatusRuntimeException e)
{
logger.warning("### RPC failed: {0}" + e.getStatus());
return;
}
logger.info("### Received response.");
System.out.println("Destoyed VM with InstanceId" +destroyVMRequest.getId()+" = " + destroyVMResponse.getSuccess());
}
/**
* Initiates the shutdown sequence.
*
* @throws InterruptedException
* Thrown if shutdown was interrupted.
*/
public void shutdown() throws InterruptedException
{
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public static void main(String[] args)
{
// Read input args
String hostname = "";
int port = -1;
for (int i = 0; i < args.length; i++)
{
if (args[i].equals("-h"))
{
// Check if there's a following command
if ((i + 1) < args.length)
{
hostname = args[i + 1];
i++;
} else
{
ChefMateClient.showArgsPrompt();
System.exit(0);
}
}
if (args[i].equals("-p"))
{
if ((i + 1) < args.length)
{
try
{
port = Integer.parseInt(args[i + 1]);
i++;
} catch (NumberFormatException e)
{
ChefMateClient.showArgsPrompt();
System.exit(0);
}
} else
{
ChefMateClient.showArgsPrompt();
System.exit(0);
}
}
}
if (hostname.isEmpty() || port == -1)
{
ChefMateClient.showArgsPrompt();
System.exit(0);
}
System.out.println("Connecting to " + hostname + ":" + port);
ChefMateClient client = new ChefMateClient(hostname, port);
// Loop for user input commands
Scanner scanner = new Scanner(System.in);
boolean receiveUserCommands = true;
while (receiveUserCommands)
{
ChefMateClient.showUserCommandPrompt();
System.out.println("\n Enter command: \n");
String command = scanner.nextLine();
if (command.equals("createVM"))
{
String requestId = UUID.randomUUID().toString();
System.out.println("\n Enter Instance Name: ");
String name = scanner.nextLine();
System.out.println("\n Enter Instance Tag: ");
String tag = scanner.nextLine();
System.out.println("\n Enter Instance Region: ");
String region = scanner.nextLine();
System.out.println("\n Enter Instance ImageId: ");
String imageId = scanner.nextLine();
System.out.println("\n Enter Instance Type : ");
String instanceType = scanner.nextLine();
System.out.println("\n Enter Security GroupIds: ");
String securityGroupIds = scanner.nextLine();
Chefmate.CreateVMRequest createVMRequest = Chefmate.CreateVMRequest.newBuilder().setName(name)
.setTag(tag).setRegion(region).setImageId(imageId).setInstanceType(instanceType).addSecurityGroupIds(securityGroupIds).build();
client.sendCreateVMRequest(createVMRequest);
} else if (command.equals("shutdown"))
{
try
{
client.shutdown();
receiveUserCommands = false;
} catch (InterruptedException e)
{
logger.warning("Client was interrupted at shutdown.");
receiveUserCommands = false;
}
} else if (command.startsWith("destroyVM"))
{
String[] arr = command.split(" ");
if (arr.length != 2)
{
logger.warning("### Wrong syntax.");
} else
{
DestroyVMRequest destroyVMRequest = DestroyVMRequest.newBuilder().setId(VMInstanceId.newBuilder().setId(arr[1])).build();
client.sendDestroyVMRequest(destroyVMRequest);
}
}
}
scanner.close();
}
/**
* Shows the command prompt for user commands.
*/
private static void showUserCommandPrompt()
{
System.out.println("Available Commands: \n");
System.out.println("createVM \n\t Create VM Instance ");
System.out.println("destroyVM \n\t Destroy the VM Instance");
System.out.println("shutdown \n\t Terminates this client and closes all connections.");
}
/**
* Shows the args prompt for startup arguments.
*/
private static void showArgsPrompt()
{
System.out.println("Usage: \n <appname> command argument");
System.out.println("-h \t The host address to connect to. \n -p \t The port to connect to.");
}
}
|
package polyglot.ext.jl.ast;
import polyglot.ast.*;
import polyglot.types.*;
import polyglot.visit.*;
import polyglot.util.*;
/**
* An <code>Expr</code> represents any Java expression. All expressions
* must be subtypes of Expr.
*/
public abstract class Expr_c extends Term_c implements Expr
{
protected Type type;
public Expr_c(Position pos) {
super(pos);
}
/**
* Get the type of the expression. This may return an
* <code>UnknownType</code> before type-checking, but should return the
* correct type after type-checking.
*/
public Type type() {
return this.type;
}
/** Set the type of the expression. */
public Expr type(Type type) {
if (type == this.type) return this;
Expr_c n = (Expr_c) copy();
n.type = type;
return n;
}
public void dump(CodeWriter w) {
super.dump(w);
if (type != null) {
w.allowBreak(4, " ");
w.begin(0);
w.write("(type " + type + ")");
w.end();
}
}
/** Get the precedence of the expression. */
public Precedence precedence() {
return Precedence.UNKNOWN;
}
public boolean constantValueSet() {
return true;
}
public boolean isConstant() {
return false;
}
public Object constantValue() {
return null;
}
public String stringValue() {
return (String) constantValue();
}
public boolean booleanValue() {
return ((Boolean) constantValue()).booleanValue();
}
public byte byteValue() {
return ((Byte) constantValue()).byteValue();
}
public short shortValue() {
return ((Short) constantValue()).shortValue();
}
public char charValue() {
return ((Character) constantValue()).charValue();
}
public int intValue() {
return ((Integer) constantValue()).intValue();
}
public long longValue() {
return ((Long) constantValue()).longValue();
}
public float floatValue() {
return ((Float) constantValue()).floatValue();
}
public double doubleValue() {
return ((Double) constantValue()).doubleValue();
}
public boolean isTypeChecked() {
return super.isTypeChecked() && type != null && type.isCanonical();
}
public Node buildTypes(TypeBuilder tb) throws SemanticException {
return type(tb.typeSystem().unknownType(position()));
}
/**
* Correctly parenthesize the subexpression <code>expr<code> given
* the its precendence and the precedence of the current expression.
*
* If the sub-expression has the same precedence as this expression
* we do not parenthesize.
*
* @param expr The subexpression.
* (right-) associative operator.
* @param w The output writer.
* @param pp The pretty printer.
*/
public void printSubExpr(Expr expr, CodeWriter w, PrettyPrinter pp) {
printSubExpr(expr, true, w, pp);
}
/**
* Correctly parenthesize the subexpression <code>expr<code> given
* the its precendence and the precedence of the current expression.
*
* If the sub-expression has the same precedence as this expression
* we parenthesize if the sub-expression does not associate; e.g.,
* we parenthesis the right sub-expression of a left-associative
* operator.
*
* @param expr The subexpression.
* @param associative Whether expr is the left (right) child of a left-
* (right-) associative operator.
* @param w The output writer.
* @param pp The pretty printer.
*/
public void printSubExpr(Expr expr, boolean associative,
CodeWriter w, PrettyPrinter pp) {
if (! associative && precedence().equals(expr.precedence()) ||
precedence().isTighter(expr.precedence())) {
w.write("(");
printBlock(expr, w, pp);
w.write( ")");
}
else {
print(expr, w, pp);
}
}
}
|
package arena;
// Libraries
import gui.*;
import robot.*;
import random.*;
import scenario.*;
import operation.*;
import exception.*;
import stackable.*;
import parameters.*;
/**
* <b>World - general game configuration.</b><br>
* Manages the time, players and the
* arena of the game.
*
* @author Karina Suemi
* @author Renato Cordeiro Ferreira
* @author Vinicius Silva
*
* @see Action
* @see gui.Textual
*/
public class World implements Game
{
// Global settings
private static int id = 1;
private static int time = 0;
private static int nPlayers;
// Global characteristics
private static Map map;
private static Robot turn;
/* Robot list */
private static RobotList armies;
// Graphical User Interface (GUI)
private static Textual GUI;
/**
* Builds a new arena with n players and
* a given weather.
* @param np Number of players
* @param w Weather
*/
public static void genesis(int np, Weather w)
throws InvalidOperationException
{
// Set game configurations
nPlayers = np;
map = new Map(w);
armies = new RobotList(nPlayers);
// Create map
Robot[][] initial = map.genesis(nPlayers);
// Set up initial robots
for(int i = 0; i < nPlayers; i++)
for(int j = 0; j < ROBOTS_NUM_INITIAL; j++)
{
Debugger.say("[i:",i,"],[j:",j,"]");
if(initial[i][j] == null)
Debugger.say("[World] É null");
armies.add(initial[i][j]);
}
// Initializes GUI
GUI = new Textual(map);
if(Debugger.info) GUI.printMiniMap();
}
/**
* Runs one game time step. On each
* turn, sort the robots accordingly
* to their priorities, solving conflicts
* randomically. Then, executes their
* actions and attend their requests.
*/
public static void timeStep()
{
time++; // On each time step, increments time
// Debug
String pre = "\n[WORLD] ====================== ";
Debugger.say(pre + time + "ts");
armies.sort(); // Organize armies accordingly to
// their priorities.
for(Robot r: armies)
{
// Set global turn
turn = r;
// Debug
Debugger.print("\n[" + turn.toString() + "]");
Debugger.say ("[" + time + "ts]");
try { turn.run(); }
catch (Exception e)
{
System.out.println
("[World]["+ turn.toString() +"] " + e);
}
}
if(!(Debugger.info)) GUI.paint();
}
/**
* Receive the robot's syscalls.
* Uses an object with type 'operation'
* to execute some action, which could
* be an attack (HIT), an iteraction
* with the environment (DRAG/DROP),
* a displacement (MOVE) or even to get
* visual info (SEE/LOOK).
*
* @param op Operation
* @return Stackable with the answer
* (or Num 0 if the system
* refused the operation).
*/
public static Stackable[] ctrl(Operation op)
throws InvalidOperationException
{
return Action.ctrl(map, turn, op);
}
/**
* Create a new robot in the map.
* Make a new robot to the player 'player',
* with name 'name', putting it in the
* position (i,j) of the map, programmed
* with the assembly program defined by
* the file in 'pathToProg'.
*
* @param player Robot owner
* @param name Name of the new robot
* @param i Vertical position
* @param j Horizontal position
* @param pathToProg Robot assembly program
*/
public static void insertArmy
(int player, String name, int i, int j, String pathToProg)
throws SegmentationFaultException
{
Robot r = map.insertArmy(name, player, id++,
i, j, pathToProg);
armies.add(r);
}
/**
* Remove a given robot from the map.
* Take out the robot from the map and
* remove it from the Robot List.
*
* @param dead Robot to be removed.
*/
public static void removeArmy(Robot dead)
throws SegmentationFaultException
{
map.removeScenario(dead.i, dead.j);
armies.remove(dead);
}
/**
* Remove a given scenario from the map.
* Take out a scenario from the position
* (i,j) of the map.
*
* @param i Vertical position
* @param j Horizontal position
*/
public static void destroy(int i, int j)
{
// Remove all scenarios, but robots.
// This ones are removed by the ctrl.
Scenario s = map.map[i][j].getScenario();
try
{
if(s instanceof Robot)
removeArmy((Robot) s);
else map.removeScenario(i,j);
}
catch(SegmentationFaultException e)
{
System.err.println(
"[World] Destroying in invalid " +
"position (" + i + "," + j + ")");
}
}
}
|
package me.openphoto.android.app;
import me.openphoto.android.app.model.Photo;
import me.openphoto.android.app.twitter.TwitterProvider;
import me.openphoto.android.app.twitter.TwitterUtils;
import me.openphoto.android.app.util.GuiUtils;
import me.openphoto.android.app.util.LoadingControl;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.WazaBe.HoloEverywhere.LayoutInflater;
import com.WazaBe.HoloEverywhere.app.Activity;
import com.WazaBe.HoloEverywhere.app.Dialog;
/**
* @author Eugene Popovich
*/
public class TwitterFragment extends CommonDialogFragment
{
public static final String TAG = TwitterFragment.class.getSimpleName();
static final String TWEET = "TwitterFragmentTweet";
Photo photo;
private EditText messageEt;
private LoadingControl loadingControl;
private Button sendButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_twitter, container);
init(view, savedInstanceState);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(TWEET, messageEt.getText().toString());
}
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
loadingControl = (LoadingControl) activity;
}
public void setPhoto(Photo photo)
{
this.photo = photo;
}
void init(View view, Bundle savedInstanceState)
{
try
{
new ShowCurrentlyLoggedInUserTask(view).execute();
messageEt = (EditText) view.findViewById(R.id.message);
if (savedInstanceState != null)
{
messageEt.setText(savedInstanceState.getString(TWEET));
} else
{
messageEt.setText(String.format(
getString(R.string.share_twitter_default_msg),
photo.getUrl(Photo.URL)));
}
Button logOutButton = (Button) view.findViewById(R.id.logoutBtn);
logOutButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
performTwitterLogout();
}
});
sendButton = (Button) view.findViewById(R.id.sendBtn);
sendButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
postTweet();
}
});
} catch (Exception ex)
{
GuiUtils.error(TAG, R.string.errorCouldNotInitTwitterFragment, ex,
getActivity());
dismiss();
}
}
protected void postTweet()
{
new TweetTask().execute();
}
private void performTwitterLogout()
{
TwitterUtils.logout(getActivity());
dismiss();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog result = super.onCreateDialog(savedInstanceState);
result.setTitle(R.string.share_twitter_dialog_title);
return result;
}
private class ShowCurrentlyLoggedInUserTask extends
AsyncTask<Void, Void, Boolean>
{
TextView loggedInAsText;
String name;
Context activity = getActivity();
ShowCurrentlyLoggedInUserTask(View view)
{
loggedInAsText = (TextView) view
.findViewById(R.id.loggedInAs);
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
loggedInAsText.setText(null);
loadingControl.startLoading();
}
@Override
protected Boolean doInBackground(Void... params)
{
try
{
Twitter twitter = TwitterProvider.getTwitter(activity);
name = twitter.getScreenName();
return true;
} catch (Exception ex)
{
GuiUtils.error(TAG,
R.string.errorCouldNotRetrieveTwitterScreenName,
ex,
activity);
}
return false;
}
@Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
loadingControl.stopLoading();
if (result.booleanValue())
{
loggedInAsText.setText(String
.format(
activity.getString(R.string.share_twitter_logged_in_as),
name));
}
}
}
private class TweetTask extends
AsyncTask<Void, Void, Boolean>
{
Context activity = getActivity();
@Override
protected void onPreExecute()
{
super.onPreExecute();
sendButton.setEnabled(false);
loadingControl.startLoading();
}
@Override
protected Boolean doInBackground(Void... params)
{
try
{
sendTweet(messageEt.getText()
.toString(), activity);
return true;
} catch (Exception ex)
{
GuiUtils.error(TAG, R.string.errorCouldNotSendTweet, ex,
getActivity());
}
return false;
}
@Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
loadingControl.stopLoading();
if (result.booleanValue())
{
GuiUtils.info(
R.string.share_twitter_success_message);
}
Dialog dialog = TwitterFragment.this.getDialog();
if (dialog != null && dialog.isShowing())
{
TwitterFragment.this.dismiss();
}
}
}
public static void sendTweet(String message, Context context)
throws TwitterException
{
Twitter twitter = TwitterProvider.getTwitter(context);
if (twitter != null)
{
sendTweet(message, twitter);
}
}
public static void sendTweet(String message, Twitter twitter)
throws TwitterException
{
StatusUpdate update = new StatusUpdate(message);
twitter.updateStatus(update);
}
}
|
package converter;
import converters.JsonConverter;
import datamodel.Job;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class JsonConverterTest {
/**
* Test converting objects to stings.
*/
@Test
public void convertObjectToJsonString() {
String object = JsonConverter.objectToJsonString(new Job("13"));
final String jsonRepresentation = "{\"id\":\"13\"}";
assertTrue(object.equals(jsonRepresentation));
}
/**
* Test converting strings to objects.
*/
@Test
public void convertJsonStringToObject() {
final String jsonRepresentation = "{\"id\":\"13\"}";
Job deserializedJob = JsonConverter.jsonStringToObject(jsonRepresentation, Job.class);
String id = deserializedJob.getId();
assertTrue("13".equals(id));
}
}
|
package com.gallatinsystems.survey.dao;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.ArrayUtils;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.common.util.HttpUtil;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyGroup;
public class SurveyUtils {
private static final Logger log = Logger.getLogger(SurveyUtils.class
.getName());
public static Survey copySurvey(Survey source, SurveyDto dto) {
final SurveyDAO sDao = new SurveyDAO();
final Survey tmp = new Survey();
final QuestionGroupDao qgDao = new QuestionGroupDao();
final Map<Long, Long> qMap = new HashMap<Long, Long>();
BeanUtils.copyProperties(source, tmp, Constants.EXCLUDED_PROPERTIES);
// set name and surveyGroupId to values we got from the dashboard
tmp.setCode(dto.getCode());
tmp.setName(dto.getName());
tmp.setSurveyGroupId(dto.getSurveyGroupId());
tmp.setStatus(Survey.Status.NOT_PUBLISHED);
tmp.setPath(getPath(tmp));
log.log(Level.INFO, "Copying `Survey` " + source.getKey().getId());
final Survey newSurvey = sDao.save(tmp);
log.log(Level.INFO, "New `Survey` ID: " + newSurvey.getKey().getId());
final List<QuestionGroup> qgList = qgDao
.listQuestionGroupBySurvey(source.getKey().getId());
if (qgList == null) {
return newSurvey;
}
log.log(Level.INFO, "Copying " + qgList.size() + " `QuestionGroup`");
int qgOrder = 1;
for (final QuestionGroup sourceQG : qgList) {
SurveyUtils.copyQuestionGroup(sourceQG, newSurvey.getKey().getId(),
qgOrder++, qMap);
}
return newSurvey;
}
public static QuestionGroup copyQuestionGroup(QuestionGroup source,
Long newSurveyId, Integer order, Map<Long, Long> qMap) {
final QuestionGroupDao qgDao = new QuestionGroupDao();
final QuestionDao qDao = new QuestionDao();
final QuestionGroup tmp = new QuestionGroup();
BeanUtils.copyProperties(source, tmp, Constants.EXCLUDED_PROPERTIES);
tmp.setSurveyId(null); // reset parent SurveyId, it will get set by the
// save action
log.log(Level.INFO, "Copying `QuestionGroup` "
+ source.getKey().getId());
final QuestionGroup newQuestionGroup = qgDao.save(tmp, newSurveyId,
order);
log.log(Level.INFO, "New `QuestionGroup` ID: "
+ newQuestionGroup.getKey().getId());
List<Question> qList = qDao.listQuestionsInOrderForGroup(source
.getKey().getId());
if (qList == null) {
return newQuestionGroup;
}
log.log(Level.INFO, "Copying " + qList.size() + " `Question`");
final List<Question> dependentQuestionList = new ArrayList<Question>();
int qCount = 1;
for (Question q : qList) {
final Question qTmp = SurveyUtils.copyQuestion(q, newQuestionGroup
.getKey().getId(), qCount++);
qMap.put(q.getKey().getId(), qTmp.getKey().getId());
if (qTmp.getDependentFlag() != null && qTmp.getDependentFlag()) {
dependentQuestionList.add(qTmp);
}
}
// fixing dependencies
log.log(Level.INFO, "Fixing dependencies for " + dependentQuestionList.size()
+ " `Question`");
for (Question nQ : dependentQuestionList) {
nQ.setDependentQuestionId(qMap.get(nQ.getDependentQuestionId()));
}
qDao.save(dependentQuestionList);
return newQuestionGroup;
}
public static Question copyQuestion(Question source,
Long newQuestionGroupId, Integer order) {
final QuestionDao qDao = new QuestionDao();
final QuestionOptionDao qoDao = new QuestionOptionDao();
final Question tmp = new Question();
final String[] questionExcludedProps = { "questionOptionMap",
"questionHelpMediaMap", "scoringRules", "translationMap" };
final String[] allExcludedProps = (String[]) ArrayUtils.addAll(
questionExcludedProps, Constants.EXCLUDED_PROPERTIES);
BeanUtils.copyProperties(source, tmp, allExcludedProps);
log.log(Level.INFO, "Copying `Question` " + source.getKey().getId());
final Question newQuestion = qDao.save(tmp, newQuestionGroupId);
log.log(Level.INFO, "New `Question` ID: "
+ newQuestion.getKey().getId());
if (!Question.Type.OPTION.equals(newQuestion.getType())) {
// Nothing more to do
return newQuestion;
}
final TreeMap<Integer, QuestionOption> options = qoDao
.listOptionByQuestion(source.getKey().getId());
if (options == null) {
return newQuestion;
}
log.log(Level.INFO, "Copying " + options.values().size()
+ " `QuestionOption`");
// Copying Question Options
for (QuestionOption qo : options.values()) {
SurveyUtils.copyQuestionOption(qo, newQuestion.getKey().getId());
}
return newQuestion;
}
public static QuestionOption copyQuestionOption(QuestionOption source,
Long newQuestionId) {
final QuestionOptionDao qDao = new QuestionOptionDao();
final QuestionOption tmp = new QuestionOption();
BeanUtils.copyProperties(source, tmp, Constants.EXCLUDED_PROPERTIES);
tmp.setQuestionId(newQuestionId);
log.log(Level.INFO, "Copying `QuestionOption` "
+ source.getKey().getId());
final QuestionOption newQuestionOption = qDao.save(tmp);
log.log(Level.INFO, "New `QuestionOption` ID: "
+ newQuestionOption.getKey().getId());
return newQuestionOption;
}
private static String getPath(Survey s) {
if (s == null) {
return null;
}
final SurveyGroupDAO dao = new SurveyGroupDAO();
final SurveyGroup sg = dao.getByKey(s.getSurveyGroupId());
if (sg == null) {
return null;
}
return sg.getName() + "/" + s.getName();
}
/**
* Sends a POST request of a collection of surveyIds to a server defined by
* the `flowServices` property
*
* The property `alias` define the baseURL property that is sent in the
* request
*
* @param surveyIds
* Collection of ids (Long) that requires processing
* @param action
* A string indicating the action that will be used, this string
* is used for building the URL, with the `flowServices`
* property + / + action
* @return The response from the server or null when `flowServices` is not
* defined, or an error in the request happens
*/
public static String notifyReportService(Collection<Long> surveyIds,
String action) {
final String flowServiceURL = PropertyUtil
.getProperty("flowServices");
final String baseURL = PropertyUtil.getProperty("alias");
if (flowServiceURL == null || "".equals(flowServiceURL)) {
log.log(Level.SEVERE,
"Error trying to notify server. It's not configured, check `flowServices` property");
return null;
}
try {
final JSONObject payload = new JSONObject();
payload.put("surveyIds", surveyIds);
payload.put("baseURL", (baseURL.startsWith("http") ? baseURL
: "http://" + baseURL));
log.log(Level.INFO, "Sending notification (" + action
+ ") for surveys: " + surveyIds);
final String postString = "criteria="
+ URLEncoder.encode(payload.toString(), "UTF-8");
log.log(Level.FINE, "POST string: " + postString);
final String response = new String(HttpUtil.doPost(flowServiceURL
+ "/" + action, postString), "UTF-8");
log.log(Level.INFO, "Response from server: " + response);
return response;
} catch (Exception e) {
log.log(Level.SEVERE,
"Error notifying the report service: " + e.getMessage(), e);
}
return null;
}
}
|
package com.parrot.arsdk.arutils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.content.Context;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.os.Build;
import java.util.UUID;
import java.io.InputStream;
import java.io.OutputStream;
import com.parrot.arsdk.arsal.ARSALBLEManager;
import com.parrot.arsdk.arsal.ARSALBLEManager.ARSALManagerNotificationData;
import com.parrot.arsdk.arsal.ARSALPrint;
import com.parrot.arsdk.arsal.ARSAL_ERROR_ENUM;
import com.parrot.arsdk.arsal.ARUUID;
import com.parrot.arsdk.arnetworkal.ARNetworkALBLENetwork;
import java.nio.ByteBuffer;
public class ARUtilsRFCommFtp
{
private static final String LOG_TAG = "ARUtilsRFCommFTP.java";
private static final String RFCOMM_UPDATE_KEY = "UPD";
public final static String RFCOMM_GETTING_KEY = "kARUTILS_BLERFComm_Getting";
private ARSALBLEManager bleManager = null;
private BluetoothGatt gattDevice = null;
private int port;
private int connectionCount = 0;
private Lock connectionLock = new ReentrantLock();
private ArrayList<BluetoothGattCharacteristic> arrayGetting = null;
private native void nativeProgressCallback(long nativeCallbackObject, float percent);
private native static void nativeJNIInit();
private BluetoothGattCharacteristic rfCommWriteCharac;
private BluetoothGattCharacteristic rfCommReadCharac;
// Type of message
protected static final int ST_NOT_CONNECTED = 0;
protected static final int ST_CONNECTING = 1;
protected static final int ST_CONNECTED = 2;
public static final byte TYPE_MES_OPEN_SESSION = 0x00;
public static final byte TYPE_MES_CLOSE_SESSION = 0x01;
private static final byte TYPE_MES_ACKNOWLEDGT = 0x02;
public static final byte TYPE_MES_DATA = (byte) 0x80; // get or set request
public static final String SOFTWARE_DOWNLOAD_SIZE_SET = "/api/software/download_size/set";
private static final UUID MY_UUID = UUID.fromString("8b6814d3-6ce7-4498-9700-9312c1711f63"); // TODO change this name
private static final Integer RFCOMM_CHANNEL = 21;
private BluetoothSocket mSocket;
private InputStream mInStream;
private OutputStream mOutStream;
private boolean mIsOpeningSession = false;
private int mState = ST_NOT_CONNECTED;
private BluetoothDevice mDevice;
static
{
nativeJNIInit();
}
private ARUtilsRFCommFtp()
{
}
private static class ARUtilsRFCommFtpHolder
{
private final static ARUtilsRFCommFtp instance = new ARUtilsRFCommFtp();
}
public static ARUtilsRFCommFtp getInstance(Context context)
{
ARUtilsRFCommFtp instance = ARUtilsRFCommFtpHolder.instance;
if (context == null)
{
throw new IllegalArgumentException("Context must not be null");
}
instance.setBLEManager(context);
return instance;
}
private synchronized void setBLEManager(Context context)
{
if (this.bleManager == null)
{
if (context == null)
{
throw new IllegalArgumentException("Context must not be null");
}
this.bleManager = ARSALBLEManager.getInstance(context);
}
}
public boolean registerDevice(BluetoothGatt gattDevice, int port)
{
ARSALPrint.d(LOG_TAG, "registerDevice " + gattDevice.toString() + " port : " + port);
boolean ret = true;
/*if (connectionCount == 0)
{*/
if ((this.gattDevice != gattDevice) || (this.port != port))
{
this.gattDevice = gattDevice;
this.port = port;
connectionCount++;
searchForInterestingCharacs();
ret = registerCharacteristics();
}
else if (this.gattDevice == null)
{
ARSALPrint.e(LOG_TAG, "registerDevice : Bad parameters");
ret = false;
}
else
{
ARSALPrint.e(LOG_TAG, "already on good device");
}
/*}
else if ((this.gattDevice == gattDevice) && (this.port == port))
{
connectionCount++;
}
else
{
ARSALPrint.e(LOG_TAG, "Bad parameters");
ret = false;
}*/
return ret;
}
public boolean unregisterDevice()
{
boolean ret = true;
if (connectionCount > 0)
{
if (connectionCount == 1)
{
this.gattDevice = null;
this.port = 0;
unregisterCharacteristics();
}
connectionCount
}
else
{
ARSALPrint.e(LOG_TAG, "Bad parameters");
ret = false;
}
return ret;
}
@SuppressLint("NewApi")
public void searchForInterestingCharacs()
{
List<BluetoothGattService> services = gattDevice.getServices();
ARSAL_ERROR_ENUM error = ARSAL_ERROR_ENUM.ARSAL_OK;
boolean ret = true;
ARSALPrint.d(LOG_TAG, "registerCharacteristics");
// store in variables the characteristics we will need
Iterator<BluetoothGattService> servicesIterator = services.iterator();
while (servicesIterator.hasNext())
{
BluetoothGattService service = servicesIterator.next();
String serviceUuid = ARUUID.getShortUuid(service.getUuid());
String name = ARUUID.getShortUuid(service.getUuid());
ARSALPrint.e(LOG_TAG, "service " + name);
if (serviceUuid.startsWith(ARNetworkALBLENetwork.ARNETWORKAL_BLENETWORK_PARROT_SERVICE_PREFIX_UUID_RFCOMM))
{
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
Iterator<BluetoothGattCharacteristic> characteristicsIterator = characteristics.iterator();
while (characteristicsIterator.hasNext())
{
BluetoothGattCharacteristic characteristic = characteristicsIterator.next();
String characteristicUuid = ARUUID.getShortUuid(characteristic.getUuid());
ARSALPrint.e(LOG_TAG, "characteristic " + characteristicUuid);
if (characteristicUuid.startsWith(ARNetworkALBLENetwork.ARNETWORKAL_BLENETWORK_PARROT_CHARACTERISTIC_PREFIX_UUID_RFCOMM_READ))
{
this.rfCommReadCharac = characteristic;
}
else if (characteristicUuid.startsWith(ARNetworkALBLENetwork.ARNETWORKAL_BLENETWORK_PARROT_CHARACTERISTIC_PREFIX_UUID_RFCOMM_WRITE))
{
this.rfCommWriteCharac = characteristic;
this.rfCommReadCharac = characteristic;
}
}
}
}
}
public boolean registerCharacteristics()
{
boolean ret = false;
ARSALPrint.d(LOG_TAG, "registerCharacteristics");
arrayGetting = null;
if (this.rfCommReadCharac != null)
{
this.arrayGetting = new ArrayList<BluetoothGattCharacteristic>();
this.arrayGetting.add(rfCommReadCharac);
bleManager.registerNotificationCharacteristics(this.arrayGetting, RFCOMM_GETTING_KEY);
ret = true;
}
return ret;
}
public boolean unregisterCharacteristics()
{
boolean ret = true;
ARSALPrint.d(LOG_TAG, "unregisterCharacteristics");
ret = bleManager.unregisterNotificationCharacteristics(RFCOMM_GETTING_KEY);
return ret;
}
/* Do nothing*/
/**
* Open session
*/
private void openSession() {
ARSALPrint.d(LOG_TAG, "open RFComm session");
mIsOpeningSession = true;
write(getHeaderFirst(0, TYPE_MES_OPEN_SESSION));
byte[] readArray = new byte[4096];
try {
// wait for the answer
int readLength = mInStream.read(readArray);
}
catch (IOException e) {
closeConnection();
return;
}
mIsOpeningSession = false;
mState = ST_CONNECTED;
}
/**
* Close session
*/
private void closeSession() {
ARSALPrint.d(LOG_TAG, "close RFComm session");
mIsOpeningSession = true;
write(getHeaderFirst(0, TYPE_MES_CLOSE_SESSION));
byte[] readArray = new byte[4096];
try {
// wait for the answer
int readLength = mInStream.read(readArray);
}
catch (IOException e) {
closeConnection();
return;
}
mState = ST_NOT_CONNECTED;
}
private void unpairDevice(BluetoothDevice device) {
try
{
Method m = device.getClass()
.getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
}
catch (Exception e)
{
ARSALPrint.e(LOG_TAG, e.getMessage());
}
}
private boolean sendFile(File file, long nativeCallbackObject, Semaphore cancelSem)
{
int nbSstoredBytes = 0; // for now, send the entire file (=> no resume)
boolean ret = true;
FileInputStream f = null;
try {
f = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
byte[] buffer = new byte[978];
int len = 0;
long total = 0;
int id = 0;
float percent = 0.f;
float lastPercent = 0.f;
try {
// Skip bytes that already saved on divice
if(nbSstoredBytes > 0) {
while (nbSstoredBytes > 0) {
int nbSkipped = (int) f.skip(nbSstoredBytes);
nbSstoredBytes -= nbSkipped ;
}
}
long fileSize = file.length();
// Send to device
while ( ret && (len = f.read(buffer)) > 0 ) {
total += len;
byte[] request = new byte[len];
System.arraycopy(buffer, 0, request, 0, len);
//long time = System.currentTimeMillis();
if(!sendFirmwareOnDevice(request, id)){
ARSALPrint.e(LOG_TAG, "upload firmware, task was canceled");
f.close();
return false;
}
/*if (System.currentTimeMillis() - time > 500) {
try {
Log.e(LOG_TAG, "fixIssuesOnHtcDevices");
//fixIssuesOnHtcDevices();
} catch (Exception e) {
}
}*/
percent = ((float)total / (float)fileSize) * 100.f;
if (nativeCallbackObject != 0)
{
// no need of this block for now, because we have no resume for now
/*if ((resume == true) && (totalPacket < resumeIndex))
{
if ((percent - lastPercent) > 1.f)
{
lastPercent = percent;
nativeProgressCallback(nativeCallbackObject, percent);
}
}
else
{*/
nativeProgressCallback(nativeCallbackObject, percent);
}
if (isConnectionCanceled(cancelSem))
{
ARSALPrint.d(LOG_TAG, "Canceled received during file upload");
ret = false;
}
id++;
}
} catch (Exception e) {
e.printStackTrace();
try {
f.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return false;
}
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
ARSALPrint.e(LOG_TAG, "Sending done. Sent " + total + " bytes");
return ret;
}
public boolean sendFirmwareOnDevice(byte[] data, int id)
{
boolean success = (mState == ST_CONNECTED);
if(success)
{
byte[] request = getUploadPacket(data, id);
//long time = System.currentTimeMillis();
try
{
success = write(request);
}
catch (Exception e)
{
success = false;
}
/*if (System.currentTimeMillis() < time + 10000) {
try {
fixIssuesOnHtcDevices();
} catch (Exception e) {
}
}*/
}
return success;
}
private synchronized boolean write(byte[] buffer)
{
boolean success = false;
try
{
mOutStream.write(buffer);
Thread.sleep(40);
success = true;
}
catch (IOException e)
{
ARSALPrint.e(LOG_TAG, "Exception during write" + e.getMessage());
}
catch (InterruptedException e)
{
ARSALPrint.e(LOG_TAG, "Exception during sleep" + e.getMessage());
}
return success;
}
/**
* Return header of message
* @param length - size of message
*/
private static byte[] getHeaderFirst(int length, byte type) {
// 3-byte header : ZZ + T
// ZZ - total number of bytes of the packet (including this header)
// T - type massage
byte[] zz = sizeIntToByte(length + 3); // 3 bytes of header
byte[] t = new byte[1];
t[0] = type;
byte[] header = new byte[zz.length + t.length];
System.arraycopy(zz, 0, header, 0, zz.length);
System.arraycopy(t, 0, header, zz.length, t.length);
return header;
}
/**
* Return ZZ (2 bytes) - total number of bytes of the messages,
* (Most Significant Byte first, then Least Significant Byte)
*/
private static byte[] sizeIntToByte(int length) {
byte[] zz = new byte[2];
zz = new byte[]{(byte)(length >>> 8), (byte)(length)};
//zz = new byte[]{(byte)(length), (byte)(length >>> 8)};
return zz;
}
/**
* Return ZZ (2 bytes) - total number of bytes of the messages,
* (Most Significant Byte first, then Least Significant Byte)
*/
private static byte[] sizeIntToByte2(int length) {
byte[] zz = new byte[2];
zz = new byte[]{(byte)(length), (byte)(length >>> 8)};
return zz;
}
public synchronized void closeConnection() {
ARSALPrint.e(LOG_TAG, "closeConnection");
try
{
if (mInStream != null)
{
mInStream.close();
mInStream = null;
}
}
catch (IOException e)
{
ARSALPrint.e(LOG_TAG, "Closing of mInStream failed", e);
}
try
{
if (mOutStream != null)
{
mOutStream.close();
mOutStream = null;
}
}
catch (IOException e)
{
ARSALPrint.e(LOG_TAG, "Closing of mOutStream failed", e);
}
try
{
if (mSocket != null)
{
mSocket.close();
mSocket = null;
}
}
catch (IOException e)
{
ARSALPrint.e(LOG_TAG, "Closing of mSocket failed", e);
}
if (mDevice != null)
{
unpairDevice(mDevice);
mDevice = null;
}
mState = ST_NOT_CONNECTED;
}
/**
* Return packet in a specific format for uploading to Zik. Use for updating firmware.
*/
private static byte[] getUploadPacket(byte[] data, int id) {
// 3-byte header
// 4-byte header for uploading: XYZZ (see download2.odt)
// 1-byte packet type (DATA = 0)
// 2-byte packet identifier (MSB first),
// core on several bytes
// 2-byte trailer (sign)
// X current packet number, on 1 byte, value 1
// Y total number of packets, on 1 byte, value 1
// ZZ total number of bytes of the packet (including this header)
// optional trailer (sign) : inclusive OR (1 byte) and exclusive OR (1 byte).
// These 2 bytes are computed from start of packet up to last header byte
int sizePack2 = data.length + 9;
byte[] header = getHeaderFirst(sizePack2, TYPE_MES_DATA); // ignoring on Zik side, but need
byte[] xy = {0x01, 0x01};
byte[] zzDesordered = ByteBuffer.allocate(2).putShort((short)(data.length + 9)).array();
byte[] zz = {zzDesordered[1], zzDesordered[0]};
//byte[] zz = sizeIntToByte(data.length + 9); // without length of the first header, 2 byte - trailer (sign) at the end
byte[] pktType = {0x00};
byte[] pktIdDesordered = ByteBuffer.allocate(2).putShort((short)id).array();//sizeIntToByte2(id);
byte[] pktId = {pktIdDesordered[1], pktIdDesordered[0]};
byte[] request = new byte[data.length + 12]; // a;; header and trailer
System.arraycopy(header, 0, request, 0, header.length);
System.arraycopy(xy, 0, request, header.length, xy.length);
System.arraycopy(zz, 0, request, header.length + xy.length, zz.length);
System.arraycopy(pktType, 0, request, header.length + xy.length + zz.length, pktType.length);
System.arraycopy(pktId, 0, request, header.length + xy.length + zz.length + pktType.length, pktId.length);
System.arraycopy(data, 0, request, header.length + xy.length + zz.length + pktType.length + pktId.length, data.length);
// signing
byte a = 0x00;
byte b = 0x00;
for ( int i=header.length; i<request.length; i++ ) { // ignoring the first header (3 bytes)
//for ( int i=0; i<request.length - 2; i++ ) { // ignoring the first header (3 bytes)
a |= request[i];
b ^= request[i];
}
byte[] sign = {(byte) a, (byte) b};
System.arraycopy(sign, 0, request, header.length + xy.length + zz.length + pktType.length + pktId.length + data.length, sign.length);
return request;
}
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.stream.*;
import javax.swing.*;
public class MainPanel extends JPanel {
protected final Set<Integer> disableIndexSet = new HashSet<>();
protected final JTextField field = new JTextField("1, 2, 5");
protected final JList list = makeList(disableIndexSet);
public MainPanel() {
super(new BorderLayout(5, 5));
initDisableIndex(disableIndexSet);
ActionMap am = list.getActionMap();
am.put("selectNextRow", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
int index = list.getSelectedIndex();
for (int i = index + 1; i < list.getModel().getSize(); i++) {
if (!disableIndexSet.contains(i)) {
list.setSelectedIndex(i);
break;
}
}
}
});
am.put("selectPreviousRow", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
int index = list.getSelectedIndex();
for (int i = index - 1; i >= 0; i
if (!disableIndexSet.contains(i)) {
list.setSelectedIndex(i);
break;
}
}
}
});
JButton button = new JButton("init");
button.addActionListener(e -> {
initDisableIndex(disableIndexSet);
list.repaint();
});
Box box = Box.createHorizontalBox();
box.add(new JLabel("Disabled Item Index:"));
box.add(field);
box.add(Box.createHorizontalStrut(2));
box.add(button);
add(new JScrollPane(list));
add(box, BorderLayout.NORTH);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setPreferredSize(new Dimension(320, 240));
}
private static JList makeList(final Set<Integer> disableIndexSet) {
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("aaaaaaaaaaaa");
model.addElement("bbbbbbbbbbbbbbbbbb");
model.addElement("ccccccccccc");
model.addElement("dddddddddddd");
model.addElement("eeeeeeeeeeeeeeeeeee");
model.addElement("fffffffffffffffffffffff");
model.addElement("ggggggggg");
JList<String> list = new JList<>(model);
list.setCellRenderer(new DefaultListCellRenderer() {
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c;
if (disableIndexSet.contains(index)) {
c = super.getListCellRendererComponent(list, value, index, false, false);
c.setEnabled(false);
} else {
c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
return c;
}
});
// list.setSelectionModel(new DefaultListSelectionModel() {
// @Override public boolean isSelectedIndex(int index) {
// return !disableIndexSet.contains(index) && super.isSelectedIndex(index);
return list;
}
protected final void initDisableIndex(Set<Integer> set) {
set.clear();
try {
set.addAll(Arrays.stream(field.getText().split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::valueOf).collect(Collectors.toSet()));
} catch (NumberFormatException ex) {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(field, "invalid value.\n" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
// 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
package edu.umd.cs.findbugs.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
public class IO {
static ThreadLocal myByteBuf = new ThreadLocal() {
protected Object initialValue() {
return new byte[4096];
}
};
static ThreadLocal myCharBuf = new ThreadLocal() {
protected Object initialValue() {
return new char[4096];
}
};
public static String readAll(InputStream in) throws IOException {
return readAll(new InputStreamReader(in));
}
public static String readAll(Reader reader) throws IOException {
BufferedReader r = new BufferedReader(reader);
StringWriter w = new StringWriter();
copy(r, w);
return w.toString();
}
public static long copy(InputStream in, OutputStream out)
throws IOException {
return copy(in, out, Long.MAX_VALUE);
}
public static long copy(Reader in, Writer out)
throws IOException {
return copy(in, out, Long.MAX_VALUE);
}
public static long copy(InputStream in, OutputStream out,
long maxBytes)
throws IOException {
long total = 0;
int sz;
byte buf [] = (byte[]) myByteBuf.get();
while (maxBytes > 0 &&
(sz = in.read(buf, 0,
(int) Math.min(maxBytes, (long) buf.length)))
> 0) {
total += sz;
maxBytes -= sz;
out.write(buf, 0, sz);
}
return total;
}
public static long copy(Reader in, Writer out,
long maxChars)
throws IOException {
long total = 0;
int sz;
char buf [] = (char[]) myCharBuf.get();
while (maxChars > 0 &&
(sz = in.read(buf, 0,
(int) Math.min(maxChars, (long) buf.length)))
> 0) {
total += sz;
maxChars -= sz;
out.write(buf, 0, sz);
}
return total;
}
/**
* Close given InputStream, ignoring any resulting exception.
*
* @param inputStream the InputStream to close
*/
public static void close(InputStream inputStream) {
try {
inputStream.close();
} catch (IOException e) {
// Ignore
}
}
/**
* Close given OutputStream, ignoring any resulting exception.
*
* @param outputStream the OutputStream to close
*/
public static void close(OutputStream outputStream) {
try {
outputStream.close();
} catch (IOException e) {
// Ignore
}
}
}
|
public class Dragon extends Bushi implements Deplacable {
public Dragon(int abs, int ord) {
super(abs, ord, 3, 0);
}
public ArrayList<Bushi> listerDeplacement(Plateau p) {
int i;
int j;
ArrayList<Bushi> possible = new ArrayList<Bushi>();
// i & j reprsente la valeur du dcalage par rapport aux coordonnes
// courantes
for (i = -1; i <= 1; i++) {
for (j = 1; j >= -1; j
// System.out.println("x= " + (this.abs + i) + " y =" +
// (this.ord + j));
if(p.plateau[this.ord +j][this.abs + i].etat != 0 ){
if (this.reachable(this.abs + 2 * i, this.ord + 2 * j, p)) {
possible.add(p.plateau[this.ord + 2 * j][this.abs + 2 * i]);
}
}
}
}
return possible;
}
@Override
public String toString() {
return "Dragon [" + this.abs + ", " + this.ord+"]";
}
}
* /*public Bushi verifieObstacle(Plateau p){ this.demanderDplacement(p); int
* abs_deplacement =this.demanderDplacement(p).getAbs(); int
* ord_deplacement=this.demanderDplacement(p).getOrd();
*
* int abs_inter = (this.abs + abs_deplacement)/2; int ord_inter = (this.ord +
* ord_deplacement)/2;
*
* if (p.plateau[abs_inter][ord_inter].isOccupee()){ return
* p.plateau[abs_inter][ord_inter]; } else { return new Dragon(-1,-1,50); }
*
* }
*
* }
*/
|
package com.parc.ccn.network.daemons.repo;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeMap;
import javax.xml.stream.XMLStreamException;
import com.parc.ccn.Library;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.MalformedContentNameStringException;
import com.parc.ccn.data.WirePacket;
import com.parc.ccn.data.query.Interest;
import com.parc.ccn.library.CCNNameEnumerator;
import com.parc.ccn.library.profiles.VersioningProfile;
/**
* An initial implementation of the repository using a file system
* based repository. We are using the XMLEncodeable representation to
* represent content on the disk
*
* Note: This layer purposefully should not make any non-static calls into the
* CCN library
*
* @author rasmusse
*
*/
public class RFSImpl implements Repository {
public final static String CURRENT_VERSION = "1.3";
public final static String META_DIR = ".meta";
public final static String NORMAL_COMPONENT = "0";
public final static String SPLIT_COMPONENT = "1";
private static final String REPO_PRIVATE = "private";
private static final String VERSION = "version";
private static final String REPO_LOCALNAME = "local";
private static final String REPO_GLOBALPREFIX = "global";
private static String DEFAULT_LOCAL_NAME = "Repository";
private static String DEFAULT_GLOBAL_NAME = "/parc.com/csl/ccn/Repos";
private static final int TOO_LONG_SIZE = 200;
protected String _repositoryRoot = null;
protected File _repositoryFile;
protected RFSLocks _locker;
protected Policy _policy = null;
protected RepositoryInfo _info = null;
protected ArrayList<ContentName> _nameSpace = new ArrayList<ContentName>();
public String[] initialize(String[] args) throws RepositoryException {
boolean policyFromFile = false;
boolean nameFromArgs = false;
boolean globalFromArgs = false;
String localName = DEFAULT_LOCAL_NAME;
String globalPrefix = DEFAULT_GLOBAL_NAME;
String[] outArgs = args;
Policy policy = new BasicPolicy(null);
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-root")) {
if (args.length < i + 2)
throw new InvalidParameterException();
_repositoryRoot = args[i + 1];
i++;
} else if (args[i].equals("-policy")) {
policyFromFile = true;
if (args.length < i + 2)
throw new InvalidParameterException();
File policyFile = new File(args[i + 1]);
try {
policy.update(new FileInputStream(policyFile), false);
} catch (Exception e) {
throw new InvalidParameterException(e.getMessage());
}
} else if (args[i].equals("-local")) {
if (args.length < i + 2)
throw new InvalidParameterException();
localName = args[i + 1];
nameFromArgs = true;
} else if (args[i].equals("-global")) {
if (args.length < i + 2)
throw new InvalidParameterException();
globalPrefix = args[i + 1];
if (!globalPrefix.startsWith("/"))
globalPrefix = "/" + globalPrefix;
globalFromArgs = true;
}
}
if (_repositoryRoot == null) {
throw new InvalidParameterException();
}
_repositoryFile = new File(_repositoryRoot);
_repositoryFile.mkdirs();
_locker = new RFSLocks(_repositoryRoot + File.separator + META_DIR);
String version = checkFile(VERSION, CURRENT_VERSION, false);
if (version != null && !version.trim().equals(CURRENT_VERSION))
throw new RepositoryException("Bad repository version: " + version);
String checkName = checkFile(REPO_LOCALNAME, localName, nameFromArgs);
localName = checkName != null ? checkName : localName;
checkName = checkFile(REPO_GLOBALPREFIX, globalPrefix, globalFromArgs);
globalPrefix = checkName != null ? checkName : globalPrefix;
try {
_info = new RepositoryInfo(localName, globalPrefix, CURRENT_VERSION);
} catch (MalformedContentNameStringException e1) {
throw new RepositoryException(e1.getMessage());
}
/*
* Read policy file from disk if it exists and we didn't read it in as an argument.
* Otherwise save the new policy to disk.
*/
if (!policyFromFile) {
try {
ContentObject policyObject = getContent(
new Interest(ContentName.fromNative(REPO_NAMESPACE + "/" + _info.getLocalName() + "/" + REPO_POLICY)));
if (policyObject != null) {
ByteArrayInputStream bais = new ByteArrayInputStream(policyObject.content());
policy.update(bais, false);
}
} catch (MalformedContentNameStringException e) {} // None of this should happen
catch (XMLStreamException e) {}
catch (IOException e) {}
} else {
saveContent(policy.getPolicyContent());
}
setPolicy(policy);
if (_nameSpace.size() == 0) {
try {
_nameSpace.add(ContentName.fromNative("/"));
} catch (MalformedContentNameStringException e) {}
}
return outArgs;
}
/**
* Check data file - create new one if none exists
* @throws RepositoryException
*/
private String checkFile(String fileName, String contents, boolean forceWrite) throws RepositoryException {
File dirFile = new File(_repositoryRoot + File.separator + META_DIR + File.separator + REPO_PRIVATE);
File file = new File(_repositoryRoot + File.separator + META_DIR + File.separator + REPO_PRIVATE
+ File.separator + fileName);
try {
if (!forceWrite && file.exists()) {
FileInputStream fis = new FileInputStream(file);
byte [] content = new byte[fis.available()];
fis.read(content);
fis.close();
return new String(content);
} else {
dirFile.mkdirs();
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(contents.getBytes());
fos.close();
return null;
}
} catch (FileNotFoundException e) {} catch (IOException e) {
throw new RepositoryException(e.getMessage());
}
return null;
}
/**
* Check for data routed for the repository and take special
* action if it is. Returns true if data is for repository.
*
* @param co
* @return
* @throws RepositoryException
*/
public boolean checkPolicyUpdate(ContentObject co) throws RepositoryException {
if (_info.getPolicyName().isPrefixOf(co.name())) {
ByteArrayInputStream bais = new ByteArrayInputStream(co.content());
try {
_policy.update(bais, true);
_nameSpace = _policy.getNameSpace();
ContentName policyName = ContentName.fromNative(REPO_NAMESPACE + "/" + _info.getLocalName() + "/" + REPO_POLICY);
ContentObject policyCo = new ContentObject(policyName, co.signedInfo(), co.content(), co.signature());
saveContent(policyCo);
} catch (XMLStreamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedContentNameStringException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
/**
* Go through all the "possible matches" and find the best one
* to match the interest
*
* @param interest
* @return
*/
public ContentObject getContent(Interest interest) throws RepositoryException {
TreeMap<ContentName, ArrayList<File>>possibleMatches = getPossibleMatches(interest);
// Note: these possible match names INCLUDE include the digest
ContentObject bestMatch = null;
for (ContentName name : possibleMatches.keySet()) {
if (bestMatch == null) {
bestMatch = checkMatch(interest, name, possibleMatches.get(name));
} else {
ContentObject checkMatch = null;
if (interest.orderPreference() != null) {
/*
* Must test in this order since ORDER_PREFERENCE_LEFT is 0
*/
if ((interest.orderPreference() & (Interest.ORDER_PREFERENCE_RIGHT | Interest.ORDER_PREFERENCE_ORDER_NAME))
== (Interest.ORDER_PREFERENCE_RIGHT | Interest.ORDER_PREFERENCE_ORDER_NAME)) {
if (name.compareTo(bestMatch.name()) > 0) {
checkMatch = checkMatch(interest, name, possibleMatches.get(name));
if (checkMatch != null)
bestMatch = checkMatch;
}
} else if ((interest.orderPreference() & (Interest.ORDER_PREFERENCE_LEFT | Interest.ORDER_PREFERENCE_ORDER_NAME))
== (Interest.ORDER_PREFERENCE_LEFT | Interest.ORDER_PREFERENCE_ORDER_NAME)) {
if (name.compareTo(bestMatch.name()) < 0) {
checkMatch = checkMatch(interest, name, possibleMatches.get(name));
if (checkMatch != null)
bestMatch = checkMatch;
}
}
} else
checkMatch = checkMatch(interest, name, possibleMatches.get(name));
/*
* Try to get the closest match in size
*/
if (checkMatch != null) {
int cOffset = checkMatch.name().count() - interest.name().count();
int bOffset = bestMatch.name().count() - interest.name().count();
if (cOffset < bOffset)
bestMatch = checkMatch;
}
}
}
return bestMatch;
}
/**
* If the interest has no publisher ID we can optimize this by first checking the interest against the name
* and only reading the content from the file if this check matches.
* JDT: Actually, a pre-check on the name should always be ok as long as final check is
* performed on the content object itself.
*
* @param interest
* @param name - ContentName WITH digest component
* @param file
* @return
* @throws RepositoryException
*/
private ContentObject checkMatch(Interest interest, ContentName name, ArrayList<File>files) throws RepositoryException {
for (File file: files) {
if (null == interest.publisherID()) {
// Since the name INCLUDES digest component and the Interest.matches() convention for name
// matching is that the name DOES NOT include digest component (conforming to the convention
// for ContentObject.name() that the digest is not present) we must REMOVE the content
// digest first or this test will not always be correct
ContentName digestFreeName = new ContentName(name.count()-1, name.components());
if (!interest.matches(digestFreeName, null))
return null;
}
ContentObject testMatch = getContentFromFile(file);
if (testMatch != null) {
if (interest.matches(testMatch))
return testMatch;
}
}
return null;
}
/**
* Pull out anything that might be a match to the interest. This includes
* any file that matches the prefix and any member of the "encodedNames"
* that matches the prefix.
* Results returned map from ContentName without digest to list of Files
*/
private TreeMap<ContentName, ArrayList<File>> getPossibleMatches(Interest interest) {
TreeMap<ContentName, ArrayList<File>> results = new TreeMap<ContentName, ArrayList<File>>();
File file = new File(_repositoryFile + interest.name().toString());
ContentName lowerName = new ContentName(null != interest.nameComponentCount() ? interest.nameComponentCount() : interest.name().count(),
interest.name().components());
getAllFileResults(file, results, lowerName);
return results;
}
/**
* Subprocess of getting "possible" matching results.
* Recursively get all files below us and add them to the results.
* If we are at a leaf, we want to decode the filename to a ContentName,
* or encode the ContentName to a filename to check to see if it exists.
*
* @param file
* @param results - map from ContentName WITH digest to File
* @param name
*/
private void getAllFileResults(File file, TreeMap<ContentName, ArrayList<File>> results, ContentName name) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
getAllFileResults(f, results, new ContentName(name, f.getName().getBytes()));
}
} else if (file.exists()) {
if (file.getName().endsWith(".rfs")) {
/*
* We assume this is a file with identical data but different pub IDs
* Remove the last part and put all files into the "potential" results.
* We'll figure out which one(s) we want later
*/
name = new ContentName(name.count() - 1, name.components());
}
ContentName decodedName = decodeName(name);
addOneFileToMap(decodedName, file, results);
} else {
// Convert to name we can use as a file
ContentName encodedName = encodeName(name);
File encodedFile = new File(_repositoryFile + encodedName.toString());
if (encodedFile.isDirectory()) {
getAllFileResults(encodedFile, results, encodedName);
}
else {
encodedFile = new File(_repositoryFile + encodedName.toString());
if (encodedFile.exists()) {
// The name here must contain a digest, for it maps to something
// that is not a directory in the filesystem, and the only files
// are for the leaf content objects and have digest as last component
addOneFileToMap(name, encodedFile, results);
}
}
}
}
/**
* Restore ContentObject from wire data on disk
* @param fileName
* @return
* @throws RepositoryException
*/
public static ContentObject getContentFromFile(File fileName) throws RepositoryException {
try {
FileInputStream fis = new FileInputStream(fileName);
byte[] buf = new byte[fis.available()];
fis.read(buf);
fis.close();
WirePacket packet = new WirePacket();
packet.decode(buf);
if (packet.data().size() == 1)
return packet.data().get(0);
} catch (Exception e) {
throw new RepositoryException(e.getMessage());
}
return null;
}
/**
* Main routine to save a content object under a filename. Normally we just
* create a new file and save the data in XMLEncoded form in the file.
*
* If we already had content saved under the same name do the following:
* - Read the data and see if it matches - if so we're done.
* - Otherwise we put all files with the same digest in a directory using
* the digest name as the directory name. So if we have a name clash
* with a non-directory, this is the first name clash with an old
* digest name and we need to remove the old data, change the file
* to a directory, then put back the old data in the directory and
* add the new data. If we already had a name clash, we can just
* add the data to the new directory.
* @throws RepositoryException
*/
public void saveContent(ContentObject content) throws RepositoryException {
File file = null;
ContentName newName = content.name().clone();
newName.components().add(content.contentDigest());
newName = encodeName(newName);
ContentName dirName = new ContentName(newName.count() - 1, newName.components());
File dirFile = new File(_repositoryRoot, dirName.toString());
dirFile.mkdirs();
file = new File(_repositoryRoot, newName.toString());
if (file.exists()) {
boolean isDuplicate = true;
ContentObject prevContent = null;
if (file.isFile()) {
// New name clash
try {
prevContent = getContentFromFile(file);
if (prevContent != null) {
if (prevContent.equals(content))
return;
}
file.delete();
file.mkdir();
try {
File prevFile = File.createTempFile("RFS", ".rfs", file);
saveContentToFile(prevFile, prevContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (RepositoryException e1) {
// This could happen if there are 2 simultaneous requests
// to create the data and the first isn't yet complete (I guess)
// For now just remove the old data and try to recreate it.
file.delete();
isDuplicate = false;
}
}
if (isDuplicate) {
try {
file = File.createTempFile("RFS", ".rfs", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
saveContentToFile(file, content);
}
/**
* Algorithm is:
* Save wire data to fileName/<digest>
*
* @param file
* @param content
* @throws RepositoryException
*/
private void saveContentToFile(File file, ContentObject content) throws RepositoryException {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
WirePacket packet = new WirePacket(content);
fos.write(packet.encode());
fos.close();
} catch (Exception e) {
throw new RepositoryException(e.getMessage());
}
}
/**
* Encode all components of a ContentName
* This could result in more components than originally input due to splitting of
* components.
*
* @param name
* @return
*/
public static ContentName encodeName(ContentName name) {
StringTokenizer st = new StringTokenizer(name.toString(), "/");
String newUri = "/";
while (st.hasMoreTokens()) {
String token = st.nextToken();
while ((token.length() + 1) > TOO_LONG_SIZE) {
int length = TOO_LONG_SIZE - 1;
String nextPiece = token.substring(0, length);
// Avoid fragmenting binary encoded URI
if (nextPiece.charAt(length - 1) == '%') length
if (nextPiece.charAt(length - 2) == '%') length -= 2;
newUri += SPLIT_COMPONENT + token.substring(0, length) + "/";
token = token.substring(length);
}
newUri += NORMAL_COMPONENT + token + "/";
}
try {
return ContentName.fromURI(newUri);
} catch (MalformedContentNameStringException e) {
return null; //shouldn't happen
}
}
/**
* Decode a name built from filename components into a CCN name. The new
* name could contain less components than the input name.
*
* @param name
* @return
*/
public static ContentName decodeName(ContentName name) {
String newUri = "/";
StringTokenizer st = new StringTokenizer(name.toString(), "/");
String nextComponent = "";
while (st.hasMoreTokens()) {
String token = st.nextToken();
token = token.replace("%25", "%"); // Need to fix URI replacement for %
if (token.startsWith(SPLIT_COMPONENT))
nextComponent += token.substring(1);
else {
newUri += nextComponent + token.substring(1) + "/";
nextComponent = "";
}
}
try {
return ContentName.fromURI(newUri);
} catch (MalformedContentNameStringException e) {
return null; //shouldn't happen
}
}
private void addOneFileToMap(ContentName name, File file, TreeMap<ContentName, ArrayList<File>>map) {
ArrayList<File> files = map.get(name);
if (files == null)
files = new ArrayList<File>();
files.add(file);
map.put(name, files);
}
public String getUsage() {
return " -root repository_root [-policy policy_file] [-local local_name] [-global global_prefix]\n";
}
public void setPolicy(Policy policy) {
_policy = policy;
ArrayList<ContentName> newNameSpace = _policy.getNameSpace();
_nameSpace.clear();
for (ContentName name : newNameSpace)
_nameSpace.add(name);
}
public ArrayList<ContentName> getNamespace() {
return _nameSpace;
}
public byte[] getRepoInfo(ArrayList<ContentName> names) {
try {
RepositoryInfo rri = _info;
if (names != null)
rri = new RepositoryInfo(_info.getLocalName(), _info.getGlobalPrefix(), CURRENT_VERSION, names);
return rri.encode();
} catch (XMLStreamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedContentNameStringException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ArrayList<ContentName> getNamesWithPrefix(Interest i) {
Library.logger().setLevel(java.util.logging.Level.FINE);
ArrayList<ContentName> names = new ArrayList<ContentName>();
Timestamp interestTS = null;
Timestamp fileTS = null;
try{
interestTS = VersioningProfile.getVersionAsTimestamp(i.name());
}
catch(Exception e){
interestTS = null;
}
ContentName cropped = i.name().cut(CCNNameEnumerator.NEMARKER);
ContentName encoded = RFSImpl.encodeName(cropped);
File encodedFile = new File(_repositoryFile + encoded.toString());
long lastModified = encodedFile.lastModified();
fileTS = new Timestamp(lastModified);
if(interestTS!=null)
Library.logger().fine("localTime: "+System.currentTimeMillis()+" interest time: "+interestTS.getTime()+" fileTS: "+fileTS.getTime());
ContentName n = new ContentName();
if(interestTS == null || fileTS.after(interestTS)){
//we have something new to report
Library.logger().fine("path to file: "+encodedFile.getName());
String[] matches = encodedFile.list();
if (matches != null) {
for(String s: matches){
names.add(RFSImpl.decodeName(new ContentName(n, s.getBytes())));
}
}
}
if(names.size() > 0){
String toprint = "---names to return: ";
for(ContentName ntr: names)
toprint.concat(" "+ntr.toString());
Library.logger().fine(toprint+"
return names;
}
else{
Library.logger().finest("No new names for this prefix since the last request, dropping request and not responding.");
return null;
}
}
}
|
package test.ccn.data.util;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.sql.Timestamp;
import java.util.logging.Level;
import javax.xml.stream.XMLStreamException;
import org.bouncycastle.util.Arrays;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import test.ccn.data.content.CCNEncodableCollectionData;
import com.parc.ccn.Library;
import com.parc.ccn.config.ConfigurationException;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.content.CollectionData;
import com.parc.ccn.data.content.LinkReference;
import com.parc.ccn.data.security.LinkAuthenticator;
import com.parc.ccn.data.security.PublisherID;
import com.parc.ccn.data.security.SignedInfo;
import com.parc.ccn.data.security.PublisherID.PublisherType;
import com.parc.ccn.data.util.NullOutputStream;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.io.CCNVersionedInputStream;
import com.parc.security.crypto.DigestHelper;
/**
* Works. Currently very slow, as it's timing
* out lots of blocks. End of stream markers will help with that, as
* will potentially better binary ccnb decoding.
* @author smetters
*
*/
public class CCNEncodableObjectTest {
static final String baseName = "test";
static final String subName = "smetters";
static final String document1 = "report";
static final String document2 = "key";
static final String document3 = "cv.txt";
static final String prefix = "drawing_";
static ContentName namespace;
static ContentName [] ns = null;
static public byte [] contenthash1 = new byte[32];
static public byte [] contenthash2 = new byte[32];
static public byte [] publisherid1 = new byte[32];
static public byte [] publisherid2 = new byte[32];
static PublisherID pubID1 = null;
static PublisherID pubID2 = null;
static int NUM_LINKS = 100;
static LinkAuthenticator [] las = new LinkAuthenticator[NUM_LINKS];
static LinkReference [] lrs = null;
static CollectionData small1;
static CollectionData small2;
static CollectionData empty;
static CollectionData big;
static CCNLibrary library;
static Level oldLevel;
@AfterClass
public static void tearDownAfterClass() throws Exception {
Library.logger().setLevel(oldLevel);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("Making stuff.");
oldLevel = Library.logger().getLevel();
// Library.logger().setLevel(Level.FINEST);
library = CCNLibrary.open();
namespace = ContentName.fromURI(new String[]{baseName, subName, document1});
ns = new ContentName[NUM_LINKS];
for (int i=0; i < NUM_LINKS; ++i) {
ns[i] = ContentName.fromNative(namespace, prefix+Integer.toString(i));
}
Arrays.fill(publisherid1, (byte)6);
Arrays.fill(publisherid2, (byte)3);
pubID1 = new PublisherID(publisherid1, PublisherType.KEY);
pubID2 = new PublisherID(publisherid2, PublisherType.ISSUER_KEY);
las[0] = new LinkAuthenticator(pubID1);
las[1] = null;
las[2] = new LinkAuthenticator(pubID2, null, null,
SignedInfo.ContentType.DATA, contenthash1);
las[3] = new LinkAuthenticator(pubID1, null, new Timestamp(System.currentTimeMillis()),
null, contenthash1);
for (int j=4; j < NUM_LINKS; ++j) {
las[j] = new LinkAuthenticator(pubID2, null, new Timestamp(System.currentTimeMillis()),null, null);
}
lrs = new LinkReference[NUM_LINKS];
for (int i=0; i < lrs.length; ++i) {
lrs[i] = new LinkReference(ns[i],las[i]);
}
empty = new CollectionData();
small1 = new CollectionData();
small2 = new CollectionData();
for (int i=0; i < 5; ++i) {
small1.add(lrs[i]);
small2.add(lrs[i+5]);
}
big = new CollectionData();
for (int i=0; i < NUM_LINKS; ++i) {
big.add(lrs[i]);
}
}
@Test
public void testSaveUpdate() {
boolean caught = false;
try {
CCNEncodableCollectionData emptycoll = new CCNEncodableCollectionData();
NullOutputStream nos = new NullOutputStream();
emptycoll.save(nos);
} catch (InvalidObjectException iox) {
// this is what we expect to happen
caught = true;
} catch (IOException ie) {
Assert.fail("Unexpected IOException!");
} catch (XMLStreamException e) {
Assert.fail("Unexpected XMLStreamException!");
} catch (ConfigurationException e) {
Assert.fail("Unexpected ConfigurationException!");
}
Assert.assertTrue("Failed to produce expected exception.", caught);
Flosser flosser = null;
boolean done = false;
try {
CCNEncodableCollectionData ecd0 = new CCNEncodableCollectionData(namespace, empty, library);
CCNEncodableCollectionData ecd1 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd2 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd3 = new CCNEncodableCollectionData(namespace, big, library);
CCNEncodableCollectionData ecd4 = new CCNEncodableCollectionData(namespace, empty, library);
flosser = new Flosser(namespace);
flosser.logNamespaces();
ecd0.save(ns[2]);
System.out.println("Version for empty collection: " + ecd0.getVersion());
ecd1.save(ns[1]);
ecd2.save(ns[1]);
System.out.println("ecd1 name: " + ecd1.getName());
System.out.println("ecd2 name: " + ecd2.getName());
System.out.println("Versions for matching collection content: " + ecd1.getVersion() + " " + ecd2.getVersion());
Assert.assertFalse(ecd1.equals(ecd2));
Assert.assertTrue(ecd1.contentEquals(ecd2));
CCNVersionedInputStream vis = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte[128];
// Will incur a timeout
while (!vis.eof()) {
int read = vis.read(buf);
if (read > 0)
baos.write(buf, 0, read);
}
System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16));
CollectionData newData = new CollectionData();
newData.decode(baos.toByteArray());
System.out.println("Decoded collection data: " + newData);
CCNVersionedInputStream vis3 = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
// Will incur a timeout
while (!vis3.eof()) {
int val = vis3.read();
if (val < 0)
break;
baos2.write((byte)val);
}
System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16));
CollectionData newData3 = new CollectionData();
newData3.decode(baos2.toByteArray());
System.out.println("Decoded collection data: " + newData3);
CCNVersionedInputStream vis2 = new CCNVersionedInputStream(ecd1.getName());
CollectionData newData2 = new CollectionData();
newData2.decode(vis2);
System.out.println("Decoded collection data from stream: " + newData);
ecd0.update(ecd1.getName());
Assert.assertEquals(ecd0, ecd1);
System.out.println("Update works!");
// latest version
ecd0.update();
Assert.assertEquals(ecd0, ecd2);
System.out.println("Update really works!");
ecd3.save(ns[2]);
ecd0.update();
ecd4.update(ns[2]);
System.out.println("ns[2]: " + ns[2]);
System.out.println("ecd3 name: " + ecd3.getName());
System.out.println("ecd0 name: " + ecd0.getName());
Assert.assertFalse(ecd0.equals(ecd3));
Assert.assertEquals(ecd3, ecd4);
System.out.println("Update really really works!");
done = true;
} catch (IOException e) {
fail("IOException! " + e.getMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
fail("XMLStreamException! " + e.getMessage());
} catch (ConfigurationException e) {
fail("ConfigurationException! " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
} finally {
try {
if (!done) { // if we have an error, stick around long enough to debug
Thread.sleep(100000);
System.out.println("Done sleeping, finishing.");
}
flosser.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() +": " + e.getMessage());
}
}
}
}
|
package ru.otus;
import ru.otus.ThreadSorter;
import java.util.Arrays;
public abstract class ThreadSorterCommonTest {
abstract ThreadSorter<Integer> createSorter();
public void sort() {
Integer[] array = {3, 6, 2, 1, 5, 4};
createSorter().sort(array);
assert Arrays.equals(array, new Integer[]{1, 2, 3, 4, 5, 6});
}
}
|
package com.phonegap;
import java.io.File;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
/**
* This class provides file directory utilities.
* All file operations are performed on the SD card.
*
* It is used by the FileUtils class.
*/
public class DirectoryManager {
private static final String LOG_TAG = "DirectoryManager";
/**
* Determine if a file or directory exists.
*
* @param name The name of the file to check.
* @return T=exists, F=not found
*/
protected static boolean testFileExists(String name) {
boolean status;
// If SD card exists
if ((testSaveLocationExists()) && (!name.equals(""))) {
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), name);
status = newPath.exists();
}
// If no SD card
else{
status = false;
}
return status;
}
/**
* Get the free disk space on the SD card
*
* @return Size in KB or -1 if not available
*/
protected static long getFreeDiskSpace() {
String status = Environment.getExternalStorageState();
long freeSpace = 0;
// If SD card exists
if (status.equals(Environment.MEDIA_MOUNTED)) {
try {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
freeSpace = availableBlocks*blockSize/1024;
} catch (Exception e) {e.printStackTrace(); }
}
// If no SD card, then return -1
else {
return -1;
}
return (freeSpace);
}
/**
* Create directory on SD card.
*
* @param directoryName The name of the directory to create.
* @return T=successful, F=failed
*/
protected static boolean createDirectory(String directoryName) {
boolean status;
// Make sure SD card exists
if ((testSaveLocationExists()) && (!directoryName.equals(""))) {
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), directoryName);
status = newPath.mkdir();
status = true;
}
// If no SD card or invalid dir name
else {
status = false;
}
return status;
}
/**
* Determine if SD card exists.
*
* @return T=exists, F=not found
*/
protected static boolean testSaveLocationExists() {
String sDCardStatus = Environment.getExternalStorageState();
boolean status;
// If SD card is mounted
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
status = true;
}
// If no SD card
else {
status = false;
}
return status;
}
/**
* Delete directory.
*
* @param fileName The name of the directory to delete
* @return T=deleted, F=could not delete
*/
protected static boolean deleteDirectory(String fileName) {
boolean status;
SecurityManager checker = new SecurityManager();
// Make sure SD card exists
if ((testSaveLocationExists()) && (!fileName.equals(""))) {
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), fileName);
checker.checkDelete(newPath.toString());
// If dir to delete is really a directory
if (newPath.isDirectory()) {
String[] listfile = newPath.list();
// Delete all files within the specified directory and then delete the directory
try{
for (int i=0; i < listfile.length; i++){
File deletedFile = new File (newPath.toString()+"/"+listfile[i].toString());
deletedFile.delete();
}
newPath.delete();
Log.i("DirectoryManager deleteDirectory", fileName);
status = true;
}
catch (Exception e){
e.printStackTrace();
status = false;
}
}
// If dir not a directory, then error
else {
status = false;
}
}
// If no SD card
else {
status = false;
}
return status;
}
/**
* Delete file.
*
* @param fileName The name of the file to delete
* @return T=deleted, F=not deleted
*/
protected static boolean deleteFile(String fileName) {
boolean status;
SecurityManager checker = new SecurityManager();
// Make sure SD card exists
if ((testSaveLocationExists()) && (!fileName.equals(""))) {
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), fileName);
checker.checkDelete(newPath.toString());
// If file to delete is really a file
if (newPath.isFile()){
try {
Log.i("DirectoryManager deleteFile", fileName);
newPath.delete();
status = true;
}catch (SecurityException se){
se.printStackTrace();
status = false;
}
}
// If not a file, then error
else {
status = false;
}
}
// If no SD card
else {
status = false;
}
return status;
}
/**
* Create a new file object from two file paths.
*
* @param file1 Base file path
* @param file2 Remaining file path
* @return File object
*/
private static File constructFilePaths (String file1, String file2) {
File newPath;
if (file2.startsWith(file1)) {
newPath = new File(file2);
}
else {
newPath = new File(file1+"/"+file2);
}
return newPath;
}
/**
* This method will determine the file properties of the file specified
* by the filePath. Creates a JSONObject with name, lastModifiedDate and
* size properties.
*
* @param filePath the file to get the properties of
* @return a JSONObject with the files properties
*/
protected static JSONObject getFile(String filePath) {
File fp = new File(filePath);
JSONObject obj = new JSONObject();
try {
obj.put("name", fp.getAbsolutePath());
obj.put("lastModifiedDate", new Date(fp.lastModified()).toString());
obj.put("size", fp.length());
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return obj;
}
/**
* This method returns a JSONArray of file paths. Android's default
* location where files can be written is Environment.getExternalStorageDirectory().
* We are returning a array with one element so the interface can remain
* consistent with BlackBerry as they have two areas where files can be
* written.
*
* @return an array of file paths
*/
protected static JSONArray getRootPaths() {
JSONArray retVal = new JSONArray();
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
retVal.put(path);
return retVal;
}
}
|
package naftoreiclag.villagefive.util;
import java.util.ArrayList;
import java.util.List;
// APUS_
public class HistoryArray<T> {
final public int size;
private int nextInput = 0;
List<T> array = new ArrayList<T>();
public HistoryArray(int size) {
this.size = size;
for(int i = 0; i < size; ++ i) {
array.add(null);
}
}
public int wrap(int x) {
return ((x % size) + size) % size;
}
public void add(T thing) {
array.set(nextInput, thing);
nextInput = wrap(nextInput + 1);
}
public void clear() {
array.clear();
}
public T get(int pos) {
if(pos >= size || pos < 0) {
return null;
} else {
return array.get(wrap(nextInput - 1 - pos));
}
}
public void set(int pos, T thing) {
if(pos < size && pos >= 0) {
array.set(wrap(nextInput - 1 - pos), thing);
}
}
public int getSize() {
return size;
}
}
|
package net.pricing.common.parser.helper;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import net.pricing.common.parser.helper.CSVParser;
import net.pricing.common.utils.FileUtils;
import net.pricing.common.utils.PricingColumn;
import net.pricing.common.utils.PricingConstants;
import net.pricing.common.utils.PricingRow;
import org.apache.log4j.Logger;
/**
* @author Yuliia Petrushenko
* @version
*/
public class CSVParser {
private static final Logger logger = Logger.getLogger(CSVParser.class);
private String[] columns;
private List<PricingColumn> columnsIndexing;
private String delimiter;
public List<PricingRow> parseFile(File file, String[] columns,
String delimiter) {
List<PricingRow> resultList = new ArrayList<PricingRow>();
this.columns = new String[columns.length];
this.columns = columns;
columnsIndexing = new ArrayList<PricingColumn>();
this.delimiter = delimiter;
try {
logger.debug("[parserFile]
FileInputStream fileIn = new FileInputStream(file);
DataInputStream in = new DataInputStream(fileIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strHeader = br.readLine();
findHeaderColumns(strHeader);
String strLine = new String();
resultList = new ArrayList<PricingRow>();
while ((strLine = br.readLine()) != null) {
PricingRow pricingRow = new PricingRow();
String[] array = strLine.split(delimiter);
for (int i = 0; i < array.length; i++) {
for (PricingColumn currentColumn : columnsIndexing) {
if (currentColumn.getIndex() == i) {
PricingColumn pColumn = new PricingColumn();
pColumn.setIndex(currentColumn.getIndex());
pColumn.setName(currentColumn.getName());
pColumn.setValue(array[i]);
pricingRow.addColumn(pColumn);
}
}
}
if (pricingRow.getColumns() != null) {
if (pricingRow.getColumns().size() != columnsIndexing
.size()) {
pricingRow.setErrorRow(true);
}
resultList.add(pricingRow);
}
}
in.close();
logger.debug("[parseFile]
} catch (IOException e) {
logger.error("[parseFile] --> IOException" + e.getMessage());
}
return resultList;
}
public File parseFromCsv(File file) {
if (!FileUtils.isFileExtMatchesTheParser(file.getName(),
PricingConstants.CSV_FILE_EXTENSION)) {
return null;
}
return file;
}
private void findHeaderColumns(String headerRow) {
String[] strHeaderArr = headerRow.toLowerCase().split(this.delimiter);
for (int i = 0; i < strHeaderArr.length; i++) {
String currentName = strHeaderArr[i].toLowerCase()
.replace("\"", "").trim();
for (int j = 0; j < this.columns.length; j++) {
if (currentName.equals(columns[j].toLowerCase().trim())) {
PricingColumn currentColumn = new PricingColumn();
currentColumn.setIndex(i);
currentColumn.setName(columns[j]);
columnsIndexing.add(currentColumn);
break;
}
}
}
}
}
|
package net.sf.mzmine.data.impl;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import net.sf.mzmine.data.Parameter;
import net.sf.mzmine.data.ParameterType;
import net.sf.mzmine.data.StorableParameterSet;
import net.sf.mzmine.util.Range;
import org.dom4j.Element;
/**
* Simple storage for the parameters and their values. Typical module will
* inherit this class and define the parameters for the constructor.
*/
public class SimpleParameterSet implements StorableParameterSet {
public static final String PARAMETER_ELEMENT_NAME = "parameter";
public static final String PARAMETER_NAME_ATTRIBUTE = "name";
public static final String PARAMETER_TYPE_ATTRIBUTE = "type";
// Parameters
private Parameter parameters[];
// Parameter -> value
private Hashtable<Parameter, Object> values;
// Multiple selection parameter -> multiple values (array of possible
// values)
private Hashtable<Parameter, Object[]> multipleSelectionValues;
/**
* This constructor is only used for cloning
*/
private SimpleParameterSet() {
this(new Parameter[0]);
}
/**
* Checks if project contains current value for some of the parameters, and
* initializes this object using those values if present.
*
*/
public SimpleParameterSet(Parameter[] initParameters) {
this.parameters = initParameters;
values = new Hashtable<Parameter, Object>();
multipleSelectionValues = new Hashtable<Parameter, Object[]>();
}
/**
* @see net.sf.mzmine.data.ParameterSet#getAllParameters()
*/
public Parameter[] getParameters() {
return parameters;
}
/**
* @see net.sf.mzmine.data.ParameterSet#getParameter(java.lang.String)
*/
public Parameter getParameter(String name) {
for (Parameter p : parameters) {
if (p.getName().equals(name))
return p;
}
return null;
}
/**
* @see net.sf.mzmine.data.ParameterSet#getParameterValue(net.sf.mzmine.data.Parameter)
*/
public Object getParameterValue(Parameter parameter) {
Object value = values.get(parameter);
if (value == null)
value = parameter.getDefaultValue();
return value;
}
public void setMultipleSelection(Parameter parameter,
Object[] selectionArray) {
assert parameter.getType() == ParameterType.MULTIPLE_SELECTION;
multipleSelectionValues.put(parameter, selectionArray);
}
public Object[] getMultipleSelection(Parameter parameter) {
return multipleSelectionValues.get(parameter);
}
public void setParameterValue(Parameter parameter, Object value)
throws IllegalArgumentException {
Object possibleValues[] = parameter.getPossibleValues();
if ((possibleValues != null)
&& (parameter.getType() != ParameterType.MULTIPLE_SELECTION)
&& (parameter.getType() != ParameterType.ORDERED_LIST)) {
for (Object possibleValue : possibleValues) {
// We compare String version of the values, in case some values
// were specified as Enum constants
if (possibleValue.toString().equals(value.toString())) {
values.put(parameter, possibleValue);
return;
}
}
// Value not found
throw (new IllegalArgumentException("Invalid value " + value
+ " for parameter " + parameter));
}
switch (parameter.getType()) {
case BOOLEAN:
if (!(value instanceof Boolean))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case INTEGER:
if (!(value instanceof Integer))
throw (new IllegalArgumentException("Value type mismatch"));
int intValue = (Integer) value;
Integer minIValue = (Integer) parameter.getMinimumValue();
if ((minIValue != null) && (intValue < minIValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minIValue));
Integer maxIValue = (Integer) parameter.getMaximumValue();
if ((maxIValue != null) && (intValue > maxIValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxIValue));
break;
case DOUBLE:
if (!(value instanceof Double))
throw (new IllegalArgumentException("Value type mismatch"));
double doubleValue = (Double) value;
Double minFValue = (Double) parameter.getMinimumValue();
if ((minFValue != null) && (doubleValue < minFValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minFValue));
Double maxFValue = (Double) parameter.getMaximumValue();
if ((maxFValue != null) && (doubleValue > maxFValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxFValue));
break;
case RANGE:
if (!(value instanceof Range))
throw (new IllegalArgumentException("Value type mismatch"));
Range rangeValue = (Range) value;
Double minRValue = (Double) parameter.getMinimumValue();
if ((minRValue != null) && (rangeValue.getMin() < minRValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minRValue));
Double maxRValue = (Double) parameter.getMaximumValue();
if ((maxRValue != null) && (rangeValue.getMax() > maxRValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxRValue));
break;
case STRING:
if (!(value instanceof String))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case MULTIPLE_SELECTION:
if (!value.getClass().isArray())
throw (new IllegalArgumentException("Value type mismatch"));
Object valueArray[] = (Object[]) value;
if (parameter.getMinimumValue() != null) {
int min = (Integer) parameter.getMinimumValue();
if (valueArray.length < min)
throw (new IllegalArgumentException(
"Please select minimum " + min
+ " values for parameter " + parameter));
}
if (parameter.getMaximumValue() != null) {
int max = (Integer) parameter.getMaximumValue();
if (valueArray.length > max)
throw (new IllegalArgumentException(
"Please select maximum " + max
+ " values for parameter " + parameter));
}
break;
case FILE_NAME:
if (!(value instanceof String))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case ORDERED_LIST:
if (!value.getClass().isArray())
throw (new IllegalArgumentException("Value type mismatch"));
break;
}
values.put(parameter, value);
}
/**
* @see net.sf.mzmine.data.ParameterSet#exportValuesToXML(org.w3c.dom.Element)
*/
public void exportValuesToXML(Element element) {
for (Parameter p : parameters) {
Element newElement = element.addElement(PARAMETER_ELEMENT_NAME);
newElement.addAttribute(PARAMETER_NAME_ATTRIBUTE, p.getName());
newElement.addAttribute(PARAMETER_TYPE_ATTRIBUTE,
p.getType().toString());
if ((p.getType() == ParameterType.MULTIPLE_SELECTION)
|| (p.getType() == ParameterType.ORDERED_LIST)) {
Object[] values = (Object[]) getParameterValue(p);
if (values != null) {
String valueAsString = "";
for (int i = 0; i < values.length; i++) {
if (i == values.length - 1) {
valueAsString += String.valueOf(values[i]);
} else {
valueAsString += String.valueOf(values[i]) + ",";
}
}
newElement.addText(valueAsString);
}
} else {
Object value = getParameterValue(p);
if (value != null) {
String valueAsString;
if (value instanceof Range) {
Range rangeValue = (Range) value;
valueAsString = String.valueOf(rangeValue.getMin())
+ "-" + String.valueOf(rangeValue.getMax());
} else {
valueAsString = value.toString();
}
newElement.addText(valueAsString);
}
}
}
}
/**
* @see net.sf.mzmine.data.ParameterSet#importValuesFromXML(org.w3c.dom.Element)
*/
public void importValuesFromXML(Element element) {
Iterator paramIter = element.elementIterator(PARAMETER_ELEMENT_NAME);
while (paramIter.hasNext()) {
Element paramElem = (Element) paramIter.next();
Parameter param = getParameter(paramElem.attributeValue(PARAMETER_NAME_ATTRIBUTE));
if (param == null)
continue;
ParameterType paramType = ParameterType.valueOf(paramElem.attributeValue(PARAMETER_TYPE_ATTRIBUTE));
String valueText = paramElem.getText();
if ((valueText == null) || (valueText.length() == 0))
continue;
Object value = null;
switch (paramType) {
case BOOLEAN:
value = Boolean.parseBoolean(valueText);
break;
case INTEGER:
value = Integer.parseInt(valueText);
break;
case DOUBLE:
value = Double.parseDouble(valueText);
break;
case RANGE:
String values[] = valueText.split("-");
double min = Double.parseDouble(values[0]);
double max = Double.parseDouble(values[1]);
value = new Range(min, max);
break;
case STRING:
value = valueText;
break;
case MULTIPLE_SELECTION:
String stringMultipleValues[] = valueText.split(",");
Object possibleMultipleValues[] = param.getPossibleValues();
if (possibleMultipleValues == null)
continue;
Vector<Object> multipleValues = new Vector<Object>();
for (int i = 0; i < stringMultipleValues.length; i++) {
for (int j = 0; j < possibleMultipleValues.length; j++)
if (stringMultipleValues[i].equals(String.valueOf(possibleMultipleValues[j])))
multipleValues.add(possibleMultipleValues[j]);
}
value = multipleValues.toArray();
break;
case FILE_NAME:
value = valueText;
break;
case ORDERED_LIST:
String stringValues[] = valueText.split(",");
Object possibleValues[] = param.getPossibleValues();
Object orderedValues[] = new Object[stringValues.length];
for (int i = 0; i < stringValues.length; i++) {
for (int j = 0; j < possibleValues.length; j++) {
if (stringValues[i].equals(String.valueOf(possibleValues[j])))
orderedValues[i] = possibleValues[j];
}
}
value = orderedValues;
break;
}
try {
setParameterValue(param, value);
} catch (IllegalArgumentException e) {
// ignore
}
}
}
public SimpleParameterSet clone() {
try {
// do not make a new instance of SimpleParameterSet, but instead
// clone the runtime class of this instance - runtime type may be
// inherited class
SimpleParameterSet newSet = this.getClass().newInstance();
newSet.parameters = this.parameters;
for (Parameter p : parameters) {
Object v = values.get(p);
if (v != null)
newSet.setParameterValue(p, v);
}
return newSet;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Represent method's parameters and their values in human-readable format
*/
public String toString() {
StringBuffer s = new StringBuffer();
for (Parameter p : getParameters()) {
s = s.append(p.getName() + ": " + values.get(p) + ", ");
}
return s.toString();
}
}
|
package nl.sense_os.commonsense.client;
import java.util.ArrayList;
import java.util.logging.Logger;
import nl.sense_os.commonsense.client.auth.login.LoginController;
import nl.sense_os.commonsense.client.auth.login.LoginEvents;
import nl.sense_os.commonsense.client.auth.registration.RegisterController;
import nl.sense_os.commonsense.client.common.constants.Constants;
import nl.sense_os.commonsense.client.common.constants.Keys;
import nl.sense_os.commonsense.client.common.models.SensorModel;
import nl.sense_os.commonsense.client.common.models.UserModel;
import nl.sense_os.commonsense.client.demo.DemoController;
import nl.sense_os.commonsense.client.env.create.EnvCreateController;
import nl.sense_os.commonsense.client.env.create.EnvCreateEvents;
import nl.sense_os.commonsense.client.env.list.EnvController;
import nl.sense_os.commonsense.client.env.view.EnvViewController;
import nl.sense_os.commonsense.client.groups.create.GroupCreateController;
import nl.sense_os.commonsense.client.groups.invite.InviteController;
import nl.sense_os.commonsense.client.groups.list.GroupController;
import nl.sense_os.commonsense.client.main.MainController;
import nl.sense_os.commonsense.client.main.MainEvents;
import nl.sense_os.commonsense.client.main.components.NavPanel;
import nl.sense_os.commonsense.client.sensors.delete.SensorDeleteController;
import nl.sense_os.commonsense.client.sensors.library.LibraryController;
import nl.sense_os.commonsense.client.sensors.share.SensorShareController;
import nl.sense_os.commonsense.client.sensors.unshare.UnshareController;
import nl.sense_os.commonsense.client.states.connect.StateConnectController;
import nl.sense_os.commonsense.client.states.create.StateCreateController;
import nl.sense_os.commonsense.client.states.defaults.StateDefaultsController;
import nl.sense_os.commonsense.client.states.edit.StateEditController;
import nl.sense_os.commonsense.client.states.feedback.FeedbackController;
import nl.sense_os.commonsense.client.states.list.StateListController;
import nl.sense_os.commonsense.client.utility.TestData;
import nl.sense_os.commonsense.client.viz.data.DataController;
import nl.sense_os.commonsense.client.viz.data.timeseries.Timeseries;
import nl.sense_os.commonsense.client.viz.panels.map.MapPanel;
import nl.sense_os.commonsense.client.viz.tabs.VizController;
import com.chap.links.client.Timeline;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.util.Theme;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
/**
* Entry point for the CommonSense web application. Initializes services, prepares the MVC
* framework, and dispatches the first events to show the application.
*/
public class CommonSense implements EntryPoint {
private static final Logger LOG = Logger.getLogger(CommonSense.class.getName());
public static final String LAST_DEPLOYED = "Mon Jun 27 12:01";
public static final boolean HACK_QUICK_LOGIN = Constants.ALLOW_HACKS && false;
public static final boolean HACK_SKIP_LIB_DETAILS = Constants.ALLOW_HACKS && true;
public static final boolean HACK_TEST_NAVBAR = Constants.ALLOW_HACKS && false;
public static final boolean HACK_TEST_ENVCREATOR = Constants.ALLOW_HACKS && false;
public static final boolean HACK_TEST_MAPVIZ = Constants.ALLOW_HACKS && false;
public static final boolean HACK_TEST_TIMELINE = Constants.ALLOW_HACKS && false;
/**
* Dispatches initialization event to the controllers, and shows the UI after initialization.
*/
private void initControllers() {
Dispatcher dispatcher = Dispatcher.get();
// start initializing all views
dispatcher.dispatch(MainEvents.Init);
// notify the main controller that all views are ready
dispatcher.dispatch(MainEvents.UiReady);
}
/**
* Initializes the event dispatcher by adding the application's controllers to it.
*/
private void initDispatcher() {
Dispatcher dispatcher = Dispatcher.get();
dispatcher.addController(new MainController());
dispatcher.addController(new LoginController());
dispatcher.addController(new RegisterController());
dispatcher.addController(new VizController());
dispatcher.addController(new DemoController());
dispatcher.addController(new DataController());
// sensor library controllers
dispatcher.addController(new LibraryController());
dispatcher.addController(new SensorDeleteController());
dispatcher.addController(new SensorShareController());
dispatcher.addController(new UnshareController());
// group controllers
dispatcher.addController(new GroupController());
dispatcher.addController(new GroupCreateController());
dispatcher.addController(new InviteController());
// state controllers
dispatcher.addController(new StateListController());
dispatcher.addController(new StateConnectController());
dispatcher.addController(new StateCreateController());
dispatcher.addController(new StateDefaultsController());
dispatcher.addController(new StateEditController());
dispatcher.addController(new FeedbackController());
// environment controllers
dispatcher.addController(new EnvController());
dispatcher.addController(new EnvCreateController());
dispatcher.addController(new EnvViewController());
}
@Override
public void onModuleLoad() {
GXT.setDefaultTheme(Theme.GRAY, true);
/* initialize */
initDispatcher();
if (HACK_QUICK_LOGIN) {
quickLogin();
} else if (HACK_TEST_ENVCREATOR) {
testEnvCreator();
} else if (HACK_TEST_MAPVIZ) {
testMapViz();
} else if (HACK_TEST_NAVBAR) {
testNavBar();
} else if (HACK_TEST_TIMELINE) {
testTimeline();
} else {
initControllers();
}
GXT.hideLoadingPanel("loading");
}
/**
* Logs in automatically for quicker testing.
*/
private void quickLogin() {
LOG.config("Quick login...");
initControllers();
AppEvent login = new AppEvent(LoginEvents.LoginRequest);
login.setData("username", "steven@sense-os.nl");
login.setData("password", "1234");
Dispatcher.forwardEvent(login);
}
private void testEnvCreator() {
LOG.config("Test environment creator...");
initControllers();
Maps.loadMapsApi(Keys.MAPS_KEY, "2", false, new Runnable() {
@Override
public void run() {
Dispatcher.forwardEvent(EnvCreateEvents.ShowCreator);
}
});
}
private void testMapViz() {
LOG.config("Test map visualization...");
Maps.loadMapsApi(Keys.MAPS_KEY, "2", false, new Runnable() {
@Override
public void run() {
Window window = new Window();
window.setLayout(new FitLayout());
window.setHeading("Maps test");
window.setSize("90%", "800px");
MapPanel map = new MapPanel(new ArrayList<SensorModel>(), 0, 0, "title");
window.add(map);
window.show();
window.center();
JsArray<Timeseries> data = TestData.getTimeseriesPosition(100);
map.addData(data);
}
});
}
private void testNavBar() {
Viewport viewport = new Viewport();
viewport.setLayout(new FitLayout());
viewport.setId("sense-viewport");
viewport.setStyleAttribute("background", "transparent;");
LayoutContainer north = new LayoutContainer(new FitLayout());
north.setId("sense-header");
north.setSize("100%", NavPanel.HEIGHT + "px");
viewport.add(north, new FitData(0, 0, 2000, 0));
NavPanel navPanel = new NavPanel();
north.add(navPanel, new RowData(.67, 1));
navPanel.setUser(new UserModel());
navPanel.setLoggedIn(true);
navPanel.setHighlight(NavPanel.VISUALIZATION);
RootPanel.get("gwt").add(viewport);
}
private void testTimeline() {
LOG.config("Test timeline...");
// Create a callback to be called when the visualization API has been loaded.
Runnable onLoadCallback = new Runnable() {
@Override
public void run() {
// create a data table
DataTable data = DataTable.create();
data.addColumn(DataTable.ColumnType.DATETIME, "startdate");
data.addColumn(DataTable.ColumnType.DATETIME, "enddate");
data.addColumn(DataTable.ColumnType.STRING, "content");
data.addColumn(DataTable.ColumnType.STRING, "group");
DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd");
// fill the table with some data
data.addRow();
data.setValue(0, 0, dtf.parse("2010-08-23"));
data.setValue(0, 1, dtf.parse("2010-08-30"));
data.setValue(0, 2, "Project A");
data.setValue(0, 3, "battery sensor level");
data.addRow();
data.setValue(1, 0, dtf.parse("2010-08-28"));
data.setValue(1, 1, dtf.parse("2010-09-03"));
data.setValue(1, 2, "Meeting");
data.setValue(1, 3, "battery sensor level");
data.addRow();
data.setValue(2, 0, dtf.parse("2010-08-20"));
data.setValue(2, 1, dtf.parse("2010-08-25"));
data.setValue(2, 2, "Phone Call");
data.setValue(2, 3, "foo");
data.addRow();
data.setValue(3, 0, dtf.parse("2010-08-27"));
data.setValue(3, 1, dtf.parse("2010-08-30"));
data.setValue(3, 2, "Finished");
data.setValue(3, 3, "foo");
// create options
Timeline.Options options = Timeline.Options.create();
options.setWidth("100%");
options.setHeight("200px");
options.setLayout(Timeline.Options.LAYOUT.BOX);
options.setEditable(true);
// create the timeline, with data and options
LOG.severe("Before time line instantiation");
Timeline timeline = new Timeline(data, options);
LOG.severe("After time line instantiation");
RootPanel.get("gwt").add(timeline);
}
};
// Load the visualization API, passing the onLoadCallback to be called when loading is done.
VisualizationUtils.loadVisualizationApi(onLoadCallback, Timeline.PACKAGE);
}
}
|
package org.appwork.utils.swing.dialog;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JDialog;
import javax.swing.JLabel;
import net.miginfocom.swing.MigLayout;
import org.appwork.utils.formatter.TimeFormatter;
import org.appwork.utils.swing.EDTHelper;
import org.appwork.utils.swing.SwingUtils;
public abstract class TimerDialog {
protected class InternDialog extends JDialog {
private static final long serialVersionUID = 1L;
public InternDialog() {
super(SwingUtils.getWindowForComponent(Dialog.getInstance().getParentOwner()), ModalityType.TOOLKIT_MODAL);
this.setLayout(new MigLayout("ins 5", "[]", "[fill,grow][]"));
System.out.println("Dialog parent: " + this.getParent());
if (Dialog.getInstance().getIconList() != null) {
this.setIconImages(Dialog.getInstance().getIconList());
}
}
@Override
public void dispose() {
TimerDialog.this.dispose();
super.dispose();
}
@Override
public Dimension getPreferredSize() {
return TimerDialog.this.getPreferredSize();
}
public Dimension getRealPreferredSize() {
return super.getPreferredSize();
}
public void realDispose() {
super.dispose();
}
// @Override
// public void setLayout(final LayoutManager manager) {
// super.setLayout(manager);
}
private static final long serialVersionUID = -7551772010164684078L;
/**
* Timer Thread to count down the {@link #counter}
*/
protected Thread timer;
/**
* Current timer value
*/
protected long counter;
/**
* Label to display the timervalue
*/
protected JLabel timerLbl;
protected InternDialog dialog;
private Dimension preferredSize;
private int countdownTime = 0;
public TimerDialog() {
// super(parentframe, ModalityType.TOOLKIT_MODAL);
}
/**
* interrupts the timer countdown
*/
public void cancel() {
if (this.timer != null) {
this.timer.interrupt();
this.timer = null;
this.timerLbl.setEnabled(false);
}
}
protected void dispose() {
this.getDialog().realDispose();
}
/**
* @return
*/
protected Color getBackground() {
// TODO Auto-generated method stub
return this.getDialog().getBackground();
}
/**
* @return
*/
protected long getCountdown() {
return this.getCountdownTime() > 0 ? this.getCountdownTime() : Dialog.getInstance().getCountdownTime();
}
public int getCountdownTime() {
return this.countdownTime;
}
protected InternDialog getDialog() {
if (this.dialog == null) { throw new NullPointerException("Call #org.appwork.utils.swing.dialog.AbstractDialog.displayDialog() first"); }
return this.dialog;
}
/**
* override this if you want to set a special height
*
* @return
*/
protected int getPreferredHeight() {
// TODO Auto-generated method stub
return -1;
}
/**
* @return
*/
public Dimension getPreferredSize() {
final Dimension pref = this.getDialog().getRealPreferredSize();
int w = this.getPreferredWidth();
int h = this.getPreferredHeight();
if (w <= 0) {
w = pref.width;
}
if (h <= 0) {
h = pref.height;
}
// w = Math.min(max.width, w);
// w = Math.max(min.width, w);
// h = Math.min(max.height, h);
// h = Math.max(min.height, h);
try {
if (this.isIgnoreSizeLimitations()) {
return new Dimension(Math.min(Toolkit.getDefaultToolkit().getScreenSize().width, w), Math.min(Toolkit.getDefaultToolkit().getScreenSize().height, h));
} else {
if (this.getDialog().getParent().isVisible()) {
return new Dimension(Math.min(this.getRoot().getWidth(), w), Math.min(this.getRoot().getHeight(), h));
} else {
return new Dimension(Math.min((int) (Toolkit.getDefaultToolkit().getScreenSize().width * 0.75), w), Math.min((int) (Toolkit.getDefaultToolkit().getScreenSize().height * 0.75), h));
}
}
} catch (final Throwable e) {
return pref;
}
}
/**
* overwride this to set a special width
*
* @return
*/
protected int getPreferredWidth() {
// TODO Auto-generated method stub
return -1;
}
/**
* @return
*/
private Container getRoot() {
Container ret = this.getDialog().getParent();
Container p;
while ((p = ret.getParent()) != null) {
ret = p;
}
return ret;
}
protected void initTimer(final long time) {
this.counter = time;
this.timer = new Thread() {
@Override
public void run() {
try {
// sleep while dialog is invisible
while (!TimerDialog.this.isVisible()) {
try {
Thread.sleep(200);
} catch (final InterruptedException e) {
break;
}
}
long count = TimerDialog.this.counter;
while (--count >= 0) {
if (!TimerDialog.this.isVisible()) { return; }
if (TimerDialog.this.timer == null) { return; }
final String left = TimeFormatter.formatSeconds(count, 0);
new EDTHelper<Object>() {
@Override
public Object edtRun() {
TimerDialog.this.timerLbl.setText(left);
return null;
}
}.start();
Thread.sleep(1000);
if (TimerDialog.this.counter < 0) { return; }
if (!TimerDialog.this.isVisible()) { return; }
}
if (TimerDialog.this.counter < 0) { return; }
if (!this.isInterrupted()) {
TimerDialog.this.onTimeout();
}
} catch (final InterruptedException e) {
return;
}
}
};
this.timer.start();
}
/**
* Override this method to allow dialogs beeing larger than their parents
*
* @return
*/
protected boolean isIgnoreSizeLimitations() {
return false;
}
/**
* @return
*/
protected boolean isVisible() {
// TODO Auto-generated method stub
return this.getDialog().isVisible();
}
protected void layoutDialog() {
this.dialog = new InternDialog();
if (this.preferredSize != null) {
this.dialog.setPreferredSize(this.preferredSize);
}
this.timerLbl = new JLabel(TimeFormatter.formatSeconds(this.getCountdown(), 0));
}
protected abstract void onTimeout();
public void pack() {
this.getDialog().pack();
this.getDialog().setMinimumSize(this.getDialog().getPreferredSize());
}
public void requestFocus() {
this.getDialog().requestFocus();
}
protected void setAlwaysOnTop(final boolean b) {
this.getDialog().setAlwaysOnTop(b);
}
public void setCountdownTime(final int countdownTime) {
this.countdownTime = countdownTime;
}
protected void setDefaultCloseOperation(final int doNothingOnClose) {
this.getDialog().setDefaultCloseOperation(doNothingOnClose);
}
protected void setMinimumSize(final Dimension dimension) {
this.getDialog().setMinimumSize(dimension);
}
/**
* @param dimension
*/
public void setPreferredSize(final Dimension dimension) {
try {
this.getDialog().setPreferredSize(dimension);
} catch (final NullPointerException e) {
this.preferredSize = dimension;
}
}
protected void setResizable(final boolean b) {
this.getDialog().setResizable(b);
}
/**
* @param b
*/
public void setVisible(final boolean b) {
this.getDialog().setVisible(b);
}
}
|
package org.caleydo.view.bicluster.physics;
import java.awt.geom.Rectangle2D;
import org.caleydo.view.bicluster.util.Vec2d;
/**
* @author Samuel Gratzl
*
*/
public class Physics {
private static final double ENCLOSED_ELLIPSE_FACTOR = 0.5 * Math.sqrt(2);
/**
* @return
*/
public static boolean isApproximateRects() {
return false; // change to true if you use circles
}
public static Distance distance(Rectangle2D a, Rectangle2D b) {
final Vec2d distVec = new Vec2d();
distVec.setX(a.getCenterX() - b.getCenterX());
distVec.setY(a.getCenterY() - b.getCenterY());
double d = distVec.length();
if (d <= 0) { // if the same position randomly shift
distVec.setX(Math.random() * 20 - 10);
distVec.setY(Math.random() * 20 - 10);
d = distVec.length();
}
distVec.scale(1. / d); // aka normalize
final double r1 = ellipseRadius(distVec, a.getWidth() * ENCLOSED_ELLIPSE_FACTOR, a.getHeight()
* ENCLOSED_ELLIPSE_FACTOR);
final double r2 = ellipseRadius(distVec, b.getWidth() * ENCLOSED_ELLIPSE_FACTOR, b.getHeight()
* ENCLOSED_ELLIPSE_FACTOR);
final double d_real = d - r1 - r2;
// // final double d_real = aabbDistance(a, b, distVec, d);
// // final double d_real = ellipseDistance(a, b, distVec, d);
// final double d_real = enclosedEllipseDistance(a, b, distVec, d);
// // final double d_real = circleDistance(a, b, distVec, d);
// // final double d_real = circleDiameterDistance(a, b, distVec, d);
distVec.scale(d_real);
return new Distance(distVec, d_real, r1, r2);
}
private static double aabbDistance(Rectangle2D a, Rectangle2D b, final Vec2d ray_dir, final double d) {
double ray_pos_x = b.getCenterX();
double ray_pos_y = b.getCenterY();
double r1 = d - raxBoxIntersection(ray_pos_x, ray_pos_y, ray_dir, a); // as starting from b
double r2 = raxBoxIntersection(ray_pos_x, ray_pos_y, ray_dir, b);
final double d_real = d - r1 - r2;
return d_real;
}
/**
* computes the intersection point (as distance to the given ray) to the given box
*
* @param ray_pos
* @param ray_dir
* @param r
* @return
*/
static double raxBoxIntersection(double ray_pos_x, double ray_pos_y, Vec2d ray_dir, Rectangle2D r) {
final double min_x = r.getMinX();
final double min_y = r.getMinY();
final double max_x = r.getMaxX();
final double max_y = r.getMaxY();
double tmp;
double tmin = 0;
double tmax = 0;
if (ray_dir.x() != 0) { // corner case = 0
tmin = (min_x - ray_pos_x) / ray_dir.x();
tmax = (max_x - ray_pos_x) / ray_dir.x();
if (tmin > tmax) {
tmp = tmin;
tmin = tmax;
tmax = tmp;
}
}
if (ray_dir.y() != 0) { // corner case = 0
double tymin = (min_y - ray_pos_y) / ray_dir.y();
double tymax = (max_y - ray_pos_y) / ray_dir.y();
if (tymin > tymax) {
tmp = tymin;
tymin = tymax;
tymax = tmp;
}
if (ray_dir.x() != 0) {
if ((tmin > tymax) || (tymin > tmax))
return 0;
if (tymin > tmin)
tmin = tymin;
if (tymax < tmax)
tmax = tymax;
} else {
tmin = tymin;
tmax = tymax;
}
}
tmin = Math.abs(tmin);
if (tmax < tmin)
return tmax;
return tmin;
}
private static double ellipseDistance(Rectangle2D a, Rectangle2D b, final Vec2d ray_dir, final double d) {
double r1 = ellipseRadius(ray_dir, a.getWidth() * 0.5, a.getHeight() * 0.5);
double r2 = ellipseRadius(ray_dir, b.getWidth() * 0.5, b.getHeight() * 0.5);
final double d_real = d - r1 - r2;
return d_real;
}
private static double ellipseRadius(Vec2d ray_dir, double a, double b) {
// https://en.wikipedia.org/wiki/Ellipse#Polar_form_relative_to_center
// r(\theta)=\frac{ab}{\sqrt{(b \cos \theta)^2 + (a\sin \theta)^2}}
double r = (a * b) / (Math.sqrt(pow2(a * ray_dir.x()) + pow2(b * ray_dir.y())));
return r;
}
/**
* @param d
* @return
*/
private static double pow2(double d) {
return d * d;
}
private static double enclosedEllipseDistance(Rectangle2D a, Rectangle2D b, final Vec2d ray_dir, final double d) {
// FIXME compute from the diameter of the rect a ellipse that touches it
final double factor = ENCLOSED_ELLIPSE_FACTOR;
double r1 = ellipseRadius(ray_dir, a.getWidth() * factor, a.getHeight() * factor);
double r2 = ellipseRadius(ray_dir, b.getWidth() * factor, b.getHeight() * factor);
final double d_real = d - r1 - r2;
return d_real;
}
private static double circleDistance(Rectangle2D a, Rectangle2D b, final Vec2d distVec, final double d) {
double r1 = circleRadius(a);
double r2 = circleRadius(b);
final double d_real = d - r1 - r2;
return d_real;
}
private static double circleRadius(Rectangle2D a) {
return Math.max(a.getWidth(), a.getHeight()) * 0.5f;
}
private static double circleDiameterDistance(Rectangle2D a, Rectangle2D b, final Vec2d distVec, final double d) {
double r1 = circleDiameterRadius(a);
double r2 = circleDiameterRadius(b);
final double d_real = d - r1 - r2;
return d_real;
}
private static double circleDiameterRadius(Rectangle2D a) {
return Math.sqrt(pow2(a.getWidth() * 0.5f) + pow2(a.getHeight() * 0.5f));
}
public static void main(String[] args) {
Rectangle2D a = new Rectangle2D.Double(0, 0, 2, 2);
Rectangle2D b = new Rectangle2D.Double(4, 0, 2, 2);
Rectangle2D c = new Rectangle2D.Double(0, 3, 2, 2);
Rectangle2D d = new Rectangle2D.Double(3, 3, 2, 2);
Rectangle2D e = new Rectangle2D.Double(4, 3, 2, 2);
Rectangle2D f = new Rectangle2D.Double(4, 3, 2, 3);
System.out.println("AABB\t\tellipse\t\tenclosed\t\tcircle\t\tcircleDiameter");
test(a, b);
test(a, c);
test(a, d);
test(a, e);
test(a, f);
}
private static void test(Rectangle2D a, Rectangle2D b) {
final Vec2d distVec = new Vec2d();
distVec.setX(a.getCenterX() - b.getCenterX());
distVec.setY(a.getCenterY() - b.getCenterY());
final double d = distVec.length();
distVec.scale(1. / d); // aka normalize
final double a_real = aabbDistance(a, b, distVec, d);
final double e_real = ellipseDistance(a, b, distVec, d);
final double e2_real = enclosedEllipseDistance(a, b, distVec, d);
final double c_real = circleDistance(a, b, distVec, d);
final double d_real = circleDiameterDistance(a, b, distVec, d);
System.out.format("%f\t%f\t%f\t%f\t%f\n", a_real, e_real, e2_real, c_real, d_real);
}
public static final class Distance extends Vec2d {
private final double distance;
private final double r1;
private final double r2;
public Distance(Vec2d v, double distance, double r1, double r2) {
super(v);
this.distance = distance;
this.r1 = r1;
this.r2 = r2;
}
/**
* @return the r1, see {@link #r1}
*/
public double getR1() {
return r1;
}
/**
* @return the r2, see {@link #r2}
*/
public double getR2() {
return r2;
}
/**
* @return the distance, see {@link #distance}
*/
public double getDistance() {
return distance;
}
public boolean isIntersection() {
return distance < 0;
}
}
}
|
package org.exist.xquery.functions.util;
import org.exist.dom.QName;
import org.exist.xquery.AbstractInternalModule;
import org.exist.xquery.FunctionDef;
import org.exist.xquery.XPathException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Module function definitions for util module.
*
* @author Wolfgang Meier (wolfgang@exist-db.org)
* @author ljo
* @author Andrzej Taramina (andrzej@chaeron.com)
*/
public class UtilModule extends AbstractInternalModule
{
public final static String NAMESPACE_URI = "http://exist-db.org/xquery/util";
public final static String PREFIX = "util";
public final static String INCLUSION_DATE = "2004-09-12";
public final static String RELEASED_IN_VERSION = "pre eXist-1.0";
public final static FunctionDef[] functions = {
new FunctionDef( BuiltinFunctions.signatures[0], BuiltinFunctions.class ),
new FunctionDef( BuiltinFunctions.signatures[1], BuiltinFunctions.class ),
new FunctionDef( BuiltinFunctions.signatures[2], BuiltinFunctions.class ),
new FunctionDef( ModuleInfo.moduleDescriptionSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.registeredModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.registeredModulesSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.mapModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.unmapModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.mappedModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.mappedModulesSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.moduleInfoSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.moduleInfoWithURISig, ModuleInfo.class ),
new FunctionDef( Expand.signatures[0], Expand.class ),
new FunctionDef( Expand.signatures[1], Expand.class ),
new FunctionDef( DescribeFunction.signature, DescribeFunction.class ),
new FunctionDef( FunDoctype.signature, FunDoctype.class ),
new FunctionDef( Eval.signatures[0], Eval.class ),
new FunctionDef( Eval.signatures[1], Eval.class ),
new FunctionDef( Eval.signatures[2], Eval.class ),
new FunctionDef( Eval.signatures[3], Eval.class ),
new FunctionDef( Eval.signatures[4], Eval.class ),
new FunctionDef( Eval.signatures[5], Eval.class ),
new FunctionDef( Eval.signatures[6], Eval.class ),
new FunctionDef( Eval.signatures[7], Eval.class ),
new FunctionDef( Compile.signatures[0], Compile.class ),
new FunctionDef( Compile.signatures[1], Compile.class ),
new FunctionDef( Compile.signatures[2], Compile.class ),
new FunctionDef( DocumentNameOrId.docIdSignature, DocumentNameOrId.class ),
new FunctionDef( DocumentNameOrId.docNameSignature, DocumentNameOrId.class ),
new FunctionDef( DocumentNameOrId.absoluteResourceIdSignature, DocumentNameOrId.class ),
new FunctionDef( DocumentNameOrId.resourceByAbsoluteIdSignature, DocumentNameOrId.class ),
new FunctionDef( CollectionName.signature, CollectionName.class ),
new FunctionDef( LogFunction.signatures[0], LogFunction.class ),
new FunctionDef( LogFunction.signatures[1], LogFunction.class ),
new FunctionDef( LogFunction.signatures[2], LogFunction.class ),
new FunctionDef( LogFunction.signatures[3], LogFunction.class ),
new FunctionDef( CatchFunction.signature, CatchFunction.class ),
new FunctionDef( ExclusiveLockFunction.signature, ExclusiveLockFunction.class ),
new FunctionDef( SharedLockFunction.signature, SharedLockFunction.class ),
new FunctionDef( Collations.signature, Collations.class ),
new FunctionDef( SystemProperty.signature, SystemProperty.class ),
new FunctionDef( FunctionFunction.signature, FunctionFunction.class ),
new FunctionDef( CallFunction.signature, CallFunction.class ),
new FunctionDef( NodeId.signature, NodeId.class ),
new FunctionDef( GetNodeById.signature, GetNodeById.class ),
new FunctionDef( IndexKeys.signatures[0], IndexKeys.class ),
new FunctionDef( IndexKeys.signatures[1], IndexKeys.class ),
new FunctionDef( IndexKeys.signatures[2], IndexKeys.class ),
new FunctionDef( IndexKeyOccurrences.signatures[0], IndexKeyOccurrences.class ),
new FunctionDef( IndexKeyOccurrences.signatures[1], IndexKeyOccurrences.class ),
new FunctionDef( IndexKeyDocuments.signatures[0], IndexKeyDocuments.class ),
new FunctionDef( IndexKeyDocuments.signatures[1], IndexKeyDocuments.class ),
new FunctionDef( IndexType.signature, IndexType.class ),
new FunctionDef( QNameIndexLookup.signature, QNameIndexLookup.class ),
new FunctionDef( Serialize.signatures[0], Serialize.class ),
new FunctionDef( Serialize.signatures[1], Serialize.class ),
new FunctionDef( BinaryDoc.signatures[0], BinaryDoc.class ),
new FunctionDef( BinaryDoc.signatures[1], BinaryDoc.class ),
new FunctionDef( BinaryDoc.signatures[2], BinaryDoc.class ),
new FunctionDef( BinaryToString.signatures[0], BinaryToString.class ),
new FunctionDef( BinaryToString.signatures[1], BinaryToString.class ),
new FunctionDef( BinaryToString.signatures[2], BinaryToString.class ),
new FunctionDef( BinaryToString.signatures[3], BinaryToString.class ),
new FunctionDef( Profile.signatures[0], Profile.class ),
new FunctionDef( Profile.signatures[1], Profile.class ),
new FunctionDef( PrologFunctions.signatures[0], PrologFunctions.class ),
new FunctionDef( PrologFunctions.signatures[1], PrologFunctions.class ),
new FunctionDef( PrologFunctions.signatures[2], PrologFunctions.class ),
new FunctionDef( PrologFunctions.signatures[3], PrologFunctions.class ),
new FunctionDef( SystemTime.signatures[0], SystemTime.class ),
new FunctionDef( SystemTime.signatures[1], SystemTime.class ),
new FunctionDef( SystemTime.signatures[2], SystemTime.class ),
new FunctionDef( RandomFunction.signatures[0], RandomFunction.class ),
new FunctionDef( RandomFunction.signatures[1], RandomFunction.class ),
new FunctionDef( RandomFunction.signatures[2], RandomFunction.class ),
new FunctionDef( FunUnEscapeURI.signature, FunUnEscapeURI.class ),
new FunctionDef( UUID.signatures[0], UUID.class ),
new FunctionDef( UUID.signatures[1], UUID.class ),
new FunctionDef( DeepCopyFunction.signature, DeepCopyFunction.class ),
new FunctionDef( GetSequenceType.signature, GetSequenceType.class ),
new FunctionDef( Parse.signatures[0], Parse.class ),
new FunctionDef( Parse.signatures[1], Parse.class ),
new FunctionDef( ExtractDocs.signature, ExtractDocs.class ),
new FunctionDef( NodeXPath.signature, NodeXPath.class ),
new FunctionDef( Hash.signatures[0], Hash.class ),
new FunctionDef( Hash.signatures[1], Hash.class ),
new FunctionDef( GetFragmentBetween.signature, GetFragmentBetween.class ),
new FunctionDef( BaseConverter.signatures[0], BaseConverter.class ),
new FunctionDef( BaseConverter.signatures[1], BaseConverter.class ),
new FunctionDef( Wait.signatures[0], Wait.class ),
new FunctionDef( Base64Functions.signatures[0], Base64Functions.class ),
new FunctionDef( Base64Functions.signatures[1], Base64Functions.class ),
new FunctionDef( Base64Functions.signatures[2], Base64Functions.class )
};
static {
Arrays.sort( functions, new FunctionComparator() );
}
public final static QName EXCEPTION_QNAME = new QName( "exception", UtilModule.NAMESPACE_URI, UtilModule.PREFIX );
public final static QName EXCEPTION_MESSAGE_QNAME = new QName( "exception-message", UtilModule.NAMESPACE_URI, UtilModule.PREFIX );
public UtilModule(Map<String, List<? extends Object>> parameters) throws XPathException
{
super( functions, parameters, true );
declareVariable( EXCEPTION_QNAME, null );
declareVariable( EXCEPTION_MESSAGE_QNAME, null );
}
/* (non-Javadoc)
* @see org.exist.xquery.Module#getDescription()
*/
public String getDescription()
{
return( "A module for various utility extension functions." );
}
/* (non-Javadoc)
* @see org.exist.xquery.Module#getNamespaceURI()
*/
public String getNamespaceURI()
{
return( NAMESPACE_URI );
}
/* (non-Javadoc)
* @see org.exist.xquery.Module#getDefaultPrefix()
*/
public String getDefaultPrefix()
{
return( PREFIX );
}
public String getReleaseVersion()
{
return( RELEASED_IN_VERSION );
}
}
|
package org.helioviewer.jhv.opengl;
import org.helioviewer.jhv.math.Quat;
import org.helioviewer.jhv.math.Vec2;
import com.jogamp.opengl.GL2;
public class GLSLSolarShader extends GLSLShader {
public static final GLSLSolarShader sphere = new GLSLSolarShader("/glsl/solar.vert", "/glsl/solarSphere.frag", false);
public static final GLSLSolarShader ortho = new GLSLSolarShader("/glsl/solar.vert", "/glsl/solarOrtho.frag", true);
public static final GLSLSolarShader lati = new GLSLSolarShader("/glsl/solar.vert", "/glsl/solarLati.frag", true);
public static final GLSLSolarShader polar = new GLSLSolarShader("/glsl/solar.vert", "/glsl/solarPolar.frag", true);
public static final GLSLSolarShader logpolar = new GLSLSolarShader("/glsl/solar.vert", "/glsl/solarLogPolar.frag", true);
private final boolean hasCommon;
private int isDiffRef;
private int hgltRef;
private int gridRef;
private int hgltDiffRef;
private int gridDiffRef;
private int crvalRef;
private int crotaQuatRef;
private int crotaRef;
private int crotaDiffRef;
private int deltaTRef;
private int sectorRef;
private int radiiRef;
private int polarRadiiRef;
private int cutOffDirectionRef;
private int cutOffValueRef;
private int slitRef;
private int brightRef;
private int colorRef;
private int sharpenRef;
private int enhancedRef;
private int calculateDepthRef;
private int rectRef;
private int diffRectRef;
private int viewportRef;
private int viewportOffsetRef;
private int cameraTransformationInverseRef;
private int cameraDifferenceRef;
private final float[] hglt = new float[1];
private final float[] grid = new float[2];
private final float[] crota = new float[3];
private final float[] hgltDiff = new float[1];
private final float[] gridDiff = new float[2];
private final float[] crotaDiff = new float[3];
private final int[] intArr = new int[1];
private final float[] floatArr = new float[8];
private GLSLSolarShader(String vertex, String fragment, boolean _hasCommon) {
super(vertex, fragment);
hasCommon = _hasCommon;
}
public static void init(GL2 gl) {
sphere._init(gl, sphere.hasCommon);
ortho._init(gl, ortho.hasCommon);
lati._init(gl, lati.hasCommon);
polar._init(gl, polar.hasCommon);
logpolar._init(gl, logpolar.hasCommon);
}
@Override
protected void initUniforms(GL2 gl, int id) {
isDiffRef = gl.glGetUniformLocation(id, "isdifference");
hgltRef = gl.glGetUniformLocation(id, "hglt");
gridRef = gl.glGetUniformLocation(id, "grid");
hgltDiffRef = gl.glGetUniformLocation(id, "hgltDiff");
gridDiffRef = gl.glGetUniformLocation(id, "gridDiff");
crvalRef = gl.glGetUniformLocation(id, "crval");
crotaQuatRef = gl.glGetUniformLocation(id, "crotaQuat");
crotaRef = gl.glGetUniformLocation(id, "crota");
crotaDiffRef = gl.glGetUniformLocation(id, "crotaDiff");
deltaTRef = gl.glGetUniformLocation(id, "deltaT");
sectorRef = gl.glGetUniformLocation(id, "sector");
radiiRef = gl.glGetUniformLocation(id, "radii");
polarRadiiRef = gl.glGetUniformLocation(id, "polarRadii");
cutOffDirectionRef = gl.glGetUniformLocation(id, "cutOffDirection");
cutOffValueRef = gl.glGetUniformLocation(id, "cutOffValue");
sharpenRef = gl.glGetUniformLocation(id, "sharpen");
slitRef = gl.glGetUniformLocation(id, "slit");
brightRef = gl.glGetUniformLocation(id, "brightness");
colorRef = gl.glGetUniformLocation(id, "color");
enhancedRef = gl.glGetUniformLocation(id, "enhanced");
calculateDepthRef = gl.glGetUniformLocation(id, "calculateDepth");
rectRef = gl.glGetUniformLocation(id, "rect");
diffRectRef = gl.glGetUniformLocation(id, "differencerect");
viewportRef = gl.glGetUniformLocation(id, "viewport");
viewportOffsetRef = gl.glGetUniformLocation(id, "viewportOffset");
cameraTransformationInverseRef = gl.glGetUniformLocation(id, "cameraTransformationInverse");
cameraDifferenceRef = gl.glGetUniformLocation(id, "cameraDifference");
if (hasCommon) {
setTextureUnit(gl, id, "image", GLTexture.Unit.ZERO);
setTextureUnit(gl, id, "lut", GLTexture.Unit.ONE);
setTextureUnit(gl, id, "diffImage", GLTexture.Unit.TWO);
}
}
public static void dispose(GL2 gl) {
sphere._dispose(gl);
ortho._dispose(gl);
lati._dispose(gl);
polar._dispose(gl);
logpolar._dispose(gl);
}
public void bindMatrix(GL2 gl, float[] matrix) {
gl.glUniformMatrix4fv(cameraTransformationInverseRef, 1, false, matrix, 0);
}
public void bindCameraDifference(GL2 gl, Quat quat, Quat quatDiff) {
quat.setFloatArray(floatArr, 0);
quatDiff.setFloatArray(floatArr, 4);
gl.glUniform4fv(cameraDifferenceRef, 2, floatArr, 0);
}
public void bindCRVAL(GL2 gl, Vec2 vec, Vec2 vecDiff) {
floatArr[0] = (float) vec.x;
floatArr[1] = (float) vec.y;
floatArr[2] = (float) vecDiff.x;
floatArr[3] = (float) vecDiff.y;
gl.glUniform2fv(crvalRef, 2, floatArr, 0);
}
public void bindCROTAQuat(GL2 gl, Quat quat, Quat quatDiff) {
quat.setFloatArray(floatArr, 0);
quatDiff.setFloatArray(floatArr, 4);
gl.glUniform4fv(crotaQuatRef, 2, floatArr, 0);
}
public void bindDeltaT(GL2 gl, double deltaT, double deltaTDiff) {
floatArr[0] = (float) deltaT;
floatArr[1] = (float) deltaTDiff;
gl.glUniform1fv(deltaTRef, 2, floatArr, 0);
}
public void bindRect(GL2 gl, double xOffset, double yOffset, double xScale, double yScale) {
floatArr[0] = (float) xOffset;
floatArr[1] = (float) yOffset;
floatArr[2] = (float) xScale;
floatArr[3] = (float) yScale;
gl.glUniform4fv(rectRef, 1, floatArr, 0);
}
public void bindDiffRect(GL2 gl, double diffXOffset, double diffYOffset, double diffXScale, double diffYScale) {
floatArr[0] = (float) diffXOffset;
floatArr[1] = (float) diffYOffset;
floatArr[2] = (float) diffXScale;
floatArr[3] = (float) diffYScale;
gl.glUniform4fv(diffRectRef, 1, floatArr, 0);
}
public void bindColor(GL2 gl, float red, float green, float blue, double alpha, double blend) {
floatArr[0] = (float) (red * alpha);
floatArr[1] = (float) (green * alpha);
floatArr[2] = (float) (blue * alpha);
floatArr[3] = (float) (alpha * blend);
gl.glUniform4fv(colorRef, 1, floatArr, 0);
}
public void bindSlit(GL2 gl, double left, double right) {
floatArr[0] = (float) left;
floatArr[1] = (float) right;
gl.glUniform1fv(slitRef, 2, floatArr, 0);
}
public void bindBrightness(GL2 gl, double offset, double scale, double gamma) {
floatArr[0] = (float) offset;
floatArr[1] = (float) scale;
floatArr[2] = (float) gamma;
gl.glUniform3fv(brightRef, 1, floatArr, 0);
}
public void bindSharpen(GL2 gl, double weight, double pixelWidth, double pixelHeight) {
floatArr[0] = (float) pixelWidth;
floatArr[1] = (float) pixelHeight;
floatArr[2] = -2 * (float) weight; // used for mix
gl.glUniform3fv(sharpenRef, 1, floatArr, 0);
}
public void bindEnhanced(GL2 gl, boolean enhanced) {
intArr[0] = enhanced ? 1 : 0;
gl.glUniform1iv(enhancedRef, 1, intArr, 0);
}
public void bindCalculateDepth(GL2 gl, boolean calculateDepth) {
intArr[0] = calculateDepth ? 1 : 0;
gl.glUniform1iv(calculateDepthRef, 1, intArr, 0);
}
public void bindIsDiff(GL2 gl, int isDiff) {
intArr[0] = isDiff;
gl.glUniform1iv(isDiffRef, 1, intArr, 0);
}
public void bindViewport(GL2 gl, float offsetX, float offsetY, float width, float height) {
floatArr[0] = offsetX;
floatArr[1] = offsetY;
gl.glUniform2fv(viewportOffsetRef, 1, floatArr, 0);
floatArr[0] = width;
floatArr[1] = height;
floatArr[2] = height / width;
gl.glUniform3fv(viewportRef, 1, floatArr, 0);
}
public void bindCutOffValue(GL2 gl, float val) {
floatArr[0] = val;
gl.glUniform1fv(cutOffValueRef, 1, floatArr, 0);
}
public void bindCutOffDirection(GL2 gl, float x, float y) {
floatArr[0] = x;
floatArr[1] = y;
gl.glUniform2fv(cutOffDirectionRef, 1, floatArr, 0);
}
public void bindAngles(GL2 gl, float _hglt, float _crota, float scrota, float ccrota) {
hglt[0] = _hglt;
gl.glUniform1fv(hgltRef, 1, hglt, 0);
crota[0] = _crota;
crota[1] = scrota;
crota[2] = ccrota;
gl.glUniform1fv(crotaRef, 3, crota, 0);
}
public void bindAnglesDiff(GL2 gl, float _hglt, float _crota, float scrota, float ccrota) {
hgltDiff[0] = _hglt;
gl.glUniform1fv(hgltDiffRef, 1, hgltDiff, 0);
crotaDiff[0] = _crota;
crotaDiff[1] = scrota;
crotaDiff[2] = ccrota;
gl.glUniform1fv(crotaDiffRef, 3, crotaDiff, 0);
}
public void bindAnglesLatiGrid(GL2 gl, float lon, float lat) {
grid[0] = lon;
grid[1] = lat;
gl.glUniform1fv(gridRef, 2, grid, 0);
}
public void bindAnglesLatiGridDiff(GL2 gl, float lon, float lat) {
gridDiff[0] = lon;
gridDiff[1] = lat;
gl.glUniform1fv(gridDiffRef, 2, gridDiff, 0);
}
public void bindSector(GL2 gl, float sector0, float sector1) {
floatArr[0] = sector0 == sector1 ? 0 : 1;
floatArr[1] = sector0;
floatArr[2] = sector1;
gl.glUniform1fv(sectorRef, 3, floatArr, 0);
}
public void bindRadii(GL2 gl, float innerRadius, float outerRadius) {
floatArr[0] = innerRadius;
floatArr[1] = outerRadius;
gl.glUniform1fv(radiiRef, 2, floatArr, 0);
}
public void bindPolarRadii(GL2 gl, double start, double stop) {
floatArr[0] = (float) start;
floatArr[1] = (float) stop;
gl.glUniform1fv(polarRadiiRef, 2, floatArr, 0);
}
}
|
package org.kopi.ebics.xml;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlError;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.kopi.ebics.exception.EbicsException;
import org.kopi.ebics.interfaces.EbicsRootElement;
import org.kopi.ebics.session.EbicsSession;
import org.kopi.ebics.session.OrderType;
public abstract class DefaultEbicsRootElement implements EbicsRootElement {
/**
* Constructs a new default <code>EbicsRootElement</code>
* @param session the current ebics session
*/
public DefaultEbicsRootElement(EbicsSession session) {
this.session = session;
suggestedPrefixes = new HashMap<String, String>();
}
/**
* Constructs a new default <code>EbicsRootElement</code>
*/
public DefaultEbicsRootElement() {
this(null);
}
/**
* Saves the Suggested Prefixes when the XML is printed
* @param uri the namespace URI
* @param prefix the namespace URI prefix
*/
protected static void setSaveSuggestedPrefixes(String uri, String prefix) {
suggestedPrefixes.put(uri, prefix);
}
/**
* Prints a pretty XML document using jdom framework.
* @param input the XML input
* @return the pretty XML document.
* @throws EbicsException pretty print fails
*/
public byte[] prettyPrint() throws EbicsException {
Document document;
XMLOutputter xmlOutputter;
SAXBuilder sxb;
ByteArrayOutputStream output;
sxb = new SAXBuilder();
output = new ByteArrayOutputStream();
xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
try {
document = sxb.build(new InputStreamReader(new ByteArrayInputStream(toByteArray()), "UTF-8"));
xmlOutputter.output(document, output);
} catch (JDOMException e) {
throw new EbicsException(e.getMessage());
} catch (IOException e) {
throw new EbicsException(e.getMessage());
}
return output.toByteArray();
}
/**
* Inserts a schema location to the current ebics root element.
* @param namespaceURI the name space URI
* @param localPart the local part
* @param prefix the prefix
* @param value the value
*/
public void insertSchemaLocation(String namespaceURI,
String localPart,
String prefix,
String value)
{
XmlCursor cursor;
cursor = document.newCursor();
while (cursor.hasNextToken()) {
if (cursor.isStart()) {
cursor.toNextToken();
cursor.insertAttributeWithValue(new QName(namespaceURI, localPart, prefix), value);
break;
} else {
cursor.toNextToken();
}
}
}
/**
* Generates a random file name with a prefix.
* @param type the order type.
* @return the generated file name.
*/
public static String generateName(OrderType type) {
return type.getOrderType() + new BigInteger(130, new SecureRandom()).toString(32);
}
/**
* Generates a random file name with a prefix.
* @param type the prefix to use.
* @return the generated file name.
*/
public static String generateName(String prefix) {
return prefix + new BigInteger(130, new SecureRandom()).toString(32);
}
@Override
public String toString() {
return new String(toByteArray());
}
@Override
public byte[] toByteArray() {
XmlOptions options;
options = new XmlOptions();
options.setSavePrettyPrint();
options.setSaveSuggestedPrefixes(suggestedPrefixes);
return document.xmlText(options).getBytes();
}
@Override
public void addNamespaceDecl(String prefix, String uri) {
XmlCursor cursor;
cursor = document.newCursor();
while (cursor.hasNextToken()) {
if (cursor.isStart()) {
cursor.toNextToken();
cursor.insertNamespace(prefix, uri);
break;
} else {
cursor.toNextToken();
}
}
}
@Override
public void validate() throws EbicsException {
ArrayList<XmlError> validationMessages;
boolean isValid;
validationMessages = new ArrayList<XmlError>();
isValid = document.validate(new XmlOptions().setErrorListener(validationMessages));
if (!isValid) {
String message;
Iterator<XmlError> iter;
iter = validationMessages.iterator();
message = "";
while (iter.hasNext()) {
if (!message.equals("")) {
message += ";";
}
message += iter.next().getMessage();
}
throw new EbicsException(message);
}
}
@Override
public void save(OutputStream out) throws EbicsException {
try {
byte[] element;
element = prettyPrint();
out.write(element);
out.flush();
out.close();
} catch (IOException e) {
throw new EbicsException(e.getMessage());
}
}
@Override
public void print(PrintStream stream) {
stream.println(document.toString());
}
// DATA MEMBERS
protected XmlObject document;
protected EbicsSession session;
private static Map<String, String> suggestedPrefixes;
private static final long serialVersionUID = -3928957097145095177L;
}
|
package org.objectweb.proactive.ic2d.gui;
import java.rmi.RemoteException;
import org.globus.ogce.gui.gram.gui.SubmitJobPanel;
import org.objectweb.proactive.core.event.RuntimeRegistrationEvent;
import org.objectweb.proactive.core.event.RuntimeRegistrationEventListener;
import org.objectweb.proactive.core.process.ExternalProcess;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.ic2d.IC2D;
import org.objectweb.proactive.ic2d.data.ActiveObject;
import org.objectweb.proactive.ic2d.data.IC2DObject;
import org.objectweb.proactive.ic2d.event.IC2DObjectListener;
import org.objectweb.proactive.ic2d.gui.data.IC2DPanel;
import org.objectweb.proactive.ic2d.gui.jobmonitor.JobMonitorFrame;
import org.objectweb.proactive.ic2d.gui.process.ProcessControlFrame;
import org.objectweb.proactive.ic2d.gui.util.DialogUtils;
import org.objectweb.proactive.ic2d.gui.util.MessagePanel;
import org.objectweb.proactive.ic2d.spy.SpyEvent;
import org.objectweb.proactive.ic2d.util.ActiveObjectFilter;
import org.objectweb.proactive.ic2d.util.IC2DMessageLogger;
public class IC2DFrame extends javax.swing.JFrame implements IC2DObjectListener,RuntimeRegistrationEventListener {
private static final int DEFAULT_WIDTH = 850;
private static final int DEFAULT_HEIGHT = 600;
private int options;
private IC2DPanel ic2dPanel;
private IC2DObject ic2dObject;
private IC2DMessageLogger logger;
private IC2DGUIController controller;
private ActiveObjectFilter activeObjectFilter;
private ActiveObjectCommunicationRecorder communicationRecorder;
private EventListsPanel eventListsPanel;
private javax.swing.JFrame eventListsFrame;
private javax.swing.JFrame processesFrame;
private javax.swing.JFrame globusProcessFrame;
private javax.swing.JFrame fileChooserFrame;
private ExternalProcess externalProcess;
private ProActiveRuntimeImpl proActiveRuntimeImpl ;
private static final String HOME=System.getProperty("user.home");
private javax.swing.JFrame jobMonitorFrame;
public IC2DFrame(IC2DObject ic2dObject) {
this(ic2dObject, IC2D.NOTHING);
}
public IC2DFrame(IC2DObject object, int options) {
super("IC2D");
this.options = options;
this.setSize(new java.awt.Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
this.ic2dObject = object;
setJMenuBar(createMenuBar());
activeObjectFilter = new ActiveObjectFilter();
controller = new MyController();
communicationRecorder = new ActiveObjectCommunicationRecorder();
MessagePanel messagePanel = new MessagePanel("Messages");
logger = messagePanel.getMessageLogger();
ic2dObject.registerLogger(logger);
ic2dObject.registerListener(this);
eventListsPanel = new EventListsPanel(ic2dObject, controller);
ic2dPanel = new IC2DPanel(this, ic2dObject, controller, communicationRecorder, activeObjectFilter, eventListsPanel);
java.awt.Container c = getContentPane();
c.setLayout(new java.awt.BorderLayout());
//Create the split pane
javax.swing.JSplitPane splitPanel = new javax.swing.JSplitPane(javax.swing.JSplitPane.VERTICAL_SPLIT, false, ic2dPanel, messagePanel);
splitPanel.setDividerLocation(DEFAULT_HEIGHT-200);
splitPanel.setOneTouchExpandable(true);
c.add(splitPanel, java.awt.BorderLayout.CENTER);
// Listeners
proActiveRuntimeImpl = (ProActiveRuntimeImpl)ProActiveRuntimeImpl.getProActiveRuntime();
proActiveRuntimeImpl.addRuntimeRegistrationEventListener(this);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
jobMonitorFrame = createJobMonitorFrame ();
processesFrame = createProcessesFrame();
setVisible(true);
eventListsFrame = createEventListFrame(eventListsPanel);
//fileChooserFrame = createFileChooserFrame();
logger.log("IC2D ready !");
}
public void activeObjectAdded(ActiveObject activeObject) {
}
public void activeObjectRemoved(ActiveObject activeObject) {
communicationRecorder.removeActiveObject(activeObject);
}
/* (non-Javadoc)
* @see org.objectweb.proactive.core.event.RuntimeRegistrationEventListener#runtimeRegistered(org.objectweb.proactive.core.event.RuntimeRegistrationEvent)
*/
public void runtimeRegistered(RuntimeRegistrationEvent event) {
ProActiveRuntime proActiveRuntimeRegistered;
String protocol;
String host;
protocol = event.getProtocol();
proActiveRuntimeRegistered = proActiveRuntimeImpl.getProActiveRuntime(event.getRegisteredRuntimeName());
host = proActiveRuntimeRegistered.getVMInformation().getInetAddress().getCanonicalHostName();
try {
ic2dObject.getWorldObject().addHostObject(host,protocol);
} catch (RemoteException e) {
// TODO Auto-generated catch block
logger.log("Cannot create the RMI Host " + host, e);
}
}
public void objectWaitingForRequest(ActiveObject object, SpyEvent spyEvent) {
ic2dPanel.objectWaitingForRequest(object, spyEvent);
eventListsPanel.objectWaitingForRequest(object, spyEvent);
}
public void objectWaitingByNecessity(ActiveObject object, SpyEvent spyEvent) {
ic2dPanel.objectWaitingByNecessity(object, spyEvent);
eventListsPanel.objectWaitingByNecessity(object, spyEvent);
}
public void requestMessageSent(ActiveObject object, SpyEvent spyEvent) {
ic2dPanel.requestMessageSent(object, spyEvent);
eventListsPanel.requestMessageSent(object, spyEvent);
}
public void replyMessageSent(ActiveObject object, SpyEvent spyEvent) {
ic2dPanel.replyMessageSent(object, spyEvent);
eventListsPanel.replyMessageSent(object, spyEvent);
}
public void requestMessageReceived(ActiveObject object, SpyEvent spyEvent) {
ic2dPanel.requestMessageReceived(object, spyEvent);
eventListsPanel.requestMessageReceived(object, spyEvent);
}
public void replyMessageReceived(ActiveObject object, SpyEvent spyEvent) {
ic2dPanel.replyMessageReceived(object, spyEvent);
eventListsPanel.replyMessageReceived(object, spyEvent);
}
public void voidRequestServed(ActiveObject object, SpyEvent spyEvent) {
ic2dPanel.voidRequestServed(object, spyEvent);
eventListsPanel.voidRequestServed(object, spyEvent);
}
public void allEventsProcessed() {
ic2dPanel.allEventsProcessed();
eventListsPanel.allEventsProcessed();
}
private javax.swing.JFrame createEventListFrame(javax.swing.JPanel panel) {
// Create the timeLine panel
final javax.swing.JFrame frame = new javax.swing.JFrame("Events lists");
frame.setLocation(new java.awt.Point(0, DEFAULT_HEIGHT));
frame.setSize(new java.awt.Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT/2));
java.awt.Container c = frame.getContentPane();
c.setLayout(new java.awt.GridLayout(1,1));
javax.swing.JScrollPane scrollingEventListsPanel = new javax.swing.JScrollPane(panel);
scrollingEventListsPanel.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_NEVER);
c.add(scrollingEventListsPanel);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
frame.setVisible(! frame.isVisible());
}
});
frame.setVisible(true);
return frame;
}
private javax.swing.JFrame createProcessesFrame() {
final javax.swing.JFrame frame = new ProcessControlFrame();
frame.setLocation(new java.awt.Point(DEFAULT_WIDTH, 0));
// Listeners
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
frame.setVisible(! frame.isVisible());
}
});
return frame;
}
private JobMonitorFrame createJobMonitorFrame () {
final JobMonitorFrame frame = new JobMonitorFrame (controller);
frame.setLocation(new java.awt.Point(DEFAULT_WIDTH, 0));
// Listeners
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
frame.setVisible(! frame.isVisible());
}
});
return frame;
}
// private javax.swing.JFrame createFileChooserFrame() {
// final javax.swing.JFrame frame = new DeployFileChooserFrame();
// //frame.setLocation(new java.awt.Point(DEFAULT_WIDTH, 0));
// // Listeners
// frame.addWindowListener(new java.awt.event.WindowAdapter() {
// public void windowClosing(java.awt.event.WindowEvent e) {
// frame.setVisible(! frame.isVisible());
// return frame;
// private javax.swing.JFrame createGlobusProcessFrame() {
// final javax.swing.JFrame frame = new GlobusProcessControlFrame(externalProcess);
// //frame.setLocation(new java.awt.Point(DEFAULT_WIDTH, 0));
// // Listeners
// frame.addWindowListener(new java.awt.event.WindowAdapter() {
// public void windowClosing(java.awt.event.WindowEvent e) {
// frame.setVisible(! frame.isVisible());
// return frame;
private javax.swing.JMenuBar createMenuBar() {
javax.swing.JMenuBar menuBar = new javax.swing.JMenuBar();
// monitoring menu
javax.swing.JMenu monitoringMenu = new javax.swing.JMenu("Monitoring");
// Add new RMI host
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor a new RMI host");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DialogUtils.openNewRMIHostDialog(IC2DFrame.this, ic2dObject.getWorldObject(), logger);
}
});
monitoringMenu.add(b);
}
// Add new RMI Node
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor a new RMI Node");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DialogUtils.openNewNodeDialog(IC2DFrame.this, ic2dObject.getWorldObject(), logger);
}
});
monitoringMenu.add(b);
}
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor a new Ibis host");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DialogUtils.openNewIbisHostDialog(IC2DFrame.this, ic2dObject.getWorldObject(), logger);
}
});
monitoringMenu.add(b);
}
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor all JINI Hosts");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
ic2dObject.getWorldObject().addHosts();
}
});
monitoringMenu.add(b);
}
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor a new JINI Hosts");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DialogUtils.openNewJINIHostDialog(IC2DFrame.this, ic2dObject.getWorldObject(), logger);
}
});
monitoringMenu.add(b);
}
monitoringMenu.addSeparator();
// Add new GLOBUS host
//deprecated
// javax.swing.JMenuItem b = new javax.swing.JMenuItem("Monitor new GLOBUS host");
// b.addActionListener(new java.awt.event.ActionListener() {
// public void actionPerformed(java.awt.event.ActionEvent e) {
// DialogUtils.openNewGlobusHostDialog((java.awt.Component) IC2DFrame.this, ic2dObject.getWorldObject(), logger);
// //b.setEnabled((options & IC2D.GLOBUS) != 0);
// monitoringMenu.add(b);
// monitoringMenu.addSeparator();
// Edit the filter list
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Show filtered classes");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DialogUtils.openFilteredClassesDialog(IC2DFrame.this, ic2dPanel, activeObjectFilter);
}
});
b.setToolTipText("Filter active objects");
monitoringMenu.add(b);
}
monitoringMenu.addSeparator();
// Display the legend
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Legend");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
doLegend();
}
});
b.setToolTipText("Display the legend");
monitoringMenu.add(b);
}
monitoringMenu.addSeparator();
// exit
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Quit");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
System.exit(0);
}
});
monitoringMenu.add(b);
}
menuBar.add(monitoringMenu);
// //Deploy
// javax.swing.JMenu DeployMenu = new javax.swing.JMenu("Deploy");
// javax.swing.JMenuItem b = new javax.swing.JMenuItem("Deploy with descriptors");
// b.addActionListener(new java.awt.event.ActionListener() {
// public void actionPerformed(java.awt.event.ActionEvent e) {
// JFrame frame = createFileChooserFrame();
// frame.setVisible(true);
// DeployMenu.add(b);
// menuBar.add(DeployMenu);
// look and feel
{
javax.swing.JMenu lookMenu = new javax.swing.JMenu("Look & feel");
javax.swing.UIManager.LookAndFeelInfo[] infos = javax.swing.UIManager.getInstalledLookAndFeels();
for (int i = 0; i < infos.length; i++) {
javax.swing.AbstractAction a = new javax.swing.AbstractAction(infos[i].getName(), null) {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
String classname = (String)getValue("class");
//javax.swing.JFrame frame = (javax.swing.JFrame)getValue("frame");
javax.swing.UIManager.setLookAndFeel(classname);
javax.swing.SwingUtilities.updateComponentTreeUI(IC2DFrame.this);
javax.swing.SwingUtilities.updateComponentTreeUI(eventListsFrame);
javax.swing.SwingUtilities.updateComponentTreeUI(processesFrame);
} catch (Exception ex) {
}
}
};
a.putValue("frame", this);
a.putValue("class", infos[i].getClassName());
lookMenu.add(a);
}
menuBar.add(lookMenu);
}
// Window
javax.swing.JMenu windowMenu = new javax.swing.JMenu("Window");
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Hide/Show EventsList windows");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (eventListsFrame.isVisible()) {
eventListsFrame.hide();
} else {
eventListsFrame.show();
}
}
});
windowMenu.add(b);
}
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Hide/Show Processes windows");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (processesFrame.isVisible()) {
processesFrame.hide();
} else {
processesFrame.show();
}
}
});
windowMenu.add(b);
}
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Hide/Show Job Monitor windows");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (jobMonitorFrame.isVisible()) {
jobMonitorFrame.hide();
} else {
jobMonitorFrame.show();
}
}
});
windowMenu.add(b);
}
menuBar.add(windowMenu);
// Globus
javax.swing.JMenu globusMenu = new javax.swing.JMenu("Globus");
{
javax.swing.JMenuItem b = new javax.swing.JMenuItem("Start a new Node with Globus");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
SubmitJobPanel.main(new String[0]);
// if (fileChooserFrame.isVisible()) {
// fileChooserFrame.hide();
// } else {
// fileChooserFrame.show();
}
});
globusMenu.add(b);
}
// javax.swing.JMenuItem b = new javax.swing.JMenuItem("Initialize proxy");
// b.addActionListener(new java.awt.event.ActionListener() {
// public void actionPerformed(java.awt.event.ActionEvent e) {
// GridProxyInit.main(new String[0]);
//// if (((FileChooser)fileChooserFrame).ready()){
//// ((FileChooser)fileChooserFrame).changeVisibilityGlobusProcessFrame();
//// else {
//// logger.log("Please select the deployment file with the file chooser in the window menu!");
// globusMenu.add(b);
menuBar.add(globusMenu);
return menuBar;
}
private void doLegend() {
Legend legend = Legend.uniqueInstance();
legend.setVisible(! legend.isVisible());
}
private class MyController implements IC2DGUIController {
private boolean isLayoutAutomatic = true;
public MyController() {
}
public boolean isLayoutAutomatic() {
return isLayoutAutomatic;
}
public void setAutomaticLayout(boolean b) {
isLayoutAutomatic = b;
}
public void warn(String message) {
logger.warn(message);
}
public void log(String message) {
logger.log(message);
}
public void log(String message, Throwable e) {
logger.log(message, e);
}
public void log(Throwable e) {
logger.log(e);
}
}
}
|
package org.owasp.esapi.reference;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.ValidationErrorList;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationAvailabilityException;
import org.owasp.esapi.errors.ValidationException;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;
public class DefaultValidator implements org.owasp.esapi.Validator {
/** OWASP AntiSamy markup verification policy */
private Policy antiSamyPolicy = null;
/** constants */
private static final int MAX_CREDIT_CARD_LENGTH = 19;
private static final int MAX_PARAMETER_NAME_LENGTH = 100;
private static final int MAX_PARAMETER_VALUE_LENGTH = 65535;
public DefaultValidator() {
}
public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidInput( context, input, type, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
try {
context = ESAPI.encoder().canonicalize( context );
String canonical = ESAPI.encoder().canonicalize( input );
if ( type == null || type.length() == 0 ) {
throw new RuntimeException( "Validation misconfiguration, specified type to validate against was null: context=" + context + ", type=" + type + "), input=" + input );
}
if (isEmpty(canonical)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input required.", "Input required: context=" + context + ", type=" + type + "), input=" + input, context );
}
if (canonical.length() > maxLength) {
throw new ValidationException( context + ": Invalid input. The maximum length of " + maxLength + " characters was exceeded.", "Input exceeds maximum allowed length of " + maxLength + " by " + (canonical.length()-maxLength) + " characters: context=" + context + ", type=" + type + "), input=" + input, context );
}
Pattern p = ((DefaultSecurityConfiguration)ESAPI.securityConfiguration()).getValidationPattern( type );
if ( p == null ) {
try {
p = Pattern.compile( type );
} catch( PatternSyntaxException e ) {
throw new RuntimeException( "Validation misconfiguration, specified type to validate against was null: context=" + context + ", type=" + type + "), input=" + input );
}
}
if ( !p.matcher(canonical).matches() ) {
throw new ValidationException( context + ": Invalid input. Please conform to: " + p.pattern() + " with a maximum length of " + maxLength, "Invalid input: context=" + context + ", type=" + type + "( " + p.pattern() + "), input=" + input, context );
}
return canonical;
} catch (EncodingException e) {
throw new ValidationException( context + ": Invalid input. An encoding error occurred.", "Error canonicalizing user input", e, context);
}
}
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInput(context, input, type, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* Returns true if input is a valid date according to the specified date format.
*/
public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException {
try {
getValidDate( context, input, format, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*
* Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException,
* and input that is clearly an attack will generate a descriptive IntrusionException.
*
*
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException {
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input date required", "Input date required: context=" + context + ", input=" + input, context );
}
Date date = format.parse(input);
return date;
} catch (Exception e) {
throw new ValidationException( context + ": Invalid date must follow " + format + " format", "Invalid date: context=" + context + ", format=" + format + ", input=" + input, e, context);
}
}
/**
* {@inheritDoc}
*
* Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException,
* and input that is clearly an attack will generate a descriptive IntrusionException.
*
*
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDate(context, input, format, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return null;
}
/**
* {@inheritDoc}
*
* Returns true if input is "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas
* on how to do HTML validation in a whitelist way, as this is an extremely difficult problem.
*
*
*/
public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException {
try {
if ( antiSamyPolicy == null ) {
if (ESAPI.securityConfiguration().getResourceDirectory() == null) {
//load via classpath
ClassLoader loader = getClass().getClassLoader();
InputStream in = null;
try {
in = loader.getResourceAsStream("antisamy-esapi.xml");
if (in != null) {
antiSamyPolicy = Policy.getInstance(in);
}
} catch (Exception e) {
antiSamyPolicy = null;
} finally {
if (in != null) try { in.close (); } catch (Throwable ignore) {}
}
if (antiSamyPolicy == null) {
throw new IllegalArgumentException ("Can't load antisamy-esapi.xml as a classloader resource");
}
} else {
//load via fileio
antiSamyPolicy = Policy.getInstance( ESAPI.securityConfiguration().getResourceDirectory() + "antisamy-esapi.xml");
}
}
AntiSamy as = new AntiSamy();
CleanResults test = as.scan(input, antiSamyPolicy);
return(test.getErrorMessages().size() == 0);
} catch (Exception e) {
return false;
}
}
/**
* {@inheritDoc}
*
* Returns canonicalized and validated "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas
* on how to do HTML validation in a whitelist way, as this is an extremely difficult problem.
*
*
*/
public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input HTML required", "Input HTML required: context=" + context + ", input=" + input, context );
}
if (input.length() > maxLength) {
throw new ValidationException( context + ": Invalid HTML. You enterted " + input.length() + " characters. Input can not exceed " + maxLength + " characters.", context + " input exceedes maxLength by " + (input.length()-maxLength) + " characters", context);
}
try {
if ( antiSamyPolicy == null ) {
if (ESAPI.securityConfiguration().getResourceDirectory() == null) {
//load via classpath
ClassLoader loader = getClass().getClassLoader();
InputStream in = null;
try {
in = loader.getResourceAsStream("antisamy-esapi.xml");
if (in != null) {
antiSamyPolicy = Policy.getInstance(in);
}
} catch (Exception e) {
antiSamyPolicy = null;
} finally {
if (in != null) try { in.close (); } catch (Throwable ignore) {}
}
if (antiSamyPolicy == null) {
throw new IllegalArgumentException ("Can't load antisamy-esapi.xml as a classloader resource");
}
} else {
//load via fileio
antiSamyPolicy = Policy.getInstance( ESAPI.securityConfiguration().getResourceDirectory() + "antisamy-esapi.xml");
}
}
AntiSamy as = new AntiSamy();
CleanResults test = as.scan(input, antiSamyPolicy);
List errors = test.getErrorMessages();
if ( errors.size() > 0 ) {
// just create new exception to get it logged and intrusion detected
new ValidationException( "Invalid HTML input: context=" + context, "Invalid HTML input: context=" + context + ", errors=" + errors, context );
}
return(test.getCleanHTML().trim());
} catch (ScanException e) {
throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input: context=" + context + " error=" + e.getMessage(), e, context );
} catch (PolicyException e) {
throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input does not follow rules in antisamy-esapi.xml: context=" + context + " error=" + e.getMessage(), e, context );
}
}
/**
* ValidationErrorList variant of getValidSafeHTML
*/
public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidSafeHTML(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid credit card. Maxlength is mandated by valid credit card type.
*
*
*/
public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException {
try {
getValidCreditCard( context, input, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns a canonicalized and validated credit card number as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input credit card required", "Input credit card required: context=" + context + ", input=" + input, context );
}
String canonical = getValidInput( context, input, "CreditCard", MAX_CREDIT_CARD_LENGTH, allowNull);
// perform Luhn algorithm checking
StringBuffer digitsOnly = new StringBuffer();
char c;
for (int i = 0; i < canonical.length(); i++) {
c = canonical.charAt(i);
if (Character.isDigit(c)) {
digitsOnly.append(c);
}
}
int sum = 0;
int digit = 0;
int addend = 0;
boolean timesTwo = false;
for (int i = digitsOnly.length() - 1; i >= 0; i
digit = Integer.parseInt(digitsOnly.substring(i, i + 1));
if (timesTwo) {
addend = digit * 2;
if (addend > 9) {
addend -= 9;
}
} else {
addend = digit;
}
sum += addend;
timesTwo = !timesTwo;
}
int modulus = sum % 10;
if (modulus != 0) throw new ValidationException( context + ": Invalid credit card input", "Invalid credit card input: context=" + context, context );
return canonical;
}
/**
* ValidationErrorList variant of getValidCreditCard
*/
public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidCreditCard(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* Returns true if the directory path (not including a filename) is valid.
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidDirectoryPath(String context, String input, boolean allowNull) throws IntrusionException {
try {
getValidDirectoryPath( context, input, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns a canonicalized and validated directory path as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidDirectoryPath(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context );
}
// do basic validation
String canonical = getValidInput( context, input, "DirectoryName", 255, false);
// get the canonical path without the drive letter if present
String cpath = new File(canonical).getCanonicalPath().replaceAll( "\\\\", "/");
String temp = cpath.toLowerCase();
if (temp.length() >= 2 && temp.charAt(0) >= 'a' && temp.charAt(0) <= 'z' && temp.charAt(1) == ':') {
cpath = cpath.substring(2);
}
// prepare the input without the drive letter if present
String escaped = canonical.replaceAll( "\\\\", "/");
temp = escaped.toLowerCase();
if (temp.length() >= 2 && temp.charAt(0) >= 'a' && temp.charAt(0) <= 'z' && temp.charAt(1) == ':') {
escaped = escaped.substring(2);
}
// the path is valid if the input matches the canonical path
if (!escaped.equals(cpath.toLowerCase())) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
return canonical;
} catch (IOException e) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not exist: context=" + context + ", input=" + input, e, context );
}
}
/**
* ValidationErrorList variant of getValidDirectoryPath
*/
public String getValidDirectoryPath(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDirectoryPath(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* Returns true if input is a valid file name.
*/
public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException {
try {
getValidFileName( context, input, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns a canonicalized and validated file name as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidFileName(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
String canonical = "";
// detect path manipulation
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context );
}
// do basic validation
canonical = ESAPI.encoder().canonicalize(input);
getValidInput( context, input, "FileName", 255, true );
File f = new File(canonical);
String c = f.getCanonicalPath();
String cpath = c.substring(c.lastIndexOf(File.separator) + 1);
// the path is valid if the input matches the canonical path
if (!input.equals(cpath.toLowerCase())) {
throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
} catch (IOException e) {
throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context );
} catch (EncodingException ee) {
throw new IntrusionException( context + ": Invalid file name", "Invalid file name: context=" + context + ", canonical=" + canonical, ee );
}
// verify extensions
List extensions = ESAPI.securityConfiguration().getAllowedFileExtensions();
Iterator i = extensions.iterator();
while (i.hasNext()) {
String ext = (String) i.next();
if (input.toLowerCase().endsWith(ext.toLowerCase())) {
return canonical;
}
}
throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+ESAPI.securityConfiguration().getAllowedFileExtensions()+")", "Invalid file name does not have valid extension ( "+ESAPI.securityConfiguration().getAllowedFileExtensions()+"): context=" + context+", input=" + input, context );
}
/**
* Returns a canonicalized and validated file name as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidFileName(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileName(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid number.
*
*
*/
public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException {
try {
getValidNumber(context, input, minValue, maxValue, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns a validated number as a double. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException {
Double minDoubleValue = new Double(minValue);
Double maxDoubleValue = new Double(maxValue);
return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull);
}
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidNumber(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
//not sure what to return on error
return new Double(0);
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid number.
*
*
*/
public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException {
return isValidDouble( context, input, minValue, maxValue, allowNull );
}
/**
* Returns a validated number as a double. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException {
if (minValue > maxValue) {
//should this be a RunTime?
throw new ValidationException( context + ": Invalid double input: context", "Validation parameter error for double: maxValue ( " + maxValue + ") must be greater than minValue ( " + minValue + ") for " + context, context );
}
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input required: context", "Input required: context=" + context + ", input=" + input, context );
}
try {
Double d = new Double(Double.parseDouble(input));
if (d.isInfinite()) throw new ValidationException( "Invalid double input: context=" + context, "Invalid double input is infinite: context=" + context + ", input=" + input, context );
if (d.isNaN()) throw new ValidationException( "Invalid double input: context=" + context, "Invalid double input is infinite: context=" + context + ", input=" + input, context );
if (d.doubleValue() < minValue) throw new ValidationException( "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context, "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context );
if (d.doubleValue() > maxValue) throw new ValidationException( "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context, "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context );
return d;
} catch (NumberFormatException e) {
throw new ValidationException( context + ": Invalid double input", "Invalid double input format: context=" + context + ", input=" + input, e, context);
}
}
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDouble(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
//not sure what to return on error
return new Double(0);
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid number.
*
*
*/
public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException {
try {
getValidInteger( context, input, minValue, maxValue, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns a validated number as a double. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException {
if (minValue > maxValue) {
//should this be a RunTime?
throw new ValidationException( context + ": Invalid Integer", "Validation parameter error for double: maxValue ( " + maxValue + ") must be greater than minValue ( " + minValue + ") for " + context, context );
}
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context );
}
try {
int i = Integer.parseInt(input);
if (i < minValue || i > maxValue ) throw new ValidationException( context + ": Invalid Integer. Value must be between " + minValue + " and " + maxValue, "Invalid int input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context );
return new Integer(i);
} catch (NumberFormatException e) {
throw new ValidationException( context + ": Invalid integer input", "Invalid int input: context=" + context + ", input=" + input, e, context );
}
}
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInteger(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
//not sure what to return on error
return new Integer(0);
}
/**
* Returns true if input is valid file content.
*/
public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException {
try {
getValidFileContent( context, input, maxBytes, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns validated file content as a byte array. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context );
}
long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize();
if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context );
if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context );
return input;
}
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileContent(context, input, maxBytes, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
//not sure what to return on error
return input;
}
/**
* Returns true if a file upload has a valid name, path, and content.
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*
*/
public boolean isValidFileUpload(String context, String directorypath, String filename, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException {
return( isValidFileName( context, filename, allowNull ) &&
isValidDirectoryPath( context, directorypath, allowNull ) &&
isValidFileContent( context, content, maxBytes, allowNull ) );
}
/**
* Validates the filepath, filename, and content of a file. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public void assertValidFileUpload(String context, String directorypath, String filename, byte[] content, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException {
getValidFileName( context, filename, allowNull );
getValidDirectoryPath( context, directorypath, allowNull );
getValidFileContent( context, content, maxBytes, allowNull );
}
/**
* ValidationErrorList variant of assertValidFileUpload
*/
public void assertValidFileUpload(String context, String filepath, String filename, byte[] content, int maxBytes, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
assertValidFileUpload(context, filepath, filename, content, maxBytes, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
/**
* Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed
* characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* Uses current HTTPRequest saved in EASPI Authenticator
*/
public boolean isValidHTTPRequest() throws IntrusionException {
try {
assertIsValidHTTPRequest();
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed
* characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public boolean isValidHTTPRequest(HttpServletRequest request) throws IntrusionException {
try {
assertIsValidHTTPRequest(request);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed
* characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* Uses current HTTPRequest saved in EASPI Authenticator
*
*/
public void assertIsValidHTTPRequest() throws ValidationException, IntrusionException {
HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest();
assertIsValidHTTPRequest(request);
}
/**
* Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed
* characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
private void assertIsValidHTTPRequest(HttpServletRequest request) throws ValidationException, IntrusionException {
if (request == null) {
throw new ValidationException( "Input required: HTTP request is null", "Input required: HTTP request is null" );
}
if ( !request.getMethod().equals( "GET") && !request.getMethod().equals("POST") ) {
throw new IntrusionException( "Bad HTTP method received", "Bad HTTP method received: " + request.getMethod() );
}
Iterator i1 = request.getParameterMap().entrySet().iterator();
while (i1.hasNext()) {
Map.Entry entry = (Map.Entry) i1.next();
String name = (String) entry.getKey();
getValidInput( "HTTP request parameter: " + name, name, "HTTPParameterName", MAX_PARAMETER_NAME_LENGTH, false );
String[] values = (String[]) entry.getValue();
Iterator i3 = Arrays.asList(values).iterator();
while (i3.hasNext()) {
String value = (String) i3.next();
getValidInput( "HTTP request parameter: " + name, value, "HTTPParameterValue", MAX_PARAMETER_VALUE_LENGTH, true );
}
}
if (request.getCookies() != null) {
Iterator i2 = Arrays.asList(request.getCookies()).iterator();
while (i2.hasNext()) {
Cookie cookie = (Cookie) i2.next();
String name = cookie.getName();
getValidInput( "HTTP request cookie: " + name, name, "HTTPCookieName", MAX_PARAMETER_NAME_LENGTH, true );
String value = cookie.getValue();
getValidInput( "HTTP request cookie: " + name, value, "HTTPCookieValue", MAX_PARAMETER_VALUE_LENGTH, true );
}
}
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
if (name != null && !name.equalsIgnoreCase( "Cookie")) {
getValidInput( "HTTP request header: " + name, name, "HTTPHeaderName", MAX_PARAMETER_NAME_LENGTH, true );
Enumeration e2 = request.getHeaders(name);
while (e2.hasMoreElements()) {
String value = (String) e2.nextElement();
getValidInput( "HTTP request header: " + name, value, "HTTPHeaderValue", MAX_PARAMETER_VALUE_LENGTH, true );
}
}
}
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid list item.
*
*
*/
public boolean isValidListItem(String context, String input, List list) {
try {
getValidListItem( context, input, list);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidListItem(String context, String input, List list) throws ValidationException, IntrusionException {
if (list.contains(input)) return input;
throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context );
}
/**
* ValidationErrorList variant of getValidListItem
*/
public String getValidListItem(String context, String input, List list, ValidationErrorList errors) throws IntrusionException {
try {
return getValidListItem(context, input, list);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* {@inheritDoc}
*
* Returns true if the parameters in the current request contain all required parameters and only optional ones in addition.
*
*
*/
public boolean isValidHTTPRequestParameterSet(String context, Set requiredNames, Set optionalNames) {
try {
assertIsValidHTTPRequestParameterSet( context, requiredNames, optionalNames);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Validates that the parameters in the current request contain all required parameters and only optional ones in
* addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional) throws ValidationException, IntrusionException {
HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest();
Set actualNames = request.getParameterMap().keySet();
// verify ALL required parameters are present
Set missing = new HashSet(required);
missing.removeAll(actualNames);
if (missing.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context );
}
// verify ONLY optional + required parameters are present
Set extra = new HashSet(actualNames);
extra.removeAll(required);
extra.removeAll(optional);
if (extra.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context );
}
}
/**
* ValidationErrorList variant of assertIsValidHTTPRequestParameterSet
*/
public void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional, ValidationErrorList errors) throws IntrusionException {
try {
assertIsValidHTTPRequestParameterSet(context, required, optional);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
public boolean isValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public byte[] getValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context );
}
if (input.length > maxLength) {
throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + input, context);
}
for (int i = 0; i < input.length; i++) {
if (input[i] < 33 || input[i] > 126) {
throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + input, context);
}
}
return input;
}
/**
* ValidationErrorList variant of getValidPrintable
*/
public byte[] getValidPrintable(String context, byte[] input,int maxLength, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
return getValidPrintable(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* {@inheritDoc}
*
* Returns true if input is valid printable ASCII characters (32-126).
*
*
*/
public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
String canonical = "";
try {
canonical = ESAPI.encoder().canonicalize(input);
return new String( getValidPrintable( context, canonical.getBytes(), maxLength, allowNull) );
} catch (EncodingException e) {
throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context);
}
}
/**
* ValidationErrorList variant of getValidPrintable
*/
public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
return getValidPrintable(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* Returns true if input is a valid redirect location.
*/
public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException {
return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull);
}
/**
* Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull);
}
/**
* ValidationErrorList variant of getValidRedirectLocation
*/
public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidRedirectLocation(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return input;
}
/**
* {@inheritDoc}
*
* This implementation reads until a newline or the specified number of
* characters.
*/
public String safeReadLine(InputStream in, int max) throws ValidationException {
if (max <= 0)
throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream");
StringBuffer sb = new StringBuffer();
int count = 0;
int c;
try {
while (true) {
c = in.read();
if ( c == -1 ) {
if (sb.length() == 0) return null;
break;
}
if (c == '\n' || c == '\r') break;
count++;
if (count > max) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")");
}
sb.append((char) c);
}
return sb.toString();
} catch (IOException e) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e);
}
}
/**
* Helper function to check if a String is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(String input) {
return (input==null || input.trim().length() == 0);
}
/**
* Helper function to check if a byte array is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(byte[] input) {
return (input==null || input.length == 0);
}
}
|
package org.pentaho.di.trans.steps.groupby;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueDataUtil;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Groups informations based on aggregation rules. (sum, count, ...)
*
* @author Matt
* @since 2-jun-2003
*/
public class GroupBy extends BaseStep implements StepInterface
{
private static Class<?> PKG = GroupByMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private GroupByMeta meta;
private GroupByData data;
public GroupBy(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
meta=(GroupByMeta)getStepMeta().getStepMetaInterface();
data=(GroupByData)stepDataInterface;
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(GroupByMeta)smi;
data=(GroupByData)sdi;
Object[] r=getRow(); // get row!
if (first)
{
// What is the output looking like?
data.inputRowMeta = getInputRowMeta();
// In case we have 0 input rows, we still want to send out a single row aggregate
// However... the problem then is that we don't know the layout from receiving it from the previous step over the row set.
// So we need to calculated based on the metadata...
if (data.inputRowMeta==null)
{
data.inputRowMeta = getTransMeta().getPrevStepFields(getStepMeta());
}
data.outputRowMeta = data.inputRowMeta.clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
// Do all the work we can beforehand
// Calculate indexes, loop up fields, etc.
data.counts = new long[meta.getSubjectField().length];
data.subjectnrs = new int[meta.getSubjectField().length];
data.cumulativeSumSourceIndexes = new ArrayList<Integer>();
data.cumulativeSumTargetIndexes = new ArrayList<Integer>();
data.cumulativeAvgSourceIndexes = new ArrayList<Integer>();
data.cumulativeAvgTargetIndexes = new ArrayList<Integer>();
for (int i=0;i<meta.getSubjectField().length;i++)
{
data.subjectnrs[i] = data.inputRowMeta.indexOfValue(meta.getSubjectField()[i]);
if (data.subjectnrs[i]<0)
{
logError(BaseMessages.getString(PKG, "GroupBy.Log.AggregateSubjectFieldCouldNotFound",meta.getSubjectField()[i])); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
if (meta.getAggregateType()[i]==GroupByMeta.TYPE_GROUP_CUMULATIVE_SUM)
{
data.cumulativeSumSourceIndexes.add(data.subjectnrs[i]);
// The position of the target in the output row is the input row size + i
data.cumulativeSumTargetIndexes.add(data.inputRowMeta.size()+i);
}
if (meta.getAggregateType()[i]==GroupByMeta.TYPE_GROUP_CUMULATIVE_AVERAGE)
{
data.cumulativeAvgSourceIndexes.add(data.subjectnrs[i]);
// The position of the target in the output row is the input row size + i
data.cumulativeAvgTargetIndexes.add(data.inputRowMeta.size()+i);
}
}
data.previousSums = new Object[data.cumulativeSumTargetIndexes.size()];
data.previousAvgSum = new Object[data.cumulativeAvgTargetIndexes.size()];
data.previousAvgCount = new long[data.cumulativeAvgTargetIndexes.size()];
data.groupnrs = new int[meta.getGroupField().length];
for (int i=0;i<meta.getGroupField().length;i++)
{
data.groupnrs[i] = data.inputRowMeta.indexOfValue(meta.getGroupField()[i]);
if (data.groupnrs[i]<0)
{
logError(BaseMessages.getString(PKG, "GroupBy.Log.GroupFieldCouldNotFound",meta.getGroupField()[i])); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
}
// Create a metadata value for the counter Integers
data.valueMetaInteger = new ValueMeta("count", ValueMetaInterface.TYPE_INTEGER);
data.valueMetaNumber = new ValueMeta("sum", ValueMetaInterface.TYPE_NUMBER);
// Initialize the group metadata
initGroupMeta(data.inputRowMeta);
// Create a new group aggregate (init)
newAggregate(r);
// for speed: groupMeta+aggMeta
data.groupAggMeta=new RowMeta();
data.groupAggMeta.addRowMeta(data.groupMeta);
data.groupAggMeta.addRowMeta(data.aggMeta);
}
if (r==null) // no more input to be expected... (or none received in the first place)
{
if (meta.passAllRows()) // ALL ROWS
{
if (data.previous!=null)
{
calcAggregate(data.previous);
addToBuffer(data.previous);
}
data.groupResult = getAggregateResult();
Object[] row = getRowFromBuffer();
long lineNr=0;
while (row!=null)
{
int size = data.inputRowMeta.size();
row=RowDataUtil.addRowData(row, size, data.groupResult);
size+=data.groupResult.length;
lineNr++;
if (meta.isAddingLineNrInGroup() && !Const.isEmpty(meta.getLineNrInGroupField()))
{
Object lineNrValue= new Long(lineNr);
// ValueMetaInterface lineNrValueMeta = new ValueMeta(meta.getLineNrInGroupField(), ValueMetaInterface.TYPE_INTEGER);
// lineNrValueMeta.setLength(9);
row=RowDataUtil.addValueData(row, size, lineNrValue);
size++;
}
addCumulativeSums(row);
addCumulativeAverages(row);
putRow(data.outputRowMeta, row);
row = getRowFromBuffer();
}
closeInput();
}
else // JUST THE GROUP + AGGREGATE
{
// Don't forget the last set of rows...
if (data.previous!=null)
{
calcAggregate(data.previous);
}
Object[] result = buildResult(data.previous);
if (result!=null) {
putRow(data.groupAggMeta, result);
}
}
setOutputDone();
return false;
}
if (first)
{
first=false;
data.previous = data.inputRowMeta.cloneRow(r); // copy the row to previous
}
else
{
calcAggregate(data.previous);
//System.out.println("After calc, agg="+agg);
if (meta.passAllRows())
{
addToBuffer(data.previous);
}
}
// System.out.println("Check for same group...");
if (!sameGroup(data.previous, r))
{
// System.out.println("Different group!");
if (meta.passAllRows())
{
// System.out.println("Close output...");
// Not the same group: close output (if any)
closeOutput();
// System.out.println("getAggregateResult()");
// Get all rows from the buffer!
data.groupResult = getAggregateResult();
// System.out.println("dump rows from the buffer");
Object[] row = getRowFromBuffer();
long lineNr=0;
while (row!=null)
{
int size = data.inputRowMeta.size();
row=RowDataUtil.addRowData(row, size, data.groupResult);
size+=data.groupResult.length;
lineNr++;
if (meta.isAddingLineNrInGroup() && !Const.isEmpty(meta.getLineNrInGroupField()))
{
Object lineNrValue= new Long(lineNr);
// ValueMetaInterface lineNrValueMeta = new ValueMeta(meta.getLineNrInGroupField(), ValueMetaInterface.TYPE_INTEGER);
// lineNrValueMeta.setLength(9);
row=RowDataUtil.addValueData(row, size, lineNrValue);
size++;
}
addCumulativeSums(row);
addCumulativeAverages(row);
putRow(data.outputRowMeta, row);
row = getRowFromBuffer();
}
closeInput();
}
else
{
Object[] result = buildResult(data.previous);
if (result!=null) {
putRow(data.groupAggMeta, result); // copy row to possible alternate rowset(s).
}
}
newAggregate(r); // Create a new group aggregate (init)
}
data.previous=data.inputRowMeta.cloneRow(r);
if (checkFeedback(getLinesRead()))
{
if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "GroupBy.LineNumber")+getLinesRead()); //$NON-NLS-1$
}
return true;
}
private void addCumulativeSums(Object[] row) throws KettleValueException {
// We need to adjust this row with cumulative averages?
for (int i=0;i<data.cumulativeSumSourceIndexes.size();i++)
{
int sourceIndex = data.cumulativeSumSourceIndexes.get(i);
Object previousTarget = data.previousSums[i];
Object sourceValue = row[sourceIndex];
int targetIndex = data.cumulativeSumTargetIndexes.get(i);
ValueMetaInterface sourceMeta = data.inputRowMeta.getValueMeta(sourceIndex);
ValueMetaInterface targetMeta = data.outputRowMeta.getValueMeta(targetIndex);
// If the first values where null, or this is the first time around, just take the source value...
if (targetMeta.isNull(previousTarget))
{
row[targetIndex]=sourceMeta.convertToNormalStorageType(sourceValue);
}
else
{
// If the source value is null, just take the previous target value
if (sourceMeta.isNull(sourceValue))
{
row[targetIndex] = previousTarget;
}
else
{
row[targetIndex] = ValueDataUtil.plus(targetMeta, data.previousSums[i], sourceMeta, row[sourceIndex]);
}
}
data.previousSums[i] = row[targetIndex];
}
}
private void addCumulativeAverages(Object[] row) throws KettleValueException {
// We need to adjust this row with cumulative sums
for (int i=0;i<data.cumulativeAvgSourceIndexes.size();i++)
{
int sourceIndex = data.cumulativeAvgSourceIndexes.get(i);
Object previousTarget = data.previousAvgSum[i];
Object sourceValue = row[sourceIndex];
int targetIndex = data.cumulativeAvgTargetIndexes.get(i);
ValueMetaInterface sourceMeta = data.inputRowMeta.getValueMeta(sourceIndex);
ValueMetaInterface targetMeta = data.outputRowMeta.getValueMeta(targetIndex);
// If the first values where null, or this is the first time around, just take the source value...
Object sum = null;
if (targetMeta.isNull(previousTarget))
{
sum=sourceMeta.convertToNormalStorageType(sourceValue);
}
else
{
// If the source value is null, just take the previous target value
if (sourceMeta.isNull(sourceValue))
{
sum = previousTarget;
}
else
{
if (sourceMeta.isInteger())
{
sum = ValueDataUtil.plus(data.valueMetaInteger, data.previousAvgSum[i], sourceMeta, row[sourceIndex]);
}
else
{
sum = ValueDataUtil.plus(targetMeta, data.previousAvgSum[i], sourceMeta, row[sourceIndex]);
}
}
}
data.previousAvgSum[i] = sum;
if (!sourceMeta.isNull(sourceValue)) data.previousAvgCount[i]++;
if (sourceMeta.isInteger()) {
// Change to number as the exception
if (sum==null)
{
row[targetIndex] = null;
}
else
{
row[targetIndex] = new Double( ((Long)sum).doubleValue() / data.previousAvgCount[i] );
}
}
else
{
row[targetIndex] = ValueDataUtil.divide(targetMeta, sum, data.valueMetaInteger, data.previousAvgCount[i]);
}
}
}
// Is the row r of the same group as previous?
private boolean sameGroup(Object[] previous, Object[] r) throws KettleValueException
{
return data.inputRowMeta.compare(previous, r, data.groupnrs) == 0;
}
// Calculate the aggregates in the row...
@SuppressWarnings("unchecked")
private void calcAggregate(Object[] r) throws KettleValueException
{
for (int i=0;i<data.subjectnrs.length;i++)
{
Object subj = r[data.subjectnrs[i]];
ValueMetaInterface subjMeta=data.inputRowMeta.getValueMeta(data.subjectnrs[i]);
Object value = data.agg[i];
ValueMetaInterface valueMeta=data.aggMeta.getValueMeta(i);
//System.out.println(" calcAggregate value, i="+i+", agg.size()="+agg.size()+", subj="+subj+", value="+value);
switch(meta.getAggregateType()[i])
{
case GroupByMeta.TYPE_GROUP_SUM :
data.agg[i]=ValueDataUtil.sum(valueMeta, value, subjMeta, subj);
break;
case GroupByMeta.TYPE_GROUP_AVERAGE :
if (!subjMeta.isNull(subj)) {
data.agg[i]=ValueDataUtil.sum(valueMeta, value, subjMeta, subj);
data.counts[i]++;
}
break;
case GroupByMeta.TYPE_GROUP_STANDARD_DEVIATION :
if (!subjMeta.isNull(subj)) {
data.counts[i]++;
double n = data.counts[i];
double x = subjMeta.getNumber(subj);
double sum = (Double)value;
double mean = data.mean[i];
double delta = x - mean;
mean = mean + (delta/n);
sum = sum + delta*(x-mean);
data.mean[i] = mean;
data.agg[i] = sum;
}
break;
case GroupByMeta.TYPE_GROUP_COUNT_DISTINCT :
if (!subjMeta.isNull(subj)) {
if (data.distinctObjs == null) {
data.distinctObjs = new Set[meta.getSubjectField().length];
}
if (data.distinctObjs[i] == null) {
data.distinctObjs[i] = new TreeSet<Object>();
}
Object obj = subjMeta.convertToNormalStorageType(subj);
if (!data.distinctObjs[i].contains(obj)) {
data.distinctObjs[i].add(obj);
data.agg[i] = (Long)value + 1;
}
}
case GroupByMeta.TYPE_GROUP_COUNT_ALL :
if (!subjMeta.isNull(subj)) {
data.counts[i]++;
}
break;
case GroupByMeta.TYPE_GROUP_MIN :
if(subjMeta.isSortedDescending()) {
// Account for negation in ValueMeta.compare() - See PDI-2302
if (subjMeta.compare(value,valueMeta,subj)<0) data.agg[i]=subj;
} else {
if (subjMeta.compare(subj,valueMeta,value)<0) data.agg[i]=subj;
}
break;
case GroupByMeta.TYPE_GROUP_MAX :
if(subjMeta.isSortedDescending()) {
// Account for negation in ValueMeta.compare() - See PDI-2302
if (subjMeta.compare(value,valueMeta,subj)>0) data.agg[i]=subj;
} else {
if (subjMeta.compare(subj,valueMeta,value)>0) data.agg[i]=subj;
}
break;
case GroupByMeta.TYPE_GROUP_FIRST :
if (!(subj==null) && value==null) data.agg[i]=subj;
break;
case GroupByMeta.TYPE_GROUP_LAST :
if (!(subj==null)) data.agg[i]=subj;
break;
case GroupByMeta.TYPE_GROUP_FIRST_INCL_NULL:
// This is on purpose. The calculation of the
// first field is done when setting up a new group
// This is just the field of the first row
// if (linesWritten==0) value.setValue(subj);
break;
case GroupByMeta.TYPE_GROUP_LAST_INCL_NULL :
data.agg[i]=subj;
break;
case GroupByMeta.TYPE_GROUP_CONCAT_COMMA :
if (!(subj==null))
{
String vString=valueMeta.getString(value);
if (vString.length()>0) vString=vString+", "; //$NON-NLS-1$
data.agg[i]=vString+subjMeta.getString(subj);
}
break;
case GroupByMeta.TYPE_GROUP_CONCAT_STRING :
if (!(subj==null))
{
String separator="";
if(!Const.isEmpty(meta.getValueField()[i])) separator=environmentSubstitute(meta.getValueField()[i]);
String vString=valueMeta.getString(value);
if (vString.length()>0) vString=vString+separator; //$NON-NLS-1$
data.agg[i]=vString+subjMeta.getString(subj);
}
break;
default: break;
}
}
}
// Initialize a group..
private void newAggregate(Object[] r)
{
// Put all the counters at 0
for (int i=0;i<data.counts.length;i++) data.counts[i]=0;
data.distinctObjs = null;
data.agg = new Object[data.subjectnrs.length];
data.mean = new double[data.subjectnrs.length]; // sets all doubles to 0.0
data.aggMeta=new RowMeta();
for (int i=0;i<data.subjectnrs.length;i++)
{
ValueMetaInterface subjMeta=data.inputRowMeta.getValueMeta(data.subjectnrs[i]);
Object v=null;
ValueMetaInterface vMeta=null;
switch(meta.getAggregateType()[i])
{
case GroupByMeta.TYPE_GROUP_SUM :
case GroupByMeta.TYPE_GROUP_AVERAGE :
case GroupByMeta.TYPE_GROUP_CUMULATIVE_SUM :
case GroupByMeta.TYPE_GROUP_CUMULATIVE_AVERAGE :
vMeta = new ValueMeta(meta.getAggregateField()[i], subjMeta.isNumeric()?subjMeta.getType():ValueMetaInterface.TYPE_NUMBER);
switch(subjMeta.getType())
{
case ValueMetaInterface.TYPE_BIGNUMBER: v=new BigDecimal("0"); break;
case ValueMetaInterface.TYPE_INTEGER: v=new Long(0L); break;
case ValueMetaInterface.TYPE_NUMBER:
default: v=new Double(0.0); break;
}
break;
case GroupByMeta.TYPE_GROUP_STANDARD_DEVIATION :
vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_NUMBER);
v=new Double(0.0);
break;
case GroupByMeta.TYPE_GROUP_COUNT_DISTINCT :
case GroupByMeta.TYPE_GROUP_COUNT_ALL :
vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_INTEGER);
v=new Long(0L);
break;
case GroupByMeta.TYPE_GROUP_FIRST :
case GroupByMeta.TYPE_GROUP_LAST :
case GroupByMeta.TYPE_GROUP_FIRST_INCL_NULL :
case GroupByMeta.TYPE_GROUP_LAST_INCL_NULL :
case GroupByMeta.TYPE_GROUP_MIN :
case GroupByMeta.TYPE_GROUP_MAX :
vMeta = subjMeta.clone();
vMeta.setName(meta.getAggregateField()[i]);
v = r==null ? null : r[data.subjectnrs[i]];
break;
case GroupByMeta.TYPE_GROUP_CONCAT_COMMA :
vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_STRING);
v = ""; //$NON-NLS-1$
break;
case GroupByMeta.TYPE_GROUP_CONCAT_STRING :
vMeta = new ValueMeta(meta.getAggregateField()[i], ValueMetaInterface.TYPE_STRING);
v = ""; //$NON-NLS-1$
break;
default:
// TODO raise an error here because we cannot continue successfully maybe the UI should validate this
break;
}
if (meta.getAggregateType()[i]!=GroupByMeta.TYPE_GROUP_COUNT_ALL &&
meta.getAggregateType()[i]!=GroupByMeta.TYPE_GROUP_COUNT_DISTINCT)
{
vMeta.setLength(subjMeta.getLength(), subjMeta.getPrecision());
}
if (v!=null) data.agg[i]=v;
data.aggMeta.addValueMeta(vMeta);
}
// Also clear the cumulative data...
for (int i=0;i<data.previousSums.length;i++) data.previousSums[i]=null;
for (int i=0;i<data.previousAvgCount.length;i++)
{
data.previousAvgCount[i]=0L;
data.previousAvgSum[i]=null;
}
}
private Object[] buildResult(Object[] r) throws KettleValueException
{
Object[] result=null;
if (r!=null || meta.isAlwaysGivingBackOneRow()) {
result = RowDataUtil.allocateRowData(data.groupnrs.length);
if (r!=null)
{
for (int i=0;i<data.groupnrs.length;i++)
{
result[i]=r[data.groupnrs[i]];
}
}
result=RowDataUtil.addRowData(result, data.groupnrs.length, getAggregateResult());
}
return result;
}
private void initGroupMeta(RowMetaInterface previousRowMeta) throws KettleValueException
{
data.groupMeta=new RowMeta();
for (int i=0;i<data.groupnrs.length;i++)
{
data.groupMeta.addValueMeta(previousRowMeta.getValueMeta(data.groupnrs[i]));
}
return;
}
private Object[] getAggregateResult() throws KettleValueException
{
Object[] result = new Object[data.subjectnrs.length];
if (data.subjectnrs!=null)
{
for (int i=0;i<data.subjectnrs.length;i++)
{
Object ag = data.agg[i];
switch(meta.getAggregateType()[i])
{
case GroupByMeta.TYPE_GROUP_SUM : break;
case GroupByMeta.TYPE_GROUP_AVERAGE :
ag=ValueDataUtil.divide(data.aggMeta.getValueMeta(i), ag,
new ValueMeta("c",ValueMetaInterface.TYPE_INTEGER), new Long(data.counts[i]));
break; //$NON-NLS-1$
case GroupByMeta.TYPE_GROUP_COUNT_ALL : ag=new Long(data.counts[i]); break;
case GroupByMeta.TYPE_GROUP_COUNT_DISTINCT : break;
case GroupByMeta.TYPE_GROUP_MIN : break;
case GroupByMeta.TYPE_GROUP_MAX : break;
case GroupByMeta.TYPE_GROUP_STANDARD_DEVIATION :
double sum = (Double)ag / data.counts[i];
ag = Double.valueOf( Math.sqrt( sum ) );
break;
default: break;
}
result[i]=ag;
}
}
return result;
}
private void addToBuffer(Object[] row) throws KettleFileException
{
data.bufferList.add(row);
if (data.bufferList.size()>5000)
{
if (data.rowsOnFile==0)
{
try
{
data.tempFile = File.createTempFile(meta.getPrefix(), ".tmp", new File(environmentSubstitute(meta.getDirectory()))); //$NON-NLS-1$
data.fos=new FileOutputStream(data.tempFile);
data.dos=new DataOutputStream(data.fos);
data.firstRead = true;
}
catch(IOException e)
{
throw new KettleFileException(BaseMessages.getString(PKG, "GroupBy.Exception.UnableToCreateTemporaryFile"), e); //$NON-NLS-1$
}
}
// OK, save the oldest rows to disk!
Object[] oldest = (Object[]) data.bufferList.get(0);
data.inputRowMeta.writeData(data.dos, oldest);
data.bufferList.remove(0);
data.rowsOnFile++;
}
}
private Object[] getRowFromBuffer() throws KettleFileException
{
if (data.rowsOnFile>0)
{
if (data.firstRead)
{
// Open the inputstream first...
try
{
data.fis=new FileInputStream( data.tempFile );
data.dis=new DataInputStream( data.fis );
data.firstRead = false;
}
catch(IOException e)
{
throw new KettleFileException(BaseMessages.getString(PKG, "GroupBy.Exception.UnableToReadBackRowFromTemporaryFile"), e); //$NON-NLS-1$
}
}
// Read one row from the file!
Object[] row;
try
{
row = data.inputRowMeta.readData(data.dis);
}
catch (SocketTimeoutException e)
{
throw new KettleFileException(e); // Shouldn't happen on files
}
data.rowsOnFile
return row;
}
else
{
if (data.bufferList.size()>0)
{
Object[] row = (Object[])data.bufferList.get(0);
data.bufferList.remove(0);
return row;
}
else
{
return null; // Nothing left!
}
}
}
private void closeOutput() throws KettleFileException
{
try
{
if (data.dos!=null) { data.dos.close(); data.dos=null; }
if (data.fos!=null) { data.fos.close(); data.fos=null; }
data.firstRead = true;
}
catch(IOException e)
{
throw new KettleFileException(BaseMessages.getString(PKG, "GroupBy.Exception.UnableToCloseInputStream"), e); //$NON-NLS-1$
}
}
private void closeInput() throws KettleFileException
{
try
{
if (data.fis!=null) { data.fis.close(); data.fis=null; }
if (data.dis!=null) { data.dis.close(); data.dis=null; }
}
catch(IOException e)
{
throw new KettleFileException(BaseMessages.getString(PKG, "GroupBy.Exception.UnableToCloseInputStream"), e); //$NON-NLS-1$
}
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(GroupByMeta)smi;
data=(GroupByData)sdi;
if (super.init(smi, sdi))
{
data.bufferList = new ArrayList<Object[]>();
data.rowsOnFile = 0;
return true;
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
if (data.tempFile!=null) data.tempFile.delete();
super.dispose(smi, sdi);
}
}
|
import ui.Display;
import util.Utilities;
public class Engine {
public static void main(String[] args) {
Utilities.init();
Display displayVar = new Display("aprctsrpg");
displayVar.addStage(new StageBattle());
displayVar.addStage(new StagePrologue());
displayVar.addStage(new StageTeam());
displayVar.addStage(new StageBattleTutorial());
displayVar.addStage(new StageFour());
displayVar.addStage(new HeadQuarters());
displayVar.addStage(new ZombiePatrol());
displayVar.addStage(new WeaponUpgrade());
displayVar.addStage(new MotherZombie());
displayVar.addStage(new EndGame());
displayVar.begin();
}
}
|
package edu.virginia.vcgr.genii.client.cmd.tools;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.morgan.util.io.StreamUtils;
import edu.virginia.vcgr.genii.client.byteio.ByteIOConstants;
import edu.virginia.vcgr.genii.client.cmd.ReloadShellException;
import edu.virginia.vcgr.genii.client.cmd.ToolException;
import edu.virginia.vcgr.genii.client.dialog.UserCancelException;
import edu.virginia.vcgr.genii.client.gpath.GeniiPath;
import edu.virginia.vcgr.genii.client.io.LoadFileResource;
import edu.virginia.vcgr.genii.client.rns.RNSException;
import edu.virginia.vcgr.genii.client.rp.ResourcePropertyException;
import edu.virginia.vcgr.genii.client.security.axis.AuthZSecurityException;
public class QosManagerTool extends BaseGridTool
{
static final private String _DESCRIPTION = "config/tooldocs/description/dqos-manager";
static final private String _USAGE = "config/tooldocs/usage/uqos-manager";
static final private String _MANPAGE = "config/tooldocs/man/qos-manager";
static QosManagerTool QosManager = null;
static QosManagerTool factory() {
if (QosManager == null) {
QosManager = new QosManagerTool();
}
return QosManager;
}
private String _spec_path_to_schedule = null;
private String _spec_id_to_schedule = null;
private String _spec_id_to_remove = null;
private String _status_path_to_add = null;
private String _container_id_to_remove = null;
private boolean _show_db = false;
private boolean _show_db_verbose = false;
private boolean _clean_db = false;
private boolean _monitor = false;
private boolean _test_db = false;
private String QOSDBPath = "/home/dg/database/";
private String QOSDBName = QOSDBPath + "qos.db";
public QosManagerTool()
{
super(new LoadFileResource(_DESCRIPTION), new LoadFileResource(_USAGE),
false, ToolCategory.ADMINISTRATION);
addManPage(new LoadFileResource(_MANPAGE));
}
@Option({ "schedule" })
public void set_schedule(String spec_path)
{
_spec_path_to_schedule = spec_path;
}
@Option({ "schedule-id" })
public void set_schedule_id(String spec_id)
{
_spec_id_to_schedule = spec_id;
}
@Option({ "rm-spec" })
public void set_rm_spec(String spec_id)
{
_spec_id_to_remove = spec_id;
}
@Option({ "add-container" })
public void set_add_container(String status_path)
{
_status_path_to_add = status_path;
}
@Option({ "rm-container" })
public void set_rm_container(String container_id)
{
_container_id_to_remove = container_id;
}
@Option({ "show-db" })
public void set_show_db()
{
_show_db = true;
}
@Option({ "show-db-verbose" })
public void set_show_db_verbose()
{
_show_db_verbose = true;
}
@Option({ "clean-db" })
public void set_clean_db()
{
_clean_db = true;
}
@Option({ "monitor" })
public void set_monitor()
{
_monitor = true;
}
@Option({ "test-db" })
public void set_test_db()
{
_test_db = true;
}
@Override
protected int runCommand() throws ReloadShellException, ToolException,
UserCancelException, RNSException, AuthZSecurityException,
IOException, ResourcePropertyException
{
qos_manager(getArgument(0));
return 0;
}
@Override
protected void verify() throws ToolException
{
}
private class QosSpec
{
public String SpecId = ""; // (str) a unique string
public int Availability = 99; // (int) with presumed leading 0
public int Reliability = 99; // (int) with presumed leading 0
public int ReservedSize = 100; // (int) MB
public int UsedSize = 0; // (int) MB
public int DataIntegrity = 0; // (int) 0 to 10**6, 0 is worst
public String Bandwidth = "Low"; // (str) 'High' or 'Low'
public String Latency = "High"; // (str) 'High' or 'Low'
public String PhysicalLocations = ""; // (str) locations separated by ;
public String SpecPath = ""; // (str) grid path to a spec file
public QosSpec() {
}
// Constructor from a SQlite ResultSet
public QosSpec(ResultSet rs) {
try {
this.SpecId = rs.getString(1);
this.Availability = rs.getInt(2);
this.Reliability = rs.getInt(3);
this.ReservedSize = rs.getInt(4);
this.UsedSize = rs.getInt(5);
this.DataIntegrity = rs.getInt(6);
this.Bandwidth = rs.getString(7);
this.Latency = rs.getString(8);
this.PhysicalLocations = rs.getString(9);
this.SpecPath = rs.getString(10);
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
public boolean parse_string(String spec_string) {
System.out.println("(qm) NYI.");
return false;
}
public String to_string() {
String spec_str = this.SpecId + ',' + this.Availability + ','
+ this.Reliability + ',' + this.ReservedSize + ','
+ this.UsedSize + ',' + this.DataIntegrity + ','
+ this.Bandwidth + ',' + this.Latency + ','
+ this.PhysicalLocations + ',' + this.SpecPath;
return spec_str;
}
public boolean read_from_file(String file_path) {
System.out.println("(qm) NYI.");
return false;
}
public boolean write_to_file(String file_path) {
System.out.println("(qm) NYI.");
return false;
}
public String get_sql_header() {
String header = " Specifications(" +
"SpecId TEXT PRIMARY KEY UNIQUE," +
"Availability INT," +
"Reliability INT," +
"ReservedSize INT," +
"UsedSize INT," +
"DataIntegrity INT," +
"Bandwidth TEXT," +
"Latency TEXT," +
"PhysicalLocations TEXT," +
"SpecPath TEXT" +
");";
return header;
}
public String to_sql_string() {
String spec_sql_str = "'" + this.SpecId + "',"
+ this.Availability + "," + this.Reliability + ","
+ this.ReservedSize + "," + this.UsedSize + ","
+ this.DataIntegrity + ",'" + this.Bandwidth + "','"
+ this.Latency + "','" + this.PhysicalLocations + "','"
+ this.SpecPath + "'";
return spec_sql_str;
}
}
private class ContainerStatus
{
public String ContainerId = ""; // (str) a unique string
// static information
public int StorageTotal = 0; // (int) MB
public String PathToSwitch = ""; // (str) may be multiple switches
public int CoresAvailable = 0; // (int) for concurrency
public double StorageRBW = 0.0; // (flt) max MB/s
public double StorageWBW = 0.0; // (flt) max MB/s
public int StorageRLatency = 0; // (int) min uSec
public int StorageWLatency = 0; // (int) min uSec
public int StorageRAIDLevel = 0; // (int) range 0..6
public double CostPerGBMonth = 0.0; // (flt) allocation units
public int DataIntegrity = 0; // (int) 0 to 10**6, 0 is worst
// dynamic information
public int StorageReserved = 0; // (int) MB, containers dont know
public int StorageUsed = 0; // (int) MB
public int StorageReliability = 0; // (int) with presumed leading 0
public int ContainerAvailability = 0; // (int) with presumed leading 0
public double StorageRBW_dyn = 0.0; // (flt) MB/s. Avg of past 10 min
public double StorageWBW_dyn = 0.0; // (flt) MB/s. Avg of past 10 min
// extra information
public String PhysicalLocation = ""; // (str) physical location
public String NetworkAddress = ""; // (str) container rns service
public String StatusPath = ""; // (str) status file genii path
public ContainerStatus() {
}
// Constructor from a SQLite ResultSet
public ContainerStatus(ResultSet rs) {
try {
this.ContainerId = rs.getString(1);
this.StorageTotal = rs.getInt(2);
this.PathToSwitch = rs.getString(3);
this.CoresAvailable = rs.getInt(4);
this.StorageRBW = rs.getDouble(5);
this.StorageWBW = rs.getDouble(6);
this.StorageRLatency = rs.getInt(7);
this.StorageWLatency = rs.getInt(8);
this.StorageRAIDLevel = rs.getInt(9);
this.CostPerGBMonth = rs.getDouble(10);
this.DataIntegrity = rs.getInt(11);
this.StorageReserved = rs.getInt(12);
this.StorageUsed = rs.getInt(13);
this.StorageReliability = rs.getInt(14);
this.ContainerAvailability = rs.getInt(15);
this.StorageRBW_dyn = rs.getDouble(16);
this.StorageWBW_dyn = rs.getDouble(17);
this.PhysicalLocation = rs.getString(18);
this.NetworkAddress = rs.getString(19);
this.StatusPath = rs.getString(20);
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
public boolean parse_string(String spec_string) {
System.out.println("(qm) NYI.");
return false;
}
public String to_string() {
String status_str = this.ContainerId + ','
+ this.StorageTotal + ',' + this.PathToSwitch + ','
+ this.CoresAvailable + ',' + this.StorageRBW + ','
+ this.StorageWBW + ',' + this.StorageRLatency + ','
+ this.StorageWLatency + ',' + this.StorageRAIDLevel + ','
+ this.CostPerGBMonth + ',' + this.DataIntegrity + ','
+ this.StorageReserved + ',' + this.StorageUsed + ','
+ this.StorageReliability + ','
+ this.ContainerAvailability + ','
+ this.StorageRBW_dyn + ',' + this.StorageWBW_dyn + ','
+ this.PhysicalLocation + ',' + this.NetworkAddress + ','
+ this.StatusPath;
return status_str;
}
public boolean read_from_file(String file_path) {
System.out.println("(qm) NYI.");
return false;
}
public boolean write_to_file(String file_path) {
System.out.println("(qm) NYI.");
return false;
}
public String get_sql_header() {
String header = " Containers(" +
"ContainerId" + " TEXT PRIMARY KEY UNIQUE," +
"StorageTotal" + " INT ," +
"PathToSwitch" + " TEXT," +
"CoresAvailable" + " INT ," +
"StorageRBW" + " REAL," +
"StorageWBW" + " REAL," +
"StorageRLatency" + " INT ," +
"StorageWLatency" + " INT ," +
"StorageRAIDLevel" + " INT ," +
"CostPerGBMonth" + " REAL," +
"DataIntegrity" + " INT ," +
"StorageReserved" + " INT ," +
"StorageUsed" + " INT ," +
"StorageReliability" + " INT ," +
"ContainerAvailability" + " INT ," +
"StorageRBW_dyn" + " REAL," +
"StorageWBW_dyn" + " REAL," +
"PhysicalLocation" + " TEXT," +
"NetworkAddress" + " TEXT," +
"StatusPath" + " TEXT" +
");";
return header;
}
public String to_sql_string() {
String status_sql_str = "'" + this.ContainerId + "',"
+ this.StorageTotal + ",'" + this.PathToSwitch + "',"
+ this.CoresAvailable + "," + this.StorageRBW + ","
+ this.StorageWBW + "," + this.StorageRLatency + ","
+ this.StorageWLatency + "," + this.StorageRAIDLevel + ","
+ this.CostPerGBMonth + "," + this.DataIntegrity + ","
+ this.StorageReserved + "," + this.StorageUsed + ","
+ this.StorageReliability + "," + this.ContainerAvailability + ","
+ this.StorageRBW_dyn + "," + this.StorageWBW_dyn + ","
+ "'" + this.PhysicalLocation + "',"
+ "'" + this.NetworkAddress + "','" + this.StatusPath + "'";
return status_sql_str;
}
}
public void qos_manager(String arg) throws IOException
{
if (_spec_path_to_schedule != null) {
System.out.println("(qm) main: Schedule a QoS specs file at "
+ _spec_path_to_schedule);
schedule(_spec_path_to_schedule, _spec_id_to_schedule);
} else if (_spec_id_to_schedule != null) {
System.out.println("(qm) main: Schedule a QoS specs id "
+ _spec_id_to_schedule);
schedule(_spec_path_to_schedule, _spec_id_to_schedule);
} else if (_spec_id_to_remove != null) {
System.out.println("(qm) main: Remove a QoS specs id "
+ _spec_id_to_remove);
db_remove_spec(_spec_id_to_remove);
} else if (_status_path_to_add != null) {
System.out.println("(qm) main: Add a container with status file at "
+ _status_path_to_add);
ContainerStatus status = read_status_file(_status_path_to_add);
db_update_container(status, true); // init
} else if (_container_id_to_remove != null) {
System.out.println("(qm) main: Remove container id "
+ _container_id_to_remove);
db_remove_container(_container_id_to_remove);
} else if (_show_db) {
System.out.println("(qm) main: Show information of the QoS database.");
db_summary(false);
} else if (_show_db_verbose) {
System.out.println("(qm) main: Show details of the QoS database.");
db_summary(true);
} else if (_clean_db) {
System.out.println("(qm) main: Clean QoS database.");
db_init();
} else if (_monitor) {
System.out.println("(qm) main: Monitor container status and specs.");
monitor_all();
} else if (_test_db) {
System.out.println("(qm) main: Test the QoS database.");
test_db();
} else {
System.out.println("(qm) main: Please run 'help qos-manager' for usable options.");
}
}
private void db_destroy() {
File dbFile = new File(this.QOSDBName);
dbFile.delete();
}
private boolean db_init() {
ContainerStatus status = new ContainerStatus();
QosSpec spec = new QosSpec();
// if exists
File dbFile = new File(this.QOSDBName);
if(dbFile.exists()){
db_destroy();
}
Connection conn = null;
Statement stmt = null;
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
System.out.println("(qm) db: Connect to QoS DB successfully.");
stmt = conn.createStatement();
// create table1 and table2
String create_spec_table = "CREATE TABLE" + spec.get_sql_header();
String create_status_table = "CREATE TABLE" + status.get_sql_header();
stmt.executeUpdate(create_spec_table);
stmt.executeUpdate(create_status_table);
String sql = "CREATE TABLE Relationships(SpecId TEXT, ContainerId TEXT, UNIQUE(SpecId, ContainerId) ON CONFLICT REPLACE);";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
return true;
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return false;
}
private void db_summary(boolean verbose) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
if (verbose == true) {
System.out.println("
System.out.println("(qm) db: QoS Database Details:");
stmt = conn.createStatement();
System.out.println(" - Specifications:");
String sql = "SELECT * FROM Specifications;";
ResultSet rs_spec = stmt.executeQuery(sql);
ResultSetMetaData rsmd_spec = rs_spec.getMetaData();
int numberOfColumns_spec = rsmd_spec.getColumnCount();
System.out.print(" ");
for (int i = 1; i <= numberOfColumns_spec; i++) {
if (i > 1) System.out.print(", ");
String columnName_spec = rsmd_spec.getColumnName(i);
System.out.print(columnName_spec);
}
System.out.println("");
while (rs_spec.next()) {
System.out.print(" ");
for (int i = 1; i <= numberOfColumns_spec; i++) {
if (i > 1) System.out.print(", ");
String columnValue_spec = rs_spec.getString(i);
System.out.print(columnValue_spec);
}
System.out.println("");
}
System.out.println(" - Containers:");
sql = "SELECT * FROM Containers;";
ResultSet rs_container = stmt.executeQuery(sql);
ResultSetMetaData rsmd_container = rs_container.getMetaData();
int numberOfColumns_container = rsmd_container.getColumnCount();
System.out.print(" ");
for (int i = 1; i <= numberOfColumns_container; i++) {
if (i > 1) System.out.print(", ");
String columnName_container = rsmd_container.getColumnName(i);
System.out.print(columnName_container);
}
System.out.println("");
while (rs_container.next()) {
System.out.print(" ");
for (int i = 1; i <= numberOfColumns_container; i++) {
if (i > 1) System.out.print(", ");
String columnValue_container = rs_container.getString(i);
System.out.print(columnValue_container);
}
System.out.println("");
}
System.out.println(" - Relationships:");
sql = "SELECT * FROM Relationships;";
ResultSet rs_relationship = stmt.executeQuery(sql);
ResultSetMetaData rsmd_relationship = rs_container.getMetaData();
int numberOfColumns_relationship = rsmd_relationship.getColumnCount();
System.out.print(" ");
for (int i = 1; i <= numberOfColumns_relationship; i++) {
if (i > 1) System.out.print(" -> ");
String columnName_relationship = rsmd_relationship.getColumnName(i);
System.out.print(columnName_relationship);
}
System.out.println("");
while (rs_relationship.next()) {
System.out.print(" ");
for (int i = 1; i <= numberOfColumns_relationship; i++) {
if (i > 1) System.out.print(" -> ");
String columnValue_relationship = rs_relationship.getString(i);
System.out.print(columnValue_relationship);
}
System.out.println("");
}
} else { // verbose == false
System.out.println("
System.out.println("(qm) db: QoS Database Summary:");
stmt = conn.createStatement();
String sql = "SELECT SpecId FROM Specifications;";
ResultSet rs_spec = stmt.executeQuery(sql);
System.out.print(" Specifications:\t");
while (rs_spec.next()) {
String columnValue_spec = rs_spec.getString(1);
System.out.print(" " + columnValue_spec + ";");
}
System.out.println("");
sql = "SELECT ContainerId FROM Containers;";
ResultSet rs_container = stmt.executeQuery(sql);
System.out.print(" Containers:\t");
while (rs_container.next()) {
String columnValue_container = rs_container.getString(1);
System.out.print(" " + columnValue_container + ";");
}
System.out.println("");
sql = "SELECT * FROM Relationships;";
ResultSet rs_relationship = stmt.executeQuery(sql);
System.out.print(" Relationships:\t");
while (rs_relationship.next()) {
String spec_id = rs_relationship.getString(1);
String container_id = rs_relationship.getString(2);
System.out.print(" " + spec_id + " -> " + container_id + ";");
}
System.out.println("");
}
System.out.println("
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
}
private boolean db_update_container(ContainerStatus status, boolean init) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:"+this.QOSDBName);
stmt = conn.createStatement();
assert (status != null);
String status_sql_str = status.to_sql_string();
// TODO: check existence
if (init) {
// Insert new container
System.out.println("(qm) db: Insert status of container: " + status.ContainerId);
String sql = "INSERT INTO Containers VALUES (" + status_sql_str + ");";
stmt.executeUpdate(sql);
} else {
// Update existing container
System.out.println("(qm) db: Update status of container: " + status.ContainerId);
String sql = "DELETE FROM Containers WHERE ContainerId = '" + status.ContainerId + "';";
stmt.executeUpdate(sql);
sql = "INSERT INTO Containers VALUES (" + status_sql_str + ");";
stmt.executeUpdate(sql);
}
stmt.close();
conn.close();
return true;
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return false;
}
private boolean db_add_scheduled_spec(QosSpec spec,
List<String> scheduled_container_ids, boolean init)
{
Connection conn = null;
Statement stmt = null;
assert(spec != null);
String spec_sql_str = spec.to_sql_string();
// TODO: check existence, update container reserved size, file copy, etc.
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
if (init) {
// Insert new spec
System.out.println("(qm) db: Insert scheduled spec: " + spec.SpecId);
String sql = "INSERT INTO Specifications VALUES (" + spec_sql_str + ");";
stmt.executeUpdate(sql);
for (int i = 0; i < scheduled_container_ids.size(); i++) {
sql = "INSERT INTO Relationships VALUES ('" + spec.SpecId + "','"
+ scheduled_container_ids.get(i) + "');";
stmt.executeUpdate(sql);
}
} else {
// Update existing spec
System.out.println("(qm) db: Update scheduled spec: " + spec.SpecId);
String sql = "DELETE FROM Relationships WHERE SpecId = '" + spec.SpecId + "';";
stmt.executeUpdate(sql);
sql = "DELETE FROM Specifications WHERE SpecId = '" + spec.SpecId + "';";
stmt.executeUpdate(sql);
sql = "INSERT INTO Specifications VALUES (" + spec_sql_str + ");";
stmt.executeUpdate(sql);
for (int i = 0; i < scheduled_container_ids.size(); i++) {
sql = "INSERT INTO Relationships VALUES ('" + spec.SpecId + "','"
+ scheduled_container_ids.get(i) + "');";
stmt.executeUpdate(sql);
}
}
stmt.close();
conn.close();
return true;
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return false;
}
private boolean db_remove_spec(String spec_id) {
System.out.println("(qm) db: Remove specification: " + spec_id);
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT ReservedSize FROM Specifications WHERE SpecId = '" + spec_id + "';";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
int spec_reserved = rs.getInt(1);
sql = "SELECT ContainerId FROM Relationships WHERE SpecId = '" + spec_id + "';";
ResultSet rs_container = stmt.executeQuery(sql);
List<String> container_list = new ArrayList<String>();
while (rs_container.next()) {
container_list.add(rs_container.getString(1));
}
for (int i = 0; i < container_list.size(); i++) {
sql = "SELECT StorageReserved FROM Containers WHERE ContainerId = '" + container_list.get(i) + "';";
ResultSet rs_reserved = stmt.executeQuery(sql);
int storage_reserved = rs_reserved.getInt(1);
storage_reserved -= spec_reserved;
sql = "UPDATE Containers SET StorageReserved = " + storage_reserved
+ " WHERE ContainerId =" + "'" + container_list.get(i) +"';";
stmt.executeUpdate(sql);
}
sql = "DELETE FROM Specifications WHERE SpecId = '" + spec_id + "';";
stmt.executeUpdate(sql);
sql = "DELETE FROM Relationships WHERE SpecId = '" + spec_id + "';";
stmt.executeUpdate(sql);
}
stmt.close();
conn.close();
return true;
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return false;
}
private boolean db_remove_container(String container_id) {
System.out.println("(qm) db: Remove container: " + container_id);
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT * FROM Containers WHERE ContainerId = '" + container_id + "';";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
sql = "SELECT * FROM Relationships WHERE ContainerId = '" + container_id + "';";
ResultSet rs_specs = stmt.executeQuery(sql);
if (rs_specs.next()) {
System.out.println("(qm) db: ERROR: specifications on container are not rescheduled.");
return false;
}
sql = "DELETE FROM Containers WHERE ContainerId = '" + container_id + "';";
stmt.executeUpdate(sql);
}
stmt.close();
conn.close();
return true;
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return false;
}
private List<String> db_get_container_ids_for_spec(String spec_id) {
System.out.println("(qm) db: Get container ids for specification: " + spec_id);
List<String> container_ids = new ArrayList<String>();
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT ContainerId FROM Relationships WHERE SpecId = '" + spec_id + "';";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
container_ids.add(rs.getString(1));
}
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return container_ids;
}
private List<String> db_get_spec_ids_on_container(String container_id) {
System.out.println("(qm) db: Get spec ids on container: " + container_id);
List<String> spec_ids = new ArrayList<String>();
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT SpecId FROM Relationships WHERE ContainerId = '" + container_id + "';";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
spec_ids.add(rs.getString(1));
}
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return spec_ids;
}
private List<String> db_get_container_id_list() {
System.out.println("(qm) db: Get container id list. ");
List<String> container_ids = new ArrayList<String>();
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT ContainerId From Containers;";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
container_ids.add(rs.getString(1));
}
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return container_ids;
}
private List<String> db_get_spec_id_list() {
System.out.println("(qm) db: Get specification id list. ");
List<String> spec_ids = new ArrayList<String>();
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT SpecId From Specifications;";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
spec_ids.add(rs.getString(1));
}
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return spec_ids;
}
private ContainerStatus db_get_status(String container_id) {
System.out.println("(qm) db: Get container stautus for: " + container_id);
ContainerStatus status = null;
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT * FROM Containers WHERE ContainerId = '" + container_id + "';";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
status = new ContainerStatus(rs);
}
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return status;
}
private QosSpec db_get_spec(String spec_id) {
System.out.println("(qm) db: Get specification contents for: " + spec_id);
QosSpec spec = null;
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + this.QOSDBName);
stmt = conn.createStatement();
String sql = "SELECT * FROM Specifications WHERE SpecId = '" + spec_id + "';";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
spec = new QosSpec(rs);
}
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}
return spec;
}
private void test_db() {
db_init();
db_summary(false);
db_summary(true);
ContainerStatus status = new ContainerStatus();
status.ContainerId = "container1";
status.NetworkAddress = "//aaa";
db_update_container(status, true);
db_summary(true);
//status = new ContainerStatus()
status.ContainerId = "container2";
status.NetworkAddress = "//bbb";
db_update_container(status, true);
db_summary(true);
//status = new ContainerStatus()
status.ContainerId = "container1";
status.NetworkAddress = "//ccc";
status.StorageTotal = 1000;
db_update_container(status, false);
db_summary(true);
QosSpec spec = new QosSpec();
spec.SpecId = "client1-spec1";
List<String> container_list = new ArrayList<String>();
container_list.add("container1");
db_add_scheduled_spec(spec, container_list, true);
db_summary(true);
//spec = new QosSpec();
spec.SpecId = "client1-spec1";
container_list.clear();
container_list.add("container1");
container_list.add("container2");
db_add_scheduled_spec(spec, container_list, false);
db_summary(true);
//spec = new QosSpec();
spec.SpecId = "client1-spec1";
container_list.clear();
container_list.add("container2");
db_add_scheduled_spec(spec, container_list, false);
db_summary(true);
db_remove_spec("client1-spec1");
db_summary(true);
//spec = new QosSpec();
spec.SpecId = "client1-spec1";
container_list.clear();
container_list.add("container1");
container_list.add("container2");
db_add_scheduled_spec(spec, container_list, true);
db_summary(false);
db_summary(true);
System.out.println(db_get_container_ids_for_spec("client1-spec1").toString());
System.out.println(db_get_spec_ids_on_container("container1").toString());
System.out.println(db_get_container_id_list().toString());
System.out.println(db_get_spec_id_list().toString());
status = db_get_status("container1x");
if (status != null)
System.out.println("Error");
status = db_get_status("container1");
if (status != null)
System.out.println(status.to_string());
else
System.out.println("Error");
spec = db_get_spec("xxx");
if (spec != null) System.out.println("Error");
spec = db_get_spec("client1-spec1");
if (spec != null) System.out.println(spec.to_string());
else System.out.println("Error");
}
// Check if disk space is satisfied
// Rule: for every container, free space >= (client reserved - client used)
private boolean check_space(QosSpec spec, List<ContainerStatus> status_list) {
for (int i = 0; i < status_list.size(); i++) {
ContainerStatus status = status_list.get(i);
if (status.StorageTotal - status.StorageUsed < spec.ReservedSize - spec.UsedSize) {
return false;
}
}
return status_list.size() > 0;
}
// Reliability rule: All container together should satisfy the spec
private boolean check_reliability(QosSpec spec, List<ContainerStatus> status_list) {
double spec_reliability = Double.parseDouble("0." + Integer.toString(spec.Reliability));
double container_failure = 1.0;
for (int i = 0; i < status_list.size(); i++) {
ContainerStatus status = status_list.get(i);
container_failure = container_failure *
(1 - Double.parseDouble("0." + Integer.toString(status.StorageReliability)));
}
if (1 - container_failure >= spec_reliability) {
return true;
} else {
return false;
}
}
// Availability rule: All container together should satisfy the spec
private boolean check_availability(QosSpec spec, List<ContainerStatus> status_list) {
double spec_availability = Double.parseDouble("0." + Integer.toString(spec.Availability));
double container_unavailable = 1.0;
for (int i = 0; i < status_list.size(); i++) {
ContainerStatus status = status_list.get(i);
container_unavailable = container_unavailable *
(1 - Double.parseDouble("0." + Integer.toString(status.ContainerAvailability)));
}
if (1 - container_unavailable >= spec_availability) {
return true;
} else {
return false;
}
}
// Bandwidth rule: Even if there are multiple replications, client only use
// one container for the spec. Only check the primary container.
boolean check_bandwidth(QosSpec spec, List<ContainerStatus> status_list) {
if (spec.Bandwidth == "Low") {
return true;
} else {
double BW_threshold = 5.0; // assume 5 MB/s is the threshold
// the first container is the primary container to use
ContainerStatus primary = status_list.get(0);
double free_RBW = primary.StorageRBW - primary.StorageRBW_dyn;
double free_WBW = primary.StorageWBW - primary.StorageWBW_dyn;
if (free_RBW >= BW_threshold && free_WBW >= BW_threshold) {
return true;
} else {
return false;
}
}
}
// Rule: Every container should satisfy the data integrity requirement.
boolean check_dataintegrity(QosSpec spec, List<ContainerStatus> status_list) {
for (int i = 0; i < status_list.size(); i++) {
ContainerStatus status = status_list.get(i);
if (status.DataIntegrity < spec.DataIntegrity) {
return false;
}
}
return true;
}
// check latency using physical location, assuming if first two levels
// are the same, the latency can be satisfied; only check the primary
boolean check_latency(QosSpec spec, List<ContainerStatus> status_list) {
if (spec.Latency == "High") {
return true;
} else {
ContainerStatus primary = status_list.get(0);
// TODO: parse strings
//String spec_level1 = spec.PhysicalLocations.strip().split('/')[1];
//String spec_level2 = spec.PhysicalLocations.strip().split('/')[2];
//String container_level1 = primary.PhysicalLocation.strip().split('/')[1];
//String container_level2 = primary.PhysicalLocation.strip().split('/')[2];
//if (spec_level1 == container_level1 && spec_level2 == contaienr_level2) {
// return true;
//} else {
// return false;
return false;
}
}
// QoS Checker main entry: Check if a list of container can satisfy a spec
boolean check_all(QosSpec spec, List<ContainerStatus> status_list) {
System.out.println("(qm) checker: Check satisfiability of spec " + spec.SpecId +
" on containers " + status_list.toString());
boolean satisfied = true;
if (status_list.size() == 0) { // not scheduled
return false;
}
// Check disk space
satisfied = satisfied && check_space(spec, status_list);
if (!satisfied) {
System.out.println("(qm) checker: Disk space not satisfied for spec: " + spec.SpecId);
}
// Check data integrity
satisfied = satisfied && check_dataintegrity(spec, status_list);
if (!satisfied) {
System.out.println("(qm) checker: Dataintegrity not satisfied for spec: " + spec.SpecId);
}
// Check reliability
satisfied = satisfied && check_reliability(spec, status_list);
if (!satisfied) {
System.out.println("(qm) checker: Reliability not satisfied for spec: " + spec.SpecId);
}
// Check availability
satisfied = satisfied && check_availability(spec, status_list);
if (!satisfied) {
System.out.println("(qm) checker: Availability not satisfied for spec: " + spec.SpecId);
}
// Check bandwidth
satisfied = satisfied && check_bandwidth(spec, status_list);
if (!satisfied) {
System.out.println("(qm) checker: Bandwidth not satisfied for spec: " + spec.SpecId);
}
// Check latency
satisfied = satisfied && check_latency(spec, status_list);
if (!satisfied) {
System.out.println("(qm) checker: Latency not satisfied for spec: " + spec.SpecId);
}
if (satisfied) {
System.out.println("(qm) checker: Spec " + spec.SpecId + " is satisfied on " + status_list.toString());
}
return satisfied;
}
// Get client QoS spec from a genii path
QosSpec read_spec_file(String spec_path) {
char[] data = new char[ByteIOConstants.PREFERRED_SIMPLE_XFER_BLOCK_SIZE];
int read;
InputStream in = null;
InputStreamReader reader = null;
String spec_str = "";
QosSpec spec = null;
try {
GeniiPath path = new GeniiPath(spec_path);
in = path.openInputStream();
reader = new InputStreamReader(in);
while ((read = reader.read(data, 0, data.length)) > 0) {
String s = new String(data, 0, read);
spec_str += s;
}
} catch (IOException e) {
System.out.println(e.toString());
spec_str = "";
} finally {
StreamUtils.close(reader);
StreamUtils.close(in);
}
if (spec_str != "") {
spec = new QosSpec();
boolean succ = spec.parse_string(spec_str);
if (succ) {
System.out.println("(qm) Get QoS specs from " + spec_path);
return spec;
}
}
System.out.println("(qm) Fail to get QoS specs from " + spec_path);
return null;
}
// Schedule filter: filter out some single containers
boolean schedule_filter(QosSpec spec, ContainerStatus status) {
if (status.ContainerAvailability <= 0) return false;
if (status.StorageReliability <= 0) return false;
List<ContainerStatus> tmp = new ArrayList<ContainerStatus>();
tmp.add(status);
if (!check_space(spec, tmp)) return false;
if (!check_dataintegrity(spec, tmp)) return false;
return true;
}
// return a list of scheduled container ids
public List<String> schedule(String spec_path, String spec_id) {
assert(spec_path == null && spec_id != null || spec_path != null && spec_id == null);
QosSpec spec = null;
if (spec_path != null) {
spec = read_spec_file(spec_path);
} else {
spec = db_get_spec(spec_id);
}
List<String> scheduled_containers = new ArrayList<String>();
List<String> container_ids = db_get_container_id_list();
List<ContainerStatus> status_list = new ArrayList<ContainerStatus>();
// filter out some containers
List<ContainerStatus> tmp = new ArrayList<ContainerStatus>();
for (int i = 0; i < container_ids.size(); i++) {
ContainerStatus status = db_get_status(container_ids.get(i));
if (schedule_filter(spec, status)) {
status_list.add(status);
}
}
boolean scheduled = false;
// try a single container
for (int i = 0; i < status_list.size(); i++) {
tmp.clear();
tmp.add(status_list.get(i));
if (check_all(spec, tmp)) {
scheduled = true;
break;
}
}
// try 2 containers
if (!scheduled) {
for (int i = 0; i < status_list.size(); i++) {
for (int j = i; j < status_list.size(); j++) {
tmp.clear();
tmp.add(status_list.get(i));
tmp.add(status_list.get(j));
if (check_all(spec, tmp)) {
scheduled = true;
break;
}
}
}
}
// try 3 containers
if (!scheduled) {
for (int i = 0; i < status_list.size(); i++) {
for (int j = i; j < status_list.size(); j++) {
for (int k = j; k < status_list.size(); k++) {
tmp.clear();
tmp.add(status_list.get(i));
tmp.add(status_list.get(j));
tmp.add(status_list.get(k));
if (check_all(spec, tmp)) {
scheduled = true;
break;
}
}
}
}
}
// try 4 containers
if (!scheduled) {
for (int i = 0; i < status_list.size(); i++) {
for (int j = i; j < status_list.size(); j++) {
for (int k = j; k < status_list.size(); k++) {
for (int l = k; l < status_list.size(); l++) {
tmp.clear();
tmp.add(status_list.get(i));
tmp.add(status_list.get(j));
tmp.add(status_list.get(k));
tmp.add(status_list.get(l));
if (check_all(spec, tmp)) {
scheduled = true;
break;
}
}
}
}
}
}
if (scheduled) {
double costs = 0;
for (ContainerStatus status: tmp) {
scheduled_containers.add(status.ContainerId);
costs += status.CostPerGBMonth;
}
double cost = costs / 1024.0 * spec.ReservedSize;
System.out.println("(qm) Schedule results: " + scheduled_containers.toString());
System.out.printf("(qm) Cost: $%.2f/month", cost);
}
return scheduled_containers;
}
// Get container status from a genii path
ContainerStatus read_status_file(String status_path) {
char[] data = new char[ByteIOConstants.PREFERRED_SIMPLE_XFER_BLOCK_SIZE];
int read;
InputStream in = null;
InputStreamReader reader = null;
String status_str = "";
ContainerStatus status = null;
try {
GeniiPath path = new GeniiPath(status_path);
in = path.openInputStream();
reader = new InputStreamReader(in);
while ((read = reader.read(data, 0, data.length)) > 0) {
String s = new String(data, 0, read);
status_str += s;
}
} catch (IOException e) {
System.out.println(e.toString());
status_str = "";
} finally {
StreamUtils.close(reader);
StreamUtils.close(in);
}
if (status_str != "") {
status = new ContainerStatus();
boolean succ = status.parse_string(status_str);
if (succ) {
System.out.println("(qm) Get container status from " + status_path);
return status;
}
}
System.out.println("(qm) Fail to get container status from " + status_path);
return null;
}
// Monitor a qos spec
private boolean monitor_spec(String spec_id) {
List<String> container_ids = db_get_container_ids_for_spec(spec_id);
QosSpec spec = db_get_spec(spec_id);
List<ContainerStatus> status_list = new ArrayList<ContainerStatus>();
for (int i = 0; i < container_ids.size(); i++) {
status_list.add(db_get_status(container_ids.get(i)));
}
boolean satisfied = check_all(spec, status_list);
if (!satisfied) {
// reschedule
List<String> rescheduled = schedule(null, spec_id);
db_add_scheduled_spec(spec, rescheduled, false); //update
}
return true;
}
// Monitor qos specs related to a container
private boolean monitor_specs_on_container(String container_id) {
List<String> spec_ids = db_get_spec_ids_on_container(container_id);
for (int i = 0; i < spec_ids.size(); i++) {
monitor_spec(spec_ids.get(i));
}
return true;
}
// Update status of a container to qos database
private boolean monitor_container(String container_id) {
ContainerStatus status_in_db = db_get_status(container_id);
assert(status_in_db != null);
ContainerStatus status_remote = read_status_file(status_in_db.StatusPath);
if (status_remote == null) {
System.out.println("(qm) monitor: Container " + container_id +
" is not available.");
// TODO: update database and reschedule
} else {
// Avoid overwriting the reserved size (container doesn't know this)
status_remote.StorageReserved = status_in_db.StorageReserved;
db_update_container(status_remote, false);
// Call QoS Monitor
System.out.println("(qm) monitor: Call QoS Monitor for " + container_id);
monitor_specs_on_container(container_id);
}
return true;
}
// Monitor all containers in the qos database.
private boolean monitor_all() {
List<String> container_ids = db_get_container_id_list();
for (int i = 0; i < container_ids.size(); i++) {
monitor_container(container_ids.get(i));
}
return true;
}
}
|
package risk;
import java.io.FileReader;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public final class JSONBoardImport {
private static JSONParser parser = new JSONParser();
private static RiskBoard board = new RiskBoard();
private static Map<String, List<String>> storedConnections = new HashMap<String, List<String>>();
// Private constructor so an instance is never created
private JSONBoardImport(String fileName){
throw new AssertionError(); // Never call this
}
/**
* Takes a file name, and reads in JSON code to create a new risk board.
*
* @param fileName the name of the file with valid JSON information
* @return a RiskBoard setup by the file
*/
public static RiskBoard newBoard(String fileName){
try {
Object obj = parser.parse(new FileReader(fileName));
// The whole object is the board containing continents
JSONObject board = (JSONObject) obj;
board = (JSONObject) board.get("board");
// The continents are an array of territories
JSONArray continents = (JSONArray) board.get("continents");
// For each continent specified, parse each territory
for(Object con : continents) {
JSONObject continent = (JSONObject) con;
// continent.get("name"); // Name of the continent, use later?
// The territories are in an array of JSON objects
JSONArray territories = (JSONArray) continent.get("territories");
// for each territory, pass the info to a parser for territories
for(Object ter : territories) {
parseTerritory((JSONObject) ter);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return board;
}
/**
* Helper method to parse territories and add them to the board
*
* @param ter a JSONObject with a territory
*/
private static void parseTerritory(JSONObject ter) {
// Add a territory with the name based on the JSON name
String name = ter.get("name").toString();
Territory terra = new Territory(name);
// ter.get("faction"); // Saved faction data
// ter.get("troops"); // Saved troops data
// Create Territory objects and add them to the connections list
for (Object obj : (JSONArray) ter.get("connections")) {
String newName = (String) obj;
terra.addConnection(new Territory(newName));
}
board.addTerritory(terra);
}
}
|
package cx2x.xcodeml.helper;
import cx2x.xcodeml.exception.*;
import cx2x.xcodeml.xnode.*;
import exc.xcodeml.XcodeMLtools_Fmod;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* The class XnodeUtil contains only static method to help manipulating the
* raw Elements in the XcodeML representation by using the abstracted Xnode.
*
* @author clementval
*/
public class XnodeUtil {
private static final String XMOD_FILE_EXTENSION = ".xmod";
/**
* Find a function definition according to a function call.
* @param xcodeml The XcodeML program to search in.
* @param fctCall The function call used to find the function definition.
* @return A function definition element if found. Null otherwise.
*/
public static XfunctionDefinition findFunctionDefinition(XcodeProgram xcodeml,
Xnode fctCall)
{
if(xcodeml.getElement() == null){
return null;
}
String name = fctCall.findNode(Xcode.NAME).getValue();
NodeList nList = xcodeml.getElement().
getElementsByTagName(Xname.F_FUNCTION_DEFINITION);
for (int i = 0; i < nList.getLength(); i++) {
Node fctDefNode = nList.item(i);
if (fctDefNode.getNodeType() == Node.ELEMENT_NODE) {
Xnode dummyFctDef = new Xnode((Element)fctDefNode);
Xnode fctDefName = dummyFctDef.find(Xcode.NAME);
if(name != null &&
fctDefName.getValue().toLowerCase().equals(name.toLowerCase()))
{
return new XfunctionDefinition(dummyFctDef.getElement());
}
}
}
return null;
}
/**
* Find a function definition in a module definition.
* @param module Module definition in which we search for the function
* definition.
* @param name Name of the function to be found.
* @return A function definition element if found. Null otherwise.
*/
public static XfunctionDefinition findFunctionDefinitionInModule(
XmoduleDefinition module, String name)
{
if(module.getElement() == null){
return null;
}
NodeList nList = module.getElement().
getElementsByTagName(Xname.F_FUNCTION_DEFINITION);
for (int i = 0; i < nList.getLength(); i++) {
Node n = nList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
XfunctionDefinition fctDef = new XfunctionDefinition((Element)n);
if(fctDef.getName().getValue().equals(name)){
return fctDef;
}
}
}
return null;
}
/**
* Find all array references elements in a given body and give var name.
* @param parent The body element to search for the array references.
* @param arrayName Name of the array for the array reference to be found.
* @return A list of all array references found.
*/
public static List<Xnode> getAllArrayReferences(Xnode parent,
String arrayName)
{
List<Xnode> references = new ArrayList<>();
NodeList nList = parent.getElement().
getElementsByTagName(Xname.F_ARRAY_REF);
for (int i = 0; i < nList.getLength(); i++) {
Node n = nList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Xnode ref = new Xnode((Element) n);
Xnode var = ref.find(Xcode.VARREF, Xcode.VAR);
if(var != null && var.getValue().toLowerCase().
equals(arrayName.toLowerCase()))
{
references.add(ref);
}
}
}
return references;
}
/**
* Demote an array reference to a var reference.
* @param ref The array reference to be modified.
*/
public static void demoteToScalar(Xnode ref){
Xnode var = ref.find(Xcode.VARREF, Xcode.VAR).cloneObject();
insertAfter(ref, var);
ref.delete();
}
/**
* Demote an array reference to a reference with fewer dimensions.
* @param ref The array reference to be modified.
* @param keptDimensions List of dimensions to be kept. Dimension index starts
* at 1.
*/
public static void demote(Xnode ref, List<Integer> keptDimensions){
for(int i = 1; i < ref.getChildren().size(); ++i){
if(!keptDimensions.contains(i)){
ref.getChild(i).delete();
}
}
}
/**
* Retrieve the index ranges of an array notation.
* @param arrayRef The array reference statements to extract the ranges from.
* @return A list if indexRanges elements.
*/
public static List<Xnode> getIdxRangesFromArrayRef(Xnode arrayRef){
List<Xnode> ranges = new ArrayList<>();
if(arrayRef.Opcode() != Xcode.FARRAYREF){
return ranges;
}
for(Xnode el : arrayRef.getChildren()){
if(el.Opcode() == Xcode.INDEXRANGE){
ranges.add(el);
}
}
return ranges;
}
/**
* Compare two list of indexRange.
* @param list1 First list of indexRange.
* @param list2 Second list of indexRange.
* @return True if the indexRange at the same position in the two list are all
* identical. False otherwise.
*/
public static boolean compareIndexRanges(List<Xnode> list1,
List<Xnode> list2)
{
if(list1.size() != list2.size()){
return false;
}
for(int i = 0; i < list1.size(); ++i){
if(!isIndexRangeIdentical(list1.get(i), list2.get(i), true)){
return false;
}
}
return true;
}
/**
* <pre>
* Intersect two sets of elements in XPath 1.0
*
* This method use Xpath to select the correct nodes. Xpath 1.0 does not have
* the intersect operator but only union. By using the Kaysian Method, we can
* it is possible to express the intersection of two node sets.
*
* $set1[count(.|$set2)=count($set2)]
*
* </pre>
* @param s1 First set of element.
* @param s2 Second set of element.
* @return Xpath query that performs the intersect operator between s1 and s2.
*/
private static String xPathIntersect(String s1, String s2){
return String.format("%s[count(.|%s)=count(%s)]", s1, s2, s2);
}
/**
* <pre>
* Find all assignment statement from a node until the end pragma.
*
* We intersect all assign statements which are next siblings of
* the "from" element with all the assign statements which are previous
* siblings of the ending pragma.
* </pre>
*
* @param from The element from which the search is initiated.
* @param endPragma Value of the end pragma. Search will be performed until
* there.
* @return A list of all assign statements found. List is empty if no
* statements are found.
*/
public static List<Xnode> getArrayAssignInBlock(Xnode from, String endPragma){
/* Define all the assign element with array refs which are next siblings of
* the "from" element */
String s1 = String.format(
"following-sibling::%s[%s]",
Xname.F_ASSIGN_STMT,
Xname.F_ARRAY_REF
);
/* Define all the assign element with array refs which are previous siblings
* of the end pragma element */
String s2 = String.format(
"following-sibling::%s[text()=\"%s\"]/preceding-sibling::%s[%s]",
Xname.PRAGMA_STMT,
endPragma,
Xname.F_ASSIGN_STMT,
Xname.F_ARRAY_REF
);
// Use the Kaysian method to express the intersect operator
String intersect = XnodeUtil.xPathIntersect(s1, s2);
return getFromXpath(from, intersect);
}
/**
* Get all array references in the siblings of the given element.
* @param from Element to start from.
* @param identifier Array name value.
* @return List of all array references found. List is empty if nothing is
* found.
*/
public static List<Xnode> getAllArrayReferencesInSiblings(Xnode from,
String identifier)
{
String s1 = String.format("following-sibling::*//%s[%s[%s[text()=\"%s\"]]]",
Xname.F_ARRAY_REF,
Xname.VAR_REF,
Xname.VAR,
identifier
);
return getFromXpath(from, s1);
}
/**
* Get the first assignment statement for an array reference.
* @param from Statement to look from.
* @param arrayName Identifier of the array.
* @return The assignment statement if found. Null otherwise.
*/
public static Xnode getFirstArrayAssign(Xnode from, String arrayName){
String s1 = String.format(
"following::%s[%s[%s[%s[text()=\"%s\"]] and position()=1]]",
Xname.F_ASSIGN_STMT,
Xname.F_ARRAY_REF,
Xname.VAR_REF,
Xname.VAR,
arrayName
);
try {
NodeList output = evaluateXpath(from.getElement(), s1);
if(output.getLength() == 0){
return null;
}
Element assign = (Element) output.item(0);
return new Xnode(assign);
} catch (XPathExpressionException ignored) {
return null;
}
}
/**
* Find all the nested do statement groups following the inductions iterations
* define in inductionVars and being located between the "from" element and
* the end pragma.
* @param from Element from which the search is started.
* @param endPragma End pragma that terminates the search block.
* @param inductionVars Induction variables that define the nested group to
* locates.
* @return List of do statements elements (outer most loops for each nested
* group) found between the "from" element and the end pragma.
*/
public static List<Xnode> findDoStatement(Xnode from, Xnode endPragma,
List<String> inductionVars)
{
/* s1 is selecting all the nested do statement groups that meet the criteria
* from the "from" element down to the end of the block. */
String s1 = "following::";
String dynamic_part_s1 = "";
for(int i = inductionVars.size() - 1; i >= 0; --i){
/*
* Here is example of there xpath query format for 1,2 and 3 nested loops
*
* FdoStatement[Var[text()="induction_var"]]
*
* FdoStatement[Var[text()="induction_var"] and
* body[FdoStatement[Var[text()="induction_var"]]]
*
* FdoStatement[Var[text()="induction_var"] and
* body[FdoStatement[Var[text()="induction_var"] and
* body[FdoStatement[Var[text()="induction_var"]]]]
*/
String tempQuery;
if(i == inductionVars.size() - 1) { // first iteration
tempQuery = String.format("%s[%s[text()=\"%s\"]]",
Xname.F_DO_STATEMENT,
Xname.VAR,
inductionVars.get(i));
} else {
tempQuery = String.format("%s[%s[text()=\"%s\"] and %s[%s]]",
Xname.F_DO_STATEMENT,
Xname.VAR,
inductionVars.get(i),
Xname.BODY,
dynamic_part_s1); // Including previously formed xpath query
}
dynamic_part_s1 = tempQuery;
}
s1 = s1 + dynamic_part_s1;
List<Xnode> doStatements = new ArrayList<>();
try {
NodeList output = evaluateXpath(from.getElement(), s1);
for (int i = 0; i < output.getLength(); i++) {
Element el = (Element) output.item(i);
Xnode doStmt = new Xnode(el);
if(doStmt.getLineNo() != 0 &&
doStmt.getLineNo() < endPragma.getLineNo())
{
doStatements.add(doStmt);
}
}
} catch (XPathExpressionException ignored) {
}
return doStatements;
}
/**
* Evaluates an Xpath expression and return its result as a NodeList.
* @param from Element to start the evaluation.
* @param xpath Xpath expression.
* @return Result of evaluation as a NodeList.
* @throws XPathExpressionException if evaluation fails.
*/
private static NodeList evaluateXpath(Element from, String xpath)
throws XPathExpressionException
{
XPathExpression ex = XPathFactory.newInstance().newXPath().compile(xpath);
return (NodeList)ex.evaluate(from, XPathConstants.NODESET);
}
/**
* Find all array references in the next children that match the given
* criteria.
*
* This methods use powerful Xpath expression to locate the correct nodes in
* the AST
*
* Here is an example of such a query that return all node that are array
* references for the array "array6" with an offset of 0 -1
*
* //FarrayRef[varRef[Var[text()="array6"]] and arrayIndex and
* arrayIndex[minusExpr[Var and FintConstant[text()="1"]]]]
*
* @param from The element from which the search is initiated.
* @param identifier Identifier of the array.
* @param offsets List of offsets to be search for.
* @return A list of all array references found.
*/
public static List<Xnode> getAllArrayReferencesByOffsets(Xnode from,
String identifier, List<Integer> offsets)
{
String offsetXpath = "";
for (int i = 0; i < offsets.size(); ++i){
if(offsets.get(i) == 0){
offsetXpath +=
String.format("%s[position()=%s and %s]",
Xname.ARRAY_INDEX,
i+1,
Xname.VAR
);
} else if(offsets.get(i) > 0) {
offsetXpath +=
String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]",
Xname.ARRAY_INDEX,
i+1,
Xname.MINUS_EXPR,
Xname.VAR,
Xname.F_INT_CONST,
offsets.get(i));
} else {
offsetXpath +=
String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]",
Xname.ARRAY_INDEX,
i+1,
Xname.MINUS_EXPR,
Xname.VAR,
Xname.F_INT_CONST,
Math.abs(offsets.get(i)));
}
if(i != offsets.size()-1){
offsetXpath += " and ";
}
}
// Start of the Xpath query
String xpathQuery = String.format(".//%s[%s[%s[text()=\"%s\"]] and %s]",
Xname.F_ARRAY_REF,
Xname.VAR_REF,
Xname.VAR,
identifier,
offsetXpath
);
return getFromXpath(from, xpathQuery);
}
/**
* Find a pragma element in the previous nodes containing a given keyword.
* @param from Element to start from.
* @param keyword Keyword to be found in the pragma.
* @return The pragma if found. Null otherwise.
*/
public static Xnode findPreviousPragma(Xnode from, String keyword) {
if (from == null || from.getElement() == null) {
return null;
}
Node prev = from.getElement().getPreviousSibling();
Node parent = from.getElement();
do {
while (prev != null) {
if (prev.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) prev;
if (element.getTagName().equals(Xcode.FPRAGMASTATEMENT.code())
&& element.getTextContent().toLowerCase().
contains(keyword.toLowerCase())) {
return new Xnode(element);
}
}
prev = prev.getPreviousSibling();
}
parent = parent.getParentNode();
prev = parent;
} while (parent != null);
return null;
}
/**
* Find all the index elements (arrayIndex and indexRange) in an element.
* @param parent Root element to search from.
* @return A list of all index ranges found.
*/
public static List<Xnode> findIndexes(Xnode parent){
List<Xnode> indexRanges = new ArrayList<>();
if(parent == null || parent.getElement() == null){
return indexRanges;
}
Node node = parent.getElement().getFirstChild();
while (node != null){
if(node.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element)node;
switch (element.getTagName()){
case Xname.ARRAY_INDEX:
case Xname.INDEX_RANGE:
indexRanges.add(new Xnode(element));
break;
}
}
node = node.getNextSibling();
}
return indexRanges;
}
/**
* Find all the name elements in an element.
* @param parent Root element to search from.
* @return A list of all name elements found.
*/
public static List<Xnode> findAllNames(Xnode parent){
return findAll(Xcode.NAME, parent);
}
/**
* Find all the var elements that are real references to a variable. Var
* element nested in an arrayIndex element are excluded.
* @param parent Root element to search from.
* @return A list of all var elements found.
*/
public static List<Xnode> findAllReferences(Xnode parent){
List<Xnode> vars = findAll(Xcode.VAR, parent);
List<Xnode> realReferences = new ArrayList<>();
for(Xnode var : vars){
if(!((Element)var.getElement().getParentNode()).getTagName().
equals(Xcode.ARRAYINDEX.code()))
{
realReferences.add(var);
}
}
return realReferences;
}
/**
* Find all the var elements that are real references to a variable. Var
* element nested in an arrayIndex element are excluded.
* @param parent Root element to search from.
* @param id Identifier of the var to be found.
* @return A list of all var elements found.
*/
public static List<Xnode> findAllReferences(Xnode parent, String id){
List<Xnode> vars = findAll(Xcode.VAR, parent);
List<Xnode> realReferences = new ArrayList<>();
for(Xnode var : vars){
if(!((Element)var.getElement().getParentNode()).getTagName().
equals(Xcode.ARRAYINDEX.code())
&& var.getValue().toLowerCase().equals(id.toLowerCase()))
{
realReferences.add(var);
}
}
return realReferences;
}
/**
* Find all the pragma element in an XcodeML tree.
* @param xcodeml The XcodeML program to search in.
* @return A list of all pragmas found in the XcodeML program.
*/
public static List<Xnode> findAllPragmas(XcodeProgram xcodeml){
NodeList pragmaList = xcodeml.getDocument()
.getElementsByTagName(Xcode.FPRAGMASTATEMENT.code());
List<Xnode> pragmas = new ArrayList<>();
for (int i = 0; i < pragmaList.getLength(); i++) {
Node pragmaNode = pragmaList.item(i);
if (pragmaNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) pragmaNode;
pragmas.add(new Xnode(element));
}
}
return pragmas;
}
/**
* Extract the body of a do statement and place it directly after it.
* @param loop The do statement containing the body to be extracted.
*/
public static void extractBody(Xnode loop){
extractBody(loop, loop);
}
/**
* Extract the body of a do statement and place it after the reference node.
* @param loop The do statement containing the body to be extracted.
* @param ref Element after which statement are shifted.
*/
public static void extractBody(Xnode loop, Xnode ref){
Element loopElement = loop.getElement();
Element body = XnodeUtil.findFirstElement(loopElement,
Xname.BODY);
if(body == null){
return;
}
Node refNode = ref.getElement();
for(Node childNode = body.getFirstChild(); childNode!=null;){
Node nextChild = childNode.getNextSibling();
// Do something with childNode, including move or delete...
if(childNode.getNodeType() == Node.ELEMENT_NODE){
insertAfter(refNode, childNode);
refNode = childNode;
}
childNode = nextChild;
}
}
/**
* Delete an element for the tree.
* @param element Element to be deleted.
*/
public static void delete(Element element){
if(element == null || element.getParentNode() == null){
return;
}
element.getParentNode().removeChild(element);
}
public static boolean writeXcodeML(XcodeML xcodeml, String outputFile,
int indent)
throws IllegalTransformationException
{
try {
XnodeUtil.cleanEmptyTextNodes(xcodeml.getDocument());
Transformer transformer
= TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount",
Integer.toString(indent));
DOMSource source = new DOMSource(xcodeml.getDocument());
if(outputFile == null){
// Output to console
StreamResult console = new StreamResult(System.out);
transformer.transform(source, console);
} else {
// Output to file
StreamResult console = new StreamResult(new File(outputFile));
transformer.transform(source, console);
}
} catch (Exception ignored){
throw new IllegalTransformationException("Cannot output file: " +
outputFile, 0);
}
return true;
}
/**
* Removes text nodes that only contains whitespace. The conditions for
* removing text nodes, besides only containing whitespace, are: If the
* parent node has at least one child of any of the following types, all
* whitespace-only text-node children will be removed: - ELEMENT child -
* CDATA child - COMMENT child.
* @param parentNode Root node to start the cleaning.
*/
private static void cleanEmptyTextNodes(Node parentNode) {
boolean removeEmptyTextNodes = false;
Node childNode = parentNode.getFirstChild();
while (childNode != null) {
removeEmptyTextNodes |= checkNodeTypes(childNode);
childNode = childNode.getNextSibling();
}
if (removeEmptyTextNodes) {
removeEmptyTextNodes(parentNode);
}
}
/*
* PRIVATE SECTION
*/
/**
* Remove all empty text nodes in the subtree.
* @param parentNode Root node to start the search.
*/
private static void removeEmptyTextNodes(Node parentNode) {
Node childNode = parentNode.getFirstChild();
while (childNode != null) {
// grab the "nextSibling" before the child node is removed
Node nextChild = childNode.getNextSibling();
short nodeType = childNode.getNodeType();
if (nodeType == Node.TEXT_NODE) {
boolean containsOnlyWhitespace = childNode.getNodeValue()
.trim().isEmpty();
if (containsOnlyWhitespace) {
parentNode.removeChild(childNode);
}
}
childNode = nextChild;
}
}
/**
* Check the type of the given node.
* @param childNode Node to be checked.
* @return True if the node contains data. False otherwise.
*/
private static boolean checkNodeTypes(Node childNode) {
short nodeType = childNode.getNodeType();
if (nodeType == Node.ELEMENT_NODE) {
cleanEmptyTextNodes(childNode); // recurse into subtree
}
return nodeType == Node.ELEMENT_NODE || nodeType == Node.CDATA_SECTION_NODE
|| nodeType == Node.COMMENT_NODE;
}
/**
* Insert a node directly after a reference node.
* @param refNode The reference node. New node will be inserted after this
* one.
* @param newNode The new node to be inserted.
*/
private static void insertAfter(Node refNode, Node newNode){
refNode.getParentNode().insertBefore(newNode, refNode.getNextSibling());
}
/**
* Find the first element with tag corresponding to elementName nested under
* the parent element.
* @param parent The root element to search from.
* @param elementName The tag of the element to search for.
* @return The first element found under parent with the corresponding tag.
* Null if no element is found.
*/
private static Element findFirstElement(Element parent, String elementName){
NodeList elements = parent.getElementsByTagName(elementName);
if(elements.getLength() == 0){
return null;
}
return (Element) elements.item(0);
}
/**
* Find the first element with tag corresponding to elementName in the direct
* children of the parent element.
* @param parent The root element to search from.
* @param elementName The tag of the element to search for.
* @return The first element found in the direct children of the element
* parent with the corresponding tag. Null if no element is found.
*/
private static Element findFirstChildElement(Element parent, String elementName){
NodeList nodeList = parent.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node nextNode = nodeList.item(i);
if(nextNode.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) nextNode;
if(element.getTagName().equals(elementName)){
return element;
}
}
}
return null;
}
/**
* Get the depth of an element in the AST.
* @param element XML element for which the depth is computed.
* @return A depth value greater or equal to 0.
*/
private static int getDepth(Element element){
Node parent = element.getParentNode();
int depth = 0;
while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
++depth;
parent = parent.getParentNode();
}
return depth;
}
/**
* Shift all statements from the first siblings of the "from" element until
* the "until" element (not included).
* @param from Start element for the swifting.
* @param until End element for the swifting.
* @param targetBody Body element in which statements are inserted.
*/
public static void shiftStatementsInBody(Xnode from,
Xnode until, Xnode targetBody)
{
Node currentSibling = from.getElement().getNextSibling();
Node firstStatementInBody = targetBody.getElement().getFirstChild();
while(currentSibling != null && currentSibling != until.getElement()){
Node nextSibling = currentSibling.getNextSibling();
targetBody.getElement().insertBefore(currentSibling,
firstStatementInBody);
currentSibling = nextSibling;
}
}
/**
* Copy the whole body element into the destination one. Destination is
* overwritten.
* @param from The body to be copied.
* @param to The destination of the copied body.
*/
public static void copyBody(Xnode from, Xnode to){
Node copiedBody = from.cloneNode();
if(to.getBody() != null){
to.getBody().delete();
}
to.getElement().appendChild(copiedBody);
}
/**
* Check whether the given type is a built-in type or is a type defined in the
* type table.
* @param type Type to check.
* @return True if the type is built-in. False otherwise.
*/
public static boolean isBuiltInType(String type){
switch (type){
case Xname.TYPE_F_CHAR:
case Xname.TYPE_F_COMPLEX:
case Xname.TYPE_F_INT:
case Xname.TYPE_F_LOGICAL:
case Xname.TYPE_F_REAL:
case Xname.TYPE_F_VOID:
return true;
default:
return false;
}
}
/* XNODE SECTION */
/**
* Find module definition element in which the child is included if any.
* @param from The child element to search from.
* @return A XmoduleDefinition object if found. Null otherwise.
*/
public static XmoduleDefinition findParentModule(Xnode from) {
Xnode moduleDef = findParent(Xcode.FMODULEDEFINITION, from);
if(moduleDef == null){
return null;
}
return new XmoduleDefinition(moduleDef.getElement());
}
/**
* Find function definition in the ancestor of the give element.
* @param from Element to start search from.
* @return The function definition found. Null if nothing found.
*/
public static XfunctionDefinition findParentFunction(Xnode from){
Xnode fctDef = findParent(Xcode.FFUNCTIONDEFINITION, from);
if(fctDef == null){
return null;
}
return new XfunctionDefinition(fctDef.getElement());
}
/**
* Find element of the the given type that is directly after the given from
* element.
* @param opcode Code of the element to be found.
* @param from Element to start the search from.
* @return The element found. Null if no element is found.
*/
public static Xnode findDirectNext(Xcode opcode, Xnode from) {
if(from == null){
return null;
}
Node nextNode = from.getElement().getNextSibling();
while (nextNode != null){
if(nextNode.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) nextNode;
if(element.getTagName().equals(opcode.code())){
return new Xnode(element);
}
return null;
}
nextNode = nextNode.getNextSibling();
}
return null;
}
/**
* Delete all the elements between the two given elements.
* @param start The start element. Deletion start from next element.
* @param end The end element. Deletion end just before this element.
*/
public static void deleteBetween(Xnode start, Xnode end){
List<Element> toDelete = new ArrayList<>();
Node node = start.getElement().getNextSibling();
while (node != null && node != end.getElement()){
if(node.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element)node;
toDelete.add(element);
}
node = node.getNextSibling();
}
for(Element e : toDelete){
delete(e);
}
}
/**
* Insert an element just after a reference element.
* @param refElement The reference element.
* @param element The element to be inserted.
*/
public static void insertAfter(Xnode refElement, Xnode element){
XnodeUtil.insertAfter(refElement.getElement(), element.getElement());
}
/**
* Find the first element with tag corresponding to elementName.
* @param opcode The XcodeML code of the element to search for.
* @param parent The root element to search from.
* @param any If true, find in any nested element under parent. If false,
* only direct children are search for.
* @return first element found. Null if no element is found.
*/
public static Xnode find(Xcode opcode, Xnode parent, boolean any){
Element el;
if(any){
el = findFirstElement(parent.getElement(), opcode.code());
} else {
el = findFirstChildElement(parent.getElement(), opcode.code());
}
return (el == null) ? null : new Xnode(el);
}
/**
* Find element of the the given type that is directly after the given from
* element.
* @param opcode Code of the element to be found.
* @param from Element to start the search from.
* @return The element found. Null if no element is found.
*/
public static Xnode findNext(Xcode opcode, Xnode from) {
return findInDirection(opcode, from, true);
}
/**
* Find an element in the ancestor of the given element.
* @param opcode Code of the element to be found.
* @param from Element to start the search from.
* @return The element found. Null if nothing found.
*/
public static Xnode findParent(Xcode opcode, Xnode from){
return findInDirection(opcode, from, false);
}
/**
* Find an element either in the next siblings or in the ancestors.
* @param opcode Code of the element to be found.
* @param from Element to start the search from.
* @param down If True, search in the siblings. If false, search in the
* ancestors.
* @return The element found. Null if nothing found.
*/
private static Xnode findInDirection(Xcode opcode, Xnode from, boolean down){
if(from == null){
return null;
}
Node nextNode = down ? from.getElement().getNextSibling() :
from.getElement().getParentNode();
while(nextNode != null){
if (nextNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nextNode;
if(element.getTagName().equals(opcode.code())){
return new Xnode(element);
}
}
nextNode = down ? nextNode.getNextSibling() : nextNode.getParentNode();
}
return null;
}
public static void appendBody(Xnode originalBody, Xnode extraBody)
throws IllegalTransformationException
{
if(originalBody == null || originalBody.getElement() == null
|| extraBody == null || extraBody.getElement() == null
|| originalBody.Opcode() != Xcode.BODY
|| extraBody.Opcode() != Xcode.BODY)
{
throw new IllegalTransformationException("One of the body is null.");
}
// Append content of loop-body (loop) to this loop-body
Node childNode = extraBody.getElement().getFirstChild();
while(childNode != null){
Node nextChild = childNode.getNextSibling();
// Do something with childNode, including move or delete...
if(childNode.getNodeType() == Node.ELEMENT_NODE){
originalBody.getElement().appendChild(childNode);
}
childNode = nextChild;
}
}
/**
* Check if the two element are direct children of the same parent element.
* @param e1 First element.
* @param e2 Second element.
* @return True if the two element are direct children of the same parent.
* False otherwise.
*/
public static boolean hasSameParentBlock(Xnode e1, Xnode e2) {
return !(e1 == null || e2 == null || e1.getElement() == null
|| e2.getElement() == null)
&& e1.getElement().getParentNode() ==
e2.getElement().getParentNode();
}
/**
Compare the iteration range of two do statements.
* @param e1 First do statement.
* @param e2 Second do statement.
* @param withLowerBound Compare lower bound or not.
* @return True if the iteration range are identical.
*/
private static boolean compareIndexRanges(Xnode e1, Xnode e2,
boolean withLowerBound)
{
// The two nodes must be do statement
if (e1.Opcode() != Xcode.FDOSTATEMENT || e2.Opcode() != Xcode.FDOSTATEMENT) {
return false;
}
Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false);
Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false);
Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false);
Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false);
return compareValues(inductionVar1, inductionVar2) &&
isIndexRangeIdentical(indexRange1, indexRange2, withLowerBound);
}
/**
* Compare the iteration range of two do statements.
* @param e1 First do statement.
* @param e2 Second do statement.
* @return True if the iteration range are identical.
*/
public static boolean hasSameIndexRange(Xnode e1, Xnode e2) {
return compareIndexRanges(e1, e2, true);
}
/**
* Compare the iteration range of two do statements.
* @param e1 First do statement.
* @param e2 Second do statement.
* @return True if the iteration range are identical besides the lower bound.
*/
public static boolean hasSameIndexRangeBesidesLower(Xnode e1, Xnode e2) {
return compareIndexRanges(e1, e2, false);
}
/**
* Compare the inner values of two nodes.
* @param n1 First node.
* @param n2 Second node.
* @return True if the values are identical. False otherwise.
*/
private static boolean compareValues(Xnode n1, Xnode n2) {
return !(n1 == null || n2 == null)
&& n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase());
}
/**
* Compare the inner value of the first child of two nodes.
* @param n1 First node.
* @param n2 Second node.
* @return True if the value are identical. False otherwise.
*/
private static boolean compareFirstChildValues(Xnode n1, Xnode n2) {
if(n1 == null || n2 == null){
return false;
}
Xnode c1 = n1.getChild(0);
Xnode c2 = n2.getChild(0);
return compareValues(c1, c2);
}
/**
* Compare the inner values of two optional nodes.
* @param n1 First node.
* @param n2 Second node.
* @return True if the values are identical or elements are null. False
* otherwise.
*/
private static boolean compareOptionalValues(Xnode n1, Xnode n2){
return n1 == null && n2 == null || (n1 != null && n2 != null &&
n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase()));
}
/**
* Compare the iteration range of two do statements
* @param idx1 First do statement.
* @param idx2 Second do statement.
* @param withLowerBound If true, compare lower bound. If false, lower bound
* is not compared.
* @return True if the index range are identical.
*/
private static boolean isIndexRangeIdentical(Xnode idx1, Xnode idx2,
boolean withLowerBound)
{
if (idx1.Opcode() != Xcode.INDEXRANGE || idx2.Opcode() != Xcode.INDEXRANGE) {
return false;
}
if (idx1.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE) &&
idx2.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)) {
return true;
}
Xnode low1 = idx1.find(Xcode.LOWERBOUND);
Xnode up1 = idx1.find(Xcode.UPPERBOUND);
Xnode low2 = idx2.find(Xcode.LOWERBOUND);
Xnode up2 = idx2.find(Xcode.UPPERBOUND);
Xnode s1 = idx1.find(Xcode.STEP);
Xnode s2 = idx2.find(Xcode.STEP);
if (s1 != null) {
s1 = s1.getChild(0);
}
if (s2 != null) {
s2 = s2.getChild(0);
}
if(withLowerBound){
return compareFirstChildValues(low1, low2) &&
compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2);
} else {
return compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2);
}
}
public static void swapIterationRange(Xnode e1, Xnode e2)
throws IllegalTransformationException
{
// The two nodes must be do statement
if(e1.Opcode() != Xcode.FDOSTATEMENT || e2.Opcode() != Xcode.FDOSTATEMENT){
return;
}
Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false);
Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false);
Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false);
Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false);
if(inductionVar1 == null || inductionVar2 == null ||
indexRange1 == null || indexRange2 == null)
{
throw new IllegalTransformationException("Induction variable or index " +
"range missing.");
}
Xnode low1 = indexRange1.find(Xcode.LOWERBOUND).getChild(0);
Xnode up1 = indexRange1.find(Xcode.UPPERBOUND).getChild(0);
Xnode s1 = indexRange1.find(Xcode.STEP).getChild(0);
Xnode low2 = indexRange2.find(Xcode.LOWERBOUND).getChild(0);
Xnode up2 = indexRange2.find(Xcode.UPPERBOUND).getChild(0);
Xnode s2 = indexRange2.find(Xcode.STEP).getChild(0);
// Set the range of loop2 to loop1
XnodeUtil.insertAfter(inductionVar2, inductionVar1.cloneObject());
XnodeUtil.insertAfter(low2, low1.cloneObject());
XnodeUtil.insertAfter(up2, up1.cloneObject());
XnodeUtil.insertAfter(s2, s1.cloneObject());
XnodeUtil.insertAfter(inductionVar1, inductionVar2.cloneObject());
XnodeUtil.insertAfter(low1, low2.cloneObject());
XnodeUtil.insertAfter(up1, up2.cloneObject());
XnodeUtil.insertAfter(s1, s2.cloneObject());
inductionVar1.delete();
inductionVar2.delete();
low1.delete();
up1.delete();
s1.delete();
low2.delete();
up2.delete();
s2.delete();
}
/**
* Get the depth of an element in the AST.
* @param element The element for which the depth is computed.
* @return A depth value greater or equal to 0.
*/
public static int getDepth(Xnode element) {
if(element == null || element.getElement() == null){
return -1;
}
return getDepth(element.getElement());
}
/**
* Copy the enhanced information from an element to a target element.
* Enhanced information include line number and original file name.
* @param base Base element to copy information from.
* @param target Target element to copy information to.
*/
public static void copyEnhancedInfo(Xnode base, Xnode target) {
target.setLine(base.getLineNo());
target.setFile(base.getFile());
}
/**
* Insert an element just before a reference element.
* @param ref The reference element.
* @param insert The element to be inserted.
*/
public static void insertBefore(Xnode ref, Xnode insert){
ref.getElement().getParentNode().insertBefore(insert.getElement(),
ref.getElement());
}
/**
* Get a list of T elements from an xpath query executed from the
* given element.
* @param from Element to start from.
* @param query XPath query to be executed.
* @return List of all array references found. List is empty if nothing is
* found.
*/
private static List<Xnode> getFromXpath(Xnode from, String query)
{
List<Xnode> elements = new ArrayList<>();
try {
XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query);
NodeList output = (NodeList) ex.evaluate(from.getElement(),
XPathConstants.NODESET);
for (int i = 0; i < output.getLength(); i++) {
Element element = (Element) output.item(i);
elements.add(new Xnode(element));
}
} catch (XPathExpressionException ignored) {
}
return elements;
}
/**
* Find specific argument in a function call.
* @param value Value of the argument to be found.
* @param fctCall Function call to search from.
* @return The argument if found. Null otherwise.
*/
public static Xnode findArg(String value, Xnode fctCall){
if(fctCall.Opcode() != Xcode.FUNCTIONCALL) {
return null;
}
Xnode args = fctCall.find(Xcode.ARGUMENTS);
if(args == null){
return null;
}
for(Xnode arg : args.getChildren()){
if(value.toLowerCase().equals(arg.getValue().toLowerCase())){
return arg;
}
}
return null;
}
/**
* Find all elements of a given type in the subtree.
* @param opcode Type of the element to be found.
* @param parent Root of the subtree.
* @return List of all elements found in the subtree.
*/
public static List<Xnode> findAll(Xcode opcode, Xnode parent) {
List<Xnode> elements = new ArrayList<>();
if(parent == null) {
return elements;
}
NodeList nodes = parent.getElement().getElementsByTagName(opcode.code());
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
elements.add(new Xnode((Element)n));
}
}
return elements;
}
/**
* Create a new FunctionCall element with elements name and arguments as
* children.
* @param xcodeml The current XcodeML program unit in which the elements
* are created.
* @param returnType Value of the type attribute for the functionCall element.
* @param name Value of the name element.
* @param nameType Value of the type attribute for the name element.
* @return The newly created element.
*/
public static Xnode createFctCall(XcodeProgram xcodeml, String returnType,
String name, String nameType){
Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml);
fctCall.setAttribute(Xattr.TYPE, returnType);
Xnode fctName = new Xnode(Xcode.NAME, xcodeml);
fctName.setValue(name);
fctName.setAttribute(Xattr.TYPE, nameType);
Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml);
fctCall.appendToChildren(fctName, false);
fctCall.appendToChildren(args, false);
return fctCall;
}
/**
* Create a new FarrayRef element with varRef element as a child with the
* given Var element.
* @param xcodeml The current XcodeML program unit in which the elements
* are created.
* @param type Value of the type attribute for the FarrayRef element.
* @param var Var element nested in the varRef element.
* @return The newly created element.
*/
public static Xnode createArrayRef(XcodeProgram xcodeml, XbasicType type,
Xnode var)
{
Xnode ref = new Xnode(Xcode.FARRAYREF, xcodeml);
ref.setAttribute(Xattr.TYPE, type.getRef());
Xnode varRef = new Xnode(Xcode.VARREF, xcodeml);
varRef.setAttribute(Xattr.TYPE, type.getType());
varRef.appendToChildren(var, false);
ref.appendToChildren(varRef, false);
return ref;
}
/**
* Create a new Id element with all the underlying needed elements.
* @param xcodeml The current XcodeML program unit in which the elements
* are created.
* @param type Value for the attribute type.
* @param sclass Value for the attribute sclass.
* @param nameValue Value of the name inner element.
* @return The newly created element.
*/
public static Xid createId(XcodeProgram xcodeml, String type, String sclass,
String nameValue)
{
Xnode id = new Xnode(Xcode.ID, xcodeml);
Xnode internalName = new Xnode(Xcode.NAME, xcodeml);
internalName.setValue(nameValue);
id.appendToChildren(internalName, false);
id.setAttribute(Xattr.TYPE, type);
id.setAttribute(Xattr.SCLASS, sclass);
return new Xid(id.getElement());
}
/**
* Constructs a new basicType element with the given information.
* @param xcodeml The current XcodeML file unit in which the elements
* are created.
* @param type Type hash.
* @param ref Reference type.
* @param intent Optional intent information.
* @return The newly created element.
*/
public static XbasicType createBasicType(XcodeML xcodeml, String type,
String ref, Xintent intent)
{
Xnode bt = new Xnode(Xcode.FBASICTYPE, xcodeml);
bt.setAttribute(Xattr.TYPE, type);
if(ref != null) {
bt.setAttribute(Xattr.REF, ref);
}
if(intent != null) {
bt.setAttribute(Xattr.INTENT, intent.toString());
}
return new XbasicType(bt.getElement());
}
/**
* Create a new XvarDecl object with all the underlying elements.
* @param xcodeml The current XcodeML file unit in which the elements
* are created.
* @param nameType Value for the attribute type of the name element.
* @param nameValue Value of the name inner element.
* @return The newly created element.
*/
public static XvarDecl createVarDecl(XcodeML xcodeml, String nameType,
String nameValue)
{
Xnode varD = new Xnode(Xcode.VARDECL, xcodeml);
Xnode internalName = new Xnode(Xcode.NAME, xcodeml);
internalName.setValue(nameValue);
internalName.setAttribute(Xattr.TYPE, nameType);
varD.appendToChildren(internalName, false);
return new XvarDecl(varD.getElement());
}
/**
* Constructs a new name element with name value and optional type.
* @param xcodeml Current XcodeML file unit in which the element is
* created.
* @param name Name value.
* @param type Optional type value.
* @return The newly created element.
*/
public static Xnode createName(XcodeML xcodeml, String name, String type)
{
Xnode n = new Xnode(Xcode.NAME, xcodeml);
n.setValue(name);
if(type != null){
n.setAttribute(Xattr.TYPE, type);
}
return n;
}
/**
* Create an empty assumed shape indexRange element.
* @param xcodeml Current XcodeML file unit in which the element is
* created.
* @return The newly created element.
*/
public static Xnode createEmptyAssumedShaped(XcodeML xcodeml) {
Xnode range = new Xnode(Xcode.INDEXRANGE, xcodeml);
range.setAttribute(Xattr.IS_ASSUMED_SHAPE, Xname.TRUE);
return range;
}
/**
* Create an indexRange element to loop over an assumed shape array.
* @param xcodeml Current XcodeML file unit in which the element is
* created.
* @param arrayVar Var element representing the array variable.
* @param startIndex Lower bound index value.
* @param dimension Dimension index for the upper bound value.
* @return The newly created element.
*/
public static Xnode createAssumedShapeRange(XcodeML xcodeml, Xnode arrayVar,
int startIndex, int dimension)
{
// Base structure
Xnode indexRange = new Xnode(Xcode.INDEXRANGE, xcodeml);
Xnode lower = new Xnode(Xcode.LOWERBOUND, xcodeml);
Xnode upper = new Xnode(Xcode.UPPERBOUND, xcodeml);
indexRange.appendToChildren(lower, false);
indexRange.appendToChildren(upper, false);
// Lower bound
Xnode lowerBound = new Xnode(Xcode.FINTCONSTANT, xcodeml);
lowerBound.setValue(String.valueOf(startIndex));
lower.appendToChildren(lowerBound, false);
// Upper bound
Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml);
upper.appendToChildren(fctCall, false);
fctCall.setAttribute(Xattr.IS_INTRINSIC, Xname.TRUE);
fctCall.setAttribute(Xattr.TYPE, Xname.TYPE_F_INT);
Xnode name = new Xnode(Xcode.NAME, xcodeml);
name.setValue(Xname.INTRINSIC_SIZE);
fctCall.appendToChildren(name, false);
Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml);
fctCall.appendToChildren(args, false);
args.appendToChildren(arrayVar, true);
Xnode dim = new Xnode(Xcode.FINTCONSTANT, xcodeml);
dim.setValue(String.valueOf(dimension));
args.appendToChildren(dim, false);
return indexRange;
}
/**
* Create a new FifStatement element with an empty then body.
* @param xcodeml Current XcodeML file unit in which the element is
* created.
* @return The newly created element.
*/
public static Xnode createIfThen(XcodeML xcodeml){
Xnode root = new Xnode(Xcode.FIFSTATEMENT, xcodeml);
Xnode cond = new Xnode(Xcode.CONDITION, xcodeml);
Xnode thenBlock = new Xnode(Xcode.THEN, xcodeml);
Xnode thenBody = new Xnode(Xcode.BODY, xcodeml);
thenBlock.appendToChildren(thenBody, false);
root.appendToChildren(cond, false);
root.appendToChildren(thenBlock, false);
return root;
}
/**
* Create a new FdoStatement element with an empty body.
* @param xcodeml Current XcodeML file unit in which the element is
* created.
* @param inductionVar Var element for the induction variable.
* @param indexRange indexRange element for the iteration range.
* @return The newly created element.
*/
public static Xnode createDoStmt(XcodeML xcodeml, Xnode inductionVar,
Xnode indexRange)
{
Xnode root = new Xnode(Xcode.FDOSTATEMENT, xcodeml);
root.appendToChildren(inductionVar, false);
root.appendToChildren(indexRange, false);
Xnode body = new Xnode(Xcode.BODY, xcodeml);
root.appendToChildren(body, false);
return root;
}
/**
* Create a new var element.
* @param type Value of the type attribute.
* @param value Value of the var.
* @param scope Value of the scope attribute.
* @param xcodeml Current XcodeML file unit in which the element is created.
* @return The newly created element.
*/
public static Xnode createVar(String type, String value, Xscope scope,
XcodeML xcodeml)
{
Xnode var = new Xnode(Xcode.VAR, xcodeml);
var.setAttribute(Xattr.TYPE, type);
var.setAttribute(Xattr.SCOPE, scope.toString());
var.setValue(value);
return var;
}
/**
* Find module containing the function and read its .xmod file.
* @param fctDef Function definition nested in the module.
* @return Xmod object if the module has been found and read. Null otherwise.
*/
public static Xmod findContainingModule(XfunctionDefinition fctDef){
XmoduleDefinition mod = findParentModule(fctDef);
if(mod == null){
return null;
}
String modName = mod.getAttribute(Xattr.NAME);
for(String dir : XcodeMLtools_Fmod.getSearchPath()){
String path = dir + "/" + modName + XMOD_FILE_EXTENSION;
File f = new File(path);
if(f.exists()){
Document doc = readXmlFile(path);
return doc != null ? new Xmod(doc, modName, dir) : null;
}
}
return null;
}
/**
* Read XML file.
* @param input Xml file path.
* @return Document if the XML file could be read. Null otherwise.
*/
public static Document readXmlFile(String input){
try {
File fXmlFile = new File(input);
if(!fXmlFile.exists()){
return null;
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
return doc;
} catch(Exception ignored){}
return null;
}
/**
* Create the id and varDecl elements and add them to the symbol/declaration
* table.
* @param name Name of the variable.
* @param type Type of the variable.
* @param sclass Scope class of the variable (from Xname).
* @param fctDef Function definition in which id and decl are created.
* @param xcodeml Current XcodeML program unit in which the elements will be
* created.
*/
public static void createIdAndDecl(String name, String type, String sclass,
XfunctionDefinition fctDef,
XcodeProgram xcodeml)
{
Xid id = XnodeUtil.createId(xcodeml, type, sclass, name);
fctDef.getSymbolTable().add(id);
XvarDecl decl = XnodeUtil.createVarDecl(xcodeml, type, name);
fctDef.getDeclarationTable().add(decl);
}
/**
* Create a name element and adds it as a parameter of the given function
* type.
* @param xcodeml Current XcodeML file unit.
* @param nameValue Value of the name element to create.
* @param type Type of the name element to create.
* @param fctType Function type in which the element will be added as a
* parameter.
*/
public static void createAndAddParam(XcodeML xcodeml, String nameValue,
String type, XfunctionType fctType)
{
Xnode param = XnodeUtil.createName(xcodeml, nameValue, type);
fctType.getParams().add(param);
}
/**
* Try to locate a function definition in the current declaration table or
* recursively in the modules' delcaration tables.
* @param dt Declaration table to search in.
* @param fctName Function's name to be found.
* @return The function definition if found. Null otherwise.
*/
public static XfunctionDefinition findFunctionDefinition(XglobalDeclTable dt,
String fctName)
{
Iterator<Map.Entry<String, Xnode>> it = dt.getIterator();
while(it.hasNext()){
Map.Entry<String, Xnode> entry = it.next();
if(entry.getValue() instanceof XmoduleDefinition){
XfunctionDefinition fctDef = findFunctionDefinitionInModule(
(XmoduleDefinition)entry.getValue(), fctName);
if(fctDef != null){
return fctDef;
}
} else if (entry.getValue() instanceof XfunctionDefinition){
XfunctionDefinition fctDef = (XfunctionDefinition)entry.getValue();
if(fctDef.getName().getValue().equals(fctName)){
return fctDef;
}
}
}
return null;
}
}
|
package cc.example.reference;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.GlyphVector;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import javax.swing.JFrame;
import javax.swing.JPanel;
import cc.adjusting.bolder.NullStroke;
public class AwtStrokeExample extends JPanel
{
private static final long serialVersionUID = 1L;
static final int WIDTH = 1420;
static final int HEIGHT = 1050;
/** These are the various stroke objects we'll demonstrate */
Stroke[] strokes = new Stroke[] { new BasicStroke(4.0f), // The standard,
// predefined
// stroke
new NullStroke(), // A Stroke that does nothing
new DoubleStroke(8.0f, 2.0f), // A Stroke that strokes twice
new ControlPointsStroke(2.0f), // Shows the vertices & control
// points
new SloppyStroke(2.0f, 3.0f) // Perturbs the shape before stroking
};
@Override
public void paint(Graphics g1)
{
Graphics2D g = (Graphics2D) g1;
// Get a shape to work with. Here we'll use the letter B
Font f = new Font("", Font.BOLD, 140);
GlyphVector gv = f.createGlyphVector(g.getFontRenderContext(), "");
System.out.println(gv.getNumGlyphs());
Shape shape = gv.getOutline();
// Set drawing attributes and starting position
g.setColor(Color.black);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.translate(20, 160);
// Draw the shape once with each stroke
for (int i = 0; i < strokes.length; i++)
{
g.setStroke(strokes[i]); // set the stroke
g.draw(shape); // draw the shape
g.translate(0, 160); // move to the right
}
}
/**
*
*
* @param args
*
*/
public static void main(String[] args)
{
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setContentPane(new AwtStrokeExample());
f.setSize(WIDTH, HEIGHT);
f.setVisible(true);
}
@Override
public String getName()
{
return "";
}
@Override
public int getWidth()
{
return WIDTH;
}
@Override
public int getHeight()
{
return HEIGHT;
}
}
// /**
// * This Stroke implementation does nothing. Its createStrokedShape() method
// * returns an unmodified shape. Thus, drawing a shape with this Stroke is the
// * same as filling that shape!
// */
// class NullStroke implements Stroke
// public Shape createStrokedShape(Shape s)
// return s;
/**
* This Stroke implementation applies a BasicStroke to a shape twice. If you
* draw with this Stroke, then instead of outlining the shape, you're outlining
* the outline of the shape.
*/
class DoubleStroke implements Stroke
{
BasicStroke stroke1;
BasicStroke stroke2; // the two strokes to use
/**
*
*
* @param width1
*
* @param width2
*
*/
public DoubleStroke(float width1, float width2)
{
stroke1 = new BasicStroke(width1); // Constructor arguments specify
stroke2 = new BasicStroke(width2); // the line widths for the strokes
}
@Override
public Shape createStrokedShape(Shape s)
{
// Use the first stroke to create an outline of the shape
Shape outline = stroke1.createStrokedShape(s);
// Use the second stroke to create an outline of that outline.
// It is this outline of the outline that will be filled in
return stroke2.createStrokedShape(outline);
}
}
/**
* This Stroke implementation strokes the shape using a thin line, and also
* displays the end points and Bezier curve control points of all the line and
* curve segments that make up the shape. The radius argument to the constructor
* specifies the size of the control point markers. Note the use of PathIterator
* to break the shape down into its segments, and of GeneralPath to build up the
* stroked shape.
*/
class ControlPointsStroke implements Stroke
{
float radius; // how big the control point markers should be
/**
*
*
* @param radius
*
*/
public ControlPointsStroke(float radius)
{
this.radius = radius;
}
@Override
public Shape createStrokedShape(Shape shape)
{
// Start off by stroking the shape with a thin line. Store the
// resulting shape in a GeneralPath object so we can add to it.
GeneralPath strokedShape = new GeneralPath(
new BasicStroke(0.3f).createStrokedShape(shape));
// Use a PathIterator object to iterate through each of the line and
// curve segments of the shape. For each one, mark the endpoint and
// control points (if any) by adding a rectangle to the GeneralPath
float[] coords = new float[6];
int cnt = 0;
for (PathIterator i = shape.getPathIterator(null); !i.isDone(); i
.next())
{
int type = i.currentSegment(coords);
switch (type)
{
case PathIterator.SEG_CUBICTO:
markPoint(strokedShape, coords[4], coords[5]); // falls through
case PathIterator.SEG_QUADTO:
markPoint(strokedShape, coords[2], coords[3]); // falls through
case PathIterator.SEG_MOVETO:
case PathIterator.SEG_LINETO:
markPoint(strokedShape, coords[0], coords[1]); // falls through
case PathIterator.SEG_CLOSE:
break;
}
++cnt;
}
System.out.println(cnt);
return strokedShape;
}
/**
* Add a small square centered at (x,y) to the specified path
*
* @param path
*
* @param x
*
* @param y
*
*/
void markPoint(GeneralPath path, float x, float y)
{
path.moveTo(x - radius, y - radius); // Begin a new sub-path
path.lineTo(x + radius, y - radius); // Add a line segment to it
path.lineTo(x + radius, y + radius); // Add a second line segment
path.lineTo(x - radius, y + radius); // And a third
path.closePath(); // Go back to last moveTo position
}
}
/**
* This Stroke implementation randomly perturbs the line and curve segments that
* make up a Shape, and then strokes that perturbed shape. It uses PathIterator
* to loop through the Shape and GeneralPath to build up the modified shape.
* Finally, it uses a BasicStroke to stroke the modified shape. The result is a
* "sloppy" looking shape.
*/
class SloppyStroke implements Stroke
{
BasicStroke stroke;
float sloppiness;
/**
*
*
* @param width
*
* @param sloppiness
*
*/
public SloppyStroke(float width, float sloppiness)
{
this.stroke = new BasicStroke(width); // Used to stroke modified shape
this.sloppiness = sloppiness; // How sloppy should we be?
}
@Override
public Shape createStrokedShape(Shape shape)
{
GeneralPath newshape = new GeneralPath(); // Start with an empty shape
// Iterate through the specified shape, perturb its coordinates, and
// use them to build up the new shape.
float[] coords = new float[6];
for (PathIterator i = shape.getPathIterator(null); !i.isDone(); i
.next())
{
int type = i.currentSegment(coords);
switch (type)
{
case PathIterator.SEG_MOVETO:
perturb(coords, 2);
newshape.moveTo(coords[0], coords[1]);
break;
case PathIterator.SEG_LINETO:
perturb(coords, 2);
newshape.lineTo(coords[0], coords[1]);
break;
case PathIterator.SEG_QUADTO:
perturb(coords, 4);
newshape.quadTo(coords[0], coords[1], coords[2], coords[3]);
break;
case PathIterator.SEG_CUBICTO:
perturb(coords, 6);
newshape.curveTo(coords[0], coords[1], coords[2], coords[3],
coords[4], coords[5]);
break;
case PathIterator.SEG_CLOSE:
newshape.closePath();
break;
}
}
// Finally, stroke the perturbed shape and return the result
return stroke.createStrokedShape(newshape);
}
// Randomly modify the specified number of coordinates, by an amount
// specified by the sloppiness field.
/**
*
*
* @param coords
*
* @param numCoords
*
*/
void perturb(float[] coords, int numCoords)
{
for (int i = 0; i < numCoords; i++)
coords[i] += (float) ((Math.random() * 2 - 1.0) * sloppiness);
}
}
|
package com.banana.banana.love;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import android.content.Context;
import android.util.Log;
import com.banana.banana.LogoutResponse;
import com.banana.banana.MyApplication;
import com.banana.banana.WithDrawReponse;
import com.banana.banana.dday.DdayResponse;
import com.banana.banana.dday.DdayResult;
import com.banana.banana.login.AutoLoginResponse;
import com.banana.banana.login.LoginResult;
import com.banana.banana.main.CoupleInfoResult;
import com.banana.banana.main.UserInfoResponse;
import com.banana.banana.main.UserInfoResult;
import com.banana.banana.mission.BananaItemResponse;
import com.banana.banana.mission.MissionIngResult;
import com.banana.banana.mission.MissionResult;
import com.banana.banana.setting.NoticeResponse;
import com.banana.banana.setting.WomanInfoResponse;
import com.banana.banana.signup.JoinResult;
import com.banana.banana.signup.WomanInfoParcelData;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.MySSLSocketFactory;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
public class NetworkManager {
private static NetworkManager instance;
public static NetworkManager getInstnace() {
if (instance == null) {
instance = new NetworkManager();
}
return instance;
}
AsyncHttpClient client;
private NetworkManager() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
client = new AsyncHttpClient();
client.setSSLSocketFactory(socketFactory);
client.setCookieStore(new PersistentCookieStore(MyApplication.getContext()));
client.setTimeout(30000);
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
}
public HttpClient getHttpClient() {
return client.getHttpClient();
}
public interface OnResultListener<T> {
public void onSuccess(T result);
public void onFail(int code);
}
public static final String SERVER = "http://yeolwoo.mooo.com";
public static final String HTTPS_SERVER = "https://yeolwoo.mooo.com";
public static final String LOGIN_URL = HTTPS_SERVER + "/users/login";
public void login(Context context, String user_id, String user_pass, String user_phone, String user_regid, final OnResultListener<LoginResult> listener) {
RequestParams params = new RequestParams();
params.put("user_id", user_id);
params.put("user_pw", user_pass);
params.put("user_phone", user_phone);
params.put("user_regid", user_regid);
Log.i("login", "login");
client.post(context, LOGIN_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
LoginResult results = gson.fromJson(responseString, LoginResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String ACCEPT_LOGIN_URL = HTTPS_SERVER + "/users/acceptlogin";
public void acceptLogin(Context context, String user_id, String user_pass, String user_phone, String user_regid, final OnResultListener<LoginResult> listener) {
RequestParams params = new RequestParams();
params.put("user_id", user_id);
params.put("user_pw", user_pass);
params.put("user_phone", user_phone);
params.put("user_regid", user_regid);
client.post(context, ACCEPT_LOGIN_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
LoginResult results = gson.fromJson(responseString, LoginResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String JOIN_URL = HTTPS_SERVER + "/users/join";
public void addjoin(Context context, String user_id, String user_pw, String user_phone, String user_regid, String user_regdate, final OnResultListener<JoinResult> listener) {
RequestParams param = new RequestParams();
param.put("user_id", user_id);
param.put("user_pw", user_pw);
param.put("user_phone", user_phone);
param.put("user_regid", user_regid);
param.put("user_regdate", user_regdate);
client.post(context, JOIN_URL, param, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
JoinResult results = gson.fromJson(responseString, JoinResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
//public static final String SEARCH_JOIN_INFO_URL = SERVER + "/users/join/%s/%s/%s";
/*
public void searchJoinInfo(Context context, int join_code, String gender, int user_req, final OnResultListener<JoinResult> listener) {
RequestParams param = new RequestParams();
param.put("join_code", join_code);
param.put("gender", gender);
param.put("user_req", user_req);
String url = String.format(SEARCH_JOIN_INFO_URL, join_code, gender, user_req);
client.get(context, url, param, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
JoinResult results = gson.fromJson(responseString, JoinResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
*/
public static final String SEARCH_JOIN_INFO_URL = SERVER + "/users/join";
public void searchJoinInfo(Context context, final OnResultListener<JoinResult> listener) {
client.get(context, SEARCH_JOIN_INFO_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
JoinResult results = gson.fromJson(responseString, JoinResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String COUPLE_ASK_URL = SERVER + "/couple/ask";
public void coupleAsk(Context context, String auth_phone, String user_gender, final OnResultListener<JoinResult> listener) {
RequestParams params = new RequestParams();
params.put("auth_phone", auth_phone);
params.put("user_gender", user_gender);
client.post(context, COUPLE_ASK_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
JoinResult results = gson.fromJson(responseString, JoinResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String COUPLE_ANSWER_URL = SERVER + "/couple/answer";
public void coupleAnswer(Context context, final OnResultListener<JoinResult> listener) {
client.post(COUPLE_ANSWER_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
JoinResult results = gson.fromJson(responseString, JoinResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String USERS_COMMON_URL = SERVER + "/users/common";
public void addCommonInfo(Context context, String couple_birth, String user_birth, final OnResultListener<JoinResult> listener) {
RequestParams params = new RequestParams();
params.put("couple_birth", couple_birth);
params.put("user_birth", user_birth);
client.post(context, USERS_COMMON_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
JoinResult results = gson.fromJson(responseString, JoinResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String ADD_WOMAN_INFO_URL = SERVER + "/users/woman";
public void addWomanInfo(Context context, WomanInfoParcelData data, final OnResultListener<JoinResult> listener) {
RequestParams params = new RequestParams();
params.put("womaninfodata", data);
Gson gson = new Gson();
String json = gson.toJson(data);
try {
client.post(context, ADD_WOMAN_INFO_URL, new StringEntity(json), "application/json", new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
JoinResult results = gson.fromJson(responseString, JoinResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static final String COUPLE_INFO_URL = SERVER + "/couple";
public void getCoupleInfoList(Context context, final OnResultListener<CoupleInfoResult> listener) {
client.get(context, COUPLE_INFO_URL, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
}
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
CoupleInfoResponse results = gson.fromJson(responseString, CoupleInfoResponse.class);
CoupleInfoResult list = results.result;
listener.onSuccess(list);
}
});
}
public static final String USER_INFO_URL = SERVER + "/users/userinfo";
public void getUserInfo(Context context, final OnResultListener<UserInfoResult> listener) {
client.get(context, USER_INFO_URL, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
UserInfoResponse results = gson.fromJson(responseString, UserInfoResponse.class);
UserInfoResult list = results.result;
listener.onSuccess(list);
}
});
}
public static final String MY_CONDITION_URL = SERVER + "/couple/mycondition";
public void myCondition(Context context, int condition_no, final OnResultListener<UserInfoResult> listener) {
RequestParams params = new RequestParams();
params.put("condition_no", ""+condition_no);
client.post(context, MY_CONDITION_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
UserInfoResponse results = gson.fromJson(responseString, UserInfoResponse.class);
UserInfoResult list = results.result;
listener.onSuccess(list);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
}
});
}
public static final String DDAY_SEARCH_URL = SERVER + "/ddays";
public void getDdayList(Context context, final OnResultListener<DdayResult> listener) {
RequestParams params = new RequestParams();
client.get(context, DDAY_SEARCH_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
DdayResponse results = gson.fromJson(responseString, DdayResponse.class);
DdayResult list = results.result;
listener.onSuccess(list);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String DDAY_ADD_URL = SERVER + "/ddays/add";
public void addDday(Context context, String ddayname, String ddaydate, int ddayrepeat, final OnResultListener<DdayResponse> listener) {
RequestParams params = new RequestParams();
params.put("dday_repeat", ""+ddayrepeat);
params.put("dday_name", ddayname);
params.put("dday_date", ddaydate);
client.post(context, DDAY_ADD_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
DdayResponse results = gson.fromJson(responseString, DdayResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String DDAY_EDIT_URL = SERVER + "/ddays/%s/modify";
public void editDday(Context context, int ddayno, String ddayname, String ddaydate, int ddayrepeat, final OnResultListener<DdayResponse> listener) {
RequestParams params = new RequestParams();
params.put("dday_name", ddayname);
params.put("dday_date", ddaydate);
String url = String.format(DDAY_EDIT_URL, ddayno);
client.post(context, url, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
DdayResponse results = gson.fromJson(responseString, DdayResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String DDAY_DELETE_URL = SERVER + "/ddays/%s/delete";
public void deleteDday(Context context, int ddayno, final OnResultListener<DdayResponse> listener) {
String url = String.format(DDAY_DELETE_URL, ddayno);
client.post(context, url, null, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
DdayResponse results = gson.fromJson(responseString, DdayResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String GET_WOMAN_INFO_URL = SERVER + "/setting/herself";
public void getWomanInfoList(Context context, final OnResultListener<WomanInfoResponse> listener){
client.get(context, GET_WOMAN_INFO_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
WomanInfoResponse results = gson.fromJson(responseString, WomanInfoResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String LOVE_SEARCH_URL = SERVER + "/loves/%s/%s/%s";
public void getLoveList(Context context, int orderby, int year, int month, final OnResultListener<LoveSearchResult> listener) {
/*RequestParams params = new RequestParams();
params.put("year", ""+year);
params.put("month", ""+month);
params.put("orderby", ""+orderby);*/
String url = String.format(LOVE_SEARCH_URL, ""+year, ""+month, ""+orderby);
client.get(context, url, null ,new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
LoveSearchResult results = gson.fromJson(responseString, LoveSearchResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String LOVE_ADD_URL = SERVER + "/loves/add";
public void addLove(Context context, int iscondom, String loves_date, final OnResultListener<LoveSearchResult> listener) {
RequestParams params = new RequestParams();
params.put("loves_condom", ""+iscondom);
params.put("loves_date", loves_date);
client.post(context, LOVE_ADD_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
LoveSearchResult results = gson.fromJson(responseString, LoveSearchResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String LOVE_EDIT_URL = SERVER + "/loves/%s/modify";
public void modifyLove(Context context, int relation_no, int is_condom, String date, final OnResultListener<LoveSearchResult> listener) {
RequestParams params = new RequestParams();
//params.put("loves_no", ""+relation_no);
params.put("loves_condom", ""+is_condom);
params.put("loves_date", date);
String url = String.format(LOVE_EDIT_URL, relation_no);
client.post(context, url, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
LoveSearchResult results = gson.fromJson(responseString, LoveSearchResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String LOVE_DELETE_URL = SERVER + "/loves/%s/delete";
public void deleteLove(Context context, int relation_no, final OnResultListener<LoveSearchResult> listener) {
//RequestParams params = new RequestParams();
//params.put("loves_no", ""+relation_no);
String url = String.format(LOVE_DELETE_URL, ""+relation_no);
client.post(context, url, null, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
LoveSearchResult results = gson.fromJson(responseString, LoveSearchResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String MISSION_ING_LIST=SERVER+"/missions";
public void getMissionIngList(Context context, final OnResultListener<MissionIngResult> listener){
String url = String.format(MISSION_ING_LIST);
client.get(context, url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
MissionIngResult results = gson.fromJson(responseString, MissionIngResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String MISSION_LIST_URL = SERVER + "/missions/%s/%s/%s";
public void getMissionList(Context context, int year, int month, int orderby, final OnResultListener<MissionResult> listener) {
RequestParams params = new RequestParams();
params.put("year", year);
params.put("month", month);
params.put("orderby", orderby);
String url = String.format(MISSION_LIST_URL, year, month, orderby);
client.get(context, url, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
MissionResult results = gson.fromJson(responseString, MissionResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String MISSION_ADD_URL = SERVER + "/missions/add";
public void addMission(Context context, int mission_theme, final OnResultListener<MissionResult> listener) {
RequestParams params = new RequestParams();
params.put("mission_theme", mission_theme);
client.post(context, MISSION_ADD_URL, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
MissionResult results = gson.fromJson(responseString, MissionResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String MISSION_CONFIRM_URL = SERVER + "/missions/%s/confirm";
public void confirmMission(Context context, int mlist_no, final OnResultListener<MissionResult> listener) {
RequestParams params = new RequestParams();
params.put("mlist_no", mlist_no);
String url = String.format(MISSION_CONFIRM_URL, mlist_no);
client.post(context, url, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
MissionResult results = gson.fromJson(responseString, MissionResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String MISSION_INFO_URL = SERVER + "/missions/%s";
public void searchMissionInfo(Context context, int mlist_no, final OnResultListener<MissionResult> listener) {
RequestParams param = new RequestParams();
param.put("mlist_no", mlist_no);
String url = String.format(MISSION_INFO_URL, mlist_no);
client.get(context, url, param, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
MissionResult results = gson.fromJson(responseString, MissionResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String SUCCESS_MISSION_URL = SERVER + "/missons/%s/success";
public void successMisson(Context context, int mlist_no, final OnResultListener<MissionResult> listener) {
RequestParams params = new RequestParams();
params.put("mlist_no", mlist_no);
String url = String.format(SUCCESS_MISSION_URL, mlist_no);
client.post(context, url, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
MissionResult results = gson.fromJson(responseString, MissionResult.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String POSSIBLE_ITEM_LIST_URL= SERVER + "/items";
public void getBuyInfo(Context context, final OnResultListener<BananaItemResponse> listener) {
client.get(context, POSSIBLE_ITEM_LIST_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
BananaItemResponse results = gson.fromJson(responseString, BananaItemResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String OWN_ITEM_LIST_URL= SERVER + "/items/own";
public void getOwnItemInfo(Context context, final OnResultListener<BananaItemResponse> listener) {
client.get(context, OWN_ITEM_LIST_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
BananaItemResponse results = gson.fromJson(responseString, BananaItemResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String USE_ITEM_URL = SERVER + "/items/%s/use/%s";
public void useItem(Context context, int item_no, int mlist_no, final OnResultListener<BananaItemResponse> listener) {
RequestParams params = new RequestParams();
params.put("item_no", item_no);
params.put("mlist_no", mlist_no);
String url = String.format(USE_ITEM_URL, item_no, mlist_no);
client.post(context, url, params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
// TODO Auto-generated method stub
Gson gson = new Gson();
BananaItemResponse results = gson.fromJson(responseString, BananaItemResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
// TODO Auto-generated method stub
listener.onFail(statusCode);
}
});
}
public static final String NOTICE_URL = SERVER + "/setting/notice";
public void getNotic(Context context, final OnResultListener<NoticeResponse> listener) {
client.get(context, NOTICE_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
NoticeResponse results = gson.fromJson(responseString, NoticeResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String LOGOUT_URL = SERVER + "/users/logout";
public void logout(Context context, final OnResultListener<LogoutResponse> listener) {
client.post(LOGOUT_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
LogoutResponse results = gson.fromJson(responseString, LogoutResponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
public static final String WITHDRAW_URL = SERVER + "/users/withdraw";
public void withDraw(Context context, final OnResultListener<WithDrawReponse> listener) {
client.post(WITHDRAW_URL, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
Gson gson = new Gson();
WithDrawReponse results = gson.fromJson(responseString, WithDrawReponse.class);
listener.onSuccess(results);
}
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
listener.onFail(statusCode);
}
});
}
}
|
package com.dkt.mrft.models;
import com.dkt.mrft.utils.BundleDecorator;
import com.dkt.mrft.utils.Triplet;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
import net.objecthunter.exp4j.Expression;
/**
*
* @author Federico Vera {@literal <fedevera at unc.edu.ar>}
*/
public class DatasetTableModel extends AbstractTableModel {
private static final BundleDecorator i18n = new BundleDecorator("res.i18n.models");
private final ArrayList<Row> data = new ArrayList<>(128);
private final String name;
private boolean selecting = false;
public DatasetTableModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addRow(Double x, Double fx) {
synchronized(data){
data.add(new Row(false, x, fx));
final int size = data.size() - 1;
fireTableRowsInserted(size, size);
}
}
@Override
public void setValueAt(Object aValue, int row, int column) {
synchronized(data) {
int col = column;
final Row e = data.get(row);
if (!selecting) col++;
switch (col) {
case 0: e.first = (Boolean)aValue; break;
case 1: e.second = (Double) aValue; break;
case 2: e.third = (Double) aValue; break;
default: /*do nothing*/
}
if (!selecting) col
fireTableCellUpdated(row, col);
}
}
@Override
public Object getValueAt(int row, int column) {
final Row e = data.get(row);
int col = column;
if (!selecting) col++;
switch (col) {
case 0: return e.first;
case 1: return e.second;
case 2: return e.third;
default: return null;
}
}
@Override
public boolean isCellEditable(int row, int column) {
return true;
}
private final String[] cols = {i18n.__("Selection"), i18n.__("x"), i18n.__("f(x)")};
@Override
public String getColumnName(int column) {
return cols[selecting ? column : column + 1];
}
@Override
public int getColumnCount() {
return selecting ? 3 : 2;
}
@Override
public int getRowCount() {
return data.size();
}
public int getSelectedCount() {
int counter = 0;
for (final Row e : data) {
if (e.first) {
counter++;
}
}
return counter;
}
private final Class<?>[] colClass = {Boolean.class, Double.class, Double.class};
@Override
public Class<?> getColumnClass(int column) {
return colClass[selecting ? column : column + 1];
}
public void selectAll() {
synchronized (data) {
for (final Row e : data) {
if (!e.first) {
e.first = true;
}
}
fireTableDataChanged();
}
}
public void selectNone() {
synchronized (data) {
for (final Row e : data) {
if (e.first) {
e.first = false;
}
}
fireTableDataChanged();
}
}
public void selectToggle() {
synchronized (data) {
for (final Row e : data) {
e.first = !e.first;
}
fireTableDataChanged();
}
}
public void selectEnabled(boolean enabled) {
this.selecting = enabled;
fireTableStructureChanged();
}
public void cleanRows(){
synchronized (data) {
final ArrayList<Row> foo = new ArrayList<>(data);
int counter = 0;
for (final Row e : data) {
if (e.second == null || e.third == null) {
foo.add(e);
counter++;
}
}
if (counter != 0) {
data.removeAll(foo);
fireTableDataChanged();
}
}
}
public ArrayList<Row> removeSelected() {
synchronized (data) {
final ArrayList<Row> rem = new ArrayList<>(getSelectedCount());
for (final Row e : data) {
if (e.first) {
rem.add(e);
}
}
data.removeAll(rem);
fireTableDataChanged();
return rem;
}
}
public void addAll(ArrayList<Row> foo) {
synchronized (data) {
data.addAll(foo);
}
fireTableDataChanged();
}
public double getMax() {
double max = 0;
for (final Row e : data) {
max = Math.max(max, Math.abs(e.third));
}
return max;
}
public void scale(double scale) {
for (final Row e : data) {
e.third *= scale;
}
fireTableDataChanged();
}
public double[][] getValues() {
final double[][] ret = new double[2][getRowCount()];
int i = 0;
for (final Row e : data) {
ret[0][i] = e.second;
ret[1][i] = e.third;
i++;
}
return ret;
}
public double getDouble(int i, int j) {
if (j == 0) {
return data.get(i).second;
}
return data.get(i).third;
}
public void applyToX(Expression exp4X, String exp) {
synchronized (data) {
final boolean hasx = exp4X.containsVariable("x");
final boolean hasfx = exp4X.containsVariable("fx");
for (final Row e : data) {
if (hasx) exp4X.setVariable("x", e.second);
if (hasfx) exp4X.setVariable("fx", e.third);
e.second = exp4X.evaluate();
}
}
fireTableDataChanged();
}
public void applyToFX(Expression exp4FX, String exp) {
synchronized (data) {
final boolean hasx = exp4FX.containsVariable("x");
final boolean hasfx = exp4FX.containsVariable("fx");
for (final Row e : data) {
if (hasx) exp4FX.setVariable("x", e.second);
if (hasfx) exp4FX.setVariable("fx", e.third);
e.third = exp4FX.evaluate();
}
}
fireTableDataChanged();
}
public void applyToBoth(Expression exp4X, String expX, Expression exp4FX, String expFX) {
synchronized (data) {
//This is necesarry because the current version of exp4j fails when setting an
//inexistent variable
final boolean xhasx = exp4X .containsVariable("x");
final boolean xhasfx = exp4X .containsVariable("fx");
final boolean fhasx = exp4FX.containsVariable("x");
final boolean fhasfx = exp4FX.containsVariable("fx");
for (final Row e : data) {
final double x = e.second;
final double fx = e.third;
if (xhasx) exp4X.setVariable("x", x);
if (xhasfx) exp4X.setVariable("fx", fx);
e.second = exp4X.evaluate();
if (fhasx) exp4FX.setVariable("x", x);
if (fhasfx) exp4FX.setVariable("fx", fx);
e.third = exp4FX.evaluate();
}
}
fireTableDataChanged();
}
public static final class Row extends Triplet<Boolean, Double, Double> {
public Row(Boolean x, Double y, Double z) {
super(x, y, z);
}
}
}
|
package com.eddysystems.eddy;
import com.eddysystems.eddy.actions.EddyAction;
import com.eddysystems.eddy.engine.Eddy;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.ui.LightweightHint;
import org.jetbrains.annotations.NotNull;
import static com.eddysystems.eddy.engine.Utility.log;
public class EddyFileListener implements CaretListener, DocumentListener {
private final @NotNull Project project;
private final @NotNull Editor editor;
private final @NotNull Document document;
private static final @NotNull Object active_lock = new Object();
// last editor that an eddy thread has run on
private static Editor active_editor = null;
// if the eddy instance in a file listener is associated with an active hint, this is it
private static EddyFileListener active_hint_instance = null;
// an action that shows up as an intention action (lives longer than the hint)
private static EddyFileListener active_instance = null;
private static EddyAction active_action = null;
private static int active_line = -1;
// to keymapped actions that should affect the file listener that showed the last hint
public static EddyFileListener activeHintInstance() {
return active_hint_instance;
}
public static EddyAction getActionFor(Editor editor) {
synchronized (active_lock) {
if (active_instance == null || editor != active_instance.editor ||
editor.getCaretModel().getCurrentCaret().getLogicalPosition().line != active_line)
return null;
return active_action;
}
}
private boolean inChange = false;
private int lastEditLocation = -1;
public EddyFileListener(@NotNull Project project, TextEditor editor) {
this.project = project;
this.editor = editor.getEditor();
this.document = this.editor.getDocument();
VirtualFile file = FileDocumentManager.getInstance().getFile(this.document);
if (file != null)
log("making eddy for editor for file " + file.getPresentableName());
else
log("making eddy for editor for file 'null'");
// moving the caret around
this.editor.getCaretModel().addCaretListener(this);
// subscribe to document events
this.editor.getDocument().addDocumentListener(this);
}
public void dispose() {
log("disposing editor listener for " + editor);
editor.getCaretModel().removeCaretListener(this);
editor.getDocument().removeDocumentListener(this);
}
protected boolean enabled() {
return editor.getCaretModel().getCaretCount() == 1 && EddyPlugin.getInstance(project).isInitialized();
}
protected void process() {
if (!enabled()) {
// check if we're not initialized, and if so, try to reinitialize
if (!EddyPlugin.getInstance(project).isInitialized()) {
EddyPlugin.getInstance(project).requestInit();
}
return;
}
PsiDocumentManager.getInstance(project).performForCommittedDocument(document, new Runnable() {
@Override
public void run() {
synchronized (active_lock) {
EddyThread.run(new EddyThread(project,editor,lastEditLocation, new Eddy.Take() {
@Override public boolean take(Eddy.Output output) {
showHint(output);
return output.results.size() >= 4;
}
}));
active_editor = editor;
}
}
});
}
private void showHint(final Eddy.Output output) {
if (output == null)
return; // Don't make a hint if there's no output
final int line = editor.getCaretModel().getLogicalPosition().line;
final EddyAction action = new EddyAction(output,editor);
synchronized (active_lock) {
active_instance = this;
active_line = line;
active_action = action;
active_hint_instance = null;
// show hint only if we found something really good
if (output.shouldShowHint()) {
final int offset = editor.getCaretModel().getOffset();
final LightweightHint hint = EddyHintLabel.makeHint(output);
// we can only show hints from the UI thread, so schedule that
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override public void run() {
// whoever showed the hint last is it
// the execution order of later-invoked things is the same as the call order, and it's on a single thread, so
// no synchronization is needed in here
active_hint_instance = EddyFileListener.this;
HintManagerImpl.getInstanceImpl().showQuestionHint(editor, offset, offset + 1, hint, action, HintManager.ABOVE);
}
});
}
}
}
public void nextResult() {
synchronized (active_lock) {
if ( active_hint_instance == this
&& active_action.getOutput().nextBestResult())
showHint(active_action.getOutput());
}
}
public void prevResult() {
synchronized (active_lock) {
if ( active_hint_instance == this
&& active_action.getOutput().prevBestResult())
showHint(active_action.getOutput());
}
}
@Override
public void caretPositionChanged(CaretEvent e) {
if (inChange)
return;
// TODO: only process if input changed (if we switched statements?)
if (active_editor != this.editor || // process if current thread is for a different editor
e.getNewPosition().line != e.getOldPosition().line) // process if we switched lines
process();
}
@Override
public void caretAdded(CaretEvent e) {
}
@Override
public void caretRemoved(CaretEvent e) {
}
@Override
public void beforeDocumentChange(DocumentEvent event) {
inChange = true;
}
@Override
public void documentChanged(DocumentEvent event) {
inChange = false;
lastEditLocation = event.getOffset();
process();
}
}
|
package com.fsck.k9.activity;
import java.text.DateFormat;
import android.content.Context;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.R;
import com.fsck.k9.controller.MessagingListener;
import com.fsck.k9.service.MailService;
public class ActivityListener extends MessagingListener
{
private String mLoadingFolderName = null;
private String mLoadingHeaderFolderName = null;
private String mLoadingAccountDescription = null;
private String mSendingAccountDescription = null;
private int mFolderCompleted = 0;
private int mFolderTotal = 0;
private String mProcessingAccountDescription = null;
private String mProcessingCommandTitle = null;
public String formatHeader(Context context, String activityPrefix, int unreadMessageCount, DateFormat timeFormat)
{
String operation = null;
String progress = null;
if (mLoadingAccountDescription != null
|| mSendingAccountDescription != null
|| mLoadingHeaderFolderName != null
|| mProcessingAccountDescription != null)
{
progress = (mFolderTotal > 0 ?
context.getString(R.string.folder_progress, mFolderCompleted, mFolderTotal) : "");
if (mLoadingFolderName != null || mLoadingHeaderFolderName != null)
{
String displayName = mLoadingFolderName;
if (K9.INBOX.equalsIgnoreCase(displayName))
{
displayName = context.getString(R.string.special_mailbox_name_inbox);
}
if (mLoadingHeaderFolderName != null)
{
operation = context.getString(R.string.status_loading_account_folder_headers, mLoadingAccountDescription, displayName, progress);
}
else
{
operation = context.getString(R.string.status_loading_account_folder, mLoadingAccountDescription, displayName, progress);
}
}
else if (mSendingAccountDescription != null)
{
operation = context.getString(R.string.status_sending_account, mSendingAccountDescription, progress);
}
else if (mProcessingAccountDescription != null)
{
operation = context.getString(R.string.status_processing_account, mProcessingAccountDescription,
mProcessingCommandTitle != null ? mProcessingCommandTitle : "",
progress);
}
}
else
{
long nextPollTime = MailService.getNextPollTime();
if (nextPollTime != -1)
{
operation = context.getString(R.string.status_next_poll, timeFormat.format(nextPollTime));
}
else
{
operation = ""; // context.getString(R.string.status_polling_off);
}
}
return context.getString(R.string.activity_header_format, activityPrefix,
(unreadMessageCount > 0 ? context.getString(R.string.activity_unread_count, unreadMessageCount) : ""),
operation);
}
@Override
public void synchronizeMailboxFinished(
Account account,
String folder,
int totalMessagesInMailbox,
int numNewMessages)
{
mLoadingAccountDescription = null;
mLoadingFolderName = null;
}
@Override
public void synchronizeMailboxStarted(Account account, String folder)
{
mLoadingAccountDescription = account.getDescription();
mLoadingFolderName = folder;
mFolderCompleted = 0;
mFolderTotal = 0;
}
@Override
public void synchronizeMailboxHeadersStarted(Account account, String folder)
{
mLoadingHeaderFolderName = folder;
}
@Override
public void synchronizeMailboxHeadersProgress(Account account, String folder, int completed, int total)
{
mFolderCompleted = completed;
mFolderTotal = total;
}
@Override
public void synchronizeMailboxHeadersFinished(Account account, String folder,
int total, int completed)
{
mLoadingHeaderFolderName = null;
mFolderCompleted = 0;
mFolderTotal = 0;
}
@Override
public void synchronizeMailboxProgress(Account account, String folder, int completed, int total)
{
mFolderCompleted = completed;
mFolderTotal = total;
}
@Override
public void synchronizeMailboxFailed(Account account, String folder,
String message)
{
mLoadingAccountDescription = null;
mLoadingFolderName = null;
}
@Override
public void sendPendingMessagesStarted(Account account)
{
mSendingAccountDescription = account.getDescription();
}
@Override
public void sendPendingMessagesCompleted(Account account)
{
mSendingAccountDescription = null;
}
@Override
public void sendPendingMessagesFailed(Account account)
{
mSendingAccountDescription = null;
}
@Override
public void pendingCommandsProcessing(Account account)
{
mProcessingAccountDescription = account.getDescription();
mFolderCompleted = 0;
mFolderTotal = 0;
}
@Override
public void pendingCommandsFinished(Account account)
{
mProcessingAccountDescription = null;
}
@Override
public void pendingCommandStarted(Account account, String commandTitle)
{
mProcessingCommandTitle = commandTitle;
}
@Override
public void pendingCommandCompleted(Account account, String commandTitle)
{
mProcessingCommandTitle = null;
}
public int getFolderCompleted()
{
return mFolderCompleted;
}
public int getFolderTotal()
{
return mFolderTotal;
}
}
|
package com.googlecode.networklog;
import android.util.Log;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.Filter;
import android.widget.Filterable;
import android.view.View;
import android.view.ViewGroup;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.graphics.drawable.Drawable;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.os.SystemClock;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView.BufferType;
import android.util.TypedValue;
import android.os.Parcelable;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
/* newer API 11 clipboard unsupported on older APIs
import android.content.ClipboardManager;
import android.content.ClipData;
*/
/* use older clipboard API to support older devices */
import android.text.ClipboardManager;
import android.support.v4.app.Fragment;
import java.lang.StringBuilder;
import java.util.Arrays;
import java.util.Set;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
public class AppFragment extends Fragment {
// groupData bound to adapter, and filtered
public ArrayList<GroupItem> groupData;
// groupDataBuffer used to buffer incoming log entries and to hold original list data for filtering
public ArrayList<GroupItem> groupDataBuffer;
public boolean groupDataBufferIsDirty = false;
public boolean needsRefresh = false;
private ExpandableListView listView;
private CustomAdapter adapter;
public Sort preSortBy;
public Sort sortBy;
public GroupItem cachedSearchItem;
private ListViewUpdater updater;
// remember last index return by getItemByAppUid to optimize-out call to binarySearch
int lastGetItemByAppUidIndex = -1;
private NetworkLog parent = null;
private boolean gotInstalledApps = false;
private boolean doNotRefresh = false;
public class GroupItem {
protected ApplicationsTracker.AppEntry app;
protected long totalPackets;
protected long totalBytes;
protected long lastTimestamp;
// childrenData bound to adapter, holds original list of children
protected HashMap<String, ChildItem> childrenData;
// holds filtered list of children
// used in place of childrenData in getView, if non-empty
protected HashMap<String, ChildItem> childrenDataFiltered;
// holds sorted keys into childrenData
protected String[] childrenDataSorted;
protected boolean childrenNeedSort = false;
protected boolean childrenAreFiltered = false;
protected boolean childrenAreDirty = false;
protected boolean isExpanded = false;
@Override
public String toString() {
return "(" + app.uidString + ") " + app.name;
}
}
public class ChildItem {
protected String proto; // protocol (udp, tcp, igmp, icmp, etc)
protected int sentPackets;
protected int sentBytes;
protected long sentTimestamp;
protected int sentPort;
protected String sentAddress;
protected String out; // interface (rmnet, wifi, etc)
protected int receivedPackets;
protected int receivedBytes;
protected long receivedTimestamp;
protected int receivedPort;
protected String receivedAddress;
protected String in; // interface (rmnet, wifi, etc)
public String toString() {
// todo: resolver here
return sentAddress + ":" + sentPort + " -> " + receivedAddress + ":" + receivedPort;
}
}
public void clear() {
synchronized(groupData) {
synchronized(groupDataBuffer) {
for(GroupItem item : groupDataBuffer) {
synchronized(item.childrenData) {
List<String> list = new ArrayList<String>(item.childrenData.keySet());
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
String host = itr.next();
ChildItem childData = item.childrenData.get(host);
}
item.childrenData.clear();
item.childrenDataFiltered.clear();
item.childrenDataSorted = null;
item.childrenAreFiltered = false;
}
}
groupDataBuffer.clear();
groupData.clear();
groupDataBufferIsDirty = false;
}
}
getInstalledApps(false);
lastGetItemByAppUidIndex = -1;
}
protected static class SortAppsByBytes implements Comparator<GroupItem> {
public int compare(GroupItem o1, GroupItem o2) {
return o1.totalBytes > o2.totalBytes ? -1 : (o1.totalBytes == o2.totalBytes) ? 0 : 1;
}
}
protected static class SortAppsByPackets implements Comparator<GroupItem> {
public int compare(GroupItem o1, GroupItem o2) {
return o1.totalPackets > o2.totalPackets ? -1 : (o1.totalPackets == o2.totalPackets) ? 0 : 1;
}
}
protected static class SortAppsByTimestamp implements Comparator<GroupItem> {
public int compare(GroupItem o1, GroupItem o2) {
return o1.lastTimestamp > o2.lastTimestamp ? -1 : (o1.lastTimestamp == o2.lastTimestamp) ? 0 : 1;
}
}
protected static class SortAppsByName implements Comparator<GroupItem> {
public int compare(GroupItem o1, GroupItem o2) {
return o1.app.name.compareToIgnoreCase(o2.app.name);
}
}
protected static class SortAppsByUid implements Comparator<GroupItem> {
public int compare(GroupItem o1, GroupItem o2) {
return o1.app.uid < o2.app.uid ? -1 : (o1.app.uid == o2.app.uid) ? 0 : 1;
}
}
protected static class SortChildrenByBytes implements Comparator<String> {
GroupItem item;
public SortChildrenByBytes(GroupItem item) {
this.item = item;
}
public int compare(String o1, String o2) {
ChildItem c1;
ChildItem c2;
if(item.childrenAreFiltered) {
c1 = item.childrenDataFiltered.get(o1);
c2 = item.childrenDataFiltered.get(o2);
} else {
c1 = item.childrenData.get(o1);
c2 = item.childrenData.get(o2);
}
long totalBytes1 = c1.sentBytes + c1.receivedBytes;
long totalBytes2 = c2.sentBytes + c2.receivedBytes;
return totalBytes1 > totalBytes2 ? -1 : (totalBytes1 == totalBytes2) ? 0 : 1;
}
}
protected static class SortChildrenByPackets implements Comparator<String> {
GroupItem item;
public SortChildrenByPackets(GroupItem item) {
this.item = item;
}
public int compare(String o1, String o2) {
ChildItem c1;
ChildItem c2;
if(item.childrenAreFiltered) {
c1 = item.childrenDataFiltered.get(o1);
c2 = item.childrenDataFiltered.get(o2);
} else {
c1 = item.childrenData.get(o1);
c2 = item.childrenData.get(o2);
}
long totalPackets1 = c1.sentPackets + c1.receivedPackets;
long totalPackets2 = c2.sentPackets + c2.receivedPackets;
return totalPackets1 > totalPackets2 ? -1 : (totalPackets1 == totalPackets2) ? 0 : 1;
}
}
protected static class SortChildrenByTimestamp implements Comparator<String> {
GroupItem item;
public SortChildrenByTimestamp(GroupItem item) {
this.item = item;
}
public int compare(String o1, String o2) {
ChildItem c1;
ChildItem c2;
if(item.childrenAreFiltered) {
c1 = item.childrenDataFiltered.get(o1);
c2 = item.childrenDataFiltered.get(o2);
} else {
c1 = item.childrenData.get(o1);
c2 = item.childrenData.get(o2);
}
long timestamp1 = c1.sentTimestamp;
long timestamp2 = c2.sentTimestamp;
if(c1.receivedTimestamp > timestamp1) {
timestamp1 = c1.receivedTimestamp;
}
if(c2.receivedTimestamp > timestamp2) {
timestamp2 = c2.receivedTimestamp;
}
return timestamp1 > timestamp2 ? -1 : (timestamp1 == timestamp2) ? 0 : 1;
}
}
protected void preSortData() {
Comparator<GroupItem> sortMethod;
switch(preSortBy) {
case UID:
sortMethod = new SortAppsByUid();
break;
case NAME:
sortMethod = new SortAppsByName();
break;
case PACKETS:
sortMethod = new SortAppsByPackets();
break;
case BYTES:
sortMethod = new SortAppsByBytes();
break;
case TIMESTAMP:
sortMethod = new SortAppsByTimestamp();
break;
default:
return;
}
synchronized(groupData) {
Collections.sort(groupData, sortMethod);
}
}
protected void sortData() {
Comparator<GroupItem> sortMethod;
switch(sortBy) {
case UID:
sortMethod = new SortAppsByUid();
break;
case NAME:
sortMethod = new SortAppsByName();
break;
case PACKETS:
sortMethod = new SortAppsByPackets();
break;
case BYTES:
sortMethod = new SortAppsByBytes();
break;
case TIMESTAMP:
sortMethod = new SortAppsByTimestamp();
break;
default:
return;
}
synchronized(groupData) {
Collections.sort(groupData, sortMethod);
}
}
public void sortChildren() {
synchronized(groupData) {
for(GroupItem item : groupData) {
item.childrenNeedSort = true;
}
}
}
public void setDoNotRefresh(boolean value) {
doNotRefresh = value;
}
public void refreshAdapter() {
if(doNotRefresh) {
return;
}
if(listView == null) {
return;
}
int index = listView.getFirstVisiblePosition();
View v = listView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
adapter.notifyDataSetChanged();
if(MyLog.enabled) {
MyLog.d("Refreshed AppFragment adapter");
}
listView.setSelectionFromTop(index, top);
int size = adapter.getGroupCount();
for(int i = 0; i < size; i++) {
if(((GroupItem)adapter.getGroup(i)).isExpanded == true) {
listView.expandGroup(i);
} else {
listView.collapseGroup(i);
}
}
}
protected void getInstalledApps(final boolean refresh) {
synchronized(groupDataBuffer) {
synchronized(groupData) {
groupData.clear();
groupDataBuffer.clear();
synchronized(ApplicationsTracker.installedAppsLock) {
for(ApplicationsTracker.AppEntry app : ApplicationsTracker.installedApps) {
if(NetworkLog.state != NetworkLog.State.RUNNING && NetworkLog.initRunner.running == false) {
MyLog.d("[AppFragment] Initialization aborted");
return;
}
GroupItem item = new GroupItem();
item.app = app;
item.lastTimestamp = 0;
item.childrenData = new HashMap<String, ChildItem>();
item.childrenDataFiltered = new HashMap<String, ChildItem>();
groupData.add(item);
groupDataBuffer.add(item);
}
}
if(refresh == true) {
Activity activity = getActivity();
if(activity != null) {
activity.runOnUiThread(new Runnable() {
public void run() {
preSortData();
if(NetworkLog.filterTextInclude.length() > 0 || NetworkLog.filterTextExclude.length() > 0) {
setFilter("");
} else {
refreshAdapter();
}
}
});
}
}
// groupDataBuffer must always be sorted by UID for binary search
Collections.sort(groupDataBuffer, new SortAppsByUid());
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
public void setParent(NetworkLog parent) {
this.parent = parent;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible() && !isVisibleToUser) {
if(parent != null) {
parent.invalidateOptionsMenu();
}
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyLog.d("AppFragment onCreate");
setRetainInstance(true);
sortBy = NetworkLog.settings.getSortBy();
preSortBy = NetworkLog.settings.getPreSortBy();
groupData = new ArrayList<GroupItem>();
groupDataBuffer = new ArrayList<GroupItem>();
cachedSearchItem = new GroupItem();
cachedSearchItem.app = new ApplicationsTracker.AppEntry();
adapter = new CustomAdapter();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity().getApplicationContext();
MyLog.d("[AppFragment] onCreateView");
if(NetworkLog.settings == null) {
NetworkLog activity = (NetworkLog) getActivity();
if(activity != null) {
activity.loadSettings();
}
}
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(context);
tv.setText("Press for connections, long-press for graph");
layout.addView(tv);
listView = new ExpandableListView(context);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
listView.setSmoothScrollbarEnabled(false);
listView.setGroupIndicator(null);
listView.setChildIndicator(null);
listView.setDividerHeight(0);
listView.setChildDivider(getResources().getDrawable(R.color.transparent));
layout.addView(listView);
listView.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
((GroupItem)adapter.getGroup(groupPosition)).isExpanded = true;
}
});
listView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
((GroupItem)adapter.getGroup(groupPosition)).isExpanded = false;
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView parent, View v,
int position, long id)
{
/* Don't handle long clicks for child elements (will use context menu instead) */
if (ExpandableListView.getPackedPositionType(id) != ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
GroupItem group = (GroupItem) adapter.getGroup(ExpandableListView.getPackedPositionGroup(id));
showGraph(group.app.uid);
return true;
} else {
return false;
}
}
});
listView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id)
{
GroupItem group = (GroupItem) adapter.getGroup(groupPosition);
ChildItem child = (ChildItem) adapter.getChild(groupPosition, childPosition);
getActivity().startActivity(new Intent(getActivity().getApplicationContext(), AppTimelineGraph.class)
.putExtra("app_uid", group.app.uid)
.putExtra("src_addr", child.receivedAddress)
.putExtra("src_port", child.receivedPort)
.putExtra("dst_addr", child.sentAddress)
.putExtra("dst_port", child.sentPort));
return true;
}
});
registerForContextMenu(listView);
if(gotInstalledApps == false) {
getInstalledApps(true);
gotInstalledApps = true;
}
startUpdater();
return layout;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
ExpandableListView.ExpandableListContextMenuInfo info =
(ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
int type = ExpandableListView.getPackedPositionType(info.packedPosition);
int group = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int child = ExpandableListView.getPackedPositionChild(info.packedPosition);
// Only create a context menu for child items
if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.layout.app_context_menu, menu);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListContextMenuInfo info;
int groupPos;
int childPos;
switch(item.getItemId()) {
case R.id.app_copy_ip:
info = (ExpandableListContextMenuInfo) item.getMenuInfo();
groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
ChildItem childItem = (ChildItem) adapter.getChild(groupPos, childPos);
copyIpAddress(childItem);
return true;
case R.id.app_graph:
info = (ExpandableListContextMenuInfo) item.getMenuInfo();
groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
GroupItem groupItem = (GroupItem) adapter.getGroup(groupPos);
showGraph(groupItem.app.uid);
return true;
default:
return super.onContextItemSelected(item);
}
}
@SuppressWarnings("deprecation")
void copyIpAddress(ChildItem childItem) {
String hostString = "";
if(childItem.sentPackets > 0 && childItem.out != null) {
String sentAddressString;
String sentPortString;
if(NetworkLog.resolveHosts && NetworkLog.resolveCopies) {
sentAddressString = NetworkLog.resolver.resolveAddress(childItem.sentAddress);
if(sentAddressString == null) {
sentAddressString = childItem.sentAddress;
}
} else {
sentAddressString = childItem.sentAddress;
}
if(NetworkLog.resolvePorts && NetworkLog.resolveCopies) {
sentPortString = NetworkLog.resolver.resolveService(String.valueOf(childItem.sentPort));
} else {
sentPortString = String.valueOf(childItem.sentPort);
}
hostString = sentAddressString + ":" + sentPortString;
}
else if(childItem.receivedPackets > 0 && childItem.in != null) {
String receivedAddressString;
String receivedPortString;
if(NetworkLog.resolveHosts && NetworkLog.resolveCopies) {
receivedAddressString = NetworkLog.resolver.resolveAddress(childItem.receivedAddress);
if(receivedAddressString == null) {
receivedAddressString = childItem.receivedAddress;
}
} else {
receivedAddressString = childItem.receivedAddress;
}
if(NetworkLog.resolvePorts && NetworkLog.resolveCopies) {
receivedPortString = NetworkLog.resolver.resolveService(String.valueOf(childItem.receivedPort));
} else {
receivedPortString = String.valueOf(childItem.receivedPort);
}
hostString = receivedAddressString + ":" + receivedPortString;
}
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
/* newer API 11 clipboard unsupported on older devices
ClipData clip = ClipData.newPlainText("NetworkLog IP Address", hostString);
clipboard.setPrimaryClip(clip);
*/
/* use older deprecated ClipboardManager to support older devices */
clipboard.setText(hostString);
}
void showGraph(int appuid) {
getActivity().startActivity(new Intent(getActivity().getApplicationContext(), AppTimelineGraph.class)
.putExtra("app_uid", appuid));
}
Comparator comparator = new Comparator<GroupItem>() {
public int compare(GroupItem o1, GroupItem o2) {
return o1.app.uid < o2.app.uid ? -1 : (o1.app.uid == o2.app.uid) ? 0 : 1;
}
};
public int getItemByAppUid(int uid) {
synchronized(groupDataBuffer) {
// check to see if we need to search for index
// (more often than not, the last index is still the active index being requested)
if(lastGetItemByAppUidIndex < 0 || groupDataBuffer.get(lastGetItemByAppUidIndex).app.uid != uid) {
cachedSearchItem.app.uid = uid;
lastGetItemByAppUidIndex = Collections.binarySearch(groupDataBuffer, cachedSearchItem, comparator);
}
// binarySearch isn't guaranteed to return the first item of items with the same uid
// so find the first item
while(lastGetItemByAppUidIndex > 0) {
if(groupDataBuffer.get(lastGetItemByAppUidIndex - 1).app.uid == uid) {
lastGetItemByAppUidIndex
}
else {
break;
}
}
}
return lastGetItemByAppUidIndex;
}
public void rebuildLogEntries() {
Log.d("NetworkLog", "AppFragment rebuilding entries start");
long start = System.currentTimeMillis();
stopUpdater();
synchronized(groupDataBuffer) {
clear();
synchronized(NetworkLog.logFragment.listDataUnfiltered) {
Iterator<LogFragment.ListItem> iterator = NetworkLog.logFragment.listDataUnfiltered.iterator();
LogEntry entry = new LogEntry();
while(iterator.hasNext()) {
LogFragment.ListItem item = iterator.next();
entry.uid = item.app.uid;
entry.in = item.in;
entry.out = item.out;
entry.proto = item.proto;
entry.src = item.srcAddr;
entry.dst = item.dstAddr;
entry.len = item.len;
entry.spt = item.srcPort;
entry.dpt = item.dstPort;
entry.timestamp = item.timestamp;
onNewLogEntry(entry);
}
}
groupDataBufferIsDirty = true;
}
startUpdater();
long elapsed = System.currentTimeMillis() - start;
Log.d("NetworkLog", "AppFragment rebuilding entries end -- elapsed: " + elapsed);
}
// cache objects to prevent unnecessary allocations
private CharArray charBuffer = new CharArray(256);
private String srcKey;
private String dstKey;
private GroupItem newLogItem;
private ChildItem newLogChild;
public void onNewLogEntry(final LogEntry entry) {
if(MyLog.enabled) {
MyLog.d("AppFragment: NewLogEntry: [" + entry.uid + "] in=" + entry.in + " out=" + entry.out + " " + entry.src + ":" + entry.spt + " --> " + entry.dst + ":" + entry.dpt + " [" + entry.len + "]");
}
int index = getItemByAppUid(entry.uid);
if(index < 0) {
MyLog.d("No app entry");
return;
}
synchronized(groupDataBuffer) {
try {
charBuffer.reset();
charBuffer.append(entry.src).append(':').append(entry.spt).append(':').append(entry.proto).append(':');
if(entry.in != null && entry.in.length() > 0) {
charBuffer.append(entry.in);
} else {
charBuffer.append(entry.out);
}
srcKey = StringPool.get(charBuffer);
charBuffer.reset();
charBuffer.append(entry.dst).append(':').append(entry.dpt).append(':').append(entry.proto).append(':');
if(entry.in != null && entry.in.length() > 0) {
charBuffer.append(entry.in);
} else {
charBuffer.append(entry.out);
}
dstKey = StringPool.get(charBuffer);
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("NetworkLog", "[AppFragment.onNewEntry] charBuffer too long, skipping entry", e);
return;
}
// generally this will iterate once, but some apps may be grouped under the same uid
while(true) {
newLogItem = groupDataBuffer.get(index);
if(newLogItem.app.uid != entry.uid) {
break;
}
groupDataBufferIsDirty = true;
newLogItem.totalPackets++;
newLogItem.totalBytes += entry.len;
newLogItem.lastTimestamp = entry.timestamp;
if(entry.in != null && entry.in.length() != 0) {
synchronized(newLogItem.childrenData) {
newLogChild = newLogItem.childrenData.get(srcKey);
if(newLogChild == null) {
newLogChild = new ChildItem();
newLogItem.childrenData.put(srcKey, newLogChild);
}
newLogChild.in = entry.in;
newLogChild.out = null;
newLogChild.proto = entry.proto;
newLogChild.receivedPackets++;
newLogChild.receivedBytes += entry.len;
newLogChild.receivedTimestamp = entry.timestamp;
if(MyLog.enabled) {
MyLog.d("Added received packet index=" + index + " in=" + entry.in + " out=" + entry.out + " proto=" + entry.proto + " " + entry.src + ":" + entry.spt + " --> " + entry.dst + ":" + entry.dpt + "; total: " + newLogChild.receivedPackets + "; bytes: " + newLogChild.receivedBytes);
}
newLogChild.receivedPort = entry.spt;
newLogChild.receivedAddress = entry.src;
newLogChild.sentPort = entry.dpt;
newLogChild.sentAddress = entry.dst;
newLogItem.childrenNeedSort = true;
}
}
if(entry.out != null && entry.out.length() != 0) {
synchronized(newLogItem.childrenData) {
newLogChild = newLogItem.childrenData.get(dstKey);
if(newLogChild == null) {
newLogChild = new ChildItem();
newLogItem.childrenData.put(dstKey, newLogChild);
}
newLogChild.in = null;
newLogChild.out = entry.out;
newLogChild.proto = entry.proto;
newLogChild.sentPackets++;
newLogChild.sentBytes += entry.len;
newLogChild.sentTimestamp = entry.timestamp;
if(MyLog.enabled) {
MyLog.d("Added sent packet index=" + index + " in=" + entry.in + " out=" + entry.out + " " + entry.src + ":" + entry.spt + " --> " + entry.dst + ":" + entry.dpt + "; total: " + newLogChild.sentPackets + "; bytes: " + newLogChild.sentBytes);
}
newLogChild.receivedPort = entry.spt;
newLogChild.receivedAddress = entry.src;
newLogChild.sentPort = entry.dpt;
newLogChild.sentAddress = entry.dst;
newLogItem.childrenNeedSort = true;
}
}
index++;
if(index >= groupDataBuffer.size()) {
break;
}
}
}
}
public void startUpdater() {
if(updater != null) {
updater.stop();
}
updater = new ListViewUpdater();
new Thread(updater, "AppFragmentUpdater").start();
}
public void stopUpdater() {
if(updater != null) {
updater.stop();
}
}
Runnable updaterRunner = new Runnable() {
public void run() {
if(groupData == null) {
return;
}
synchronized(groupData) {
if(MyLog.enabled) {
MyLog.d("AppFragmentListUpdater enter");
}
Log.d("NetworkLog", "AppFragmentListUpdater enter");
if(groupDataBufferIsDirty) {
preSortData();
sortData();
}
if(groupDataBufferIsDirty && (NetworkLog.filterTextInclude.length() > 0 || NetworkLog.filterTextExclude.length() > 0)) {
setFilter("");
} else {
refreshAdapter();
}
}
groupDataBufferIsDirty = false;
needsRefresh = false;
if(MyLog.enabled) {
MyLog.d("AppFragmentListUpdater exit");
}
Log.d("NetworkLog", "AppFragmentListUpdater exit");
}
};
public void updaterRunOnce() {
NetworkLog.handler.post(updaterRunner);
}
// todo: this is largely duplicated in LogFragment -- move to its own file
private class ListViewUpdater implements Runnable {
boolean running = false;
public void stop() {
running = false;
}
public void run() {
running = true;
MyLog.d("Starting AppFragmentUpdater " + this);
while(running) {
if(groupDataBufferIsDirty == true || needsRefresh == true) {
updaterRunOnce();
}
try {
Thread.sleep(1000);
} catch(Exception e) {
Log.d("NetworkLog", "AppFragmentListUpdater", e);
}
}
MyLog.d("Stopped AppFragment updater " + this);
}
}
public void setFilter(CharSequence s) {
if(MyLog.enabled) {
MyLog.d("[AppFragment] setFilter(" + s + ")");
}
adapter.getFilter().filter(s);
}
private class CustomAdapter extends BaseExpandableListAdapter implements Filterable {
LayoutInflater mInflater = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
CustomFilter filter;
private class CustomFilter extends Filter {
FilterResults results = new FilterResults();
@Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<GroupItem> originalItems = new ArrayList<GroupItem>(groupDataBuffer.size());
ArrayList<GroupItem> filteredItems = new ArrayList<GroupItem>(groupDataBuffer.size());
String host;
String iface;
ChildItem childData;
boolean matched;
String sentAddressResolved;
String sentPortResolved;
String receivedAddressResolved;
String receivedPortResolved;
doNotRefresh = true;
if(MyLog.enabled) {
MyLog.d("[AppFragment] performFiltering");
}
Log.d("NetworkLog", "[appFragment] performing filtering");
synchronized(groupDataBuffer) {
originalItems.addAll(groupDataBuffer);
}
if(NetworkLog.filterTextInclude.length() == 0 && NetworkLog.filterTextExclude.length() == 0) {
if(MyLog.enabled) {
MyLog.d("[AppFragment] no constraint item count: " + originalItems.size());
}
// undo uniqueHosts filtering
// fixme: perhaps an array of indices into which items are filtered?
for(GroupItem item : originalItems) {
if(item.childrenAreFiltered) {
item.childrenAreFiltered = false;
item.childrenDataFiltered.clear();
item.childrenNeedSort = true;
}
}
results.values = originalItems;
results.count = originalItems.size();
} else {
int count = originalItems.size();
if(MyLog.enabled) {
MyLog.d("[AppFragment] item count: " + count);
}
if(NetworkLog.filterTextIncludeList.size() == 0) {
if(MyLog.enabled) {
MyLog.d("[AppFragment] no include filter, adding all items");
}
for(GroupItem item : originalItems) {
filteredItems.add(item);
synchronized(item.childrenData) {
item.childrenDataFiltered.clear();
List<String> list = new ArrayList<String>(item.childrenData.keySet());
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
host = itr.next();
childData = item.childrenData.get(host);
if(MyLog.enabled) {
MyLog.d("[AppFragment] adding filtered host " + childData);
}
item.childrenDataFiltered.put(host, childData);
item.childrenAreFiltered = true;
}
}
}
} else {
GroupItem item;
for(int i = 0; i < count; i++) {
item = originalItems.get(i);
// MyLog.d("[AppFragment] testing filtered item " + item + "; includes: [" + NetworkLog.filterTextInclude + "]");
boolean item_added = false;
matched = false;
if(NetworkLog.filterNameInclude || NetworkLog.filterUidInclude) {
for(String c : NetworkLog.filterTextIncludeList) {
if((NetworkLog.filterNameInclude && item.app.nameLowerCase.contains(c))
|| (NetworkLog.filterUidInclude && item.app.uidString.equals(c))) {
matched = true;
}
}
} else {
matched = true;
}
if(matched) {
// test filter against address/port/iface/proto
if(NetworkLog.filterAddressInclude || NetworkLog.filterPortInclude
|| NetworkLog.filterInterfaceInclude || NetworkLog.filterProtocolInclude) {
synchronized(item.childrenData) {
item.childrenDataFiltered.clear();
List<String> list = new ArrayList<String>(item.childrenData.keySet());
// todo: sort by user preference (bytes, timestamp, address, ports)
Collections.sort(list);
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
host = itr.next();
// MyLog.d("[AppFragment] testing " + host);
childData = item.childrenData.get(host);
matched = false;
if(NetworkLog.resolveHosts) {
sentAddressResolved = NetworkLog.resolver.resolveAddress(childData.sentAddress);
if(sentAddressResolved == null) {
sentAddressResolved = "";
}
receivedAddressResolved = NetworkLog.resolver.resolveAddress(childData.receivedAddress);
if(receivedAddressResolved == null) {
receivedAddressResolved = "";
}
} else {
sentAddressResolved = "";
receivedAddressResolved = "";
}
if(NetworkLog.resolvePorts) {
sentPortResolved = NetworkLog.resolver.resolveService(String.valueOf(childData.sentPort));
receivedPortResolved = NetworkLog.resolver.resolveService(String.valueOf(childData.receivedPort));
} else {
sentPortResolved = "";
receivedPortResolved = "";
}
if(childData.in != null && childData.in.length() > 0) {
iface = childData.in;
} else {
iface = childData.out;
}
for(String c : NetworkLog.filterTextIncludeList) {
if((NetworkLog.filterAddressInclude &&
((childData.sentPackets > 0 && (childData.sentAddress.contains(c) || StringPool.getLowerCase(sentAddressResolved).contains(c)))
|| (childData.receivedPackets > 0 && (childData.receivedAddress.contains(c) || StringPool.getLowerCase(receivedAddressResolved).contains(c)))))
|| (NetworkLog.filterPortInclude &&
((childData.sentPackets > 0 && (String.valueOf(childData.sentPort).equals(c) || StringPool.getLowerCase(sentPortResolved).equals(c)))
|| (childData.receivedPackets > 0 && (String.valueOf(childData.receivedPort).equals(c) || StringPool.getLowerCase(receivedPortResolved).equals(c)))))
|| (NetworkLog.filterInterfaceInclude && iface.contains(c))
|| (NetworkLog.filterProtocolInclude && StringPool.getLowerCase(NetworkLog.resolver.resolveProtocol(childData.proto)).equals(c))) {
matched = true;
break;
}
}
if(matched) {
if(!item_added) {
// MyLog.d("[AppFragment] adding filtered item " + item);
filteredItems.add(item);
item_added = true;
}
// MyLog.d("[AppFragment] adding filtered host " + childData);
item.childrenDataFiltered.put(host, childData);
item.childrenAreFiltered = true;
item.childrenNeedSort = true;
}
}
}
} else {
// no filtering for host/port, matches everything
// MyLog.d("[AppFragment] no filter for host/port; adding filtered item " + item);
filteredItems.add(item);
synchronized(item.childrenData) {
List<String> list = new ArrayList<String>(item.childrenData.keySet());
// todo: sort by user preference
Collections.sort(list);
item.childrenDataFiltered.clear();
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
host = itr.next();
childData = item.childrenData.get(host);
// MyLog.d("[AppFragment] adding filtered host " + childData);
item.childrenDataFiltered.put(host, childData);
item.childrenAreFiltered = true;
item.childrenNeedSort = true;
}
}
}
}
}
}
if(NetworkLog.filterTextExcludeList.size() > 0) {
count = filteredItems.size();
GroupItem item;
for(int i = count - 1; i >= 0; i
item = filteredItems.get(i);
// MyLog.d("[AppFragment] testing filtered item: " + i + " " + item + "; excludes: [" + NetworkLog.filterTextExclude + "]");
matched = false;
if(NetworkLog.filterNameExclude || NetworkLog.filterUidExclude) {
for(String c : NetworkLog.filterTextExcludeList) {
if((NetworkLog.filterNameExclude && item.app.nameLowerCase.contains(c))
|| NetworkLog.filterUidExclude && item.app.uidString.equals(c))
{
matched = true;
}
}
} else {
matched = false;
}
if(matched) {
// MyLog.d("[AppFragment] removing filtered item: " + item);
filteredItems.remove(i);
continue;
}
if(NetworkLog.filterAddressExclude || NetworkLog.filterPortExclude
|| NetworkLog.filterInterfaceExclude || NetworkLog.filterProtocolExclude) {
List<String> list = new ArrayList<String>(item.childrenDataFiltered.keySet());
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
host = itr.next();
childData = item.childrenDataFiltered.get(host);
matched = false;
if(NetworkLog.resolveHosts) {
sentAddressResolved = NetworkLog.resolver.resolveAddress(childData.sentAddress);
if(sentAddressResolved == null) {
sentAddressResolved = "";
}
receivedAddressResolved = NetworkLog.resolver.resolveAddress(childData.receivedAddress);
if(receivedAddressResolved == null) {
receivedAddressResolved = "";
}
} else {
sentAddressResolved = "";
receivedAddressResolved = "";
}
if(NetworkLog.resolvePorts) {
sentPortResolved = NetworkLog.resolver.resolveService(String.valueOf(childData.sentPort));
receivedPortResolved = NetworkLog.resolver.resolveService(String.valueOf(childData.receivedPort));
} else {
sentPortResolved = "";
receivedPortResolved = "";
}
if(childData.in != null && childData.in.length() > 0) {
iface = childData.in;
} else {
iface = childData.out;
}
for(String c : NetworkLog.filterTextExcludeList) {
if((NetworkLog.filterAddressExclude &&
((childData.sentPackets > 0 && (childData.sentAddress.contains(c) || StringPool.getLowerCase(sentAddressResolved).contains(c)))
|| (childData.receivedPackets > 0 && (childData.receivedAddress.contains(c) || StringPool.getLowerCase(receivedAddressResolved).contains(c)))))
|| (NetworkLog.filterPortExclude &&
((childData.sentPackets > 0 && (String.valueOf(childData.sentPort).equals(c) || StringPool.getLowerCase(sentPortResolved).equals(c)))
|| (childData.receivedPackets > 0 && (String.valueOf(childData.receivedPort).equals(c) || StringPool.getLowerCase(receivedPortResolved).equals(c)))))
|| (NetworkLog.filterInterfaceExclude && iface.contains(c))
|| (NetworkLog.filterProtocolExclude && StringPool.getLowerCase(NetworkLog.resolver.resolveProtocol(childData.proto)).equals(c))) {
matched = true;
break;
}
}
if(matched) {
// MyLog.d("[AppFragment] removing filtered host [" + host + "] " + childData);
item.childrenDataFiltered.remove(host);
}
}
if(item.childrenDataFiltered.size() == 0 && matched) {
// MyLog.d("[AppFragment] removed all hosts, removing item from filter results");
filteredItems.remove(i);
}
}
}
}
results.values = filteredItems;
results.count = filteredItems.size();
}
if(MyLog.enabled) {
MyLog.d("[AppFragment] filter returning " + results.count + " results");
}
Log.d("NetworkLog", "[AppFragment] filter returning " + results.count + " results");
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(MyLog.enabled) {
MyLog.d("[AppFragment] Publishing filter results");
}
Log.d("NetworkLog", "[AppFragment] Publishing filter results");
synchronized(groupData) {
groupData.clear();
groupData.addAll((ArrayList<GroupItem>) results.values);
preSortData();
sortData();
}
doNotRefresh = false;
refreshAdapter();
Log.d("NetworkLog", "[AppFragment] Published");
}
}
@Override
public CustomFilter getFilter() {
if(filter == null) {
filter = new CustomFilter();
}
return filter;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
GroupItem groupItem = groupData.get(groupPosition);
HashMap<String, ChildItem> children;
if(groupItem.childrenAreFiltered == false) {
children = groupItem.childrenData;
} else {
children = groupItem.childrenDataFiltered;
}
if(groupItem.childrenNeedSort == true || groupItem.childrenDataSorted == null) {
groupItem.childrenNeedSort = false;
if(groupItem.childrenDataSorted == null || groupItem.childrenDataSorted.length < children.size()) {
groupItem.childrenDataSorted = new String[children.size()];
}
children.keySet().toArray(groupItem.childrenDataSorted);
Comparator<String> sortMethod;
switch(sortBy) {
case UID:
sortMethod = new SortChildrenByBytes(groupItem);
break;
case NAME:
sortMethod = new SortChildrenByBytes(groupItem);
break;
case PACKETS:
sortMethod = new SortChildrenByPackets(groupItem);
break;
case BYTES:
sortMethod = new SortChildrenByBytes(groupItem);
break;
case TIMESTAMP:
sortMethod = new SortChildrenByTimestamp(groupItem);
break;
default:
sortMethod = new SortChildrenByBytes(groupItem);
}
Arrays.sort(groupItem.childrenDataSorted, sortMethod);
}
return children.get(groupItem.childrenDataSorted[childPosition]);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public int getChildrenCount(int groupPosition) {
GroupItem groupItem = groupData.get(groupPosition);
if(groupItem.childrenAreFiltered == false) {
return groupItem.childrenData.size();
} else {
return groupItem.childrenDataFiltered.size();
}
}
@Override
public Object getGroup(int groupPosition) {
return groupData.get(groupPosition);
}
@Override
public int getGroupCount() {
return groupData.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
GroupViewHolder holder = null;
ImageView icon;
TextView name;
TextView packets;
TextView bytes;
TextView timestamp;
TextView hosts;
GroupItem item;
synchronized(groupData) {
item = groupData.get(groupPosition);
}
if(convertView == null) {
convertView = mInflater.inflate(R.layout.appitem, null);
holder = new GroupViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (GroupViewHolder) convertView.getTag();
}
if(groupPosition == 0) {
holder.getDivider().setVisibility(View.GONE);
} else {
holder.getDivider().setVisibility(View.VISIBLE);
}
icon = holder.getIcon();
icon.setTag(item.app.packageName);
icon.setImageDrawable(ApplicationsTracker.loadIcon(getActivity().getApplicationContext(), icon, item.app.packageName));
name = holder.getName();
name.setText("(" + item.app.uid + ")" + " " + item.app.name);
packets = holder.getPackets();
packets.setText("Packets: " + item.totalPackets);
bytes = holder.getBytes();
bytes.setText("Bytes: " + item.totalBytes);
timestamp = holder.getTimestamp();
if(item.lastTimestamp != 0) {
timestamp.setText("(" + Timestamp.getTimestamp(item.lastTimestamp) + ")");
timestamp.setVisibility(View.VISIBLE);
} else {
timestamp.setVisibility(View.GONE);
}
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
ChildViewHolder holder = null;
TextView host;
TextView sentPackets;
TextView sentBytes;
TextView sentTimestamp;
TextView receivedPackets;
TextView receivedBytes;
TextView receivedTimestamp;
ChildItem item;
synchronized(groupData) {
item = (ChildItem) getChild(groupPosition, childPosition);
}
if(item == null) {
if(MyLog.enabled) {
MyLog.d("child (" + groupPosition + "," + childPosition + ") not found");
}
return null;
}
if(convertView == null) {
convertView = mInflater.inflate(R.layout.hostitem, null);
holder = new ChildViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
}
host = holder.getHost();
String hostString;
String iface;
if(item.sentPackets > 0 && item.out != null && item.out.length() > 0) {
String sentAddressString;
String sentPortString;
if(NetworkLog.resolveHosts) {
sentAddressString = NetworkLog.resolver.resolveAddress(item.sentAddress);
if(sentAddressString == null) {
sentAddressString = item.sentAddress;
}
} else {
sentAddressString = item.sentAddress;
}
if(NetworkLog.resolvePorts) {
sentPortString = NetworkLog.resolver.resolveService(String.valueOf(item.sentPort));
} else {
sentPortString = String.valueOf(item.sentPort);
}
if(item.proto != null && item.proto.length() > 0) {
iface = NetworkLog.resolver.resolveProtocol(item.proto) + "/" + item.out;
} else {
iface = item.out;
}
hostString = sentAddressString + ":" + sentPortString + " (" + iface + ")";
} else {
String receivedAddressString;
String receivedPortString;
if(NetworkLog.resolveHosts) {
receivedAddressString = NetworkLog.resolver.resolveAddress(item.receivedAddress);
if(receivedAddressString == null) {
receivedAddressString = item.receivedAddress;
}
} else {
receivedAddressString = item.receivedAddress;
}
if(NetworkLog.resolvePorts) {
receivedPortString = NetworkLog.resolver.resolveService(String.valueOf(item.receivedPort));
} else {
receivedPortString = String.valueOf(item.receivedPort);
}
if(item.proto != null && item.proto.length() > 0) {
iface = NetworkLog.resolver.resolveProtocol(item.proto) + "/" + item.in;
} else {
iface = item.in;
}
hostString = receivedAddressString + ":" + receivedPortString + " (" + iface + ")";
}
host.setText(Html.fromHtml("<u>" + hostString + "</u>")); // fixme: cache this
sentPackets = holder.getSentPackets();
sentBytes = holder.getSentBytes();
sentTimestamp = holder.getSentTimestamp();
if(item.sentPackets > 0) {
sentPackets.setText(String.valueOf(item.sentPackets));
sentBytes.setText(String.valueOf(item.sentBytes));
String timestampString = Timestamp.getTimestamp(item.sentTimestamp);
sentTimestamp.setText("(" + timestampString.substring(timestampString.indexOf('-') + 1, timestampString.length()) + ")");
sentPackets.setVisibility(View.VISIBLE);
sentBytes.setVisibility(View.VISIBLE);
sentTimestamp.setVisibility(View.VISIBLE);
holder.getSentLabel().setVisibility(View.VISIBLE);
holder.getSentPacketsLabel().setVisibility(View.VISIBLE);
holder.getSentBytesLabel().setVisibility(View.VISIBLE);
} else {
sentPackets.setVisibility(View.GONE);
sentBytes.setVisibility(View.GONE);
sentTimestamp.setVisibility(View.GONE);
holder.getSentLabel().setVisibility(View.GONE);
holder.getSentPacketsLabel().setVisibility(View.GONE);
holder.getSentBytesLabel().setVisibility(View.GONE);
}
receivedPackets = holder.getReceivedPackets();
receivedBytes = holder.getReceivedBytes();
receivedTimestamp = holder.getReceivedTimestamp();
if(item.receivedPackets > 0) {
receivedPackets.setText(String.valueOf(item.receivedPackets));
receivedBytes.setText(String.valueOf(item.receivedBytes));
String timestampString = Timestamp.getTimestamp(item.receivedTimestamp);
receivedTimestamp.setText("(" + timestampString.substring(timestampString.indexOf('-') + 1, timestampString.length()) + ")");
receivedPackets.setVisibility(View.VISIBLE);
receivedBytes.setVisibility(View.VISIBLE);
receivedTimestamp.setVisibility(View.VISIBLE);
holder.getReceivedLabel().setVisibility(View.VISIBLE);
holder.getReceivedPacketsLabel().setVisibility(View.VISIBLE);
holder.getReceivedBytesLabel().setVisibility(View.VISIBLE);
} else {
receivedPackets.setVisibility(View.GONE);
receivedBytes.setVisibility(View.GONE);
receivedTimestamp.setVisibility(View.GONE);
holder.getReceivedLabel().setVisibility(View.GONE);
holder.getReceivedPacketsLabel().setVisibility(View.GONE);
holder.getReceivedBytesLabel().setVisibility(View.GONE);
}
return convertView;
}
}
private class GroupViewHolder {
private View mView;
private ImageView mDivider = null;
private ImageView mIcon = null;
private TextView mName = null;
private TextView mPackets = null;
private TextView mBytes = null;
private TextView mTimestamp = null;
private TextView mUniqueHosts = null;
public GroupViewHolder(View view) {
mView = view;
}
public ImageView getDivider() {
if(mDivider == null) {
mDivider = (ImageView) mView.findViewById(R.id.appDivider);
}
return mDivider;
}
public ImageView getIcon() {
if(mIcon == null) {
mIcon = (ImageView) mView.findViewById(R.id.appIconx);
}
return mIcon;
}
public TextView getName() {
if(mName == null) {
mName = (TextView) mView.findViewById(R.id.appName);
}
return mName;
}
public TextView getPackets() {
if(mPackets == null) {
mPackets = (TextView) mView.findViewById(R.id.appPackets);
}
return mPackets;
}
public TextView getBytes() {
if(mBytes == null) {
mBytes = (TextView) mView.findViewById(R.id.appBytes);
}
return mBytes;
}
public TextView getTimestamp() {
if(mTimestamp == null) {
mTimestamp = (TextView) mView.findViewById(R.id.appLastTimestamp);
}
return mTimestamp;
}
}
private class ChildViewHolder {
private View mView;
private TextView mHost = null;
private TextView mSentLabel = null;
private TextView mSentPackets = null;
private TextView mSentPacketsLabel = null;
private TextView mSentBytes = null;
private TextView mSentBytesLabel = null;
private TextView mSentTimestamp = null;
private TextView mReceivedLabel = null;
private TextView mReceivedPackets = null;
private TextView mReceivedPacketsLabel = null;
private TextView mReceivedBytes = null;
private TextView mReceivedBytesLabel = null;
private TextView mReceivedTimestamp = null;
public ChildViewHolder(View view) {
mView = view;
}
public TextView getHost() {
if(mHost == null) {
mHost = (TextView) mView.findViewById(R.id.hostName);
}
return mHost;
}
public TextView getSentLabel() {
if(mSentLabel == null) {
mSentLabel = (TextView) mView.findViewById(R.id.sentLabel);
}
return mSentLabel;
}
public TextView getSentPacketsLabel() {
if(mSentPacketsLabel == null) {
mSentPacketsLabel = (TextView) mView.findViewById(R.id.sentPacketsLabel);
}
return mSentPacketsLabel;
}
public TextView getSentBytesLabel() {
if(mSentBytesLabel == null) {
mSentBytesLabel = (TextView) mView.findViewById(R.id.sentBytesLabel);
}
return mSentBytesLabel;
}
public TextView getSentPackets() {
if(mSentPackets == null) {
mSentPackets = (TextView) mView.findViewById(R.id.sentPackets);
}
return mSentPackets;
}
public TextView getSentBytes() {
if(mSentBytes == null) {
mSentBytes = (TextView) mView.findViewById(R.id.sentBytes);
}
return mSentBytes;
}
public TextView getSentTimestamp() {
if(mSentTimestamp == null) {
mSentTimestamp = (TextView) mView.findViewById(R.id.sentTimestamp);
}
return mSentTimestamp;
}
public TextView getReceivedLabel() {
if(mReceivedLabel == null) {
mReceivedLabel = (TextView) mView.findViewById(R.id.receivedLabel);
}
return mReceivedLabel;
}
public TextView getReceivedPacketsLabel() {
if(mReceivedPacketsLabel == null) {
mReceivedPacketsLabel = (TextView) mView.findViewById(R.id.receivedPacketsLabel);
}
return mReceivedPacketsLabel;
}
public TextView getReceivedBytesLabel() {
if(mReceivedBytesLabel == null) {
mReceivedBytesLabel = (TextView) mView.findViewById(R.id.receivedBytesLabel);
}
return mReceivedBytesLabel;
}
public TextView getReceivedPackets() {
if(mReceivedPackets == null) {
mReceivedPackets = (TextView) mView.findViewById(R.id.receivedPackets);
}
return mReceivedPackets;
}
public TextView getReceivedBytes() {
if(mReceivedBytes == null) {
mReceivedBytes = (TextView) mView.findViewById(R.id.receivedBytes);
}
return mReceivedBytes;
}
public TextView getReceivedTimestamp() {
if(mReceivedTimestamp == null) {
mReceivedTimestamp = (TextView) mView.findViewById(R.id.receivedTimestamp);
}
return mReceivedTimestamp;
}
}
}
|
package com.irccloud.android;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import org.json.JSONObject;
public class EventsDataSource {
public class Event {
long eid;
long bid;
int cid;
String type;
int highlight;
JSONObject event;
}
public class comparator implements Comparator<Event> {
public int compare(Event e1, Event e2) {
if(e1.eid == e2.eid)
return 0;
else if(e1.eid > e2.eid)
return 1;
else return -1;
}
}
private ArrayList<Event> events;
private static EventsDataSource instance = null;
public static EventsDataSource getInstance() {
if(instance == null)
instance = new EventsDataSource();
return instance;
}
public EventsDataSource() {
events = new ArrayList<Event>();
}
public void clear() {
events.clear();
}
public Event createEvent(long eid, int bid, int cid, String type, int highlight, JSONObject event) {
Event e = new Event();
e.eid = eid;
e.bid = bid;
e.cid = cid;
e.type = type;
e.highlight = highlight;
e.event = event;
events.add(e);
return e;
}
public Event getEvent(long eid, int bid) {
Iterator<Event> i = events.iterator();
while(i.hasNext()) {
Event e = i.next();
if(e.eid == eid && e.bid == bid)
return e;
}
return null;
}
public void deleteEvent(long eid, int bid) {
Event e = getEvent(eid, bid);
if(e != null)
events.remove(e);
}
public void deleteEventsForServer(int cid) {
ArrayList<Event> eventsToRemove = new ArrayList<Event>();
Iterator<Event> i = events.iterator();
while(i.hasNext()) {
Event e = i.next();
if(e.cid == cid)
eventsToRemove.add(e);
}
i=eventsToRemove.iterator();
while(i.hasNext()) {
Event e = i.next();
events.remove(e);
}
}
public void deleteEventsForBuffer(int bid) {
ArrayList<Event> eventsToRemove = new ArrayList<Event>();
Iterator<Event> i = events.iterator();
while(i.hasNext()) {
Event e = i.next();
if(e.bid == bid)
eventsToRemove.add(e);
}
i=eventsToRemove.iterator();
while(i.hasNext()) {
Event e = i.next();
events.remove(e);
}
}
public ArrayList<Event> getEventsForBuffer(int bid) {
ArrayList<Event> list = new ArrayList<Event>();
Iterator<Event> i = events.iterator();
while(i.hasNext()) {
Event e = i.next();
if(e.bid == bid)
list.add(e);
}
Collections.sort(list, new comparator());
return list;
}
public int getUnreadCountForBuffer(long bid, long last_seen_eid) {
int count = 0;
Iterator<Event> i = events.iterator();
while(i.hasNext()) {
Event e = i.next();
if(e.bid == bid && e.eid > last_seen_eid && (e.type.equals("buffer_msg") || e.type.equals("buffer_me_msg") ||e.type.equals("notice")))
count++;
}
return count;
}
public int getHighlightCountForBuffer(long bid, long last_seen_eid) {
int count = 0;
Iterator<Event> i = events.iterator();
while(i.hasNext()) {
Event e = i.next();
if(e.bid == bid && e.eid > last_seen_eid && e.highlight == 1)
count++;
}
return count;
}
}
|
package com.jorgediaz.util.model;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.MethodKey;
import com.liferay.portal.model.ClassedModel;
import com.liferay.portal.service.GroupLocalServiceUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ModelFactory {
public ModelFactory() {
this(null, null);
}
public ModelFactory(Class<? extends Model> defaultModelClass) {
this(defaultModelClass, null);
}
public ModelFactory(
Class<? extends Model> defaultModelClass,
Map<String, Class<? extends Model>> modelClassMap) {
this.classLoader = ModelUtil.getClassLoader();
if (defaultModelClass == null) {
this.defaultModelClass = DefaultModel.class;
}
else {
this.defaultModelClass = defaultModelClass;
}
this.modelClassMap = modelClassMap;
}
public Map<String, Model> getModelMap(Collection<String> classNames) {
Map<String, Model> modelMap = new LinkedHashMap<String, Model>();
for (String classname : classNames) {
Model model = null;
String[] attributes = null;
try {
model = this.getModelObject(classname);
if (model != null) {
attributes = model.getAttributesName();
}
}
catch (Exception e) {
if (_log.isInfoEnabled()) {
_log.info(
"Cannot get model object of " + classname +
" EXCEPTION: " + e.getClass().getName() + ": " +
e.getMessage());
}
}
if ((model != null) && (attributes != null)) {
modelMap.put(model.getName(), model);
}
}
return modelMap;
}
public Model getModelObject(Class<? extends ClassedModel> clazz) {
if ((clazz == null) || !ClassedModel.class.isAssignableFrom(clazz)) {
if (_log.isDebugEnabled()) {
_log.debug(
"Class: " + clazz.getName() + "is null or does not "+
"implements ClassedModel, returning null");
}
return null;
}
String className = clazz.getName();
Class<? extends Model> modelClass = this.defaultModelClass;
if ((this.modelClassMap != null) &&
this.modelClassMap.containsKey(className)) {
modelClass = this.modelClassMap.get(className);
}
Model model = null;
try {
model = (Model)modelClass.newInstance();
model.init(this, clazz);
}
catch (Exception e) {
_log.error(
"getModelObject(" + clazz.getName() + ") ERROR " +
e.getClass().getName() + ": " + e.getMessage());
throw new RuntimeException(e);
}
return model;
}
/**
* primaries keys can be at following ways:
*
* - single => create table
* UserGroupGroupRole (userGroupId LONG not null,groupId LONG not
* null,roleId LONG not null,primary key (userGroupId, groupId, roleId))";
*
* - multi => create table JournalArticle (uuid_ VARCHAR(75) null,id_ LONG
* not null primary key,resourcePrimKey LONG,groupId LONG,companyId LONG,
* userId LONG,userName VARCHAR(75) null,createDate DATE null,modifiedDate
* DATE null,folderId LONG,classNameId LONG,classPK LONG,treePath STRING
* null,articleId VARCHAR(75) null,version DOUBLE,title STRING null,urlTitle
* VARCHAR(150) null,description TEXT null,content TEXT null,type_
* VARCHAR(75) null,structureId VARCHAR(75) null,templateId VARCHAR(75)
* null,layoutUuid VARCHAR(75) null,displayDate DATE null,expirationDate
* DATE null,reviewDate DATE null,indexable BOOLEAN,smallImage
* BOOLEAN,smallImageId LONG,smallImageURL STRING null,status
* INTEGER,statusByUserId LONG,statusByUserName VARCHAR(75) null,statusDate
* DATE null)
*/
@SuppressWarnings("unchecked")
public final Model getModelObject(String className) {
Class<? extends ClassedModel> clazz;
try {
clazz =
(Class<? extends ClassedModel>)ModelUtil.getJavaClass(
javaClasses, classLoader, className);
}
catch (ClassNotFoundException e) {
_log.error("Class not found: " + className);
throw new RuntimeException(e);
}
return getModelObject(clazz);
}
protected List<?> executeDynamicQuery(
Class<? extends ClassedModel> clazz, DynamicQuery dynamicQuery) {
try {
Method method = getExecuteDynamicQueryMethod(clazz);
if (method == null) {
return null;
}
return (List<?>)method.invoke(null, dynamicQuery);
}
catch (ClassNotFoundException | NoSuchMethodException e) {
if (_log.isWarnEnabled()) {
_log.warn(
"executeDynamicQuery: dynamicQuery method not found for " +
clazz.getName() + " - " + e.getMessage());
}
try {
return (List<?>)GroupLocalServiceUtil.dynamicQuery(
dynamicQuery);
}
catch (SystemException se) {
throw new RuntimeException(
"executeDynamicQuery: error executing " +
"GroupLocalServiceUtil.dynamicQuery for " +
clazz.getName(), se);
}
}
catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
String cause = "";
Throwable rootException = e.getCause();
if (rootException != null) {
cause = " (root cause: " + rootException.getMessage() + ")";
}
throw new RuntimeException(
"executeDynamicQuery: error invoking dynamicQuery method for " +
clazz.getName() + cause, e);
}
}
protected ClassedModel fetchObject(
Class<? extends ClassedModel> clazz, long primaryKey) {
try {
Method method = getFetchObjectMethod(clazz);
if (method == null) {
return null;
}
return (ClassedModel)method.invoke(null, primaryKey);
}
catch (NoSuchMethodException | ClassNotFoundException
| SecurityException e) {
throw new RuntimeException(
"fetchObject: fetch" + clazz.getSimpleName() +
" method not found for " + clazz.getName(), e);
}
catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
String cause = "";
Throwable rootException = e.getCause();
if (rootException != null) {
cause = " (root cause: " + rootException.getMessage() + ")";
}
throw new RuntimeException(
"fetchObject: fetch" + clazz.getSimpleName() + " method for " +
clazz.getName() + cause, e);
}
}
protected Object[][] getDatabaseAttributesArr(
Class<? extends ClassedModel> clazz) {
String liferayModelImpl = ModelUtil.getLiferayModelImplClassName(clazz);
Class<?> classLiferayModelImpl;
try {
classLiferayModelImpl =
ModelUtil.getJavaClass(
javaClasses, classLoader, liferayModelImpl);
}
catch (ClassNotFoundException e) {
_log.error("Class not found: " + liferayModelImpl);
throw new RuntimeException(e);
}
if (classLiferayModelImpl == null) {
_log.error("Class not found: " + liferayModelImpl);
throw new RuntimeException("Class not found: " + liferayModelImpl);
}
Object[][] tableColumns =
(Object[][])ModelUtil.getLiferayModelImplField(
classLiferayModelImpl, "TABLE_COLUMNS");
if (_log.isDebugEnabled()) {
_log.debug(
"Database attributes array of " + clazz.getName() +
": " + Arrays.toString(tableColumns));
}
return tableColumns;
}
protected String getDatabaseAttributesStr(
Class<? extends ClassedModel> clazz) {
String liferayModelImpl = ModelUtil.getLiferayModelImplClassName(clazz);
Class<?> classLiferayModelImpl;
try {
classLiferayModelImpl =
ModelUtil.getJavaClass(
javaClasses, classLoader, liferayModelImpl);
}
catch (ClassNotFoundException e) {
_log.error("Class not found: " + liferayModelImpl);
throw new RuntimeException(e);
}
if (classLiferayModelImpl == null) {
_log.error("Class not found: " + liferayModelImpl);
throw new RuntimeException("Class not found: " + liferayModelImpl);
}
String tableName =
(String)ModelUtil.getLiferayModelImplField(
classLiferayModelImpl, "TABLE_NAME");
String tableSqlCreate =
(String)ModelUtil.getLiferayModelImplField(
classLiferayModelImpl, "TABLE_SQL_CREATE");
int posTableName = tableSqlCreate.indexOf(tableName);
if (posTableName <= 0) {
_log.error("Error, TABLE_NAME not found at TABLE_SQL_CREATE");
return null;
}
posTableName = posTableName + tableName.length() + 2;
String tableAttributes = tableSqlCreate.substring(
posTableName, tableSqlCreate.length() - 1);
int posPrimaryKeyMultiAttr = tableAttributes.indexOf(",primary key (");
if (posPrimaryKeyMultiAttr > 0) {
tableAttributes = tableAttributes.replaceAll(
",primary key \\(", "
tableAttributes = tableAttributes.substring(
0, tableAttributes.length() - 1);
}
if (_log.isDebugEnabled()) {
_log.debug(
"Database attributes of " + clazz.getName() + ": " +
tableAttributes);
}
return tableAttributes;
}
protected Method getExecuteDynamicQueryMethod(
Class<? extends ClassedModel> clazz)
throws ClassNotFoundException, NoSuchMethodException,
SecurityException {
Method method = null;
if (executeDynamicQueryMethods.containsKey(clazz.getName())) {
try {
method = executeDynamicQueryMethods.get(
clazz.getName()).getMethod();
}
catch (NoSuchMethodException e) {
}
}
if (method == null) {
String localServiceUtil =
ModelUtil.getLiferayLocalServiceUtilClassName(clazz);
Class<?> classLocalServiceUtil =
ModelUtil.getJavaClass(
javaClasses, classLoader, localServiceUtil);
if (localServiceUtil != null) {
method =
classLocalServiceUtil.getMethod(
"dynamicQuery", DynamicQuery.class);
}
if (method == null) {
executeDynamicQueryMethods.put(
clazz.getName(), new MethodKey());
}
else {
executeDynamicQueryMethods.put(clazz.getName(), new MethodKey(
method));
}
}
return method;
}
protected Method getFetchObjectMethod(Class<? extends ClassedModel> clazz)
throws ClassNotFoundException, NoSuchMethodException,
SecurityException {
Method method = null;
if (fetchObjectMethods.containsKey(clazz.getName())) {
try {
method = fetchObjectMethods.get(clazz.getName()).getMethod();
}
catch (NoSuchMethodException e) {
}
}
if (method == null) {
String localServiceUtil =
ModelUtil.getLiferayLocalServiceUtilClassName(clazz);
Class<?> classLocalServiceUtil =
ModelUtil.getJavaClass(
javaClasses, classLoader, localServiceUtil);
if (localServiceUtil != null) {
method =
classLocalServiceUtil.getMethod(
"fetch" + clazz.getSimpleName(), long.class);
}
if (method == null) {
fetchObjectMethods.put(clazz.getName(), new MethodKey());
}
else {
fetchObjectMethods.put(clazz.getName(), new MethodKey(method));
}
}
return method;
}
protected DynamicQuery newDynamicQuery(
Class<? extends ClassedModel> clazz, String alias) {
return DynamicQueryFactoryUtil.forClass(clazz, alias, classLoader);
}
protected ClassLoader classLoader = null;
protected Class<? extends Model> defaultModelClass = null;
protected Map<String, Class<? extends Model>> modelClassMap = null;
private static Log _log = LogFactoryUtil.getLog(ModelFactory.class);
private Map<String, MethodKey> executeDynamicQueryMethods =
new ConcurrentHashMap<String, MethodKey>();
private Map<String, MethodKey> fetchObjectMethods =
new ConcurrentHashMap<String, MethodKey>();
private Map<String, Class<?>> javaClasses =
new ConcurrentHashMap<String, Class<?>>();
}
|
package com.oux.photocaption;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.Charset;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ActionBar.OnNavigationListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.graphics.Bitmap;
import android.util.Log;
import android.content.Intent;
import android.content.Context;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.ComponentName;
import android.content.pm.LabeledIntent;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.Toast;
import android.widget.ImageView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.SpinnerAdapter;
import android.widget.ArrayAdapter;
import android.database.Cursor;
import android.view.Display;
import android.view.Window;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.content.SharedPreferences;
import com.android.gallery3d.exif.ExifInterface;
import com.android.gallery3d.exif.ExifTag;
import com.android.gallery3d.exif.IfdId;
import android.preference.PreferenceManager;
public class PhotoCaptionEdit extends Activity
{
static final String TAG = "PhotoCaptionEdit";
private static final String CAMAPP = "pref_edit_camapp";
private Uri imageUri;
private String mInitialDescription;
private static int SHOT = 100;
private static int SETTINGS = 101;
EditText descriptionView;
ImageView imageView;
File mFile;
ActionBar actionBar;
public static final String ACTION_REVIEW = "com.android.camera.action.REVIEW";
AlertDialog saveDialog;
AlertDialog deleteDialog;
static boolean mBackToShot = false;
static boolean mOneMoreShot = false;
Point mSize;
SharedPreferences mSharedPrefs;
int mTagId;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.i(TAG,"onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.app_name);
actionBar.setSubtitle(R.string.mode_edit);
Display display = getWindowManager().getDefaultDisplay();
mSize = new Point();
display.getSize(mSize);
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String tagId = mSharedPrefs.getString("pref_edit_exif_field", Integer.toString(ExifInterface.TAG_USER_COMMENT));
mTagId = Integer.parseInt(tagId);
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
Log.d(TAG,"intent:" + intent + " action:" + action + " type:" + type);
imageView = (ImageView) findViewById(R.id.ImageView);
descriptionView = (EditText)findViewById(R.id.Description);
mBackToShot = intent.getBooleanExtra("backToShot",false);
Log.i(TAG,"mBackToShot:" + mBackToShot);
// Dialogs
saveDialog = new AlertDialog.Builder(
this).create();
saveDialog.setTitle(R.string.save);
saveDialog.setMessage(getResources().getString(R.string.ask_save_description));
saveDialog.setIcon(android.R.drawable.ic_menu_save);
saveDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
getResources().getString(R.string.donotsave), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (mOneMoreShot)
{
Intent intent = new Intent(getApplicationContext(),PhotoCaptionCapture.class);
startActivity(intent);
}
finish();
}
});
saveDialog.setButton(DialogInterface.BUTTON_POSITIVE,
getResources().getString(R.string.save), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setDescription(descriptionView.getText().toString());
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.saved), Toast.LENGTH_SHORT).show();
if (mBackToShot || mOneMoreShot)
{
Intent intent = new Intent(getApplicationContext(),PhotoCaptionCapture.class);
startActivity(intent);
}
finish();
}
});
deleteDialog = new AlertDialog.Builder(
this).create();
deleteDialog.setTitle(getResources().getString(R.string.delete));
deleteDialog.setMessage(getResources().getString(R.string.ask_delete_image));
deleteDialog.setIcon(android.R.drawable.ic_menu_delete);
deleteDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
getResources().getString(R.string.donotdelete), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
deleteDialog.setButton(DialogInterface.BUTTON_POSITIVE,
getResources().getString(R.string.delete), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.deleted), Toast.LENGTH_SHORT).show();
getContentResolver().delete(imageUri,null,null);
finish();
}
});
// TODO:
// ACTION_REVIEW.equalsIgnoreCase(action)...
if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_EDIT.equals(action))
{
Log.d(TAG,"Action: "+ action);
imageUri = intent.getData();
handleImage();
} else if (Intent.ACTION_SEND.equals(action) && type != null) {
Log.d(TAG,"Action: Send");
if (type.startsWith("image/")) {
imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
handleImage();
}
} else {
Log.d(TAG,"Nothing todo");
finish();
}
}
@Override
public void onDestroy()
{
if (imageView != null)
{
BitmapDrawable bd = (BitmapDrawable)imageView.getDrawable();
if (bd != null && bd.getBitmap() != null)
bd.getBitmap().recycle();
imageView.setImageBitmap(null);
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.action_capture:
if (mInitialDescription.equals(descriptionView.getText().toString()))
{
intent = new Intent(getApplicationContext(),PhotoCaptionCapture.class);
startActivity(intent);
finish();
}
else
{
mOneMoreShot=true;
saveDialog.show();
}
return true;
case R.id.action_del:
deleteDialog.show();
return true;
case R.id.action_cancel:
if (mInitialDescription.equals(descriptionView.getText().toString()))
{
// intent = new Intent(getApplicationContext(),PhotoCaptionGallery.class);
// startActivity(intent);
finish();
}
else
saveDialog.show();
return true;
case R.id.action_settings:
intent = new Intent(getApplicationContext(),PhotoCaptionSettings.class);
startActivityForResult(intent,SETTINGS);
return true;
case R.id.action_save:
setDescription(descriptionView.getText().toString());
if (mBackToShot)
{
intent = new Intent(getApplicationContext(),PhotoCaptionCapture.class);
startActivity(intent);
}
/*
else
{
intent = new Intent(getApplicationContext(),PhotoCaptionGallery.class);
startActivity(intent);
}
*/
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
if (mInitialDescription.equals(descriptionView.getText().toString()))
finish();
else
saveDialog.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SETTINGS) {
String tagId = mSharedPrefs.getString("pref_edit_exif_field", Integer.toString(ExifInterface.TAG_USER_COMMENT));
mTagId = Integer.parseInt(tagId);
handleImage();
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String ret = cursor.getString(idx);
cursor.close();
return ret;
}
void handleImage() {
if (imageUri != null) {
Log.i(TAG, "Incoming image Uri=" + imageUri + " path=" + imageUri.getPath());
Bitmap preview_bitmap = null;
try {
String image;
if (imageUri.getScheme().equals("content"))
image = getRealPathFromURI(imageUri);
else
image = imageUri.getPath();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(image ,options);
int h=(int) Math.ceil(options.outHeight/(float)mSize.y);
int w=(int) Math.ceil(options.outWidth/(float)mSize.x);
if(h>1 || w>1){
if(h>w){
options.inSampleSize=h;
}else{
options.inSampleSize=w;
}
}
options.inJustDecodeBounds=false;
preview_bitmap=BitmapFactory.decodeFile(image,options);
imageView.setImageBitmap(preview_bitmap);
mInitialDescription = getDescription();
descriptionView.setText(mInitialDescription);
} catch (Exception e) {
e.printStackTrace();
}
}
}
String getDescription()
{
ExifInterface exifInterface = new ExifInterface();
try {
exifInterface.readExif(getContentResolver().openInputStream(imageUri));
} catch (Exception e) {
e.printStackTrace();
return "";
}
ExifTag tag = exifInterface.getTag(mTagId);
if (tag != null)
{
String description = tag.getValueAsString();
CharsetEncoder encoder =
Charset.forName("US-ASCII").newEncoder();
if (encoder.canEncode(description)) {
return description;
} else {
return "<BINARY DATA>";
}
}
return "";
}
public String decompose(String s) {
return java.text.Normalizer.normalize(s,
java.text.Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+","");
}
void setDescription(String description)
{
Log.i(TAG,"Setting description:" + description + " on " + imageUri);
ExifInterface exifInterface = new ExifInterface();
ExifTag tag = exifInterface.buildTag(mTagId, decompose(description));
if(tag != null) {
exifInterface.setTag(tag);
}
try {
if (imageUri.getScheme().equals("content"))
{
Log.i(TAG,"Content");
exifInterface.forceRewriteExif(getRealPathFromURI(imageUri));
} else {
Log.i(TAG,"File");
exifInterface.forceRewriteExif(imageUri.getPath());
}
} catch (Exception e) {
Toast.makeText(this,
getResources().getString(R.string.tagnotsaved), Toast.LENGTH_LONG).show();
Log.e(TAG, "forceRewriteExif");
e.printStackTrace();
}
}
}
|
package com.preplay.android.i18next;
/**
* @author stan
*
*/
public interface Operation {
public interface PostOperation extends Operation {
public abstract String postProcess(String source);
}
public interface PreOperation extends Operation {
public abstract String preProcess(String key);
public abstract String preProcessAfterNoValueFound(String key);
}
public static class MultiPostProcessing implements PostOperation, PreOperation {
private Operation[] mOperations;
public MultiPostProcessing(Operation... operations) {
mOperations = operations;
}
@Override
public String postProcess(String source) {
if (mOperations != null) {
for (Operation operation : mOperations) {
if (operation instanceof PostOperation) {
source = ((PostOperation) operation).postProcess(source);
}
}
}
return source;
}
@Override
public String preProcess(String key) {
if (mOperations != null) {
for (Operation operation : mOperations) {
if (operation instanceof PreOperation) {
key = ((PreOperation) operation).preProcess(key);
}
}
}
return key;
}
@Override
public String preProcessAfterNoValueFound(String key) {
return null;
}
}
public static class Plural implements PreOperation, PostOperation {
private int mCount;
private Interpolation mInterpolation;
public Plural(int count) {
this("count", count);
}
public Plural(String key, int count) {
mInterpolation = new Interpolation(key, Integer.toString(count));
mCount = count;
}
@Override
public String preProcess(String key) {
if (key != null) {
int pluralExtension = Plurals.getInstance().get(I18Next.getInstance().getOptions().getLanguage(), mCount);
if (pluralExtension != 1) {
// plural
key = key + I18Next.getInstance().getOptions().getPluralSuffix();
if (pluralExtension >= 0) {
// specific plural
key = key + "_" + pluralExtension;
}
}
}
return key;
}
@Override
public String preProcessAfterNoValueFound(String key) {
int index = key.lastIndexOf(I18Next.getInstance().getOptions().getPluralSuffix());
if (index > 0) {
return key.substring(0, index);
} else {
return null;
}
}
@Override
public String postProcess(String source) {
return mInterpolation.postProcess(source);
}
}
public static class Context implements PreOperation {
private String mContextPrefix;
public Context(String value) {
mContextPrefix = I18Next.getInstance().getOptions().getContextPrefix() + value;
}
@Override
public String preProcess(String key) {
if (mContextPrefix != null && mContextPrefix.length() > 0 && key != null) {
String keyWithContext = key + mContextPrefix;
if (I18Next.getInstance().existValue(keyWithContext)) {
key = keyWithContext;
}
}
return key;
}
@Override
public String preProcessAfterNoValueFound(String key) {
return null;
}
}
public static class SPrintF implements PostOperation {
private Object[] mArgs;
public SPrintF(Object... args) {
mArgs = args;
}
@Override
public String postProcess(String source) {
if (source != null && mArgs != null && mArgs.length > 0) {
source = String.format(source, mArgs);
}
return source;
}
}
public static class Interpolation implements PostOperation {
private StringBuffer mStringBuffer = new StringBuffer();
private CharSequence mTarget;
private CharSequence mReplacement;
public Interpolation(CharSequence target, CharSequence replacement) {
mTarget = target;
mReplacement = replacement;
}
@Override
public String postProcess(String source) {
if (source != null && mTarget != null && mTarget.length() > 0) {
Options options = I18Next.getInstance().getOptions();
String interpolationPrefix = options.getInterpolationPrefix();
String interpolationSuffix = options.getInterpolationSuffix();
mStringBuffer.setLength(0);
mStringBuffer.append(interpolationPrefix);
mStringBuffer.append(mTarget);
mStringBuffer.append(interpolationSuffix);
source = source.replace(mStringBuffer.toString(), mReplacement);
}
return source;
}
}
public static class DefaultValue implements PostOperation {
private String mValue;
public DefaultValue(String value) {
mValue = value;
}
@Override
public String postProcess(String source) {
if (source == null) {
source = mValue;
}
return source;
}
}
}
|
package com.redhat.ceylon.common;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
public class ConfigWriter {
public static void write(CeylonConfig config, File source, File destination) throws IOException {
boolean overwriteSource = destination.getCanonicalFile().equals(source.getCanonicalFile());
if (source.isFile()) {
InputStream in = null;
OutputStream out = null;
File tmpFile = null;
try {
in = new FileInputStream(source);
if (overwriteSource) {
// Send the output to a temporary file first
tmpFile = File.createTempFile(source.getName(), "tmp", source.getParentFile());
out = new FileOutputStream(tmpFile);
} else {
out = new FileOutputStream(destination);
}
write(config, in, out);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) { }
}
if (in != null) {
try {
in.close();
} catch (IOException e) { }
}
if (tmpFile != null) {
tmpFile.delete();
}
}
} else {
throw new FileNotFoundException("Couldn't open source configuration file");
}
}
public static void write(CeylonConfig config, File source, OutputStream out) throws IOException {
if (source.isFile()) {
InputStream in = null;
try {
in = new FileInputStream(source);
write(config, in, out);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) { }
}
}
} else {
throw new FileNotFoundException("Couldn't open source configuration file");
}
}
public static void write(CeylonConfig config, InputStream in, File destination) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(destination);
write(config, in, out);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) { }
}
}
}
public static void write(CeylonConfig config, File destination) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(destination);
write(config, out);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) { }
}
}
}
public static void write(CeylonConfig orgconfig, InputStream in, OutputStream out) throws IOException {
final CeylonConfig config = orgconfig.copy();
final Writer writer = new BufferedWriter(new OutputStreamWriter(out, Charset.forName("UTF-8")));
ConfigReader reader = new ConfigReader(in, new ImprovedConfigReaderListenerAdapter(new ImprovedConfigReaderListener() {
private boolean skipToNewline = false;
@Override
public void setup() throws IOException {
// Ignoring setup
}
@Override
public void onSection(String section, String text) throws IOException {
if (config.isSectionDefined(section)) {
writer.write(text);
skipToNewline = false;
} else {
skipToNewline = true;
}
}
@Override
public void onSectionEnd(String section) throws IOException {
writeOptions(writer, config, section);
}
@Override
public void onOption(String name, String value, String text) throws IOException {
if (config.isOptionDefined(name)) {
writer.write(text);
removeOptionValue(name);
skipToNewline = false;
} else {
skipToNewline = true;
}
}
@Override
public void onComment(String text) throws IOException {
if (skipToNewline) {
skipToNewline = !text.contains("\n");
} else {
writer.write(text);
}
}
@Override
public void onWhitespace(String text) throws IOException {
if (skipToNewline) {
skipToNewline = !text.contains("\n");
} else {
writer.write(text);
}
}
@Override
public void cleanup() throws IOException {
// Ignoring cleanup
}
private void removeOptionValue(String name) {
String[] values = config.getOptionValues(name);
if (values.length > 1) {
values = Arrays.copyOfRange(values, 1, values.length);
config.setOptionValues(name, values);
} else {
config.removeOption(name);
}
}
}));
reader.process();
writer.flush();
// Now write what's left of the configuration to the output
writeSections(writer, config, out);
}
public static void write(CeylonConfig orgconfig, OutputStream out) throws IOException {
final CeylonConfig config = orgconfig.copy();
final Writer writer = new BufferedWriter(new OutputStreamWriter(out, Charset.forName("UTF-8")));
writeSections(writer, config, out);
}
private static void writeSections(Writer writer, CeylonConfig config, OutputStream out) throws IOException {
String[] sections = config.getSectionNames(null);
Arrays.sort(sections);
for (String section : sections) {
if (config.getOptionNames(section).length > 0) {
writer.write(System.lineSeparator());
writer.write("[");
writer.write(section);
writer.write("]");
writer.write(System.lineSeparator());
writeOptions(writer, config, section);
}
}
}
protected static void writeOptions(Writer writer, CeylonConfig config, String section) throws IOException {
String[] names = config.getOptionNames(section);
for (String name : names) {
writeOption(writer, config, name);
config.removeOption(name);
}
}
protected static void writeOption(Writer writer, CeylonConfig config, String name) throws IOException {
String[] values = config.getOptionValues(name);
for (String value : values) {
writer.write(name);
writer.write("=");
writer.write(quote(value));
writer.write(System.lineSeparator());
}
}
private static String quote(String value) {
value = value.replace("\\", "\\\\");
value = value.replace("\"", "\\\"");
value = value.replace("\t", "\\t");
value = value.replace("\n", "\\n");
boolean needsQuotes = value.contains(";") || value.contains("#") || value.endsWith(" ");
if (needsQuotes) {
return "\"" + value + "\"";
} else {
return value;
}
}
}
interface ImprovedConfigReaderListener extends ConfigReaderListener {
public void onSectionEnd(String section) throws IOException;
}
// This adapter class improves on the standard ConfigReaderListener interface
// by adding an onSectionEnd() event which will be triggered at the end of
// each configuration section. It tries to be smart about this by considering
// whitespace and comments on the last option line to be still part of the
// last section while considering all whitespace and comments before a section
// line to be part of the new section
class ImprovedConfigReaderListenerAdapter implements ConfigReaderListener {
private ImprovedConfigReaderListener listener;
private String currentSection;
private boolean skipToNewline;
private ArrayList<Text> buffer;
interface Text {
String getText();
}
class Comment implements Text {
private String text;
public Comment(String text) {
this.text = text;
}
@Override
public String getText() {
return text;
}
}
class Whitespace implements Text {
private String text;
public Whitespace(String text) {
this.text = text;
}
@Override
public String getText() {
return text;
}
}
public ImprovedConfigReaderListenerAdapter(ImprovedConfigReaderListener listener) {
this.listener = listener;
this.currentSection = null;
this.skipToNewline = false;
this.buffer = new ArrayList<Text>();
}
@Override
public void setup() throws IOException {
// Ignoring setup
}
@Override
public void onSection(String section, String text) throws IOException {
if (currentSection != null) {
listener.onSectionEnd(currentSection);
}
flushBuffer();
currentSection = section;
listener.onSection(section, text);
skipToNewline = true;
}
@Override
public void onOption(String name, String value, String text) throws IOException {
flushBuffer();
listener.onOption(name, value, text);
skipToNewline = true;
}
@Override
public void onComment(String text) throws IOException {
if (skipToNewline) {
listener.onComment(text);
skipToNewline = !text.contains("\n");
} else {
buffer.add(new Comment(text));
}
}
@Override
public void onWhitespace(String text) throws IOException {
if (skipToNewline) {
listener.onWhitespace(text);
skipToNewline = !text.contains("\n");
} else {
buffer.add(new Whitespace(text));
}
}
@Override
public void cleanup() throws IOException {
if (currentSection != null) {
listener.onSectionEnd(currentSection);
}
flushBuffer();
}
private void flushBuffer() throws IOException {
for (Text t : buffer) {
if (t instanceof Comment) {
listener.onComment(t.getText());
} else if (t instanceof Whitespace) {
listener.onWhitespace(t.getText());
}
}
buffer.clear();
}
}
|
package com.wrapp.android.webimage;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import java.io.*;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ImageCache {
private static final long ONE_DAY_IN_SEC = 24 * 60 * 60;
private static final long CACHE_RECHECK_AGE_IN_SEC = ONE_DAY_IN_SEC;
private static final long CACHE_RECHECK_AGE_IN_MS = CACHE_RECHECK_AGE_IN_SEC * 1000;
private static final long CACHE_EXPIRATION_AGE_IN_SEC = ONE_DAY_IN_SEC * 30;
private static final long CACHE_EXPIRATION_AGE_IN_MS = CACHE_EXPIRATION_AGE_IN_SEC * 1000;
private static final String DEFAULT_CACHE_DIRECTORY_NAME = "images";
private static File cacheDirectory;
private static Map<String, SoftReference<Drawable>> drawableCache = new HashMap<String, SoftReference<Drawable>>();
public static Drawable loadImage(ImageRequest request) {
final String imageKey = getKeyForUrl(request.imageUrl);
LogWrapper.logMessage("Loading image: " + request.imageUrl);
Drawable drawable = loadImageFromMemoryCache(imageKey);
if(drawable != null) {
LogWrapper.logMessage("Found image " + request.imageUrl + " in memory cache");
return drawable;
}
drawable = loadImageFromFileCache(imageKey, request.imageUrl);
if(drawable != null) {
LogWrapper.logMessage("Found image " + request.imageUrl + " in file cache");
return drawable;
}
drawable = ImageDownloader.loadImage(imageKey, request.imageUrl);
if(drawable != null) {
saveImageInFileCache(imageKey, drawable);
if(request.cacheInMemory) {
saveImageInMemoryCache(imageKey, drawable);
}
return drawable;
}
LogWrapper.logMessage("Could not load drawable, returning null");
return drawable;
}
private static Drawable loadImageFromMemoryCache(final String imageKey) {
if(drawableCache.containsKey(imageKey)) {
// Apparently Android's SoftReference can sometimes free objects too early, see:
// If that happens then it's no big deal, as this class will simply re-load the image
// from file, but if that is the case then we should be polite and remove the imageKey
// from the cache to reflect the actual caching state of this image.
final Drawable drawable = drawableCache.get(imageKey).get();
if(drawable == null) {
drawableCache.remove(imageKey);
}
return drawable;
}
else {
return null;
}
}
private static Drawable loadImageFromFileCache(final String imageKey, final URL imageUrl) {
Drawable drawable = null;
File cacheFile = new File(getCacheDirectory(), imageKey);
if(cacheFile.exists()) {
try {
Date now = new Date();
long fileAgeInMs = now.getTime() - cacheFile.lastModified();
if(fileAgeInMs > CACHE_RECHECK_AGE_IN_MS) {
Date expirationDate = ImageDownloader.getServerTimestamp(imageUrl);
if(expirationDate.after(now)) {
drawable = Drawable.createFromStream(new FileInputStream(cacheFile), imageKey);
LogWrapper.logMessage("Cached version of " + imageUrl.toString() + " is still current, updating timestamp");
if(!cacheFile.setLastModified(now.getTime())) {
// Ugh, it seems that in some cases this call will always return false and refuse to update the timestamp
// In these cases, we manually re-write the file to disk. Yes, that sucks, but it's better than loosing
// the ability to do any intelligent file caching at all.
saveImageInFileCache(imageKey, drawable);
}
}
else {
LogWrapper.logMessage("Cached version of " + imageUrl.toString() + " found, but has expired.");
}
}
else {
drawable = Drawable.createFromStream(new FileInputStream(cacheFile), imageKey);
if(drawable == null) {
throw new Exception("Could not create drawable from image: " + imageUrl.toString());
}
}
}
catch(Exception e) {
LogWrapper.logException(e);
}
}
return drawable;
}
private static void saveImageInMemoryCache(String imageKey, final Drawable drawable) {
drawableCache.put(imageKey, new SoftReference<Drawable>(drawable));
}
private static void saveImageInFileCache(String imageKey, final Drawable drawable) {
OutputStream outputStream = null;
try {
File cacheFile = new File(getCacheDirectory(), imageKey);
BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
outputStream = new FileOutputStream(cacheFile);
bitmapDrawable.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, outputStream);
LogWrapper.logMessage("Saved image " + imageKey + " to file cache");
outputStream.flush();
outputStream.close();
}
catch(IOException e) {
LogWrapper.logException(e);
}
finally {
try {
if(outputStream != null) {
outputStream.close();
}
}
catch(IOException e) {
LogWrapper.logException(e);
}
}
}
private static File getCacheDirectory() {
if(cacheDirectory == null) {
//noinspection NullableProblems
setCacheDirectory(null, DEFAULT_CACHE_DIRECTORY_NAME);
}
return cacheDirectory;
}
public static void setCacheDirectory(String packageName, String subdirectoryName) {
File dataDirectory = new File(android.os.Environment.getExternalStorageDirectory(), "data");
if(!dataDirectory.exists()) {
dataDirectory.mkdir();
}
File packageDirectory;
if(packageName != null) {
packageDirectory = new File(dataDirectory, packageName);
if(!packageDirectory.exists()) {
packageDirectory.mkdir();
}
}
else {
packageDirectory = dataDirectory;
}
cacheDirectory = new File(packageDirectory, subdirectoryName);
if(!cacheDirectory.exists()) {
cacheDirectory.mkdir();
}
}
/**
* Clear expired images in the file cache to save disk space. This method will remove all
* images older than {@link #CACHE_EXPIRATION_AGE_IN_SEC} seconds.
*/
public static void clearOldCacheFiles() {
clearOldCacheFiles(CACHE_EXPIRATION_AGE_IN_SEC);
}
/**
* Clear all images older than a given amount of seconds.
* @param cacheAgeInSec Image expiration limit, in seconds
*/
public static void clearOldCacheFiles(long cacheAgeInSec) {
final long cacheAgeInMs = cacheAgeInSec * 1000;
Date now = new Date();
String[] cacheFiles = getCacheDirectory().list();
if(cacheFiles != null) {
for(String child : cacheFiles) {
File childFile = new File(getCacheDirectory(), child);
if(childFile.isFile()) {
long fileAgeInMs = now.getTime() - childFile.lastModified();
if(fileAgeInMs > cacheAgeInMs) {
LogWrapper.logMessage("Deleting image '" + child + "' from cache");
childFile.delete();
}
}
}
}
}
/**
* Remove all images from the fast in-memory cache. This should be called to free up memory
* when receiving onLowMemory warnings or when the activity knows it has no use for the items
* in the memory cache anymore.
*/
public static void clearMemoryCaches() {
LogWrapper.logMessage("Emptying in-memory drawable cache");
for(String key : drawableCache.keySet()) {
SoftReference reference = drawableCache.get(key);
reference.clear();
}
drawableCache.clear();
System.gc();
}
private static final char[] HEX_CHARACTERS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
/**
* Calculate a hash key for the given URL, which is used to create safe filenames and
* key strings. Internally, this method uses MD5, as that is available on Android 2.1
* devices (unlike base64, for example).
* @param url Image URL
* @return Hash for image URL
*/
public static String getKeyForUrl(URL url) {
String result = "";
try {
String urlString = url.toString();
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(urlString.getBytes(), 0, urlString.length());
byte[] resultBytes = digest.digest();
StringBuilder hexStringBuilder = new StringBuilder(2 * resultBytes.length);
for(final byte b : resultBytes) {
hexStringBuilder.append(HEX_CHARACTERS[(b & 0xf0) >> 4]).append(HEX_CHARACTERS[b & 0x0f]);
}
result = hexStringBuilder.toString();
}
catch(NoSuchAlgorithmException e) {
LogWrapper.logException(e);
}
return result;
}
}
|
package com.zms.zpc.debugger.ide;
import com.zms.zpc.emulator.board.pci.DefaultVGACard;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
public class MonitorLabel extends JLabel implements IScreen {
public DefaultVGACard vga;
public volatile boolean clearBackground = true;
public MonitorLabel(ComponentListener parent) {
this.addComponentListener(parent);
}
@Override
protected void paintComponent(Graphics g) {
paint(g);
}
@Override
public void paintAll(Graphics g) {
paint(g);
}
@Override
public void paint(Graphics g) {
if (clearBackground) {
g.setColor(Color.white);
Dimension s1 = getSize();
if (s1.getWidth() > 0 && s1.getHeight() > 0) {
g.fillRect(0, 0, s1.width, s1.height);
}
clearBackground = false;
}
if (vga != null) {
vga.paintPCMonitor(this, g);
}
}
@Override
public void paintData(Object context, BufferedImage buffer, Object data1, Object data2) {
Graphics g = (Graphics) context;
if (g instanceof Graphics2D) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
if (buffer != null) {
g.drawImage(buffer, 0, 0, this);
}
}
@Override
public void init() {
this.setDoubleBuffered(false);
this.requestFocusInWindow();
}
private Dimension size=new Dimension();
@Override
public void resized(Dimension d) {
Dimension size=this.size;
size.setSize(d);
this.setSize(size);
this.setPreferredSize(size);
this.clearBackground = true;
}
@Override
public void setData(Object data) {
vga = (DefaultVGACard) data;
}
@Override
public Component getComponent() {
return this;
}
}
|
package sqlancer.postgres;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import sqlancer.AbstractAction;
import sqlancer.IgnoreMeException;
import sqlancer.Randomly;
import sqlancer.SQLConnection;
import sqlancer.SQLProviderAdapter;
import sqlancer.StatementExecutor;
import sqlancer.common.DBMSCommon;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.common.query.SQLQueryProvider;
import sqlancer.common.query.SQLancerResultSet;
import sqlancer.postgres.PostgresOptions.PostgresOracleFactory;
import sqlancer.postgres.gen.PostgresAlterTableGenerator;
import sqlancer.postgres.gen.PostgresAnalyzeGenerator;
import sqlancer.postgres.gen.PostgresClusterGenerator;
import sqlancer.postgres.gen.PostgresCommentGenerator;
import sqlancer.postgres.gen.PostgresDeleteGenerator;
import sqlancer.postgres.gen.PostgresDiscardGenerator;
import sqlancer.postgres.gen.PostgresDropIndexGenerator;
import sqlancer.postgres.gen.PostgresIndexGenerator;
import sqlancer.postgres.gen.PostgresInsertGenerator;
import sqlancer.postgres.gen.PostgresNotifyGenerator;
import sqlancer.postgres.gen.PostgresReindexGenerator;
import sqlancer.postgres.gen.PostgresSequenceGenerator;
import sqlancer.postgres.gen.PostgresSetGenerator;
import sqlancer.postgres.gen.PostgresStatisticsGenerator;
import sqlancer.postgres.gen.PostgresTableGenerator;
import sqlancer.postgres.gen.PostgresTransactionGenerator;
import sqlancer.postgres.gen.PostgresTruncateGenerator;
import sqlancer.postgres.gen.PostgresUpdateGenerator;
import sqlancer.postgres.gen.PostgresVacuumGenerator;
import sqlancer.postgres.gen.PostgresViewGenerator;
// EXISTS
public class PostgresProvider extends SQLProviderAdapter<PostgresGlobalState, PostgresOptions> {
/**
* Generate only data types and expressions that are understood by PQS.
*/
public static boolean generateOnlyKnown;
protected String entryURL;
protected String username;
protected String password;
protected String entryPath;
protected String host;
protected String port;
protected String testURL;
protected String databaseName;
protected String createDatabaseCommand;
public PostgresProvider() {
super(PostgresGlobalState.class, PostgresOptions.class);
}
protected PostgresProvider(Class<PostgresGlobalState> globalClass, Class<PostgresOptions> optionClass) {
super(globalClass, optionClass);
}
public enum Action implements AbstractAction<PostgresGlobalState> {
ANALYZE(PostgresAnalyzeGenerator::create),
ALTER_TABLE(g -> PostgresAlterTableGenerator.create(g.getSchema().getRandomTable(t -> !t.isView()), g,
generateOnlyKnown)),
CLUSTER(PostgresClusterGenerator::create),
COMMIT(g -> {
SQLQueryAdapter query;
if (Randomly.getBoolean()) {
query = new SQLQueryAdapter("COMMIT", true);
} else if (Randomly.getBoolean()) {
query = PostgresTransactionGenerator.executeBegin();
} else {
query = new SQLQueryAdapter("ROLLBACK", true);
}
return query;
}),
CREATE_STATISTICS(PostgresStatisticsGenerator::insert),
DROP_STATISTICS(PostgresStatisticsGenerator::remove),
DELETE(PostgresDeleteGenerator::create),
DISCARD(PostgresDiscardGenerator::create),
DROP_INDEX(PostgresDropIndexGenerator::create),
INSERT(PostgresInsertGenerator::insert),
UPDATE(PostgresUpdateGenerator::create),
TRUNCATE(PostgresTruncateGenerator::create),
VACUUM(PostgresVacuumGenerator::create),
REINDEX(PostgresReindexGenerator::create),
SET(PostgresSetGenerator::create),
CREATE_INDEX(PostgresIndexGenerator::generate),
SET_CONSTRAINTS((g) -> {
StringBuilder sb = new StringBuilder();
sb.append("SET CONSTRAINTS ALL ");
sb.append(Randomly.fromOptions("DEFERRED", "IMMEDIATE"));
return new SQLQueryAdapter(sb.toString());
}),
RESET_ROLE((g) -> new SQLQueryAdapter("RESET ROLE")),
COMMENT_ON(PostgresCommentGenerator::generate),
NOTIFY(PostgresNotifyGenerator::createNotify),
LISTEN((g) -> PostgresNotifyGenerator.createListen()),
UNLISTEN((g) -> PostgresNotifyGenerator.createUnlisten()),
CREATE_SEQUENCE(PostgresSequenceGenerator::createSequence),
CREATE_VIEW(PostgresViewGenerator::create);
private final SQLQueryProvider<PostgresGlobalState> sqlQueryProvider;
Action(SQLQueryProvider<PostgresGlobalState> sqlQueryProvider) {
this.sqlQueryProvider = sqlQueryProvider;
}
@Override
public SQLQueryAdapter getQuery(PostgresGlobalState state) throws Exception {
return sqlQueryProvider.getQuery(state);
}
}
protected static int mapActions(PostgresGlobalState globalState, Action a) {
Randomly r = globalState.getRandomly();
int nrPerformed;
switch (a) {
case CREATE_INDEX:
case CLUSTER:
nrPerformed = r.getInteger(0, 3);
break;
case CREATE_STATISTICS:
nrPerformed = r.getInteger(0, 5);
break;
case DISCARD:
case DROP_INDEX:
nrPerformed = r.getInteger(0, 5);
break;
case COMMIT:
nrPerformed = r.getInteger(0, 0);
break;
case ALTER_TABLE:
nrPerformed = r.getInteger(0, 5);
break;
case REINDEX:
case RESET:
nrPerformed = r.getInteger(0, 3);
break;
case DELETE:
case RESET_ROLE:
case SET:
nrPerformed = r.getInteger(0, 5);
break;
case ANALYZE:
nrPerformed = r.getInteger(0, 3);
break;
case VACUUM:
case SET_CONSTRAINTS:
case COMMENT_ON:
case NOTIFY:
case LISTEN:
case UNLISTEN:
case CREATE_SEQUENCE:
case DROP_STATISTICS:
case TRUNCATE:
nrPerformed = r.getInteger(0, 2);
break;
case CREATE_VIEW:
nrPerformed = r.getInteger(0, 2);
break;
case UPDATE:
nrPerformed = r.getInteger(0, 10);
break;
case INSERT:
nrPerformed = r.getInteger(0, globalState.getOptions().getMaxNumberInserts());
break;
default:
throw new AssertionError(a);
}
return nrPerformed;
}
@Override
public void generateDatabase(PostgresGlobalState globalState) throws Exception {
readFunctions(globalState);
createTables(globalState, Randomly.fromOptions(4, 5, 6));
prepareTables(globalState);
}
@Override
public SQLConnection createDatabase(PostgresGlobalState globalState) throws SQLException {
if (globalState.getDmbsSpecificOptions().getTestOracleFactory().stream()
.anyMatch((o) -> o == PostgresOracleFactory.PQS)) {
generateOnlyKnown = true;
}
username = globalState.getOptions().getUserName();
password = globalState.getOptions().getPassword();
host = globalState.getOptions().getHost();
port = globalState.getOptions().getPort();
entryPath = "/test";
entryURL = globalState.getDmbsSpecificOptions().connectionURL;
// trim URL to exclude "jdbc:"
if (entryURL.startsWith("jdbc:")) {
entryURL = entryURL.substring(5);
}
String entryDatabaseName = entryPath.substring(1);
databaseName = globalState.getDatabaseName();
try {
URI uri = new URI(entryURL);
String userInfoURI = uri.getUserInfo();
String pathURI = uri.getPath();
if (userInfoURI != null) {
// username and password specified in URL take precedence
if (userInfoURI.contains(":")) {
String[] userInfo = userInfoURI.split(":", 2);
username = userInfo[0];
password = userInfo[1];
} else {
username = userInfoURI;
password = null;
}
int userInfoIndex = entryURL.indexOf(userInfoURI);
String preUserInfo = entryURL.substring(0, userInfoIndex);
String postUserInfo = entryURL.substring(userInfoIndex + userInfoURI.length() + 1);
entryURL = preUserInfo + postUserInfo;
}
if (pathURI != null) {
entryPath = pathURI;
}
if ("sqlancer".equals(host)) {
host = uri.getHost();
}
if ("sqlancer".equals(port)) {
port = Integer.toString(uri.getPort());
}
entryURL = uri.getScheme() + "://" + host + ":" + port + "/" + entryDatabaseName;
} catch (URISyntaxException e) {
throw new AssertionError(e);
}
Connection con = DriverManager.getConnection("jdbc:" + entryURL, username, password);
globalState.getState().logStatement(String.format("\\c %s;", entryDatabaseName));
globalState.getState().logStatement("DROP DATABASE IF EXISTS " + databaseName);
createDatabaseCommand = getCreateDatabaseCommand(globalState);
globalState.getState().logStatement(createDatabaseCommand);
try (Statement s = con.createStatement()) {
s.execute("DROP DATABASE IF EXISTS " + databaseName);
}
try (Statement s = con.createStatement()) {
s.execute(createDatabaseCommand);
}
con.close();
int databaseIndex = entryURL.indexOf(entryPath) + 1;
String preDatabaseName = entryURL.substring(0, databaseIndex);
String postDatabaseName = entryURL.substring(databaseIndex + entryDatabaseName.length());
testURL = preDatabaseName + databaseName + postDatabaseName;
globalState.getState().logStatement(String.format("\\c %s;", databaseName));
con = DriverManager.getConnection("jdbc:" + testURL, username, password);
return new SQLConnection(con);
}
protected void readFunctions(PostgresGlobalState globalState) throws SQLException {
SQLQueryAdapter query = new SQLQueryAdapter("SELECT proname, provolatile FROM pg_proc;");
SQLancerResultSet rs = query.executeAndGet(globalState);
while (rs.next()) {
String functionName = rs.getString(1);
Character functionType = rs.getString(2).charAt(0);
globalState.addFunctionAndType(functionName, functionType);
}
}
protected void createTables(PostgresGlobalState globalState, int numTables) throws Exception {
while (globalState.getSchema().getDatabaseTables().size() < numTables) {
try {
String tableName = DBMSCommon.createTableName(globalState.getSchema().getDatabaseTables().size());
SQLQueryAdapter createTable = PostgresTableGenerator.generate(tableName, globalState.getSchema(),
generateOnlyKnown, globalState);
globalState.executeStatement(createTable);
} catch (IgnoreMeException e) {
}
}
}
protected void prepareTables(PostgresGlobalState globalState) throws Exception {
StatementExecutor<PostgresGlobalState, Action> se = new StatementExecutor<>(globalState, Action.values(),
PostgresProvider::mapActions, (q) -> {
if (globalState.getSchema().getDatabaseTables().isEmpty()) {
throw new IgnoreMeException();
}
});
se.executeStatements();
globalState.executeStatement(new SQLQueryAdapter("COMMIT", true));
globalState.executeStatement(new SQLQueryAdapter("SET SESSION statement_timeout = 5000;\n"));
}
private String getCreateDatabaseCommand(PostgresGlobalState state) {
StringBuilder sb = new StringBuilder();
sb.append("CREATE DATABASE " + databaseName + " ");
if (Randomly.getBoolean() && ((PostgresOptions) state.getDmbsSpecificOptions()).testCollations) {
if (Randomly.getBoolean()) {
sb.append("WITH ENCODING '");
sb.append(Randomly.fromOptions("utf8"));
sb.append("' ");
}
for (String lc : Arrays.asList("LC_COLLATE", "LC_CTYPE")) {
if (!state.getCollates().isEmpty() && Randomly.getBoolean()) {
sb.append(String.format(" %s = '%s'", lc, Randomly.fromList(state.getCollates())));
}
}
sb.append(" TEMPLATE template0");
}
return sb.toString();
}
@Override
public String getDBMSName() {
return "postgres";
}
}
|
package com.jcabi.log;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.apache.log4j.LogManager;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link Logger}.
* @author Yegor Bugayenko (yegor256@gmail.com)
* @version $Id$
*/
public final class LoggerTest {
/**
* Logger can detect logging class name correctly.
* @throws Exception If something goes wrong
*/
@Test
public void detectsLoggerNameCorrectly() throws Exception {
// not implemented yet
}
/**
* Logger can detect logging class with a static param.
* @throws Exception If something goes wrong
*/
@Test
public void detectsNameOfStaticSource() throws Exception {
// not implemented yet
}
/**
* Logger can set logging level correctly.
* @throws Exception If something goes wrong
*/
@Test
public void setsLoggingLevel() throws Exception {
// not implemented yet
}
/**
* Logger can not format arrays since they are interpreted as varags.
* @throws Exception If something goes wrong
*/
@Test(expected = IllegalArgumentException.class)
public void doesntFormatArraysSinceTheyAreVarArgs() throws Exception {
Logger.format("array: %[list]s", new Object[] {"hi", 1});
}
/**
* Logger formats arrays as if they were separate arguments as they are
* interpreted as varargs.
*/
@Test
public void interpretsArraysAsVarArgs() {
MatcherAssert.assertThat(
Logger.format("array: %s : %d", new Object[] {"hello", 2}),
Matchers.is("array: hello : 2")
);
}
/**
* Logger can provide an output stream.
* @throws Exception If something goes wrong
*/
@Test
public void providesOutputStream() throws Exception {
final OutputStream stream = Logger.stream(Level.INFO, this);
final PrintWriter writer = new PrintWriter(
new OutputStreamWriter(stream, "UTF-8")
);
// @checkstyle LineLength (1 line)
writer.print("hello, \u20ac, how're\u040a?\nI'm fine, \u0000\u0007!\n");
writer.flush();
writer.close();
}
/**
* Logger throws an exception when there are less parameters than there
* are format args.
*/
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void throwsWhenParamsLessThanFormatArgs() {
Logger.format("String %s Char %c Number %d", "howdy", 'x');
}
/**
* Logger throws an exception when there are more parameters than there
* are format args.
*/
@Test(expected = IllegalArgumentException.class)
public void throwsWhenParamsMoreThanFormatArgs() {
Logger.format("String %s Number %d Char %c", "hey", 1, 'x', 2);
}
/**
* Logger can correctly check the current logging level.
* @throws Exception If fails
*/
@Test
public void checksLogLevel() throws Exception {
LogManager.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
TimeUnit.MILLISECONDS.sleep(1L);
MatcherAssert.assertThat(
Logger.isEnabled(Level.INFO, LogManager.getRootLogger()),
Matchers.is(true)
);
MatcherAssert.assertThat(
Logger.isEnabled(Level.FINEST, LogManager.getRootLogger()),
Matchers.is(false)
);
}
/**
* Logger can use String as a logger name.
*/
@Test
public void usesStringAsLoggerName() {
Logger.info("com.jcabi.log...why.not", "hello, %s!", "world!");
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.ezdo.logic.commands.DoneCommand.MESSAGE_DONE_TASK_SUCCESS;
import org.junit.Test;
import guitests.guihandles.TaskCardHandle;
import seedu.ezdo.commons.core.Messages;
import seedu.ezdo.logic.commands.DoneCommand;
import seedu.ezdo.testutil.TestTask;
import seedu.ezdo.testutil.TestUtil;
public class DoneCommandTest extends EzDoGuiTest {
@Test
public void done_success() {
//marks first task in the list as done
TestTask[] currentList = td.getTypicalTasks();
TestTask[] doneList = td.getTypicalDoneTasks();
int targetIndex = 1;
TestTask toDone = currentList[targetIndex - 1];
assertDoneSuccess(targetIndex, currentList, doneList);
//marks the middle task in the list as done
currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
doneList = TestUtil.addTasksToList(doneList, toDone);
targetIndex = currentList.length / 2;
toDone = currentList[targetIndex - 1];
assertDoneSuccess(targetIndex, currentList, doneList);
//marks last task in the list as done
currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
doneList = TestUtil.addTasksToList(doneList, toDone);
targetIndex = currentList.length;
assertDoneSuccess(targetIndex, currentList, doneList);
//invalid index
currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
doneList = TestUtil.addTasksToList(doneList, toDone);
commandBox.runCommand("done " + currentList.length + 1);
assertResultMessage("The task index provided is invalid");
//invalid command
commandBox.runCommand("done a");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE));
//invalid command
commandBox.runCommand("dones 1");
assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);
}
private void assertDoneSuccess(int targetIndexOneIndexed, final TestTask[] currentList, final TestTask[] doneList) {
TestTask taskToDone = currentList[targetIndexOneIndexed - 1]; // -1 as array uses zero indexing
TestTask[] expectedRemainder = TestUtil.removeTaskFromList(currentList, targetIndexOneIndexed);
TestTask[] expectedDone = TestUtil.addTasksToList(doneList, taskToDone);
commandBox.runCommand("done " + targetIndexOneIndexed);
// for (int i =0; i< expectedDone.length; i++) {System.out.println(expectedDone[i]);}
//confirm the list now contains all done tasks including the one just marked as done
assertTrue(taskListPanel.isListMatching(expectedDone));
//confirm the result message is correct
assertResultMessage(String.format(MESSAGE_DONE_TASK_SUCCESS, taskToDone));
//confirm the new card contains the right data
TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToDone.getName().fullName);
assertMatching(taskToDone, addedCard);
//confirm the undone list does not contain the task just marked as done
commandBox.runCommand("list");
assertTrue(taskListPanel.isListMatching(expectedRemainder));
}
}
|
package guitests;
import org.junit.Test;
import edu.emory.mathcs.backport.java.util.Arrays;
import edu.emory.mathcs.backport.java.util.Collections;
import seedu.cmdo.testutil.TestTask;
import seedu.cmdo.testutil.TestUtil;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
//@@author A0141128R
public class ListCommandTest extends ToDoListGuiTest {
@Test
public void list() {
TestTask[] currentList = td.getTypicalTasks();
TestTask[] doneList = td.getEmptyTasks();
TestTask[] blockList = td.getEmptyTasks();
//sort list
currentList = sortList(currentList);
//test for list block
TestTask timeToBlock = td.meeting;
commandBox.runCommand(timeToBlock.getBlockCommand());
blockList = TestUtil.addTasksToList(doneList, timeToBlock);
currentList = TestUtil.addTasksToList(currentList, timeToBlock);
assertListSuccess("lb", blockList);
assertListSuccess("list block", blockList);
//list all the list
assertListSuccess("la", currentList);
//done a task that is the first in the list
runCommand("done 1");
doneList = TestUtil.addTasksToList(doneList, currentList[0]);
currentList = TestUtil.removeTaskFromList(currentList, 1);
assertListSuccess("ld", doneList);
assertListSuccess("list done", doneList);
//list all the list
assertListSuccess("list all", currentList);
//remove task from the list
runCommand("delete 2");
currentList = TestUtil.removeTaskFromList(currentList, 2);
assertListSuccess("la", currentList);
}
private void runCommand(String input){
commandBox.runCommand(input);
}
//sort list
private TestTask[] sortList(TestTask... currentList){
ArrayList<TestTask> list = new ArrayList<TestTask>(Arrays.asList(currentList));
Collections.sort(list);
return list.toArray(new TestTask[currentList.length]);
}
/**
* Runs the list command to change the task done status at specified index and confirms the result is correct.
* @param targetIndexOneIndexed e.g. to done the first task in the list, 1 should be given as the target index.
* @param currentList A copy of the current list of tasks (before done).
*/
private void assertListSuccess(final String type, final TestTask[] currentList) {
runCommand(type);
//confirm the list now contains all previous tasks except the done task
assertTrue(taskListPanel.isListMatching(currentList));
}
}
|
//@@author A0138907W
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.ezdo.commons.core.Messages;
import seedu.ezdo.logic.commands.SortCommand;
import seedu.ezdo.model.EzDo;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.UniqueTaskList;
import seedu.ezdo.testutil.TestTask;
import seedu.ezdo.testutil.TypicalTestTasks;
public class SortCommandTest extends EzDoGuiTest {
@Override
protected EzDo getInitialData() {
EzDo ez = new EzDo();
TypicalTestTasks.loadEzDoWithSampleData(ez);
try {
ez.addTask(new Task(td.kappa));
ez.addTask(new Task(td.leroy));
ez.addTask(new Task(td.megan));
} catch (UniqueTaskList.DuplicateTaskException e) {
assert false : "not possible";
}
return ez;
}
@Test
public void sortByFields() {
TestTask[] expectedList;
// sort by start date
commandBox.runCommand("sort s");
expectedList = new TestTask[] {td.elle, td.george, td.daniel, td.carl, td.benson, td.fiona, td.alice, td.kappa,
td.leroy, td.megan};
assertTrue(taskListPanel.isListMatching(expectedList));
// sort by start date in descending order
commandBox.runCommand("s s d");
expectedList = new TestTask[] {td.alice, td.fiona, td.benson, td.carl, td.daniel, td.george, td.elle, td.kappa,
td.leroy, td.megan};
assertTrue(taskListPanel.isListMatching(expectedList));
// sort by due date
commandBox.runCommand("s d");
expectedList = new TestTask[] {td.carl, td.elle, td.george, td.daniel, td.fiona, td.benson, td.alice, td.kappa,
td.leroy, td.megan};
assertTrue(taskListPanel.isListMatching(expectedList));
// sort by name
commandBox.runCommand("sort n a");
expectedList = new TestTask[] {td.alice, td.benson, td.carl, td.daniel, td.elle, td.fiona, td.george, td.kappa,
td.leroy, td.megan};
assertTrue(taskListPanel.isListMatching(expectedList));
// sort by priority
commandBox.runCommand("s p");
expectedList = new TestTask[] {td.alice, td.benson, td.carl, td.daniel, td.fiona, td.elle, td.george, td.kappa,
td.leroy, td.megan};
assertTrue(taskListPanel.isListMatching(expectedList));
//invalid command
commandBox.runCommand("sort z");
assertResultMessage(SortCommand.MESSAGE_INVALID_FIELD);
//invalid command
commandBox.runCommand("sort");
assertResultMessage(String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE));
}
@Test
public void maintainSortOrder() {
TestTask[] expectedList;
commandBox.runCommand("sort d");
// check that Jack is in the right place after adding him
commandBox.runCommand(td.jack.getAddCommand(false));
expectedList = new TestTask[] {td.carl, td.elle, td.george, td.jack, td.daniel, td.fiona, td.benson, td.alice,
td.kappa, td.leroy, td.megan};
assertTrue(taskListPanel.isListMatching(expectedList));
// check that Carl is in the right place after editing his due date
commandBox.runCommand("edit 1 d/12/12/2099");
String expectedName = taskListPanel.getTask(7).getName().toString();
assertTrue(expectedName.equals(td.carl.getName().toString()));
}
//@@author A0139248X
@Test
public void sort_invalidOrder() {
commandBox.runCommand("sort p s");
assertResultMessage(String.format(SortCommand.MESSAGE_INVALID_ORDER, SortCommand.MESSAGE_USAGE))
;
}
}
|
package servlets;
import helper.SessionHelper;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Cam;
import model.Picture;
import dao.CamDao;
import dao.CamDaoImpl;
import dao.DaoFactory;
import dao.PictureDao;
@WebServlet("/picture")
public class PictureList extends HttpServlet {
private static final long serialVersionUID = 1L;
final CamDao camDao = DaoFactory.getInstance().getCamDao();
final PictureDao pictureDao = DaoFactory.getInstance().getPictureDao();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!SessionHelper.checklogin(request, response)){
return;
}
//all cams for current user
List<Cam> collectioncam = camDao.getCamsForuser(SessionHelper.currentUser(request).getId());
// for (int i = 0; i < collectioncam.size(); i++) {
// System.out.println( collectioncam.get(i));
if (collectioncam.size()==0){
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/jsp/noaccess.jsp");
requestDispatcher.forward(request, response);
return;
}
long l = collectioncam.get(0).getId();
if(request.getSession().getAttribute("cam-cam")!=null){
l =(long) request.getSession().getAttribute("cam-cam");
}
if (request.getParameter("cam")!=null){
l = Long.parseLong(request.getParameter("cam").toString());
try {
if (!collectioncam.contains(camDao.getCam(l))){
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/jsp/noaccess.jsp");
requestDispatcher.forward(request, response);
return;
}
} catch (Exception e) {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/jsp/noaccess.jsp");
requestDispatcher.forward(request, response);
return;
}
}
String date= new SimpleDateFormat("yyyy-MM-dd").format(new Date());
if(request.getSession().getAttribute("cam-date")!=null){
date =(String) request.getSession().getAttribute("cam-date");
}
if(request.getParameter("date")!=null){
date = request.getParameter("date").toString();
}
Cam cam = camDao.getCam(l);
// current cam
request.setAttribute("cam", cam);
// pictures for current cam
List<Picture> collection = pictureDao.listByCam(l, date);
request.setAttribute("pictures", collection);
request.setAttribute("cams", collectioncam);
request.setAttribute("date",date);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/pictureList.jsp");
dispatcher.forward(request, response);
request.getSession().setAttribute("cam-date", date);
request.getSession().setAttribute("cam-cam", cam.getId());
}
}
|
package Integration;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebean.config.dbplatform.H2Platform;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.ddl.DdlGenerator;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import models.Consumer;
import org.junit.Test;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import play.libs.F;
import play.libs.Yaml;
import play.test.FakeApplication;
import play.test.Helpers;
import play.test.TestBrowser;
import java.util.HashMap;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static play.test.Helpers.*;
public class DatabaseTest {
private static HashMap<String,String> getPgTestDB() {
final HashMap<String,String> postgres = new HashMap<String, String>();
postgres.put("db.default.driver","org.postgresql.Driver");
postgres.put("db.default.url","jdbc:postgresql://152.96.56.71:40000/bringtoafricatest");
postgres.put("db.default.user", "postgres");
postgres.put("db.default.password", "postgres");
postgres.put("ebean.default","models.*");
return postgres;
}
private static HashMap<String,String> getH2TestDB() {
final HashMap<String,String> postgres = new HashMap<String, String>();
postgres.put("db.default.driver", "org.h2.Driver");
postgres.put("db.default.url","jdbc:h2:~/test");
postgres.put("db.default.user", "sa");
postgres.put("db.default.password", "");
postgres.put("ebean.default", "models.*");
return postgres;
}
private static void cleanDatabase(HashMap<String,String> database){
FakeApplication app = fakeApplication(database);
Helpers.start(app);
EbeanServer server = Ebean.getServer("default");
ServerConfig config = new ServerConfig();
DdlGenerator ddl = new DdlGenerator();
ddl.setup((SpiEbeanServer) server, new H2Platform(), config);
ddl.runScript(false, ddl.generateDropDdl());
ddl.runScript(false, ddl.generateCreateDdl());
assert Consumer.find.all().size() == 0;
}
private static void fillDatabase(HashMap<String,String> database) {
FakeApplication app = fakeApplication(database);
Helpers.start(app);
Ebean.save((List) Yaml.load("test-data.yml"));
}
private static FakeApplication getApp(Boolean filledWithTestData) {
HashMap<String,String> database = getH2TestDB();
cleanDatabase(database);
if(filledWithTestData) fillDatabase(database);
return fakeApplication(database);
}
public static void runInCleanApp(F.Callback<TestBrowser> run) {
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
driver.setJavascriptEnabled(true);
running(testServer(3333, getApp(false)), driver, run);
}
public static void runInFilledApp(F.Callback<TestBrowser> run) {
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
driver.setJavascriptEnabled(true);
running(testServer(3333, getApp(true)), driver, run);
}
@Test
public void testFakeDataBase() {
runInCleanApp((TestBrowser t) -> {
assertThat(Consumer.find.findUnique() == null);
for (Consumer co : Consumer.find.all()) {
co.delete();
}
Consumer c = new Consumer();
c.setEmail("sevi_buehler@hotmail.com");
c.setFirstName("Severin2");
c.setLastName("blaaa");
c.setPasswordHashedSalted("afesadsfasdf");
c.save();
assertThat(Consumer.find.findUnique() != null);
});
}
@Test
public void testFakeDataBaseFull() {
runInFilledApp((TestBrowser t) -> {
assertThat(Consumer.find.findUnique() != null);
Consumer testConsumer = Consumer.find.where().like("email", "bob@gmail.com").findUnique();
assertThat(testConsumer.getEmail() == "bob@gmail.com");
});
}
}
|
package JavaFXSimple;
import TWoT_test.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* @author Mathias
*/
public class GUIFX extends Application {
private TWoT twot;
private TextArea textArea;
private TextField inputArea;
private String help;
private String inventory;
private int counter;
private String printHelp() {
HashMap<String, String> printHelpMSG = twot.getHelpMessages();
return printHelpMSG.get("helpMessage1") + printHelpMSG.get("helpMessage2") + printHelpMSG.get("helpMessage3");
}
private String printInventory() {
inventory = "";
ArrayList<Item> inv = new ArrayList<>();
for(Item i : twot.getInventoryItems()){
inv.add(i);
}
if(inv.isEmpty()){
return "Your inventory is empty\n";
}
else if(inv.size() >= 1){
for(Item j : inv){
inventory += j.getItemName() + "\n";
}
}
return inventory;
}
public GUIFX () {
twot = new TWoT();
}
public static void main(String[] args) {
launch(args);
}
@Override
public void start (Stage primaryStage) {
primaryStage.setTitle("The Wizard of Treldan");
textArea = new TextArea();
inputArea = new TextField();
Button button_play = new Button("NEW GAME");
Button button_load = new Button("LOAD GAME");
Button button_how = new Button("HOW TO PLAY");
Button button_exitMenu = new Button("EXIT GAME");
button_play.setMinWidth(180);
button_load.setMinWidth(180);
button_how.setMinWidth(180);
button_exitMenu.setMinWidth(180);
button_play.setMinHeight(40);
button_load.setMinHeight(40);
button_how.setMinHeight(40);
button_exitMenu.setMinHeight(40);
Button button_inventory = new Button("Inventory");
Button button_clear = new Button("Clear");
Button button_help = new Button("Help");
Button button_exit = new Button("Exit");
button_inventory.setMaxWidth(90);
button_help.setMaxWidth(90);
button_exit.setMaxWidth(90);
button_clear.setMaxWidth(90);
VBox gameButtons = new VBox(20);
gameButtons.setLayoutX(422);
gameButtons.getChildren().addAll(button_inventory, button_clear, button_help, button_exit);
VBox menuButtons = new VBox(20);
menuButtons.setLayoutX(166);
menuButtons.setLayoutY(30);
menuButtons.getChildren().addAll(button_play, button_load, button_how, button_exitMenu);
VBox outputField = new VBox(20);
textArea.setMaxWidth(422);
textArea.setMinHeight(258);
textArea.setMaxHeight(258);
textArea.setWrapText(true);
textArea.setEditable(false);
outputField.getChildren().addAll(textArea);
VBox inputField = new VBox(20);
inputArea.setMaxWidth(422);
inputArea.setMaxHeight(30);
inputField.relocate(0, 260);
inputField.getChildren().addAll(inputArea);
Pane root = new Pane(gameButtons, outputField, inputField);
Pane root2 = new Pane(menuButtons);
Scene scene1 = new Scene(root, 512, 288);
Scene menu = new Scene(root2, 512, 288);
DropShadow shade = new DropShadow();
root.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
root.setEffect(shade);
});
root.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
root.setEffect(null);
});
button_play.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{
primaryStage.setScene(scene1);
});
button_help.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{
help=printHelp();
textArea.appendText(help);
});
button_inventory.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{
inventory = printInventory();
textArea.appendText(inventory);
});
button_clear.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{
textArea.clear();
});
inputField.setOnKeyPressed(new EventHandler<KeyEvent>(){
public void handle(KeyEvent k){
if(k.getCode().equals(KeyCode.ENTER)){
textArea.appendText("Hello\n");
inputArea.clear();
}
}
});
button_exit.setOnAction(actionEvent -> Platform.exit());
button_exitMenu.setOnAction(actionEvent -> Platform.exit());
primaryStage.setScene(menu);
primaryStage.show();
String welcome = "";
for(HashMap.Entry<String, String> entry : twot.getWelcomeMessages().entrySet()){
welcome = welcome + entry.getValue();
}
textArea.appendText(welcome);
}
}
|
package tlc2.tool.distributed;
import java.io.Serializable;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateInfo;
import tlc2.tool.TraceApp;
import tlc2.tool.WorkerException;
/**
* @author Simon Zambrovski
* @version $Id$
*/
public abstract class DistApp implements TraceApp, Serializable {
public abstract String getAppName();
public abstract Boolean getCheckDeadlock();
public abstract Boolean getPreprocess();
public abstract String getFileName();
public abstract String getMetadir();
public abstract boolean canRecover();
// Returns a list of initial states.
public abstract TLCState[] getInitStates() throws WorkerException;
// Returns a list of successor states of the state s. /
public abstract TLCState[] getNextStates(TLCState s) throws WorkerException;
// Checks if the state is a valid state.
public abstract void checkState(TLCState s1, TLCState s2)
throws WorkerException;
// Checks if the state satisfies the state constraints.
public abstract boolean isInModel(TLCState s);
// Checks if a pair of states satisfy the action constraints.
public abstract boolean isInActions(TLCState s1, TLCState s2);
// Reconstruct the initial state whose fingerprint is fp.
public abstract TLCStateInfo getState(long fp);
// Reconstruct the next state of state s whose fingerprint is fp.
public abstract TLCStateInfo getState(long fp, TLCState s);
// Reconstruct the info for the transition from s to s1. /
public abstract TLCStateInfo getState(TLCState s1, TLCState s);
// Enables call stack tracing.
public abstract void setCallStack();
// Prints call stack.
public abstract String printCallStack();
/**
* @return The specification root directory
*/
public abstract String getSpecDir();
/**
* @return The (qualified) configuration file name
*/
public abstract String getConfigName();
}
|
package to.etc.domui.state;
import java.util.*;
import to.etc.domui.dom.errors.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.util.*;
final public class UIGoto {
static public final String SINGLESHOT_MESSAGE = "uigoto.msgs";
private UIGoto() {}
static private WindowSession context() {
return PageContext.getRequestContext().getWindowSession();
}
/**
* Destroy the current page and reload the exact same page with the same parameters as a
* new one. This has the effect of fully refreshing all data, and reinitializing the page
* at it's initial state.
*/
static public void reload() {
Page pg = PageContext.getCurrentPage();
Class< ? extends UrlPage> clz = pg.getBody().getClass();
PageParameters pp = pg.getPageParameters();
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, pp);
}
/**
* Push (shelve) the current page, then move to a new page. The page is parameterless, and is started in a NEW ConversationContext.
* @param clz
*/
static public void moveSub(final Class< ? extends UrlPage> clz) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.SUB, clz, null, null, null);
}
/**
* Push (shelve) the current page, then move to a new page. The page is started in a NEW ConversationContext.
*
* @param clz
* @param pp
*/
static public void moveSub(final Class< ? extends UrlPage> clz, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.SUB, clz, null, null, pp);
}
/**
* Push (shelve) the current page, then move to a new page. The page is started in a NEW ConversationContext.
*
* @param clz
* @param param A list of parameters, in {@link PageParameters#addParameters(Object...)} format.
*/
static public void moveSub(final Class< ? extends UrlPage> clz, final Object... param) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
PageParameters pp;
if(param == null || param.length == 0)
pp = null;
else
pp = new PageParameters(param);
context().internalSetNextPage(MoveMode.SUB, clz, null, null, pp);
}
/**
* Push (shelve) the current page, then move to a new page. The page JOINS the conversation context passed; if the page does not accept
* that conversation an exception is thrown.
*
* @param clz
* @param cc
* @param pp
*/
static public void moveSub(final Class< ? extends UrlPage> clz, final ConversationContext cc, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
if(cc == null)
throw new IllegalArgumentException("The conversation to join with cannot be null");
context().internalSetNextPage(MoveMode.SUB, clz, cc, null, pp);
}
/**
* Clear the entire shelf, then goto a new page. The page uses a NEW ConversationContext.
*
* @param clz
* @param pp
*/
static public void moveNew(final Class< ? extends UrlPage> clz, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.NEW, clz, null, null, pp);
}
/**
* Clear the entire shelf, then goto a new page. The page uses a NEW ConversationContext.
*
* @param clz
* @param param A list of parameters, in {@link PageParameters#addParameters(Object...)} format.
*/
static public void moveNew(final Class< ? extends UrlPage> clz, Object... param) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
PageParameters pp;
if(param == null || param.length == 0)
pp = null;
else
pp = new PageParameters(param);
context().internalSetNextPage(MoveMode.NEW, clz, null, null, pp);
}
/**
* Clear the entire shelve, then goto a new page. The page uses a NEW ConversationContext.
* @param clz
*/
static public void moveNew(final Class< ? extends UrlPage> clz) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.NEW, clz, null, null, null);
}
/**
* Replace the "current" page with a new page. The current page is destroyed; the shelve stack is not changed.
* @param clz
*/
static public void replace(final Class< ? extends UrlPage> clz) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, null);
}
/**
* Replace the "current" page with a new page. The current page is destroyed; the shelve stack is not changed.
* @param clz
* @param pp
*/
static public void replace(final Class< ? extends UrlPage> clz, final PageParameters pp) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, pp);
}
/**
* Replace the "current" page with a new page. The current page is destroyed; the shelve stack is not changed.
* On the new page show the specified message as an UI message.
* @param pg
* @param clz
* @param pp
* @param msg
*/
static public final void replace(Page pg, final Class< ? extends UrlPage> clz, final PageParameters pp, UIMessage msg) {
if(clz == null)
throw new IllegalArgumentException("The class to move-to cannot be null");
List<UIMessage> msgl = new ArrayList<UIMessage>(1);
msgl.add(msg);
WindowSession ws = pg.getConversation().getWindowSession();
ws.setAttribute(UIGoto.SINGLESHOT_MESSAGE, msgl);
context().internalSetNextPage(MoveMode.REPLACE, clz, null, null, pp);
}
static public void redirect(final String targeturl) {
context().internalSetRedirect(targeturl);
}
/**
* Move to the previously-shelved page. That page is UNSHELVED and activated. If the shelve is
* EMPTY when this call is made the application moves back to the HOME page.
*/
static public void back() {
context().internalSetNextPage(MoveMode.BACK, null, null, null, null);
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message as an ERROR message.
*
* @param pg
* @param msg
*/
static public final void clearPageAndReload(Page pg, String msg) {
clearPageAndReload(pg, pg.getBody().getClass(), pg.getPageParameters(), msg);
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message as an ERROR message.
*
* @param pg
* @param target
* @param pp
* @param msg
*/
static public final void clearPageAndReload(Page pg, Class< ? extends UrlPage> target, PageParameters pp, String msg) {
clearPageAndReload(pg, UIMessage.error(Msgs.BUNDLE, Msgs.S_PAGE_CLEARED, msg), pp);
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message.
*
* @param pg
* @param msg
*/
static public final void clearPageAndReload(Page pg, UIMessage msg) {
clearPageAndReload(pg, msg, pg.getPageParameters());
}
/**
* Destroy the current page and replace it with the new page specified. On the new page show the specified
* message.
*
* @param pg
* @param msg
* @param pp
*/
static public final void clearPageAndReload(Page pg, UIMessage msg, PageParameters pp) {
WindowSession ws = pg.getConversation().getWindowSession();
List<UIMessage> msgl = new ArrayList<UIMessage>(1);
msgl.add(msg);
ws.setAttribute(UIGoto.SINGLESHOT_MESSAGE, msgl);
pg.getConversation().destroy();
replace(pg.getBody().getClass(), pp);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.