answer
stringlengths 17
10.2M
|
|---|
package com.cliff777.usefulmethods;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UsefulMethods
{
//compares a date in string form to the current date
//and gives the difference in seconds
public int fromThenToNow(String date) throws ParseException
{
DateFormat format = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
Date now = new Date();
Date then = format.parse(date);
long difference = then.getTime() - now.getTime();
return (int) (difference/1000);
}
public static void main(String[] args)
{
new UsefulMethods();
}
public UsefulMethods()
{
//test
}
}
|
package com.dmdirc.addons.parser_twitter;
import com.dmdirc.addons.parser_twitter.api.TwitterAPI;
import com.dmdirc.addons.parser_twitter.api.TwitterErrorHandler;
import com.dmdirc.addons.parser_twitter.api.TwitterException;
import com.dmdirc.addons.parser_twitter.api.TwitterMessage;
import com.dmdirc.addons.parser_twitter.api.TwitterRawHandler;
import com.dmdirc.addons.parser_twitter.api.TwitterStatus;
import com.dmdirc.addons.parser_twitter.api.TwitterUser;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.logger.ErrorManager;
import com.dmdirc.parser.common.CallbackManager;
import com.dmdirc.parser.common.ChannelJoinRequest;
import com.dmdirc.parser.common.DefaultStringConverter;
import com.dmdirc.parser.common.IgnoreList;
import com.dmdirc.parser.common.QueuePriority;
import com.dmdirc.parser.interfaces.ChannelClientInfo;
import com.dmdirc.parser.interfaces.ChannelInfo;
import com.dmdirc.parser.interfaces.ClientInfo;
import com.dmdirc.parser.interfaces.LocalClientInfo;
import com.dmdirc.parser.interfaces.Parser;
import com.dmdirc.parser.interfaces.StringConverter;
import com.dmdirc.parser.interfaces.callbacks.AuthNoticeListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelJoinListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelMessageListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelModeChangeListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelNamesListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelNickChangeListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelNoticeListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelSelfJoinListener;
import com.dmdirc.parser.interfaces.callbacks.ChannelTopicListener;
import com.dmdirc.parser.interfaces.callbacks.DataInListener;
import com.dmdirc.parser.interfaces.callbacks.DataOutListener;
import com.dmdirc.parser.interfaces.callbacks.DebugInfoListener;
import com.dmdirc.parser.interfaces.callbacks.MotdEndListener;
import com.dmdirc.parser.interfaces.callbacks.MotdLineListener;
import com.dmdirc.parser.interfaces.callbacks.MotdStartListener;
import com.dmdirc.parser.interfaces.callbacks.NetworkDetectedListener;
import com.dmdirc.parser.interfaces.callbacks.NickChangeListener;
import com.dmdirc.parser.interfaces.callbacks.NumericListener;
import com.dmdirc.parser.interfaces.callbacks.Post005Listener;
import com.dmdirc.parser.interfaces.callbacks.PrivateMessageListener;
import com.dmdirc.parser.interfaces.callbacks.PrivateNoticeListener;
import com.dmdirc.parser.interfaces.callbacks.ServerReadyListener;
import com.dmdirc.parser.interfaces.callbacks.SocketCloseListener;
import com.dmdirc.parser.interfaces.callbacks.UnknownMessageListener;
import com.dmdirc.parser.interfaces.callbacks.UserModeDiscoveryListener;
import com.dmdirc.ui.messages.Styliser;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Twitter Parser for DMDirc.
*
* @author shane
*/
public class Twitter implements Parser, TwitterErrorHandler, TwitterRawHandler,
ConfigChangeListener {
/** Number of loops between clearing of the status cache. */
private static final long PRUNE_COUNT = 20;
/** Maximum age of items to leave in the status cache when pruning. */
private static final long PRUNE_TIME = 3600 * 1000;
/** Are we connected? */
private boolean connected = false;
/** Our owner plugin. */
private final TwitterPlugin myPlugin;
/** Twitter API. */
private TwitterAPI api = new TwitterAPI("", "", "", false, -1, false);
/** Channels we are in. */
private final Map<String, TwitterChannelInfo> channels
= new HashMap<String, TwitterChannelInfo>();
/** Clients we know. */
private final Map<String, TwitterClientInfo> clients
= new HashMap<String, TwitterClientInfo>();
/** When did we last query the API? */
private long lastQueryTime = 0;
/** Username for twitter. */
private final String myUsername;
/** Password for twitter if not able to use oauth. */
private final String myPassword;
/** Callback Manager for Twitter. */
private final CallbackManager<Twitter> myCallbackManager = new TwitterCallbackManager(this);
/** String Convertor. */
private final DefaultStringConverter myStringConverter = new DefaultStringConverter();
/** Ignore list (unused). */
private IgnoreList myIgnoreList = new IgnoreList();
/** Myself. */
private TwitterClientInfo myself = null;
/** List of currently active twitter parsers. */
protected static final List<Twitter> PARSERS = new ArrayList<Twitter>();
/** Are we waiting for authentication? */
private boolean wantAuth = false;
/** Server we are connecting to. */
private final String myServerName;
/** API Address to use. */
private final String apiAddress;
/** Are we using API Versioning? */
private boolean apiVersioning = false;
/** What API Version do we want? */
private int apiVersion = -1;
/** Address that created us. */
private final URI myAddress;
/** Main Channel Name. */
private final String mainChannelName;
/** Config Manager for this parser. */
private ConfigManager myConfigManager = null;
/** Map to store misc stuff in. */
private final Map<Object, Object> myMap = new HashMap<Object, Object>();
/** Debug enabled. */
private boolean debugEnabled;
/** Automatically leave & channels? */
private boolean autoLeaveMessageChannel;
/** Save last IDs. */
private boolean saveLastIDs;
/** Last Reply ID. */
private long lastReplyId = -1;
/** Last TimeLine ID. */
private long lastTimelineId = -1;
/** Last DM ID. */
private long lastDirectMessageId = -1;
/** Last IDs in searched hashtag channels. */
private final Map<TwitterChannelInfo, Long> lastSearchIds
= new HashMap<TwitterChannelInfo, Long>();
/** Status count. */
private int statusCount;
/** Get sent messages. */
private boolean getSentMessage;
/** Number of API calls to use. */
private int apicalls;
/** Auto append @ to nicknames. */
private boolean autoAt;
/** Replace opening nickname. */
private boolean replaceOpeningNickname;
/** hide 500 errors. */
private boolean hide500Errors;
/**
* Create a new Twitter Parser!
*
* @param address The address of the server to connect to
* @param myPlugin Plugin that created this parser
*/
protected Twitter(final URI address, final TwitterPlugin myPlugin) {
final String[] bits;
if (address.getUserInfo() == null) {
bits = new String[]{};
} else {
bits = address.getUserInfo().split(":");
}
myUsername = bits.length == 0 ? "" : bits[0];
myPassword = bits.length > 1 ? bits[1] : "";
this.myPlugin = myPlugin;
myServerName = address.getHost().toLowerCase();
myAddress = address;
resetState(true);
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "api.address." + myServerName)) {
apiAddress = getConfigManager().getOption(myPlugin.getDomain(), "api.address." + myServerName);
} else {
apiAddress = myServerName + address.getPath();
}
if (getConfigManager().hasOptionBool(myPlugin.getDomain(), "api.versioned." + myServerName)) {
apiVersioning = getConfigManager().getOptionBool(myPlugin.getDomain(), "api.versioned." + myServerName);
if (getConfigManager().hasOptionInt(myPlugin.getDomain(), "api.version." + myServerName)) {
apiVersion = getConfigManager().getOptionInt(myPlugin.getDomain(), "api.version." + myServerName);
}
}
mainChannelName = "&twitter";
}
/** {@inheritDoc} */
@Override
public void disconnect(final String message) {
connected = false;
PARSERS.remove(this);
api = new TwitterAPI("", "", "", false, -1, false);
getCallbackManager().getCallbackType(SocketCloseListener.class).call();
}
/** {@inheritDoc} */
@Override
public void joinChannel(final String channel) {
joinChannels(new ChannelJoinRequest(channel));
}
/** {@inheritDoc} */
@Override
public void joinChannel(final String channel, final String key) {
joinChannels(new ChannelJoinRequest(channel, key));
}
/** {@inheritDoc} */
@Override
public void joinChannels(final ChannelJoinRequest... channels) {
for (final ChannelJoinRequest request : channels) {
final String channel = request.getName().trim();
if (channel.equalsIgnoreCase(mainChannelName)) {
// The client is always in this channel, so ignore joins for it
continue;
}
if (isValidChannelName(channel) && getChannel(channel) == null) {
final TwitterChannelInfo newChannel = new TwitterChannelInfo(channel, this);
newChannel.addChannelClient(new TwitterChannelClientInfo(newChannel, myself));
if (channel.matches("^&[0-9]+$")) {
try {
final long id = Long.parseLong(channel.substring(1));
final TwitterStatus status = api.getStatus(id);
if (status == null) {
newChannel.setLocalTopic("Unknown status, or you do not have access to see it.");
} else {
if (status.getReplyTo() > 0) {
newChannel.setLocalTopic(status.getText() + " [Reply to: &" + status.getReplyTo() + "]");
} else {
newChannel.setLocalTopic(status.getText());
}
newChannel.setTopicSetter(status.getUser().getScreenName());
newChannel.setTopicTime(status.getTime());
final TwitterClientInfo client = (TwitterClientInfo) getClient(status.getUser().getScreenName());
if (client.isFake()) {
client.setFake(false);
clients.put(client.getNickname().toLowerCase(), client);
}
newChannel.addChannelClient(new TwitterChannelClientInfo(newChannel, client));
}
synchronized (this.channels) {
this.channels.put(channel, newChannel);
}
} catch (final NumberFormatException nfe) {
}
} else if (channel.charAt(0) == '
newChannel.setLocalTopic("Search results for " + channel);
synchronized (this.channels) {
this.channels.put(channel, newChannel);
}
}
doJoinChannel(newChannel);
} else {
sendNumericOutput(474, new String[]{":" + myServerName, "474", myself.getNickname(), channel, "Cannot join channel - name is not valid, or you are already there."});
}
}
}
/**
* Remove a channel from the known channels list.
*
* @param channel The channel to part
*/
protected void partChannel(final ChannelInfo channel) {
if (channel == null) { return; }
if (channel.getName().equalsIgnoreCase(mainChannelName)) {
doJoinChannel(channel);
} else {
synchronized (channels) {
channels.remove(channel.getName());
}
}
}
/** {@inheritDoc} */
@Override
public ChannelInfo getChannel(final String channel) {
synchronized (channels) {
return channels.containsKey(channel.toLowerCase()) ? channels.get(channel.toLowerCase()) : null;
}
}
/** {@inheritDoc} */
@Override
public Collection<? extends ChannelInfo> getChannels() {
return new ArrayList<TwitterChannelInfo>(channels.values());
}
/** {@inheritDoc} */
@Override
public void setBindIP(final String ip) {
// Ignore
}
/** {@inheritDoc} */
@Override
public int getMaxLength(final String type, final String target) {
return 140;
}
/** {@inheritDoc} */
@Override
public LocalClientInfo getLocalClient() {
return myself;
}
/** {@inheritDoc} */
@Override
public ClientInfo getClient(final String details) {
final String client = TwitterClientInfo.parseHost(details);
return clients.containsKey(client.toLowerCase()) ? clients.get(client.toLowerCase()) : new TwitterClientInfo(details, this).setFake(true);
}
/**
* Tokenise a line.
* splits by " " up to the first " :" everything after this is a single token
*
* @param line Line to tokenise
* @return Array of tokens
*/
public static String[] tokeniseLine(final String line) {
if (line == null) {
return new String[]{""};
}
final int lastarg = line.indexOf(" :");
String[] tokens;
if (lastarg > -1) {
final String[] temp = line.substring(0, lastarg).split(" ");
tokens = new String[temp.length + 1];
System.arraycopy(temp, 0, tokens, 0, temp.length);
tokens[temp.length] = line.substring(lastarg + 2);
} else {
tokens = line.split(" ");
}
return tokens;
}
/** {@inheritDoc} */
@Override
public void sendRawMessage(final String message) {
sendRawMessage(message, QueuePriority.NORMAL);
}
/** {@inheritDoc} */
@Override
public void sendInvite(final String channel, final String user) {
// TODO: Handle this properly here instead of faking IRC messages
sendRawMessage("INVITE " + user + " " + channel);
}
/** {@inheritDoc} */
@Override
public void sendRawMessage(final String message, final QueuePriority priority) {
// TODO: Parse some lines in order to fake IRC.
final String[] bits = tokeniseLine(message);
if (bits[0].equalsIgnoreCase("JOIN") && bits.length > 1) {
joinChannel(bits[1]);
} else if (bits[0].equalsIgnoreCase("WHOIS") && bits.length > 1) {
if (bits[1].equalsIgnoreCase(myServerName)) {
sendNumericOutput(311, new String[]{":" + myServerName, "311", myself.getNickname(), bits[1], "user", myServerName, "*", "Psuedo-User for DMDirc " + myServerName + " plugin"});
sendNumericOutput(312, new String[]{":" + myServerName, "312", myself.getNickname(), bits[1], myServerName, "DMDirc " + myServerName + " plugin"});
} else {
final boolean forced = bits.length > 2 && bits[1].equalsIgnoreCase(bits[2]);
final TwitterUser user = forced ? api.getUser(bits[1], true) : api.getCachedUser(bits[1]);
if (user == null) {
final String reason = "No such user found" + (forced ? ", see" : "in cache, try /WHOIS " + bits[1] + " " + bits[1] + " to poll twitter (uses 1 API call) or try") + " http://" + myAddress.getHost() + "/" + bits[1];
getCallbackManager().getCallbackType(NumericListener.class).call(401, new String[]{":" + myServerName, "401", myself.getNickname(), bits[1], reason});
} else {
// Time since last update
final long secondsIdle = (user.getStatus() == null ? user.getRegisteredTime() : System.currentTimeMillis() - user.getStatus().getTime()) / 1000;
final long signonTime = user.getRegisteredTime() / 1000;
getCallbackManager().getCallbackType(NumericListener.class).call(311, new String[]{":" + myServerName, "311", myself.getNickname(), bits[1], "user", myServerName, "*", user.getRealName() + " (http://" + myAddress.getHost() + "/" + user.getScreenName() + ")"});
final TwitterClientInfo client = (TwitterClientInfo) getClient(bits[1]);
if (client != null) {
final StringBuilder channelList = new StringBuilder();
for (final ChannelClientInfo cci : client.getChannelClients()) {
if (channelList.length() > 0) {
channelList.append(' ');
}
channelList.append(cci.getImportantModePrefix());
channelList.append(cci.getChannel().getName());
}
if (channelList.length() > 0) {
getCallbackManager().getCallbackType(NumericListener.class).call(319, new String[]{":" + myServerName, "319", myself.getNickname(), bits[1], channelList.toString()});
}
}
// AWAY Message Abuse!
getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "URL: " + user.getURL()});
getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Bio: " + user.getDescription()});
getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Location: " + user.getLocation()});
getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "Status: " + user.getStatus().getText()});
if (bits[1].equalsIgnoreCase(myself.getNickname())) {
final long[] apiCalls = api.getRemainingApiCalls();
getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance: " + apiCalls[1]});
getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Allowance Remaining: " + apiCalls[0]});
getCallbackManager().getCallbackType(NumericListener.class).call(301, new String[]{":" + myServerName, "301", myself.getNickname(), bits[1], "API Calls Used: " + apiCalls[3]});
}
getCallbackManager().getCallbackType(NumericListener.class).call(312, new String[]{":" + myServerName, "312", myself.getNickname(), bits[1], myServerName, "DMDirc " + myServerName + " plugin"});
getCallbackManager().getCallbackType(NumericListener.class).call(317, new String[]{":" + myServerName, "317", myself.getNickname(), bits[1], Long.toString(secondsIdle), Long.toString(signonTime), "seconds idle, signon time"});
}
}
getCallbackManager().getCallbackType(NumericListener.class).call(318, new String[]{":" + myServerName, "318", myself.getNickname(), bits[1], "End of /WHOIS list."});
} else if (bits[0].equalsIgnoreCase("NAMES") && bits.length > 2) {
if (bits[2].equalsIgnoreCase(mainChannelName)) {
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(bits[2]);
if (channel != null) {
getCallbackManager().getCallbackType(ChannelNamesListener.class).call(channel);
}
}
} else if (bits[0].equalsIgnoreCase("INVITE") && bits.length > 2) {
if (bits[2].equalsIgnoreCase(mainChannelName)) {
final TwitterUser user = api.addFriend(bits[1]);
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(bits[2]);
if (channel != null && user != null) {
final TwitterClientInfo ci = new TwitterClientInfo(user.getScreenName(), this);
clients.put(ci.getNickname().toLowerCase(), ci);
final TwitterChannelClientInfo cci = new TwitterChannelClientInfo(channel, ci);
channel.addChannelClient(cci);
getCallbackManager().getCallbackType(ChannelJoinListener.class).call(channel, cci);
}
} else {
getCallbackManager().getCallbackType(NumericListener.class).call(474, new String[]{":" + myServerName, "482", myself.getNickname(), bits[1], "You can't do that here."});
}
} else if (bits[0].equalsIgnoreCase("KICK") && bits.length > 2) {
if (bits[1].equalsIgnoreCase(mainChannelName)) {
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(bits[1]);
if (channel != null) {
final TwitterChannelClientInfo cci = (TwitterChannelClientInfo) channel.getChannelClient(bits[2]);
if (cci != null) {
cci.kick("Bye");
}
}
} else {
getCallbackManager().getCallbackType(NumericListener.class).call(474, new String[]{":" + myServerName, "482", myself.getNickname(), bits[1], "You can't do that here."});
}
} else {
getCallbackManager().getCallbackType(NumericListener.class).call(474, new String[]{":" + myServerName, "421", myself.getNickname(), bits[0], "Unknown Command - " + message});
}
}
/** {@inheritDoc} */
@Override
public boolean isValidChannelName(final String name) {
return name.matches("^&[0-9]+$") || name.equalsIgnoreCase(mainChannelName) || name.charAt(0) == '
}
/** {@inheritDoc} */
@Override
public String getServerName() {
return myServerName + "/" + myself.getNickname();
}
/** {@inheritDoc} */
@Override
public String getNetworkName() {
return myServerName + "/" + myself.getNickname();
}
/** {@inheritDoc} */
@Override
public String getServerSoftware() {
return myServerName;
}
/** {@inheritDoc} */
@Override
public String getServerSoftwareType() {
return "twitter";
}
/** {@inheritDoc} */
@Override
public int getMaxTopicLength() {
return 140;
}
/** {@inheritDoc} */
@Override
public String getBooleanChannelModes() {
return "";
}
/** {@inheritDoc} */
@Override
public String getListChannelModes() {
return "b";
}
/** {@inheritDoc} */
@Override
public int getMaxListModes(final char mode) {
return 0;
}
/** {@inheritDoc} */
@Override
public boolean isUserSettable(final char mode) {
return mode == 'b';
}
/** {@inheritDoc} */
@Override
public String getParameterChannelModes() {
return "";
}
/** {@inheritDoc} */
@Override
public String getDoubleParameterChannelModes() {
return "";
}
/** {@inheritDoc} */
@Override
public String getUserModes() {
return "";
}
/** {@inheritDoc} */
@Override
public String getChannelUserModes() {
return "ov";
}
/** {@inheritDoc} */
@Override
public CallbackManager<? extends Parser> getCallbackManager() {
return myCallbackManager;
}
/** {@inheritDoc} */
@Override
public long getServerLatency() {
return 0;
}
/** {@inheritDoc} */
@Override
public String getBindIP() {
return "";
}
/** {@inheritDoc} */
@Override
public Map<Object, Object> getMap() {
return myMap;
}
/** {@inheritDoc} */
@Override
public URI getURI() {
return myAddress;
}
/** {@inheritDoc} */
@Override
public String getChannelPrefixes() {
return "
}
/** {@inheritDoc} */
@Override
public boolean compareURI(final URI uri) {
return myAddress.equals(uri);
}
/** {@inheritDoc} */
@Override
public void sendCTCP(final String target, final String type, final String message) {
if (wantAuth) {
sendPrivateNotice("DMDirc has not been authorised to use this account yet.");
} else if (target.matches("^&[0-9]+$")) {
try {
final long id = Long.parseLong(target.substring(1));
if (type.equalsIgnoreCase("retweet") || type.equalsIgnoreCase("rt")) {
final TwitterStatus status = api.getStatus(id);
if (status == null) {
sendPrivateNotice("Invalid Tweet ID.");
} else {
sendPrivateNotice("Retweeting: <" + status.getUser().getScreenName() + "> " + status.getText());
if (api.retweetStatus(status)) {
sendPrivateNotice("Retweet was successful.");
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
checkTopic(channel, myself.getUser().getStatus());
} else {
sendPrivateNotice("Retweeting Failed.");
}
}
} else if (type.equalsIgnoreCase("delete") || type.equalsIgnoreCase("del")) {
final TwitterStatus status = api.getStatus(id);
if (status == null) {
sendPrivateNotice("Invalid Tweet ID.");
} else {
sendPrivateNotice("Deleting: <" + status.getUser().getScreenName() + "> " + status.getText());
if (api.deleteStatus(status)) {
sendPrivateNotice("Deleting was successful, deleted tweets will still be accessible for some time.");
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
checkTopic(channel, myself.getUser().getStatus());
} else {
sendPrivateNotice("Deleting Failed.");
}
}
}
} catch (final NumberFormatException nfe) {
sendPrivateNotice("Invalid Tweet ID.");
}
} else if (target.equalsIgnoreCase(mainChannelName) || target.charAt(0) == '
if (type.equalsIgnoreCase("update") || type.equalsIgnoreCase("refresh")) {
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
sendChannelNotice(channel, "Refreshing...");
if (channel != null && !getUpdates(channel)) {
sendChannelNotice(channel, "No new items found.");
}
}
} else {
sendPrivateNotice("This parser does not support CTCPs.");
}
}
/** {@inheritDoc} */
@Override
public void sendCTCPReply(final String target, final String type, final String message) {
sendPrivateNotice("This parser does not support CTCP replies.");
}
/** {@inheritDoc} */
@Override
public void sendMessage(final String target, final String message) {
if (target.equalsIgnoreCase(mainChannelName)) {
if (wantAuth) {
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(target);
final String[] bits = message.split(" ");
if (bits[0].equalsIgnoreCase("usepw")) {
sendChannelMessage(channel, "Switching to once-off password authentication, please enter your password.");
api.setUseOAuth(false);
return;
}
try {
if (api.useOAuth()) {
api.setAccessPin(bits[0]);
if (api.isAllowed(true)) {
IdentityManager.getConfigIdentity().setOption(myPlugin.getDomain(), "token-" + myServerName + "-" + myUsername, api.getToken());
IdentityManager.getConfigIdentity().setOption(myPlugin.getDomain(), "tokenSecret-" + myServerName + "-" + myUsername, api.getTokenSecret());
sendChannelMessage(channel, "Thank you for authorising DMDirc.");
updateTwitterChannel();
wantAuth = false;
} else {
sendChannelMessage(channel, "Authorising DMDirc failed, please try again: " + api.getOAuthURL());
}
} else {
api.setPassword(message);
if (api.isAllowed(true)) {
sendChannelMessage(channel, "Password accepted. Please note you will need to do this every time unless your password is given in the URL.");
updateTwitterChannel();
wantAuth = false;
} else {
sendChannelMessage(channel, "Password seems incorrect, please try again.");
}
}
} catch (final TwitterException te) {
sendChannelMessage(channel, "There was a problem authorising DMDirc (" + te.getCause().getMessage() + ").");
sendChannelMessage(channel, "Please try again: " + api.getOAuthURL());
}
} else {
if (setStatus(message)) {
sendPrivateNotice("Setting status ok.");
} else {
sendPrivateNotice("Setting status failed.");
}
}
} else if (wantAuth) {
sendPrivateNotice("DMDirc has not been authorised to use this account yet.");
} else if (target.matches("^&[0-9]+$")) {
try {
if (setStatus(message, Long.parseLong(target.substring(1)))) {
sendPrivateNotice("Setting status ok.");
if (autoLeaveMessageChannel) {
partChannel(getChannel(target));
}
} else {
sendPrivateNotice("Setting status failed.");
}
} catch (final NumberFormatException nfe) {
}
} else if (target.matches("^
sendPrivateNotice("Messages to '" + target + "' are not currently supported.");
} else {
if (api.newDirectMessage(target, message)) {
sendPrivateNotice("Sending Direct Message to '" + target + "' was successful.");
} else {
sendPrivateNotice("Sending Direct Message to '" + target + "' failed.");
}
}
}
/** {@inheritDoc} */
@Override
public void sendNotice(final String target, final String message) {
sendPrivateNotice("This parser does not support notices.");
}
/** {@inheritDoc} */
@Override
public void sendAction(final String target, final String message) {
sendPrivateNotice("This parser does not support CTCPs.");
}
/** {@inheritDoc} */
@Override
public String getLastLine() {
return "";
}
/** {@inheritDoc} */
@Override
public String[] parseHostmask(final String hostmask) {
return TwitterClientInfo.parseHostFull(hostmask, myPlugin, this);
}
/** {@inheritDoc} */
@Override
public int getLocalPort() {
return api.getPort();
}
/** {@inheritDoc} */
@Override
public long getPingTime() {
return System.currentTimeMillis() - lastQueryTime;
}
/** {@inheritDoc} */
@Override
public void setPingTimerInterval(final long newValue) {
/* Do Nothing. */
}
/** {@inheritDoc} */
@Override
public long getPingTimerInterval() {
return -1;
}
/** {@inheritDoc} */
@Override
public void setPingTimerFraction(final int newValue) {
/* Do Nothing. */
}
/** {@inheritDoc} */
@Override
public int getPingTimerFraction() {
return -1;
}
/**
* Send a notice to the client.
*
* @param message Message to send.
*/
protected void sendPrivateNotice(final String message) {
getCallbackManager().getCallbackType(PrivateNoticeListener.class).call(message, myServerName);
}
/**
* Send a PM to the client.
*
* @param message Message to send.
* @param hostname Who is the message from?
* @param target Who is the message to?
*/
private void sendPrivateMessage(final String message, final String hostname, final String target) {
if (hostname.equalsIgnoreCase(myUsername)) {
getCallbackManager().getCallbackType(UnknownMessageListener.class).call(message, target, hostname);
} else {
getCallbackManager().getCallbackType(PrivateMessageListener.class).call(message, hostname);
}
}
/**
* Send a message to the given channel.
*
* @param channel Channel to send message to
* @param message Message to send.
*/
private void sendChannelMessage(final ChannelInfo channel, final String message) {
sendChannelMessage(channel, message, myServerName);
}
/**
* Send a message to the given channel.
*
* @param channel Channel to send message to
* @param message Message to send.
* @param hostname Hostname that the message is from.
*/
private void sendChannelMessage(final ChannelInfo channel, final String message, final String hostname) {
sendChannelMessage(channel, new Date(), message, null, hostname);
}
/**
* Send a message to the given channel.
*
* @param channel Channel to send message to
* @param date The timestamp to be used for the message
* @param message Message to send.
* @param cci Channel Client to send from
* @param hostname Hostname that the message is from.
*/
private void sendChannelMessage(final ChannelInfo channel, final Date date, final String message, final ChannelClientInfo cci, final String hostname) {
getCallbackManager().getCallbackType(ChannelMessageListener.class).call(date, channel, cci, message, hostname);
}
/**
* Send a notice to the given channel.
*
* @param channel Channel to send notice to
* @param notice Notice to send.
*/
private void sendChannelNotice(final ChannelInfo channel, final String notice) {
sendChannelNotice(channel, notice, myServerName);
}
/**
* Send a notice to the given channel.
*
* @param channel Channel to send notice to
* @param notice Notice to send.
* @param hostname Hostname that the notice is from.
*/
private void sendChannelNotice(final ChannelInfo channel, final String notice, final String hostname) {
sendChannelNotice(channel, new Date(), notice, null, hostname);
}
/**
* Send a notice to the given channel.
*
* @param channel Channel to send notice to
* @param date The timestamp to be used for the notice
* @param notice Notice to send.
* @param cci Channel Client to send from
* @param hostname Hostname that the notice is from.
*/
private void sendChannelNotice(final ChannelInfo channel, final Date date, final String notice, final ChannelClientInfo cci, final String hostname) {
getCallbackManager().getCallbackType(ChannelNoticeListener.class).call(date, channel, cci, notice, hostname);
}
/**
* Show the user an ascii failwhale!
*/
public void showFailWhale() {
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5 ");
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5 W W W ");
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5 W W W W ");
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5 '." + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5 W ");
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5 .-\"\"-._ \\ \\.
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5 / \"-..__) .-' ");
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5 | _ / ");
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5 \\'-.__, .__.,' ");
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5 `'
sendPrivateNotice("" + Styliser.CODE_FIXED + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V" + Styliser.CODE_HEXCOLOUR + "FFFFFF,71C5C5V" + Styliser.CODE_HEXCOLOUR + "EB5405,71C5C5V");
}
/**
* Check if the given user is known on the channel, and add them if they
* are not.
*
* @param user User to check
* @return true if user was already on the channel, false if they were added.
*/
private boolean checkUserOnChannel(final TwitterUser user) {
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
if (channel == null) {
doDebug(Debug.stateError, "Tried to check user (" + user.getScreenName() + "), but channel is null.");
return false;
}
if (channel.getChannelClient(user.getScreenName()) == null) {
// User not found, perhaps a rename?
for (final ChannelClientInfo cci : channel.getChannelClients()) {
final TwitterClientInfo ci = (TwitterClientInfo) cci.getClient();
if (ci.getUserID() == user.getID()) {
final String oldName = ci.getNickname();
ci.setUser(user);
renameClient(ci, oldName);
}
}
final TwitterClientInfo ci = new TwitterClientInfo(user.getScreenName(), this);
clients.put(ci.getNickname().toLowerCase(), ci);
final TwitterChannelClientInfo cci = new TwitterChannelClientInfo(channel, ci);
channel.addChannelClient(cci);
getCallbackManager().getCallbackType(ChannelJoinListener.class).call(channel, cci);
return false;
} else {
return true;
}
}
/**
* Send a Debug Message using the parser debug api.
*
* @param code Debug Code for the message.
* @param message Content of the message.
*/
private void doDebug(final Debug code, final String message) {
if (debugEnabled) {
getCallbackManager().getCallbackType(DebugInfoListener.class).call(code.ordinal(), message);
}
}
/**
* Run the twitter parser.
*/
@Override
public void run() {
resetState();
if (myUsername.isEmpty()) {
sendPrivateNotice("Unable to connect to " + myServerName + " without a username. Disconnecting.");
getCallbackManager().getCallbackType(SocketCloseListener.class).call();
return;
}
// Get the consumerKey and consumerSecret for this server if known
// else default to our twitter key and secret
final String consumerKey;
final String consumerSecret;
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "consumerKey-" + myServerName)) {
consumerKey = getConfigManager().getOption(myPlugin.getDomain(), "consumerKey-" + myServerName);
} else {
consumerKey = "qftK3mAbLfbWWHf8shiyjw";
}
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "consumerSecret-" + myServerName)) {
consumerSecret = getConfigManager().getOption(myPlugin.getDomain(), "consumerSecret-" + myServerName);
} else {
consumerSecret = "flPr2TJGp4795DeTu4VkUlNLX8g25SpXWXZ7SKW0Bg";
}
final String token;
final String tokenSecret;
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "token-" + myServerName + "-" + myUsername)) {
token = getConfigManager().getOption(myPlugin.getDomain(), "token-" + myServerName + "-" + myUsername);
} else {
token = "";
}
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "tokenSecret-" + myServerName + "-" + myUsername)) {
tokenSecret = getConfigManager().getOption(myPlugin.getDomain(), "tokenSecret-" + myServerName + "-" + myUsername);
} else {
tokenSecret = "";
}
api = new TwitterAPI(myUsername, myPassword, apiAddress, "", consumerKey, consumerSecret, token, tokenSecret, apiVersioning, apiVersion, getConfigManager().getOptionBool(myPlugin.getDomain(), "autoAt"));
api.setSource("DMDirc");
PARSERS.add(this);
api.addErrorHandler(this);
api.addRawHandler(this);
api.setDebug(debugEnabled);
getConfigManager().addChangeListener(myPlugin.getDomain(), this);
connected = api.checkConnection();
if (!connected) {
sendPrivateNotice("Unable to connect to " + myServerName + ". Disconnecting.");
getCallbackManager().getCallbackType(SocketCloseListener.class).call();
return;
}
final TwitterChannelInfo channel = new TwitterChannelInfo(mainChannelName, this);
synchronized (channels) {
channels.put(mainChannelName, channel);
}
channel.addChannelClient(new TwitterChannelClientInfo(channel, myself));
// Fake 001
getCallbackManager().getCallbackType(ServerReadyListener.class).call();
// Fake 005
getCallbackManager().getCallbackType(NetworkDetectedListener.class).call(getNetworkName(), getServerSoftware(), getServerSoftwareType());
getCallbackManager().getCallbackType(Post005Listener.class).call();
// Fake MOTD
getCallbackManager().getCallbackType(AuthNoticeListener.class).call("Welcome to " + myServerName + ".");
getCallbackManager().getCallbackType(MotdStartListener.class).call("- " + myServerName + " Message of the Day -");
getCallbackManager().getCallbackType(MotdLineListener.class).call("- This is an experimental parser, to allow DMDirc to use " + myServerName);
getCallbackManager().getCallbackType(MotdLineListener.class).call("- ");
getCallbackManager().getCallbackType(MotdLineListener.class).call("- Your timeline appears in " + mainChannelName + " (topic is your last status)");
getCallbackManager().getCallbackType(MotdLineListener.class).call("- All messages sent to this channel (or topics set) will cause the status to be set.");
getCallbackManager().getCallbackType(MotdLineListener.class).call("- ");
getCallbackManager().getCallbackType(MotdLineListener.class).call("- Messages can be replied to using /msg &<messageid> <reply>");
getCallbackManager().getCallbackType(MotdLineListener.class).call("- Messages can be retweeted by using /ctcp &<messageid> RT or /ctcp &<messageid> RETWEET");
getCallbackManager().getCallbackType(MotdLineListener.class).call("- ");
getCallbackManager().getCallbackType(MotdEndListener.class).call(false, "End of /MOTD command");
// Fake some more on-connect crap
getCallbackManager().getCallbackType(UserModeDiscoveryListener.class).call(myself, "");
channel.setLocalTopic("No status known.");
doJoinChannel(channel);
sendChannelMessage(channel, "Checking to see if we have been authorised to use the account \"" + api.getLoginUsername() + "\"...");
if (api.isAllowed(false)) {
sendChannelMessage(channel, "DMDirc has been authorised to use the account \"" + api.getLoginUsername() + "\"");
updateTwitterChannel();
} else {
wantAuth = true;
if (api.useOAuth()) {
sendChannelMessage(channel, "Sorry, DMDirc has not been authorised to use the account \"" + api.getLoginUsername() + "\"");
sendChannelMessage(channel, "");
sendChannelMessage(channel, "Before you can use DMDirc with " + myServerName + " you need to authorise it.");
sendChannelMessage(channel, "");
sendChannelMessage(channel, "To do this, please visit: " + api.getOAuthURL());
sendChannelMessage(channel, "and then type the PIN here.");
} else {
sendChannelMessage(channel, "Sorry, You did not provide DMDirc with a password for the account \"" + api.getLoginUsername() + "\" and the server \"" + myServerName + "\" does not support OAuth or is not accepting our key.");
sendChannelMessage(channel, "");
sendChannelMessage(channel, "Before you can use DMDirc with " + myServerName + " you need to provide a password.");
sendChannelMessage(channel, "");
sendChannelMessage(channel, "To do this, please type the password here, or set it correctly in the URL (twitter://" + myUsername + ":your_password@" + myServerName + myAddress.getPath() + ").");
}
}
if (saveLastIDs) {
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "lastReplyId-" + myServerName + "-" + myUsername)) {
lastReplyId = TwitterAPI.parseLong(getConfigManager().getOption(myPlugin.getDomain(), "lastReplyId-" + myServerName + "-" + myUsername), -1);
}
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "lastTimelineId-" + myServerName + "-" + myUsername)) {
lastTimelineId = TwitterAPI.parseLong(getConfigManager().getOption(myPlugin.getDomain(), "lastTimelineId-" + myServerName + "-" + myUsername), -1);
}
if (getConfigManager().hasOptionString(myPlugin.getDomain(), "lastDirectMessageId-" + myServerName + "-" + myUsername)) {
lastDirectMessageId = TwitterAPI.parseLong(getConfigManager().getOption(myPlugin.getDomain(), "lastDirectMessageId-" + myServerName + "-" + myUsername), -1);
}
}
boolean first = true; // Used to let used know if there was no new items.
int count = 0;
while (connected) {
final int startCalls = wantAuth ? 0 : api.getUsedCalls();
// Get Updates
final boolean foundUpdates = getUpdates(channel);
if (first && !foundUpdates) {
sendChannelMessage(channel, "No new items found.");
}
first = false;
// Store last IDs
IdentityManager.getConfigIdentity().setOption(myPlugin.getDomain(), "lastReplyId-" + myServerName + "-" + myUsername, Long.toString(lastReplyId));
IdentityManager.getConfigIdentity().setOption(myPlugin.getDomain(), "lastTimelineId-" + myServerName + "-" + myUsername, Long.toString(lastTimelineId));
IdentityManager.getConfigIdentity().setOption(myPlugin.getDomain(), "lastDirectMessageId-" + myServerName + "-" + myUsername, Long.toString(lastDirectMessageId));
// Get Updates for search channels
for (final TwitterChannelInfo searchChannel : channels.values()) {
if (searchChannel.getName().startsWith("
getUpdates(searchChannel);
}
}
// Calculate number of calls remaining.
final int endCalls = wantAuth ? 0 : api.getUsedCalls();
final long[] apiCalls = wantAuth ? new long[]{0L, 0L, System.currentTimeMillis(), (long) api.getUsedCalls()} : api.getRemainingApiCalls();
doDebug(Debug.apiCalls, "Twitter calls Remaining: " + apiCalls[0]);
// laconica doesn't rate limit, so time to reset is always 0, in this case
// we will assume the time of the next hour.
final Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY) + 1, 0, 0);
final long timeLeft = (apiCalls[2] > 0 ? apiCalls[2] : cal.getTimeInMillis()) - System.currentTimeMillis();
final long sleepTime;
if (wantAuth) {
// When waiting for auth, sleep for less time so that when the
// auth happens, we can quickly start twittering!
sleepTime = 5 * 1000;
} else if (!api.isAllowed()) {
// If we aren't allowed, but aren't waiting for auth, then
// sleep for 1 minute.
sleepTime = 60 * 1000;
} else if (apiCalls[1] == 0L) {
// Twitter has said we have no API Calls in total, so sleep for
// 10 minutes and try again.
// (This will also happen if twitter didn't respond for some reason)
sleepTime = 10 * 60 * 1000;
// Also alert the user.
twitterFail("Unable to communicate with twitter or no API calls allowed, retrying in 10 minutes.");
} else if (api.getUsedCalls() > apicalls) {
// Sleep for the rest of the hour, we have done too much!
sleepTime = timeLeft;
} else {
// Else work out how many calls we have left.
// Whichever is less between the number of calls we want to make
// and the number of calls twitter is going to allow us to make.
final long callsLeft = Math.min(apicalls - api.getUsedCalls(), apiCalls[0]);
// How many calls do we make each time?
// If this is less than 0 (If there was a time reset between
// calculating the start and end calls used) then assume 3.
final long callsPerTime = (endCalls - startCalls) > 0 ? endCalls - startCalls : 3;
doDebug(Debug.apiCalls, "\tCalls Remaining: " + callsLeft);
doDebug(Debug.apiCalls, "\tCalls per time: " + callsPerTime);
// And divide this by the number of calls we make each time to
// see how many times we have to sleep this hour.
final long sleepsRequired = callsLeft / callsPerTime;
doDebug(Debug.sleepTime, "\tSleeps Required: " + sleepsRequired);
doDebug(Debug.sleepTime, "\tTime Left: " + timeLeft);
// Then finally discover how long we need to sleep for.
sleepTime = (sleepsRequired > 0) ? timeLeft / sleepsRequired : timeLeft;
}
doDebug(Debug.sleepTime, "Sleeping for: " + sleepTime);
// Sleep for sleep time,
// If we have a negative sleep time, use 5 minutes.
try {
Thread.sleep(sleepTime > 0 ? sleepTime : 5 * 60 * 1000);
} catch (final InterruptedException ex) {
}
if (++count > PRUNE_COUNT) {
api.pruneStatusCache(System.currentTimeMillis() - PRUNE_TIME);
}
}
}
/**
* Get updates from twitter.
*
* @param channel Channel that this is being used for.
* @return True if any items are found, else false.
*/
private boolean getUpdates(final TwitterChannelInfo channel) {
boolean foundItems = false;
if (!wantAuth && api.isAllowed()) {
lastQueryTime = System.currentTimeMillis();
if (channel.getName().startsWith("
long lastId = lastSearchIds.containsKey(channel) ? lastSearchIds.get(channel) : -1;
final List<TwitterStatus> statuses = api.getSearchResults(channel.getName(), lastId);
foundItems = !statuses.isEmpty();
for (final TwitterStatus status : statuses) {
final ChannelClientInfo cci = channel.getChannelClient(status.getUserName(), true);
sendChannelMessage(channel, new Date(status.getTime()), status.getText(), cci, status.getUserName());
lastId = Math.max(lastId, status.getID());
}
lastSearchIds.put(channel, lastId);
} else {
final int statusesPerAttempt = Math.min(200, statusCount);
final List<TwitterStatus> statuses = new ArrayList<TwitterStatus>();
for (final TwitterStatus status : api.getReplies(lastReplyId, statusesPerAttempt)) {
statuses.add(status);
if (status.getRetweetId() > lastReplyId) {
lastReplyId = status.getRetweetId();
}
}
for (final TwitterStatus status : api.getFriendsTimeline(lastTimelineId, statusesPerAttempt)) {
if (!statuses.contains(status)) {
statuses.add(status);
}
// Add new friends that may have been added elsewhere.
if (status.isRetweet()) {
checkUserOnChannel(status.getRetweetUser());
} else {
checkUserOnChannel(status.getUser());
}
if (status.getRetweetId() > lastTimelineId) {
lastTimelineId = status.getRetweetId();
}
}
Collections.sort(statuses);
for (final TwitterStatus status : statuses) {
foundItems = true;
final ChannelClientInfo cci = channel.getChannelClient(status.getUser().getScreenName());
String message = String.format("%s %c15 &%d", status.getText(), Styliser.CODE_COLOUR, status.getID());
if (status.getReplyTo() > 0) {
message += String.format(" %cin reply to &%d %1$c", Styliser.CODE_ITALIC, status.getReplyTo());
}
if (status.isRetweet()) {
message += String.format(" %c%c15[Retweet by %s]%1$c", Styliser.CODE_BOLD, Styliser.CODE_COLOUR, status.getRetweetUser().getScreenName());
}
final String hostname = status.getUser().getScreenName();
sendChannelMessage(channel, new Date(status.getTime()), message, cci, hostname);
}
final List<TwitterMessage> directMessages = new ArrayList<TwitterMessage>();
for (final TwitterMessage directMessage : api.getDirectMessages(lastDirectMessageId)) {
directMessages.add(directMessage);
if (directMessage.getID() > lastDirectMessageId) {
lastDirectMessageId = directMessage.getID();
}
}
if (getSentMessage) {
for (final TwitterMessage directMessage : api.getSentDirectMessages(lastDirectMessageId)) {
directMessages.add(directMessage);
if (directMessage.getID() > lastDirectMessageId) {
lastDirectMessageId = directMessage.getID();
}
}
}
Collections.sort(directMessages);
for (final TwitterMessage dm : directMessages) {
sendPrivateMessage(dm.getText(), dm.getSenderScreenName(), dm.getTargetScreenName());
}
if (myself != null && myself.getUser() != null) {
checkTopic(channel, myself.getUser().getStatus());
}
}
}
return foundItems;
}
/**
* Reset the state of the parser.
*/
private void resetState() {
resetState(false);
}
/**
* Reset the state of the parser.
*
* @param simpleMyself Don't check the config when setting myself if true.
*/
private void resetState(final boolean simpleMyself) {
connected = false;
synchronized (channels) {
channels.clear();
}
clients.clear();
if (!simpleMyself && autoAt) {
myself = new TwitterClientInfo("@" + myUsername, this);
} else {
myself = new TwitterClientInfo(myUsername, this);
}
setCachedSettings();
}
/**
* Get the Twitter API Object.
*
* @return The Twitter API Object
*/
public TwitterAPI getApi() {
return api;
}
/** {@inheritDoc} */
@Override
public StringConverter getStringConverter() {
return myStringConverter;
}
/** {@inheritDoc} */
@Override
public void setIgnoreList(final IgnoreList ignoreList) {
myIgnoreList = ignoreList;
}
/** {@inheritDoc} */
@Override
public IgnoreList getIgnoreList() {
return myIgnoreList;
}
/**
* Set the twitter status.
*
* @param message Status to use.
* @return True if status was updated, else false.
*/
public boolean setStatus(final String message) {
return setStatus(message, -1);
}
/**
* Set the twitter status.
*
* @param message Status to use.
* @param replyToId The ID this status is in reply to, or -1
* @return True if status was updated, else false.
*/
private boolean setStatus(final String message, final long replyToId) {
final StringBuffer newStatus = new StringBuffer(message);
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
if (channel != null && replaceOpeningNickname) {
final String[] bits = message.split(" ");
if (bits[0].charAt(bits[0].length() - 1) == ':') {
final String name = bits[0].substring(0, bits[0].length() - 1);
final ChannelClientInfo cci = channel.getChannelClient(name);
if (cci != null) {
if (cci.getClient().getNickname().charAt(0) == '@') {
bits[0] = cci.getClient().getNickname();
} else {
bits[0] = "@" + cci.getClient().getNickname();
}
newStatus.setLength(0);
for (final String bit : bits) {
if (newStatus.length() > 0) {
newStatus.append(' ');
}
newStatus.append(bit);
}
}
}
}
if (api.setStatus(newStatus.toString(), replyToId)) {
checkTopic(channel, myself.getUser().getStatus());
return true;
}
return false;
}
/**
* Rename the given client from the given name.
*
* @param client Client to rename
* @param old Old nickname
*/
public void renameClient(final TwitterClientInfo client, final String old) {
clients.remove(old.toLowerCase());
clients.put(client.getNickname().toLowerCase(), client);
getCallbackManager().getCallbackType(NickChangeListener.class).call(client, old);
for (final ChannelClientInfo cci : client.getChannelClients()) {
getCallbackManager().getCallbackType(ChannelNickChangeListener.class).call(client, cci.getChannel(), old);
}
}
@Override
public int getMaxLength() {
return 140;
}
/**
* Make the core think a channel was joined.
*
* @param channel Channel to join.
*/
private void doJoinChannel(final ChannelInfo channel) {
// Fake Join Channel
getCallbackManager().getCallbackType(ChannelSelfJoinListener.class).call(channel);
getCallbackManager().getCallbackType(ChannelTopicListener.class).call(channel, true);
getCallbackManager().getCallbackType(ChannelNamesListener.class).call(channel);
getCallbackManager().getCallbackType(ChannelModeChangeListener.class).call(channel, null, "", "");
}
/**
* Update the users and topic of the main channel.
*/
private void updateTwitterChannel() {
final TwitterChannelInfo channel = (TwitterChannelInfo) getChannel(mainChannelName);
checkTopic(channel, myself.getUser().getStatus());
channel.clearChannelClients();
channel.addChannelClient(new TwitterChannelClientInfo(channel, myself));
for (final TwitterUser user : api.getFriends()) {
final TwitterClientInfo ci = new TwitterClientInfo(user.getScreenName(), this);
clients.put(ci.getNickname().toLowerCase(), ci);
final TwitterChannelClientInfo cci = new TwitterChannelClientInfo(channel, ci);
channel.addChannelClient(cci);
}
api.getFollowers();
getCallbackManager().getCallbackType(ChannelNamesListener.class).call(channel);
}
/**
* Check if the topic in the given channel has been changed, and if it has
* fire the callback.
*
* @param channel channel to check.
* @param status Status to use to update the topic with.
*/
private void checkTopic(final TwitterChannelInfo channel, final TwitterStatus status) {
if (channel == null || status == null) {
return;
}
final String oldStatus = channel.getTopic();
final String newStatus = (status.isRetweet()) ? status.getRetweetText() : status.getText();
if (!newStatus.equalsIgnoreCase(oldStatus)) {
channel.setTopicSetter(status.getUser().getScreenName());
channel.setTopicTime(status.getTime() / 1000);
channel.setLocalTopic(newStatus);
getCallbackManager().getCallbackType(ChannelTopicListener.class).call(channel, false);
}
}
/** {@inheritDoc} */
@Override
public void handleTwitterError(final TwitterAPI api, final Throwable t, final String source, final String twitterInput, final String twitterOutput, final String message) {
final boolean showError = !debugEnabled && hide500Errors;
if (showError && message.matches("^\\(50[0-9]\\).*")) {
return;
}
try {
if (message.isEmpty()) {
twitterFail("Recieved an error: " + source);
} else if (debugEnabled) {
twitterFail("Recieved an error from twitter: " + message + (debugEnabled ? " [" + source + "]" : ""));
}
if (t != null) {
doDebug(Debug.twitterError, t.getClass().getSimpleName() + ": " + t + " -> " + t.getMessage());
}
// And give more information:
doDebug(Debug.twitterErrorMore, "Source: " + source);
doDebug(Debug.twitterErrorMore, "Input: " + twitterInput);
doDebug(Debug.twitterErrorMore, "Output: ");
for (final String out : twitterOutput.split("\n")) {
doDebug(Debug.twitterErrorMore, " " + out);
}
doDebug(Debug.twitterErrorMore, "");
doDebug(Debug.twitterErrorMore, "Exception:");
final String[] trace = ErrorManager.getTrace(t);
for (final String out : trace) {
doDebug(Debug.twitterErrorMore, " " + out);
}
doDebug(Debug.twitterErrorMore, "==================================");
} catch (final Exception t2) {
doDebug(Debug.twitterError, "wtf? (See Console for stack trace) " + t2);
t2.printStackTrace();
}
}
/**
* This method will send data to the NumericListener and the DataInListener
*
* @param numeric Numeric
* @param token Tokenised Representation.
*/
private void sendNumericOutput(final int numeric, final String[] token) {
getCallbackManager().getCallbackType(NumericListener.class).call(numeric, token);
final StringBuffer output = new StringBuffer();
for (final String bit : token) {
output.append(' ');
output.append(bit);
}
getCallbackManager().getCallbackType(DataInListener.class).call(output.toString().trim());
}
/** {@inheritDoc} */
@Override
public void handleRawTwitterInput(final TwitterAPI api, final String data) {
doDebug(Debug.dataIn, "
getCallbackManager().getCallbackType(DataInListener.class).call("
for (final String line : data.split("\n")) {
doDebug(Debug.dataIn, line);
getCallbackManager().getCallbackType(DataInListener.class).call(line);
}
}
/** {@inheritDoc} */
@Override
public void handleRawTwitterOutput(final TwitterAPI api, final String data) {
doDebug(Debug.dataOut, "
getCallbackManager().getCallbackType(DataOutListener.class).call("
for (final String line : data.split("\n")) {
doDebug(Debug.dataOut, line);
getCallbackManager().getCallbackType(DataOutListener.class).call(line, true);
}
}
/**
* Let the user know twitter failed in some way.
*
* @param message Message to send to the user
*/
private void twitterFail(final String message) {
if (Math.random() <= 0.10) {
showFailWhale();
}
doDebug(Debug.twitterError, message);
sendPrivateNotice(message);
}
/**
* Returns the TwitterPlugin that owns us.
*
* @return The TwitterPlugin that owns us.
*/
public TwitterPlugin getMyPlugin() {
return myPlugin;
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
setCachedSettings();
if (domain.equalsIgnoreCase(myPlugin.getDomain())) {
if (key.equalsIgnoreCase("debugEnabled")) {
api.setDebug(debugEnabled);
} else if (key.equalsIgnoreCase("autoAt")) {
sendPrivateNotice("'autoAt' setting was changed, reconnect needed.");
disconnect("'autoAt' setting was changed, reconnect needed.");
}
}
}
/**
* Get the config manager for this parser instance.
*
* @return the ConfigManager for this parser.
*/
protected ConfigManager getConfigManager() {
if (myConfigManager == null) {
myConfigManager = new ConfigManager(myAddress.getScheme(), getServerSoftwareType(), getNetworkName(), getServerName());
}
return myConfigManager;
}
/**
* Get settings from config for cache variables.
*/
private void setCachedSettings() {
saveLastIDs = getConfigManager().getOptionBool(myPlugin.getDomain(), "saveLastIDs");
statusCount = getConfigManager().getOptionInt(myPlugin.getDomain(), "statuscount");
getSentMessage = getConfigManager().getOptionBool(myPlugin.getDomain(), "getSentMessages");
apicalls = getConfigManager().getOptionInt(myPlugin.getDomain(), "apicalls");
autoAt = getConfigManager().getOptionBool(myPlugin.getDomain(), "autoAt");
replaceOpeningNickname = getConfigManager().getOptionBool(myPlugin.getDomain(), "replaceOpeningNickname");
hide500Errors = getConfigManager().getOptionBool(myPlugin.getDomain(), "hide500Errors");
debugEnabled = getConfigManager().getOptionBool(myPlugin.getDomain(), "debugEnabled");
autoLeaveMessageChannel = getConfigManager().getOptionBool(myPlugin.getDomain(), "autoLeaveMessageChannel");
}
/** {@inheritDoc} */
@Override
public Collection<? extends ChannelJoinRequest> extractChannels(final URI uri) {
return new ArrayList<ChannelJoinRequest>();
}
/** {@inheritDoc} */
@Override
public List<String> getServerInformationLines() {
return Arrays.asList(new String[]{"Twitter IRC parser: " + getServerName()});
}
}
|
package com.github.timp.anagram;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* Test the Anagrammer class.
*/
public class AnagrammerTest
extends TestCase {
/**
* Test that the application is callable.
*/
public void testAnagramMain() throws Exception {
// Anagrammer.main(new String[] {"Benedict", "Cumberbatch" });
Anagrammer.main(new String[]{"Cat", "Sick"});
}
/**
* Test that the application returns expected results.
*
* 1 minute 19 seconds.
*/
public void excluded_testLongInput() throws Exception {
Anagrammer it = new Anagrammer();
ArrayList<String> results;
results = it.run(new String[]{"Benedict", "Cumberbatch", "lover"});
assertEquals(119, results.size());
}
/**
* Test that the application returns expected results.
* 25 seconds.
*/
public void testBenedictCumberbatch() throws Exception {
Anagrammer it = new Anagrammer();
ArrayList<String> results;
results = it.run(new String[]{"Benedict", "Cumberbatch"});
assertEquals(24746, results.size());
}
/**
* Test that the application returns expected results.
* 0.6 seconds
*/
public void testAnagram() throws Exception {
Anagrammer it = new Anagrammer();
ArrayList<String> results;
results = it.run(new String[]{"anagram"});
// TODO remove repetition
assertEquals("[" +
"A Man Rag, " +
"A Ran Mag, " +
"A Gram An, " +
"A Arm Nag, " +
"A Mar Nag, " +
"A Ram Nag, " +
"A Gran Am, " +
"A Gran Ma, " +
"A Rang Am, " +
"A Rang Ma, " +
"A Man Rag, " +
"A Ran Mag, " +
"A Gram An, A Arm Nag, A Mar Nag, " +
"A Ram Nag, A Gran Am, A Gran Ma, A Rang Am, " +
"A Rang Ma, " +
"A Man Rag, A Ran Mag, A Gram An, " +
"A Arm Nag, A Mar Nag, A Ram Nag, A Gran Am, " +
"A Gran Ma, A Rang Am, A Rang Ma, " +
"A Man Rag, " +
"A Ran Mag, A Gram An, A Arm Nag, A Mar Nag, A Ram Nag, " +
"A Gran Am, A Gran Ma, A Rang Am, A Rang Ma, " +
"A Man Rag, " +
"A Ran Mag, A Gram An, A Arm Nag, A Mar Nag, " +
"A Ram Nag, A Gran Am, A Gran Ma, A Rang Am, A Rang Ma, Anagram, " +
"Man Raga, Am An Rag, Ma An Rag]", results.toString());
}
/**
* Test that the application returns expected results.
*/
public void testTheCat() throws Exception {
Anagrammer it = new Anagrammer();
ArrayList<String> results;
// 0.5s
results = it.run(new String[]{"cat", "the"});
assertEquals("[Etch At, Tech At, He Tact, The Act, The Cat]", results.toString());
}
/**
* Test that the application returns expected results.
*/
public void testLiveOnLine() throws Exception {
Anagrammer it = new Anagrammer();
ArrayList<String> results;
// Was 3s now 0.54
results = it.run(new String[]{"live", "online"});
Set testNoDuplicates = new HashSet<String>();
for (String item : results) {
if (testNoDuplicates.add(item)) {
//fail("Duplicate " + item);
}
}
// TODO remove repetition
assertEquals("[" +
"No Evil Lien, No Evil Line, No Live Lien, No Live Line, No Veil Lien, No Veil Line, No Vile Lien, No Vile Line, On Evil Lien, On Evil Line, On Live Lien, On Live Line, On Veil Lien, On Veil Line, On Vile Lien, On Vile Line, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No Even Ill I, On Even Ill I, No Lie Liven, On Lie Liven, " +
"No Evil Lien, No Evil Line, No Live Lien, No Live Line, No Veil Lien, No Veil Line, No Vile Lien, No Vile Line, On Evil Lien, On Evil Line, On Live Lien, On Live Line, On Veil Lien, On Veil Line, On Vile Lien, On Vile Line, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No Even Ill I, On Even Ill I, No Lie Liven, On Lie Liven, " +
"No Evil Lien, No Evil Line, No Live Lien, No Live Line, No Veil Lien, No Veil Line, No Vile Lien, No Vile Line, On Evil Lien, On Evil Line, On Live Lien, On Live Line, On Veil Lien, On Veil Line, On Vile Lien, On Vile Line, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No Even Ill I, On Even Ill I, No Lie Liven, On Lie Liven, " +
"No Evil Lien, No Evil Line, No Live Lien, No Live Line, No Veil Lien, No Veil Line, No Vile Lien, No Vile Line, On Evil Lien, On Evil Line, On Live Lien, On Live Line, On Veil Lien, On Veil Line, On Vile Lien, On Vile Line, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No In Eve Ill, On In Eve Ill, No In Level I, On In Level I, No Even Ill I, On Even Ill I, No Lie Liven, On Lie Liven, " +
"Evil Lo Nine, Live Lo Nine, Veil Lo Nine, Vile Lo Nine, Evil In Lone, Live In Lone, Veil In Lone, Vile In Lone, Evil Eon Nil, Evil One Nil, Live Eon Nil, Live One Nil, Veil Eon Nil, Veil One Nil, Vile Eon Nil, Vile One Nil, Evil Inn Ole, Live Inn Ole, Veil Inn Ole, Vile Inn Ole, Evil Online, Live Online, Veil Online, Vile Online, Evil Lo Nine, Live Lo Nine, Veil Lo Nine, Vile Lo Nine, Evil In Lone, Live In Lone, Veil In Lone, Vile In Lone, Evil Eon Nil, Evil One Nil, Live Eon Nil, Live One Nil, Veil Eon Nil, Veil One Nil, Vile Eon Nil, Vile One Nil, Evil Inn Ole, Live Inn Ole, Veil Inn Ole, Vile Inn Ole, Evil Online, Live Online, Veil Online, Vile Online, Evil Lo Nine, Live Lo Nine, Veil Lo Nine, Vile Lo Nine, Evil In Lone, Live In Lone, Veil In Lone, Vile In Lone, Evil Eon Nil, Evil One Nil, Live Eon Nil, Live One Nil, Veil Eon Nil, Veil One Nil, Vile Eon Nil, Vile One Nil, Evil Inn Ole, Live Inn Ole, Veil Inn Ole, Vile Inn Ole, Evil Online, Live Online, Veil Online, Vile Online, Evil Lo Nine, Live Lo Nine, Veil Lo Nine, Vile Lo Nine, Evil In Lone, Live In Lone, Veil In Lone, Vile In Lone, Evil Eon Nil, Evil One Nil, Live Eon Nil, Live One Nil, Veil Eon Nil, Veil One Nil, Vile Eon Nil, Vile One Nil, Evil Inn Ole, Live Inn Ole, Veil Inn Ole, Vile Inn Ole, Evil Online, Live Online, Veil Online, Vile Online, Evil Lo Nine, Live Lo Nine, Veil Lo Nine, Vile Lo Nine, Evil In Lone, Live In Lone, Veil In Lone, Vile In Lone, Evil Eon Nil, Evil One Nil, Live Eon Nil, Live One Nil, Veil Eon Nil, Veil One Nil, Vile Eon Nil, Vile One Nil, Evil Inn Ole, Live Inn Ole, Veil Inn Ole, Vile Inn Ole, Evil Online, Live Online, Veil Online, Vile Online, Lo Vein Lien, Lo Vein Line, Lo Vine Lien, Lo Vine Line, Lo In Nil Eve, Lo Even I Nil, Lo Linen Vie, Lo I Enliven, Lo Vein Lien, Lo Vein Line, Lo Vine Lien, Lo Vine Line, Lo In Nil Eve, Lo Even I Nil, Lo Linen Vie, Lo I Enliven, Lo Vein Lien, Lo Vein Line, Lo Vine Lien, Lo Vine Line, Lo In Nil Eve, Lo Even I Nil, Lo Linen Vie, Lo I Enliven, Lo Vein Lien, Lo Vein Line, Lo Vine Lien, Lo Vine Line, Lo In Nil Eve, Lo Even I Nil, Lo Linen Vie, Lo I Enliven, Lo Vein Lien, Lo Vein Line, Lo Vine Lien, Lo Vine Line, Lo In Nil Eve, Lo Even I Nil, Lo Linen Vie, Lo I Enliven, Vein Eon Ill, Vein One Ill, Vine Eon Ill, Vine One Ill, Vein Ole Nil, Vine Ole Nil, Vein Eon Ill, Vein One Ill, Vine Eon Ill, Vine One Ill, Vein Ole Nil, Vine Ole Nil, Neon Vie Ill, None Vie Ill, Even In Lilo, Even Ill Ion, Even Nil Oil, Even In Lilo, Even Ill Ion, Even Nil Oil, Even In Lilo, Even Ill Ion, Even Nil Oil, Lone Liven I, Lone Vie Nil, Lone Liven I, Lone Vie Nil, Linen Love I, Linen Vole I, Linen Olive, Linen Voile, Linen Love I, Linen Vole I, Linen Olive, Linen Voile, Lie Novel In, Lie Love Inn, Lie Vole Inn, Lie Nil Oven, Lie Novel In, Lie Love Inn, Lie Vole Inn, Lie Nil Oven, Lie Novel In, Lie Love Inn, Lie Vole Inn, Lie Nil Oven, Lien Love In, Lien Vole In, Line Love In, Line Vole In, Lien I Novel, Line I Novel, Lien Love In, Lien Vole In, Line Love In, Line Vole In, Lien I Novel, Line I Novel, Eel Inn Viol, Lee Inn Viol, Eel Nil Vino, Lee Nil Vino, Eel Inn Viol, Lee Inn Viol, Eel Nil Vino, Lee Nil Vino, Nee Ill Vino, Nee Nil Viol, Nee Ill Vino, Nee Nil Viol, Liven In Ole, Lino Nil Eve, Lion Nil Eve, Loin Nil Eve, Lilo Eve Inn, In Level Ion, Eon Villein, One Villein, Oil Enliven]", results.toString());
}
/**
* Test that each word in the output is capitalised.
*/
public void testAnswerWordsAreCapitalised() throws Exception {
Anagrammer it = new Anagrammer();
ArrayList<String> results;
results = it.run(new String[]{"cat", "the"});
for (String line : results) {
for (String word : line.split(" ")) {
assertTrue(word.charAt(0)>64 && word.charAt(0)<91);
}
}
assertEquals("[Etch At, Tech At, He Tact, The Act, The Cat]", results.toString());
}
}
|
package com.ecyrd.jspwiki.plugin;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.parser.Heading;
import com.ecyrd.jspwiki.parser.HeadingListener;
import com.ecyrd.jspwiki.parser.JSPWikiMarkupParser;
import java.util.*;
import java.io.StringReader;
import java.io.IOException;
/**
* Provides a table of contents.
*
* @since 2.2
* @author Janne Jalkanen
*/
public class TableOfContents
implements WikiPlugin, HeadingListener
{
private static Logger log = Logger.getLogger( TableOfContents.class );
public static final String PARAM_TITLE = "title";
public static final String PARAM_NUMBERED = "numbered";
public static final String PARAM_START = "start";
public static final String PARAM_PREFIX = "prefix";
private static final String VAR_ALREADY_PROCESSING = "__TableOfContents.processing";
StringBuffer m_buf = new StringBuffer();
private boolean m_usingNumberedList = false;
private String m_prefix = "";
private int m_starting = 0;
private int m_level1Index = 0;
private int m_level2Index = 0;
private int m_level3Index = 0;
private int m_lastLevel = 0;
public void headingAdded( WikiContext context, Heading hd )
{
log.debug("HD: "+hd.m_level+", "+hd.m_titleText+", "+hd.m_titleAnchor);
switch( hd.m_level )
{
case Heading.HEADING_SMALL:
m_buf.append("<li class=\"toclevel-3\">");
m_level3Index++;
break;
case Heading.HEADING_MEDIUM:
m_buf.append("<li class=\"toclevel-2\">");
m_level2Index++;
break;
case Heading.HEADING_LARGE:
m_buf.append("<li class=\"toclevel-1\">");
m_level1Index++;
break;
default:
throw new InternalWikiException("Unknown depth in toc! (Please submit a bug report.)");
}
if (m_level1Index < m_starting)
{
// in case we never had a large heading ...
m_level1Index++;
}
if ((m_lastLevel == Heading.HEADING_SMALL) && (hd.m_level != Heading.HEADING_SMALL))
{
m_level3Index = 0;
}
if ( ((m_lastLevel == Heading.HEADING_SMALL) || (m_lastLevel == Heading.HEADING_MEDIUM)) &&
(hd.m_level == Heading.HEADING_LARGE) )
{
m_level3Index = 0;
m_level2Index = 0;
}
String titleSection = hd.m_titleSection.replace( '%', '_' );
String url = context.getURL( WikiContext.VIEW, context.getPage().getName() );
String sectref = "#section-"+context.getEngine().encodeName(context.getPage().getName())+"-"+titleSection;
m_buf.append( "<a class=\"wikipage\" href=\""+url+sectref+"\">");
if (m_usingNumberedList)
{
switch( hd.m_level )
{
case Heading.HEADING_SMALL:
m_buf.append(m_prefix + m_level1Index + "." + m_level2Index + "."+ m_level3Index +" ");
break;
case Heading.HEADING_MEDIUM:
m_buf.append(m_prefix + m_level1Index + "." + m_level2Index + " ");
break;
case Heading.HEADING_LARGE:
m_buf.append(m_prefix + m_level1Index +" ");
break;
default:
throw new InternalWikiException("Unknown depth in toc! (Please submit a bug report.)");
}
}
m_buf.append( hd.m_titleText+"</a></li>\n" );
m_lastLevel = hd.m_level;
}
public String execute( WikiContext context, Map params )
throws PluginException
{
WikiEngine engine = context.getEngine();
WikiPage page = context.getPage();
if( context.getVariable( VAR_ALREADY_PROCESSING ) != null )
return "Table of Contents";
StringBuffer sb = new StringBuffer();
sb.append("<div class=\"toc\">\n");
sb.append("<div class=\"collapsebox\">\n");
String title = (String) params.get(PARAM_TITLE);
if( title != null )
{
sb.append("<h4>"+TextUtil.replaceEntities(title)+"</h4>\n");
}
else
{
sb.append("<h4>Table of Contents</h4>\n");
}
// should we use an ordered list?
m_usingNumberedList = false;
if (params.containsKey(PARAM_NUMBERED))
{
String numbered = (String)params.get(PARAM_NUMBERED);
if (numbered.equalsIgnoreCase("true"))
{
m_usingNumberedList = true;
}
else if (numbered.equalsIgnoreCase("yes"))
{
m_usingNumberedList = true;
}
}
// if we are using a numbered list, get the rest of the parameters (if any) ...
if (m_usingNumberedList)
{
int start = 0;
String startStr = (String)params.get(PARAM_START);
if ((startStr != null) && (startStr.matches("^\\d+$")))
{
start = Integer.parseInt(startStr);
}
if (start < 0) start = 0;
m_starting = start;
m_level1Index = start - 1;
if (m_level1Index < 0) m_level1Index = 0;
m_level2Index = 0;
m_level3Index = 0;
m_prefix = (String)params.get(PARAM_PREFIX);
if (m_prefix == null) m_prefix = "";
m_lastLevel = Heading.HEADING_LARGE;
}
try
{
String wikiText = engine.getPureText( page );
context.setVariable( VAR_ALREADY_PROCESSING, "x" );
JSPWikiMarkupParser parser = new JSPWikiMarkupParser( context,
new StringReader(wikiText) );
parser.addHeadingListener( this );
parser.parse();
sb.append( "<ul>\n"+m_buf.toString()+"</ul>\n" );
}
catch( IOException e )
{
log.error("Could not construct table of contents", e);
throw new PluginException("Unable to construct table of contents (see logs)");
}
sb.append("</div>\n</div>\n");
return sb.toString();
}
}
|
package com.levelup.java.array;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.google.common.collect.ObjectArrays;
public class InitializeArray {
@Test
public void initalize_int_array_java () {
// declares an array of integers
int[] nflNorthStadiumsCapacity;
// allocates memory for 4 integers
nflNorthStadiumsCapacity = new int[4];
// initialize elements
nflNorthStadiumsCapacity[0] = 80750;
nflNorthStadiumsCapacity[1] = 61500;
nflNorthStadiumsCapacity[2] = 64121;
nflNorthStadiumsCapacity[3] = 65000;
assertTrue(nflNorthStadiumsCapacity.length == 4);
}
@Test
public void initalize_int_array_java_shortcut () {
int[] nflNorthStadiumsCapacity = {
80750, 61500,
64121, 65000};
assertTrue(nflNorthStadiumsCapacity.length == 4);
}
@Test
public void initialize_string_array_java () {
// declares an array of strings
String[] nflNorthStadiums;
// allocates memory for 4 strings
nflNorthStadiums = new String[4];
// initialize elements
nflNorthStadiums[0] = "Lambeau Field";
nflNorthStadiums[1] = "Soldier Field";
nflNorthStadiums[2] = "Mall of America Fielddagger";
nflNorthStadiums[3] = "Ford Fielddagger";
assertTrue(nflNorthStadiums.length == 4);
}
@Test
public void initialize_string_array_java_shortcut () {
// declares an array of strings
String[] nflNorthStadiums = {
"Lambeau Field",
"Soldier Field",
"Mall of America Fielddagger",
"Ford Fielddagger"};
assertTrue(nflNorthStadiums.length == 4);
}
@Test
public void initialize_string_array_java_with_guava () {
String[] nflNorthStadiums = ObjectArrays.newArray(String.class, 4);
nflNorthStadiums[0] = "Lambeau Field";
nflNorthStadiums[1] = "Soldier Field";
nflNorthStadiums[2] = "Mall of America Fielddagger";
nflNorthStadiums[3] = "Ford Fielddagger";
assertTrue(nflNorthStadiums.length == 4);
}
@Test
public void initialize_string_array_java_with_guava_reference_type () {
String[] nflStadiums = {""};
String[] nflNorthStadiums = ObjectArrays.newArray(nflStadiums, 10);
nflNorthStadiums[0] = "Lambeau Field";
nflNorthStadiums[1] = "Soldier Field";
nflNorthStadiums[2] = "Mall of America Fielddagger";
nflNorthStadiums[3] = "Ford Fielddagger";
assertTrue(nflNorthStadiums.length == 4);
}
}
|
package com.implix.jsonrpc;
import android.os.Build;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonHttpUrlConnection implements JsonConnection {
JsonRpcImplementation rpc;
int reconnections = 3;
int connectTimeout = 15000;
int methodTimeout = 10000;
public JsonHttpUrlConnection(JsonRpcImplementation rpc) {
this.rpc = rpc;
disableConnectionReuseIfNecessary();
}
private void disableConnectionReuseIfNecessary() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
@Override
public HttpURLConnection get(String url, String request, int timeout, JsonTimeStat timeStat) throws Exception {
HttpURLConnection urlConnection = null;
for (int i = 1; i <= reconnections; i++) {
try {
urlConnection = (HttpURLConnection) new URL(url + request).openConnection();
break;
} catch (IOException e) {
if (i == reconnections) {
throw e;
}
}
}
if (rpc.getAuthKey() != null) {
urlConnection.addRequestProperty("Authorization", rpc.getAuthKey());
}
urlConnection.setConnectTimeout(connectTimeout);
if (timeout == 0) {
timeout = methodTimeout;
}
urlConnection.setReadTimeout(timeout);
timeStat.setTimeout(timeout);
if ((rpc.getDebugFlags() & JsonRpc.REQUEST_DEBUG) > 0) {
JsonLoggerImpl.longLog("REQ(GET)", request);
}
urlConnection.getInputStream();
timeStat.tickConnectionTime();
return urlConnection;
}
@Override
public HttpURLConnection post(String url, Object request, int timeout,JsonTimeStat timeStat) throws Exception {
HttpURLConnection urlConnection = null;
for (int i = 1; i <= reconnections; i++) {
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
break;
} catch (IOException e) {
if (i == reconnections) {
throw e;
}
}
}
urlConnection.addRequestProperty("Content-Type", "application/json");
if (rpc.getAuthKey() != null) {
urlConnection.addRequestProperty("Authorization", rpc.getAuthKey());
}
urlConnection.setConnectTimeout(connectTimeout);
if (timeout == 0) {
timeout = methodTimeout;
}
timeStat.setTimeout(timeout);
urlConnection.setReadTimeout(timeout);
urlConnection.setDoOutput(true);
if ((rpc.getDebugFlags() & JsonRpc.REQUEST_DEBUG) > 0) {
String req = rpc.getParser().toJson(request);
JsonLoggerImpl.longLog("REQ", req);
OutputStream stream = urlConnection.getOutputStream();
timeStat.tickConnectionTime();
Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
writer.write(req);
writer.close();
} else {
OutputStream stream = urlConnection.getOutputStream();
timeStat.tickConnectionTime();
Writer writer = new BufferedWriter(new OutputStreamWriter(stream));
rpc.getParser().toJson(request, writer);
writer.close();
}
timeStat.tickSendTime();
return urlConnection;
}
@Override
public void setMaxConnections(int max) {
System.setProperty("http.maxConnections", max + "");
}
public void setReconnections(int reconnections) {
this.reconnections = reconnections;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getMethodTimeout() {
return methodTimeout;
}
public void setMethodTimeout(int methodTimeout) {
this.methodTimeout = methodTimeout;
}
}
|
package com.interview.multiarray;
public class MatrixOf0sAnd1s {
public char[][] create(int n,int m){
char[][] matrix = new char[n][m];
int r = 0;
char ch = 'X';
int high = Math.min(n, m);
//high is min of n and m. If high is odd then high is ceiling of high/2
//else high is high/2. e.g high is 5 then high becomes 3 if high is 4
//high becomes 2
high = (int)Math.ceil(high*1.0/2);
while(r < high){
for(int i=r; i < m-r ; i++){
matrix[r][i] = ch;
}
for(int i = r; i < n-r; i++ ){
matrix[i][m-r-1] = ch;
}
for(int i = m-r-1; i >= r; i
matrix[n-r-1][i] = ch;
}
for(int i = n-r-1; i >= r; i
matrix[i][r] = ch;
}
if(ch =='X'){
ch = 'O';
}else{
ch = 'X';
}
r++;
}
return matrix;
}
public static void main(String args[]){
MatrixOf0sAnd1s mos = new MatrixOf0sAnd1s();
char matrix[][] = mos.create(4, 7);
for(int i=0; i < matrix.length; i++){
for(int j=0; j < matrix[i].length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
|
// OOO GWT Utils - utilities for creating GWT applications
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.gwt.util;
import org.junit.*;
import static org.junit.Assert.*;
/**
* Tests some additions made to {@link WikiParser}.
*/
public class WikiParserTest
{
@Test public void testBackTick ()
{
assertEquals("<p>This is <code>some code</code>.</p>\n",
WikiParser.render("This is `some code`."));
assertEquals("<p>This is <code>some == code</code>.</p>\n",
WikiParser.render("This is `some == code`."));
assertEquals("<p>This is <code>some ** code **</code>.</p>\n",
WikiParser.render("This is `some ** code **`."));
}
@Test public void testStrikeThrough ()
{
assertEquals("<p>This is <strike>struck out</strike>.</p>\n",
WikiParser.render("This is --struck out
assertEquals("<strike>nothing but struck out</strike>",
WikiParser.renderSnippet("--nothing but struck out
assertEquals("--oops, forgot the closing delimiter",
WikiParser.renderSnippet("--oops, forgot the closing delimiter"));
// make sure we didn't break <hr>s
assertEquals("\n<hr/>\n", WikiParser.render("
}
@Test public void testRenderSnippet ()
{
assertEquals("This is <code>some code</code>.",
WikiParser.renderSnippet("This is `some code`."));
assertEquals("This is <strong>bold text</strong>.",
WikiParser.renderSnippet("This is **bold text**."));
assertEquals("This is <em>italic text</em>. And some <code>monkeys</code>.",
WikiParser.renderSnippet("This is //italic text//. And some `monkeys`."));
}
@Test public void testFloat ()
{
assertEquals("<div style=\"float: left; margin-right: 5px\">left floating text</div>",
WikiParser.render("<<< left floating text"));
assertEquals("<div style=\"float: right; margin-left: 5px\">right floating text</div>",
WikiParser.render(">>> right floating text"));
}
@Test public void testEmdash ()
{
// make sure we don't erroneously identify an mdash as a strikethrough
assertEquals("This is some code with an — in it.",
WikiParser.renderSnippet("This is some code with an -- in it."));
assertEquals("<p>This is some code with an — in it.</p>\n",
WikiParser.render("This is some code with an -- in it."));
}
}
|
package com.interview.number;
import com.interview.array.ArrayAddition;
public class ArrayMultiplication {
public int[] multiplyDivideAndConquer(int arr1[],int arr2[],int low1,int high1,int low2,int high2){
if(low1 == high1 || low2 == high2){
return simpleMultiplication(arr1, arr2, low1, high1, low2, high2);
}
int mid1 = (low1 + high1)/2;
int mid2 = (low2 + high2)/2;
int r1[] = multiplyDivideAndConquer(arr1,arr2,low1,mid1,low2,mid2);
int shiftBy = high1-mid1 + high2-mid2;
r1 = shift(r1,shiftBy);
int r2[] = multiplyDivideAndConquer(arr1,arr2,mid1+1,high1,mid2+1,high2);
int r3[] = multiplyDivideAndConquer(arr1,arr2,low1,mid1,mid2+1,high2);
shiftBy = high1 - mid1;
r3 = shift(r3,shiftBy);
int r4[] = multiplyDivideAndConquer(arr1,arr2,mid1+1,high1,low2,mid2);
shiftBy = high2 - mid2;
r4 = shift(r4,shiftBy);
ArrayAddition aa = new ArrayAddition();
r1 = aa.add(r1, r2);
r1 = aa.add(r1, r3);
r1 = aa.add(r1, r4);
return r1;
}
private int[] shift(int arr[],int n){
int[] result = new int[arr.length + n];
int i=0;
for(i=0; i < arr.length; i++){
result[i] = arr[i];
}
return result;
}
public int[] simpleMultiplication(int arr1[],int arr2[],int low1,int high1,int low2,int high2){
int[] result = new int[high1-low1 + high2 -low2 + 2];
int m=0;
int c=0;
int n =0;
int index = result.length-1;
int temp[] = new int[Math.max(high1-low1+1, high2-low2+1)+1];
for(int i= high1; i >=low1; i
int l = temp.length-1;
for(int j=high2; j>=low2; j
m = arr1[i]*arr2[j] + c;
n = m%10;
temp[l
c = m/10;
}
temp[l] = c;
addToResult(result,temp,index);
index
c=0;
for(int t=0; t < temp.length; t++){
temp[t] = 0;
}
}
return result;
}
private void addToResult(int[] result,int temp[],int start){
int c=0;
for(int i=temp.length-1; i>=0 ; i
if(start == -1){
break;
}
int m = result[start] + temp[i] + c;
result[start--] = m%10;
c = m/10;
}
}
public int multiplicationImproved(int x, int y, int len){
if(len == 1){
return x*y;
}
len = len/2;
int div = power(len);
int result1 = multiplicationImproved(x/div,y/div,len);
int result2 = multiplicationImproved(x%div, y % div, len);
int result3 = multiplicationImproved(x/div + x%div,y/div + y % div,len);
return result1*div*(div -1) +
result3*div - result2*(div -1 );
}
private int power(int n){
return (int)Math.pow(10, n);
}
public static void main(String args[]){
int arr2[] = {9,9,7,4,7,9};
int arr1[] = {9,9,5,7,4,2,1};
ArrayMultiplication am = new ArrayMultiplication();
int result[] = am.multiplyDivideAndConquer(arr1, arr2, 0, arr1.length-1, 0, arr2.length-1);
for(int i=0; i < result.length; i++){
System.out.print(" " + result[i]);
}
System.out.print("\n" + am.multiplicationImproved(999, 168, 2));
}
}
|
package me.lemire.integercompression;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
import static me.lemire.integercompression.TestUtils.*;
/**
* Collection of adhoc tests.
*/
public class AdhocTest
{
@Test
public void biggerCompressedArray0() {
// No problem: for comparison.
IntegerCODEC c = new Composition(new FastPFOR(), new VariableByte());
assertSymmetry(c, 0, 16384);
}
@Test
public void biggerCompressedArray1() {
// Compressed array is bigger than original, because of VariableByte.
IntegerCODEC c = new VariableByte();
assertSymmetry(c, -1);
}
@Test
public void biggerCompressedArray2() {
// Compressed array is bigger than original, because of Composition.
IntegerCODEC c = new Composition(new FastPFOR(), new VariableByte());
assertSymmetry(c, 65535, 65535);
}
// NOTE: This require bigger 2 items for compressed array than original.
/*
@Test
public void overflowVariableByte() {
IntegerCODEC c = new VariableByte();
int[] d = new int[8];
Arrays.fill(d, -1);
assertSymmetry(c, d);
}
*/
}
|
package com.jbion.riseoflords.network;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import com.jbion.riseoflords.model.AccountState;
import com.jbion.riseoflords.model.Player;
import com.jbion.riseoflords.network.parsers.Parser;
public class RoLAdapter {
private static final String URL_INDEX = "http:
private static final String URL_GAME = "http:
private static final String PAGE_LOGIN = "verifpass";
private static final String PAGE_LOGOUT = "logout";
private static final String PAGE_USERS_LIST = "main/conseil_de_guerre";
private static final String PAGE_USER_DETAILS = "main/fiche";
private static final String PAGE_ATTACK = "main/combats";
private static final String PAGE_CHEST = "main/tresor";
private static final String PAGE_WEAPONS = "main/arsenal";
private static final String PAGE_SORCERY = "main/autel_sorciers";
public static final int ERROR_REQUEST = -1;
public static final int ERROR_STORM_ACTIVE = -2;
private final Random rand = new Random();
private final RequestSender http;
private final AccountState state;
public RoLAdapter() {
this.state = new AccountState();
http = new RequestSender();
}
private String randomCoord(int min, int max) {
return String.valueOf(rand.nextInt(max - min + 1) + min);
}
public AccountState getCurrentState() {
return state;
}
/**
* Performs the login request with the specified credentials. One needs to wait at least 5-6
* seconds to fake real login.
*
* @param username
* the username to use
* @param password
* the password to use
* @return true for successful login, false otherwise
*/
public boolean login(String username, String password) {
HttpPost postRequest = Request.from(URL_INDEX, PAGE_LOGIN)
.addPostData("LogPseudo", username)
.addPostData("LogPassword", password)
.post();
return http.execute(postRequest, r -> r.contains("Identification réussie!"));
}
/**
* Logs the current user out.
*
* @return true if the request succeeded, false otherwise
*/
public boolean logout() {
HttpGet getRequest = Request.from(URL_INDEX, PAGE_LOGOUT).get();
return http.execute(getRequest, r -> r.contains("Déjà inscrit? Connectez-vous"));
}
/**
* Returns a list of 99 users, starting at the specified rank.
*
* @param startRank
* the rank of the first user to return
* @return 99 users at most, starting at the specified rank.
*/
public List<Player> listPlayers(int startRank) {
Request builder = Request.from(URL_GAME, PAGE_USERS_LIST);
builder.addParameter("Debut", String.valueOf(startRank + 1));
if (rand.nextBoolean()) {
builder.addParameter("x", randomCoord(5, 35));
builder.addParameter("y", randomCoord(5, 25));
}
String response = http.execute(builder.get());
if (response.contains("Recherche pseudo:")) {
Parser.updateState(state, response);
return Parser.parsePlayerList(response);
} else {
return new ArrayList<>();
}
}
/**
* Displays the specified player's detail page. Used to fake a visit on the user detail page
* before an attack. The result does not matter.
*
* @param playerName
* the name of the player to lookup
* @return the specified player's current gold, or {@link #ERROR_REQUEST} if the request failed
*/
public int displayPlayer(String playerName) {
HttpGet request = Request.from(URL_GAME, PAGE_USER_DETAILS)
.addParameter("voirpseudo", playerName)
.get();
String response = http.execute(request);
if (response.contains("Seigneur " + playerName)) {
Parser.updateState(state, response);
return Parser.parsePlayerGold(response);
} else {
return ERROR_REQUEST;
}
}
/**
* Attacks the specified user with one game turn.
*
* @param username
* the name of the user to attack
* @return the gold stolen during the attack, or {@link #ERROR_REQUEST} if the request failed
*/
public int attack(String username) {
HttpPost request = Request.from(URL_GAME, PAGE_ATTACK)
.addParameter("a", "ok")
.addPostData("PseudoDefenseur", username)
.addPostData("NbToursToUse", "1")
.post();
String response = http.execute(request);
if (response.contains("remporte le combat!") || response.contains("perd cette bataille!")) {
Parser.updateState(state, response);
return Parser.parseGoldStolen(response);
} else if (response.contains("tempête magique s'abat")) {
Parser.updateState(state, response);
return ERROR_STORM_ACTIVE;
} else {
return ERROR_REQUEST;
}
}
/**
* Gets the chest page from the server, and returns the amount of money that could be stored in
* the chest.
*
* @return the amount of money that could be stored in the chest, which is the current amount of
* gold of the player, or {@link #ERROR_REQUEST} if the request failed
*/
public int displayChestPage() {
HttpGet request = Request.from(URL_GAME, PAGE_CHEST).get();
String response = http.execute(request);
if (response.contains("ArgentAPlacer")) {
Parser.updateState(state, response);
return state.gold;
} else {
return ERROR_REQUEST;
}
}
/**
* Stores the specified amount of gold into the chest. The amount has to match the current gold
* of the user, which should first be retrieved by calling {@link #displayChestPage()}.
*
* @param amount
* the amount of gold to store into the chest
* @return true if the request succeeded, false otherwise
*/
public boolean storeInChest(int amount) {
HttpPost request = Request.from(URL_GAME, PAGE_CHEST)
.addPostData("ArgentAPlacer", String.valueOf(amount))
.addPostData("x", randomCoord(10, 60))
.addPostData("y", randomCoord(10, 60))
.post();
String response = http.execute(request);
Parser.updateState(state, response);
return state.gold == 0;
}
/**
* Displays the weapons page. Used to fake a visit on the weapons page before repairing or
* buying weapons and equipment.
*
* @return the percentage of wornness of the weapons, or {@link #ERROR_REQUEST} if the request
* failed
*/
public int displayWeaponsPage() {
HttpGet request = Request.from(URL_GAME, PAGE_WEAPONS).get();
String response = http.execute(request);
if (response.contains("Faites votre choix")) {
return Parser.parseWeaponsWornness(response);
} else {
return ERROR_REQUEST;
}
}
/**
* Repairs weapons.
*
* @return true if the repair succeeded, false otherwise
*/
public boolean repairWeapons() {
HttpGet request = Request.from(URL_GAME, PAGE_WEAPONS)
.addParameter("a", "repair")
.addParameter("onglet", "")
.get();
String response = http.execute(request);
if (response.contains("Faites votre choix")) {
return Parser.parseWeaponsWornness(response) == 0;
} else {
return false;
}
}
/**
* Displays the sorcery page. Used to fake a visit on the sorcery page before casting a spell.
*
* @return the available mana, or {@link #ERROR_REQUEST} if the request failed
*/
public int displaySorceryPage() {
HttpUriRequest request = Request.from(URL_GAME, PAGE_SORCERY).get();
String response = http.execute(request);
if (response.contains("Niveau de vos sorciers")) {
return state.mana;
} else {
return ERROR_REQUEST;
}
}
/**
* Casts the dissipation spell to get rid of the protective aura. Useful before self-casting a
* storm.
*
* @return true if the request succeeded, false otherwise
*/
public boolean dissipateProtectiveAura() {
HttpGet request = Request.from(URL_GAME, PAGE_SORCERY)
.addParameter("a", "lancer")
.addParameter("idsort", "14")
.get();
String response = http.execute(request);
Parser.updateState(state, response);
return true; // TODO handle failure
}
/**
* Casts a magic storm on the specified player.
*
* @param playerName
* the amount of gold to store into the chest
* @return true if the request succeeded, false otherwise
*/
public boolean castMagicStorm(String playerName) {
HttpPost request = Request.from(URL_GAME, PAGE_SORCERY)
.addParameter("a", "lancer")
.addParameter("idsort", "5")
.addPostData("tempete_pseudo_cible", playerName)
.post();
String response = http.execute(request);
Parser.updateState(state, response);
return true; // TODO handle failure
}
}
|
package org.escalate42.javaz.option;
import org.junit.Test;
import static org.escalate42.javaz.option.OptionImpl.*;
import static org.junit.Assert.assertEquals;
public class OptionTest {
@Test
public void maybeTest() {
assertEquals(some("some string"), option("some string"));
assertEquals(none(), option(null));
}
@Test
public void maybeOrTest() {
final Option<String> first = none();
final Option<String> second = option("second");
assertEquals("second", first.or(second).orElse("third"));
}
@Test
public void maybeFMapTest() {
assertEquals(some("onetwo"), option("one").fmap(s -> s + "two"));
//noinspection AssertEqualsBetweenInconvertibleTypes
assertEquals(none(), option((String) null).fmap(s -> s + "two"));
}
@Test
public void maybeAMapTest() {
final OptionOps id = OptionOps.id;
assertEquals(some("onetwo"), option("one").amap(id.pure(s -> s + "two")));
}
@Test
public void maybeMMapTest() {
assertEquals(some("onetwo"), option("one").mmap(s -> some(s + "two")));
assertEquals(none(), option(null));
}
@Test
public void maybeOpsTest() {
final OptionOps id = OptionOps.id;
assertEquals(some("onetwo"), id.fmap(option("one"), s -> s + "two"));
assertEquals(some("onetwo"), id.amap(option("one"), id.pure(s -> s + "two")));
assertEquals(some("onetwo"), id.mmap(option("one"), s -> some(s + "two")));
}
@Test
public void yieldForTest() {
final Option<String> result = OptionOps.id.yieldFor(some("1"), some("2"), some("3"), (s1, s2, s3) -> s1 + s2 + s3);
assertEquals(some("123"), result);
}
}
|
package com.jcw.ListViewMenu;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class MenuListViewAdapter implements ListAdapter {
public static final int BOLD_FALG = Typeface.BOLD;
public static final int ITALIC_FLAG = Typeface.ITALIC;
public int MAIN_TEXT_STYLE_FLAGS = 0;
public int SUB_TEXT_STYLE_FLAGS = 0;
// To set the enabled color, you need to change the XML files... Sorry!
public int DISABLED_COLOR = Color.LTGRAY;
public int MAIN_TEXT_COLOR = Color.BLACK;
public int SUB_TEXT_COLOR = Color.BLACK;
public int LINE_SEPARATOR_COLOR = Color.WHITE;
public int BACKGROUND_COLOR = Color.WHITE;
public int MAIN_TEXT_SIZE = 21;
public int SUB_TEXT_SIZE = 12;
public int TEXT_PADDING = 12;
// This is set to -1 to imply that the height should be WRAP_CONTENT
// Note that this is used to set the minimum height rather than the
// absolute height.
public int ITEM_HEIGHT = -1;
Context context;
List<MenuListItem> items;
DataSetObserver dataSetObserver = null;
public MenuListViewAdapter(Context context) {
this.context = context;
items = new ArrayList<MenuListItem>();
}
@Override
public boolean areAllItemsEnabled() {
for (MenuListItem item : items) {
if (!item.enabled) {
return false;
}
}
return true;
}
public void itemClick(int index) {
MenuListItem item = items.get(index);
MenuItemClickListener thisListener = item.listener;
if (thisListener != null) {
thisListener.onClick(item.getText(), item.getSubheader(), item instanceof MenuListFolder);
}
if (item instanceof MenuListFolder) {
MenuListFolder folder = (MenuListFolder) item;
folder.isOpen = !folder.isOpen;
if (folder.isOpen) {
items.addAll(index + 1, folder.subitems);
} else {
removeFolder(index);
}
if (dataSetObserver != null)
dataSetObserver.onInvalidated();
}
}
public void addAll(Collection<MenuListItem> items) {
items.addAll(items);
}
public boolean remove(MenuListItem item) {
return items.remove(item);
}
/*
* This recursively remvoes all sub-folders
* along with the main folder from the list.
*/
private void removeFolder(int index) {
MenuListFolder folder = (MenuListFolder) items.get(index);
for (int i = 0; i < folder.subitems.size(); i ++) {
MenuListItem item = folder.subitems.get(i);
if (item instanceof MenuListFolder) {
removeFolder(index + i + 1);
}
}
items.removeAll(folder.subitems);
}
@Override
public boolean isEnabled(int i) {
return items.get(i).enabled;
}
@Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
this.dataSetObserver = dataSetObserver;
}
@Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
dataSetObserver = null;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i) {
return items.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
MenuListItem data = items.get(i);
return getView(data, i);
}
public void invalidate() {
if (dataSetObserver != null) {
dataSetObserver.onInvalidated();
}
}
protected View getView(MenuListItem data, final int index) {
final LinearLayout container = new LinearLayout(context);
TextView mainText = new TextView(context);
TextView subtext = new TextView(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setPadding(15 * data.getIndentFactor() + TEXT_PADDING, 15, 15, 15);
if (data.enabled) {
container.setBackgroundResource(R.drawable.enabled_background);
} else {
container.setBackgroundColor(DISABLED_COLOR);
}
if (ITEM_HEIGHT > 0) {
container.setMinimumHeight(ITEM_HEIGHT);
}
styleTextView(MAIN_TEXT_STYLE_FLAGS, mainText);
mainText.setTextColor(MAIN_TEXT_COLOR);
mainText.setText(data.getText());
mainText.setTextSize(MAIN_TEXT_SIZE);
styleTextView(SUB_TEXT_STYLE_FLAGS, subtext);
subtext.setTextColor(SUB_TEXT_COLOR);
subtext.setText(data.getSubheader());
subtext.setTextSize(SUB_TEXT_SIZE);
container.addView(mainText);
if (data.hasSubheader()) {
// To preserve the position of the main text in the center,
// only add this if it actually has text.
container.addView(subtext);
}
LinearLayout mainContainer = new LinearLayout(context);
mainContainer.setOrientation(LinearLayout.VERTICAL);
mainContainer.addView(container);
mainContainer.addView(getListSeparator());
return mainContainer;
}
/*
* this parses the style flags and applies them to the text view
*/
private void styleTextView(int flags, TextView text) {
text.setTypeface(null, flags);
}
/*
* This returns a separator that is basically the same as a separator
* on an Android list view.
*/
public View getListSeparator() {
View separator = new View(context);
separator.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 3
));
separator.setBackgroundColor(LINE_SEPARATOR_COLOR);
return separator;
}
public void addItem(MenuListItem item) {
this.items.add(item);
if (dataSetObserver != null) {
dataSetObserver.onChanged();
}
}
@Override
public int getItemViewType(int i) {
return 0;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean isEmpty() {
return items.isEmpty();
}
}
|
package org.jgum.strategy;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.or.ObjectRenderer;
import org.jgum.JGum;
import org.jgum.category.type.TypeCategory;
import org.jgum.testutil.animalhierarchy.Animal;
import org.jgum.testutil.animalhierarchy.AnimalRenderer;
import org.jgum.testutil.animalhierarchy.Cat;
import org.jgum.testutil.animalhierarchy.HasLegs;
import org.jgum.testutil.animalhierarchy.HasLegsRenderer;
import org.junit.Test;
public class StrategyTutorialTest {
class DelegationAnimalRenderer implements ObjectRenderer {
@Override
public String doRender(Object animal) {
throw new NoMyResponsibilityException();
}
}
@Test
public void noDelegationTest() {
JGum jgum = new JGum();
//instantiating categories
TypeCategory<Animal> animalCategory = jgum.forClass(Animal.class); //type category for Animal
TypeCategory<HasLegs> hasLegsCategory = jgum.forClass(HasLegs.class); //type category for HasLegs
TypeCategory<Cat> catCategory = jgum.forClass(Cat.class); //type category for Cat
//setting properties
animalCategory.setProperty(ObjectRenderer.class, new AnimalRenderer()); //ObjectRenderer property is an instance of AnimalRenderer for Animal
hasLegsCategory.setProperty(ObjectRenderer.class, new HasLegsRenderer()); //ObjectRenderer property is an instance of HasLegsRenderer for HasLegs
//testing
ObjectRenderer renderer = catCategory.getStrategy(ObjectRenderer.class);
assertEquals("animal", renderer.doRender(new Cat()));
}
@Test
public void delegationTest() {
JGum jgum = new JGum();
//instantiating categories
TypeCategory<Animal> animalCategory = jgum.forClass(Animal.class); //type category for Animal
TypeCategory<HasLegs> hasLegsCategory = jgum.forClass(HasLegs.class); //type category for HasLegs
TypeCategory<Cat> catCategory = jgum.forClass(Cat.class); //type category for Cat
//setting properties
animalCategory.setProperty(ObjectRenderer.class, new DelegationAnimalRenderer()); //ObjectRenderer property is an instance of DelegationAnimalRenderer for Animal
hasLegsCategory.setProperty(ObjectRenderer.class, new HasLegsRenderer()); //ObjectRenderer property is an instance of HasLegsRenderer for HasLegs
//testing
ObjectRenderer renderer = catCategory.getStrategy(ObjectRenderer.class);
assertEquals("has-legs", renderer.doRender(new Cat()));
}
}
|
package com.jcw.ListViewMenu;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class MenuListViewAdapter implements ListAdapter {
public static final int BOLD_FALG = Typeface.BOLD;
public static final int ITALIC_FLAG = Typeface.ITALIC;
public int MAIN_TEXT_STYLE_FLAGS = 0;
public int SUB_TEXT_STYLE_FLAGS = 0;
// To set the enabled color, you need to change the XML files... Sorry!
public int DISABLED_COLOR = Color.LTGRAY;
public int MAIN_TEXT_COLOR = Color.parseColor("#306060");
public int SUB_TEXT_COLOR = Color.parseColor("#787878");
public int LINE_SEPARATOR_COLOR;
public int BACKGROUND_COLOR;
public int MAIN_TEXT_SIZE = 18;
public int SUB_TEXT_SIZE = 12;
public int TEXT_PADDING;
// This can be set to -1 to imply that the height should be WRAP_CONTENT
// Note that this is used to set the minimum height rather than the
// absolute height.
public int ITEM_HEIGHT;
Context context;
List<MenuListItem> items;
DataSetObserver dataSetObserver = null;
public MenuListViewAdapter(Context context) {
this.context = context;
items = new ArrayList<MenuListItem>();
BACKGROUND_COLOR = context.getResources().getColor(R.color.defaultBackground);
LINE_SEPARATOR_COLOR = context.getResources().getColor(R.color.defaultBackground);
TEXT_PADDING = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, context.getResources().getDisplayMetrics());
ITEM_HEIGHT = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, context.getResources().getDisplayMetrics());
}
@Override
public boolean areAllItemsEnabled() {
for (MenuListItem item : items) {
if (!item.enabled) {
return false;
}
}
return true;
}
public void itemClick(int index) {
MenuListItem item = items.get(index);
if (!item.clickable) {
return;
}
MenuItemClickListener thisListener = item.listener;
if (thisListener != null) {
thisListener.onClick(item.getText(), item.getSubheader(), item instanceof MenuListFolder);
}
if (item instanceof MenuListFolder) {
MenuListFolder folder = (MenuListFolder) item;
folder.isOpen = !folder.isOpen;
if (folder.isOpen) {
items.addAll(index + 1, folder.subitems);
} else {
removeFolder(index);
}
if (dataSetObserver != null)
dataSetObserver.onInvalidated();
}
}
public void addAll(Collection<MenuListItem> items) {
items.addAll(items);
}
public boolean remove(MenuListItem item) {
return items.remove(item);
}
/*
* This recursively remvoes all sub-folders
* along with the main folder from the list.
*/
private void removeFolder(int index) {
MenuListFolder folder = (MenuListFolder) items.get(index);
for (int i = 0; i < folder.subitems.size(); i ++) {
MenuListItem item = folder.subitems.get(i);
if (item instanceof MenuListFolder) {
removeFolder(index + i + 1);
}
}
items.removeAll(folder.subitems);
}
@Override
public boolean isEnabled(int i) {
return items.get(i).enabled;
}
@Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
this.dataSetObserver = dataSetObserver;
}
@Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
dataSetObserver = null;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i) {
return items.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
MenuListItem data = items.get(i);
return getView(data, i);
}
public void invalidate() {
if (dataSetObserver != null) {
dataSetObserver.onInvalidated();
}
}
protected View getView(MenuListItem data, final int index) {
final LinearLayout container = new LinearLayout(context);
TextView mainText = new TextView(context);
TextView subtext = new TextView(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setPadding(15 * data.getIndentFactor() + TEXT_PADDING, 15, 15, 15);
if (data.enabled && data.clickable) {
container.setBackgroundResource(R.drawable.enabled_background);
} else if (!data.clickable) {
// In this case we want a background that doesn't change
// when it is clicked.
container.setBackgroundResource(R.drawable.normal);
} else {
container.setBackgroundColor(DISABLED_COLOR);
}
styleTextView(MAIN_TEXT_STYLE_FLAGS, mainText);
mainText.setTextColor(MAIN_TEXT_COLOR);
mainText.setText(data.getText());
mainText.setTextSize(TypedValue.COMPLEX_UNIT_SP, MAIN_TEXT_SIZE);
mainText.setEllipsize(TextUtils.TruncateAt.END);
mainText.setSingleLine();
styleTextView(SUB_TEXT_STYLE_FLAGS, subtext);
subtext.setTextColor(SUB_TEXT_COLOR);
subtext.setText(data.getSubheader());
subtext.setTextSize(TypedValue.COMPLEX_UNIT_SP, SUB_TEXT_SIZE);
subtext.setEllipsize(TextUtils.TruncateAt.END);
subtext.setSingleLine();
container.addView(mainText);
if (data.hasSubheader()) {
// To preserve the position of the main text in the center,
// only add this if it actually has text.
container.addView(subtext);
}
LinearLayout mainContainer = new LinearLayout(context);
mainContainer.setOrientation(LinearLayout.VERTICAL);
mainContainer.addView(container);
mainContainer.addView(getListSeparator());
// Now that the container has layout params attached to it,
// the height can be set. If the ITEM_HEIGHT was -1, leave
// the container as WRAP_CONTENT.
if (ITEM_HEIGHT > 0) {
container.getLayoutParams().height = ITEM_HEIGHT;
// We also need to update the padding on the top and bottom to 0
// to stop wasting any space.
container.setPadding(container.getPaddingLeft(), 0, 0, 0);
}
return mainContainer;
}
/*
* this parses the style flags and applies them to the text view
*/
private void styleTextView(int flags, TextView text) {
text.setTypeface(null, flags);
}
/*
* This returns a separator that is basically the same as a separator
* on an Android list view.
*/
public View getListSeparator() {
View separator = new View(context);
separator.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 3
));
separator.setBackgroundColor(LINE_SEPARATOR_COLOR);
return separator;
}
public void addItem(MenuListItem item) {
this.items.add(item);
if (dataSetObserver != null) {
dataSetObserver.onChanged();
}
}
@Override
public int getItemViewType(int i) {
return 0;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean isEmpty() {
return items.isEmpty();
}
}
|
package org.myrobotlab.client;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.myrobotlab.service.Runtime;
import org.junit.Test;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.lang.NameGenerator;
import org.myrobotlab.test.AbstractTest;
public class InProcessCliTest extends AbstractTest {
static PipedOutputStream pipe = null;
static PipedInputStream in = null;
static ByteArrayOutputStream bos = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
pipe = new PipedOutputStream();
in = new PipedInputStream(pipe);
bos = new ByteArrayOutputStream();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
public void write(String str) throws IOException {
pipe.write((str + "\n").getBytes());
// must read it off and process the data
sleep(300);
}
public void clear() {
bos.reset();
}
public String getResponse() {
String ret = new String(bos.toByteArray());
log.info("cd => {}", ret);
// clear();
return ret;
}
public String toJson(Object o) {
return CodecUtils.toPrettyJson(o);
}
@Test
public void testProcess() throws IOException {
InProcessCli cli = new InProcessCli(NameGenerator.getName(), "runtime", in, bos);
cli.start();
clear();
write("pwd");
String ret = getResponse();
assertEquals("/", ret);
clear();
write("ls");
assertEquals(toJson(Runtime.getServiceNames()), getResponse());
clear();
write("route");
assertEquals(toJson(Runtime.route()), getResponse());
// cd to different directory with and without /
// try a bunch of service commands
}
}
|
package com.jwetherell.algorithms;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Formatter;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import com.jwetherell.algorithms.data_structures.AVLTree;
import com.jwetherell.algorithms.data_structures.BTree;
import com.jwetherell.algorithms.data_structures.BinarySearchTree;
import com.jwetherell.algorithms.data_structures.BinaryHeap;
import com.jwetherell.algorithms.data_structures.CompactSuffixTrie;
import com.jwetherell.algorithms.data_structures.Graph.Edge;
import com.jwetherell.algorithms.data_structures.Graph.Vertex;
import com.jwetherell.algorithms.data_structures.Graph;
import com.jwetherell.algorithms.data_structures.HashMap;
import com.jwetherell.algorithms.data_structures.IntervalTree;
import com.jwetherell.algorithms.data_structures.KdTree;
import com.jwetherell.algorithms.data_structures.PatriciaTrie;
import com.jwetherell.algorithms.data_structures.QuadTree;
import com.jwetherell.algorithms.data_structures.RadixTrie;
import com.jwetherell.algorithms.data_structures.RedBlackTree;
import com.jwetherell.algorithms.data_structures.SegmentTree;
import com.jwetherell.algorithms.data_structures.SegmentTree.DynamicSegmentTree;
import com.jwetherell.algorithms.data_structures.SegmentTree.FlatSegmentTree;
import com.jwetherell.algorithms.data_structures.SuffixTree;
import com.jwetherell.algorithms.data_structures.TreeMap;
import com.jwetherell.algorithms.data_structures.TrieMap;
import com.jwetherell.algorithms.data_structures.List;
import com.jwetherell.algorithms.data_structures.Matrix;
import com.jwetherell.algorithms.data_structures.Queue;
import com.jwetherell.algorithms.data_structures.SkipList;
import com.jwetherell.algorithms.data_structures.SplayTree;
import com.jwetherell.algorithms.data_structures.Stack;
import com.jwetherell.algorithms.data_structures.SuffixTrie;
import com.jwetherell.algorithms.data_structures.Treap;
import com.jwetherell.algorithms.data_structures.Trie;
import com.jwetherell.algorithms.graph.BellmanFord;
import com.jwetherell.algorithms.graph.CycleDetection;
import com.jwetherell.algorithms.graph.Dijkstra;
import com.jwetherell.algorithms.graph.FloydWarshall;
import com.jwetherell.algorithms.graph.Johnson;
import com.jwetherell.algorithms.graph.Prim;
import com.jwetherell.algorithms.graph.TopologicalSort;
public class DataStructures {
private static final int NUMBER_OF_TESTS = 1;
private static final Random RANDOM = new Random();
private static final int ARRAY_SIZE = 100000;
private static final int RANDOM_SIZE = 1000 * ARRAY_SIZE;
private static final Integer INVALID = RANDOM_SIZE + 10;
private static final DecimalFormat FORMAT = new DecimalFormat("0.
private static Integer[] unsorted = null;
private static Integer[] sorted = null;
private static String string = null;
private static int debug = 1; // Debug level. 0=None, 1=Time and Memory (if
// enabled), 2=Time, Memory, data structure
// debug
private static boolean debugTime = true; // How much time to: add all,
// remove all, add all items in
// reverse order, remove all
private static boolean debugMemory = true; // How much memory is used by the
// data structure
private static boolean validateStructure = false; // Is the data structure
// valid (passed
// invariants) and proper
// size
private static boolean validateContents = false; // Was the item
// added/removed really
// added/removed from the
// structure
private static final int TESTS = 33; // Max number of dynamic data
// structures to test
private static final String[] testNames = new String[TESTS]; // Array to
// hold the
// test names
private static final long[][] testResults = new long[TESTS][]; // Array to
// hold the
// test
// results
private static int testIndex = 0; // Index into the tests
private static int testNumber = 0; // Number of aggregate tests which have
// been run
public static void main(String[] args) {
System.out.println("Starting tests.");
boolean passed = true;
for (int i = 0; i < NUMBER_OF_TESTS; i++) {
passed = runTests();
if (!passed)
break;
}
if (passed)
System.out.println("Tests finished. All passed.");
else
System.err.println("Tests finished. Detected a failure.");
}
private static boolean runTests() {
testIndex = 0;
testNumber++;
System.out.println("Generating data.");
StringBuilder builder = new StringBuilder();
builder.append("Array=");
unsorted = new Integer[ARRAY_SIZE];
java.util.Set<Integer> set = new java.util.HashSet<Integer>();
for (int i = 0; i < ARRAY_SIZE; i++) {
Integer j = RANDOM.nextInt(RANDOM_SIZE);
// Make sure there are no duplicates
boolean found = true;
while (found) {
if (set.contains(j)) {
j = RANDOM.nextInt(RANDOM_SIZE);
} else {
unsorted[i] = j;
set.add(j);
found = false;
}
}
unsorted[i] = j;
builder.append(j).append(',');
}
builder.append('\n');
string = builder.toString();
if (debug > 1)
System.out.println(string);
sorted = Arrays.copyOf(unsorted, unsorted.length);
Arrays.sort(sorted);
System.out.println("Generated data.");
boolean passed = true;
// MY DYNAMIC DATA STRUCTURES
passed = testAVLTree();
if (!passed) {
System.err.println("AVL Tree failed.");
return false;
}
passed = testBTree();
if (!passed) {
System.err.println("B-Tree failed.");
return false;
}
passed = testBST();
if (!passed) {
System.err.println("BST failed.");
return false;
}
passed = testHeap();
if (!passed) {
System.err.println("Heap failed.");
return false;
}
passed = testHashMap();
if (!passed) {
System.err.println("Hash Map failed.");
return false;
}
passed = testList();
if (!passed) {
System.err.println("List failed.");
return false;
}
passed = testPatriciaTrie();
if (!passed) {
System.err.println("Patricia Trie failed.");
return false;
}
passed = testQueue();
if (!passed) {
System.err.println("Queue failed.");
return false;
}
passed = testRadixTrie();
if (!passed) {
System.err.println("Radix Trie failed.");
return false;
}
passed = testRedBlackTree();
if (!passed) {
System.err.println("Red-Black Tree failed.");
return false;
}
passed = testSkipList();
if (!passed) {
System.err.println("Skip List failed.");
return false;
}
passed = testSplayTree();
if (!passed) {
System.err.println("Splay Tree failed.");
return false;
}
passed = testStack();
if (!passed) {
System.err.println("Stack failed.");
return false;
}
passed = testTreap();
if (!passed) {
System.err.println("Treap failed.");
return false;
}
passed = testTreeMap();
if (!passed) {
System.err.println("Tree Map failed.");
return false;
}
passed = testTrie();
if (!passed) {
System.err.println("Trie failed.");
return false;
}
passed = testTrieMap();
if (!passed) {
System.err.println("Trie Map failed.");
return false;
}
// JAVA DATA STRUCTURES
passed = testJavaHeap();
if (!passed) {
System.err.println("Java Heap failed.");
return false;
}
passed = testJavaHashMap();
if (!passed) {
System.err.println("Java Hash Map failed.");
return false;
}
passed = testJavaList();
if (!passed) {
System.err.println("Java List failed.");
return false;
}
passed = testJavaQueue();
if (!passed) {
System.err.println("Java Queue failed.");
return false;
}
passed = testJavaRedBlackTree();
if (!passed) {
System.err.println("Java Red-Black failed.");
return false;
}
passed = testJavaStack();
if (!passed) {
System.err.println("Java Stack failed.");
return false;
}
passed = testJavaTreeMap();
if (!passed) {
System.err.println("Java Tree Map failed.");
return false;
}
if (debugTime && debugMemory) {
String results = getTestResults(testNumber, testNames, testResults);
System.out.println(results);
}
// MY STATIC DATA STRUCTURES
passed = testCompactSuffixTrie();
if (!passed) {
System.err.println("Compact Suffix Trie failed.");
return false;
}
passed = testGraph();
if (!passed) {
System.err.println("Graph failed.");
return false;
}
passed = testIntervalTree();
if (!passed) {
System.err.println("Interval Tree failed.");
return false;
}
passed = testKdTree();
if (!passed) {
System.err.println("k-d Tree Tree failed.");
return false;
}
passed = testMatrix();
if (!passed) {
System.err.println("Matrix failed.");
return false;
}
passed = testQuadTree();
if (!passed) {
System.err.println("QuadTree failed.");
return false;
}
passed = testSegmentTree();
if (!passed) {
System.err.println("Segment Tree failed.");
return false;
}
passed = testSuffixTree();
if (!passed) {
System.err.println("Suffix Tree failed.");
return false;
}
passed = testSuffixTrie();
if (!passed) {
System.err.println("Suffix Trie failed.");
return false;
}
return true;
}
private static void handleError(Object obj) {
System.err.println(string);
System.err.println(obj.toString());
}
private static boolean testAVLTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// AVL Tree
if (debug > 1)
System.out.println("AVL Tree");
testNames[testIndex] = "AVL Tree";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
AVLTree<Integer> tree = new AVLTree<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("AVL Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("AVL Tree memory use = " + (memory / count) + " bytes");
}
boolean contains = tree.contains(INVALID);
boolean removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("AVL Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("AVL Tree remove time = " + removeTime / count + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("AVL Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("AVL Tree memory use = " + (memory / count) + " bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("AVL Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("AVL Tree remove time = " + removeTime / count + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("AVL Tree add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("AVL Tree memory use = " + (memory / (count + 1)) + " bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("AVL Tree lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("AVL Tree remove time = " + removeSortedTime + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("AVL Tree invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testBTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// B-Tree
if (debug > 1)
System.out.println("B-Tree with node.");
testNames[testIndex] = "B-Tree";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
BTree<Integer> bTree = new BTree<Integer>(4); // 2-3-4 Tree
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
bTree.add(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && !bTree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("B-Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("B-Tree memory use = " + (memory / count) + " bytes");
}
boolean contains = bTree.contains(INVALID);
boolean removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(bTree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
boolean found = bTree.contains(item);
if (!found)
return false;
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("B-Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
bTree.remove(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && bTree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("B-Tree remove time = " + removeTime / count + " ms");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
bTree.add(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size() == sorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && !bTree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("B-Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("B-Tree memory use = " + (memory / count) + " bytes");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(bTree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
bTree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("B-Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
bTree.remove(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && bTree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("B-Tree remove time = " + removeTime / count + " ms");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
bTree.add(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && !bTree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("B-Tree add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("B-Tree memory use = " + (memory / (count + 1)) + " bytes");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(bTree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
bTree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("B-Tree lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
bTree.remove(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && bTree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("B-Tree remove time = " + removeSortedTime + " ms");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("B-Tree invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testBST() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// BINARY SEARCH TREE
if (debug > 1)
System.out.println("Binary search tree with node.");
testNames[testIndex] = "Binary Search Tree";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
BinarySearchTree<Integer> bst = new BinarySearchTree<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
bst.add(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && !bst.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("BST add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("BST memory use = " + (memory / count) + " bytes");
}
boolean contains = bst.contains(INVALID);
boolean removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("BST invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(bst.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
bst.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("BST lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
bst.remove(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && bst.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("BST remove time = " + removeTime / count + " ms");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("BST invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
bst.add(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size() == sorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && !bst.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("BST add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("BST memory use = " + (memory / count) + " bytes");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("BST invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(bst.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
bst.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("BST lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
bst.remove(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && bst.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("BST remove time = " + removeTime / count + " ms");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("BST invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
bst.add(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && !bst.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("BST add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("BST memory use = " + (memory / (count + 1)) + " bytes");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("BST invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(bst.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
bst.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("BST lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
bst.remove(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && bst.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("BST remove time = " + removeSortedTime + " ms");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("BST invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testCompactSuffixTrie() {
{
// Compact Suffix Trie
if (debug > 1)
System.out.println("Compact Suffix Trie.");
String bookkeeper = "bookkeeper";
CompactSuffixTrie<String> trie = new CompactSuffixTrie<String>(bookkeeper);
if (debug > 1)
System.out.println(trie.toString());
if (debug > 1)
System.out.println(trie.getSuffixes());
boolean exists = trie.doesSubStringExist(bookkeeper);
if (!exists) {
System.err.println("YIKES!! " + bookkeeper + " doesn't exists.");
handleError(trie);
return false;
}
String failed = "booker";
exists = trie.doesSubStringExist(failed);
if (exists) {
System.err.println("YIKES!! " + failed + " exists.");
handleError(trie);
return false;
}
String pass = "kkee";
exists = trie.doesSubStringExist(pass);
if (!exists) {
System.err.println("YIKES!! " + pass + " doesn't exists.");
handleError(trie);
return false;
}
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testGraph() {
{
// UNDIRECTED GRAPH
if (debug > 1)
System.out.println("Undirected Graph.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
Graph.Vertex<Integer> v5 = new Graph.Vertex<Integer>(5);
verticies.add(v5);
Graph.Vertex<Integer> v6 = new Graph.Vertex<Integer>(6);
verticies.add(v6);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_2 = new Graph.Edge<Integer>(7, v1, v2);
edges.add(e1_2);
Graph.Edge<Integer> e1_3 = new Graph.Edge<Integer>(9, v1, v3);
edges.add(e1_3);
Graph.Edge<Integer> e1_6 = new Graph.Edge<Integer>(14, v1, v6);
edges.add(e1_6);
Graph.Edge<Integer> e2_3 = new Graph.Edge<Integer>(10, v2, v3);
edges.add(e2_3);
Graph.Edge<Integer> e2_4 = new Graph.Edge<Integer>(15, v2, v4);
edges.add(e2_4);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(11, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e3_6 = new Graph.Edge<Integer>(2, v3, v6);
edges.add(e3_6);
Graph.Edge<Integer> e5_6 = new Graph.Edge<Integer>(9, v5, v6);
edges.add(e5_6);
Graph.Edge<Integer> e4_5 = new Graph.Edge<Integer>(6, v4, v5);
edges.add(e4_5);
Graph<Integer> undirected = new Graph<Integer>(verticies, edges);
if (debug > 1)
System.out.println(undirected.toString());
Graph.Vertex<Integer> start = v1;
if (debug > 1)
System.out.println("Dijstra's shortest paths of the undirected graph from " + start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map1 = Dijkstra.getShortestPaths(undirected, start);
if (debug > 1)
System.out.println(getPathMapString(start, map1));
Graph.Vertex<Integer> end = v5;
if (debug > 1)
System.out.println("Dijstra's shortest path of the undirected graph from " + start.getValue() + " to "
+ end.getValue());
Graph.CostPathPair<Integer> pair1 = Dijkstra.getShortestPath(undirected, start, end);
if (debug > 1) {
if (pair1 != null)
System.out.println(pair1.toString());
else
System.out.println("No path from " + start.getValue() + " to " + end.getValue());
}
start = v1;
if (debug > 1)
System.out.println("Bellman-Ford's shortest paths of the undirected graph from " + start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map2 = BellmanFord.getShortestPaths(undirected, start);
if (debug > 1)
System.out.println(getPathMapString(start, map2));
end = v5;
if (debug > 1)
System.out.println("Bellman-Ford's shortest path of the undirected graph from " + start.getValue() + " to " + end.getValue());
Graph.CostPathPair<Integer> pair2 = BellmanFord.getShortestPath(undirected, start, end);
if (debug > 1) {
if (pair2 != null)
System.out.println(pair2.toString());
else
System.out.println("No path from " + start.getValue() + " to " + end.getValue());
}
// MST
if (debug > 1)
System.out.println("Prim's minimum spanning tree of the undirected graph from " + start.getValue());
Graph.CostPathPair<Integer> pair = Prim.getMinimumSpanningTree(undirected, start);
if (debug > 1)
System.out.println(pair.toString());
// Prim on a graph with cycles
java.util.List<Vertex<Integer>> cyclicVerticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> cv1 = new Graph.Vertex<Integer>(1);
cyclicVerticies.add(cv1);
Graph.Vertex<Integer> cv2 = new Graph.Vertex<Integer>(2);
cyclicVerticies.add(cv2);
Graph.Vertex<Integer> cv3 = new Graph.Vertex<Integer>(3);
cyclicVerticies.add(cv3);
Graph.Vertex<Integer> cv4 = new Graph.Vertex<Integer>(4);
cyclicVerticies.add(cv4);
Graph.Vertex<Integer> cv5 = new Graph.Vertex<Integer>(5);
cyclicVerticies.add(cv5);
java.util.List<Edge<Integer>> cyclicEdges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> ce1_2 = new Graph.Edge<Integer>(3, cv1, cv2);
cyclicEdges.add(ce1_2);
Graph.Edge<Integer> ce2_3 = new Graph.Edge<Integer>(2, cv2, cv3);
cyclicEdges.add(ce2_3);
Graph.Edge<Integer> ce3_4 = new Graph.Edge<Integer>(4, cv3, cv4);
cyclicEdges.add(ce3_4);
Graph.Edge<Integer> ce4_1 = new Graph.Edge<Integer>(1, cv4, cv1);
cyclicEdges.add(ce4_1);
Graph.Edge<Integer> ce4_5 = new Graph.Edge<Integer>(1, cv4, cv5);
cyclicEdges.add(ce4_5);
Graph<Integer> cyclicUndirected = new Graph<Integer>(cyclicVerticies, cyclicEdges);
if (debug > 1)
System.out.println(cyclicUndirected.toString());
start = cv1;
if (debug > 1)
System.out.println("Prim's minimum spanning tree of a cyclic undirected graph from " + start.getValue());
Graph.CostPathPair<Integer> cyclicPair = Prim.getMinimumSpanningTree(cyclicUndirected, start);
if (debug > 1)
System.out.println(cyclicPair.toString());
if (debug > 1)
System.out.println();
}
{
// DIRECTED GRAPH
if (debug > 1)
System.out.println("Directed Graph.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
Graph.Vertex<Integer> v5 = new Graph.Vertex<Integer>(5);
verticies.add(v5);
Graph.Vertex<Integer> v6 = new Graph.Vertex<Integer>(6);
verticies.add(v6);
Graph.Vertex<Integer> v7 = new Graph.Vertex<Integer>(7);
verticies.add(v7);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_2 = new Graph.Edge<Integer>(7, v1, v2);
edges.add(e1_2);
Graph.Edge<Integer> e1_3 = new Graph.Edge<Integer>(9, v1, v3);
edges.add(e1_3);
Graph.Edge<Integer> e1_6 = new Graph.Edge<Integer>(14, v1, v6);
edges.add(e1_6);
Graph.Edge<Integer> e2_3 = new Graph.Edge<Integer>(10, v2, v3);
edges.add(e2_3);
Graph.Edge<Integer> e2_4 = new Graph.Edge<Integer>(15, v2, v4);
edges.add(e2_4);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(11, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e3_6 = new Graph.Edge<Integer>(2, v3, v6);
edges.add(e3_6);
Graph.Edge<Integer> e6_5 = new Graph.Edge<Integer>(9, v6, v5);
edges.add(e6_5);
Graph.Edge<Integer> e4_5 = new Graph.Edge<Integer>(6, v4, v5);
edges.add(e4_5);
Graph.Edge<Integer> e4_7 = new Graph.Edge<Integer>(16, v4, v7);
edges.add(e4_7);
Graph<Integer> directed = new Graph<Integer>(Graph.TYPE.DIRECTED, verticies, edges);
if (debug > 1)
System.out.println(directed.toString());
Graph.Vertex<Integer> start = v1;
if (debug > 1)
System.out.println("Dijstra's shortest paths of the directed graph from " + start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map = Dijkstra.getShortestPaths(directed, start);
if (debug > 1)
System.out.println(getPathMapString(start, map));
Graph.Vertex<Integer> end = v5;
if (debug > 1)
System.out.println("Dijstra's shortest path of the directed graph from " + start.getValue() + " to "
+ end.getValue());
Graph.CostPathPair<Integer> pair = Dijkstra.getShortestPath(directed, start, end);
if (debug > 1) {
if (pair != null)
System.out.println(pair.toString());
else
System.out.println("No path from " + start.getValue() + " to " + end.getValue());
}
start = v1;
if (debug > 1)
System.out.println("Bellman-Ford's shortest paths of the undirected graph from " + start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map2 = BellmanFord.getShortestPaths(directed, start);
if (debug > 1)
System.out.println(getPathMapString(start, map2));
end = v5;
if (debug > 1)
System.out.println("Bellman-Ford's shortest path of the undirected graph from " + start.getValue()
+ " to " + end.getValue());
Graph.CostPathPair<Integer> pair2 = BellmanFord.getShortestPath(directed, start, end);
if (debug > 1) {
if (pair2 != null)
System.out.println(pair2.toString());
else
System.out.println("No path from " + start.getValue() + " to " + end.getValue());
}
if (debug > 1)
System.out.println();
}
{
// DIRECTED GRAPH (WITH NEGATIVE WEIGHTS)
if (debug > 1)
System.out.println("Undirected Graph with Negative Weights.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_4 = new Graph.Edge<Integer>(2, v1, v4);
edges.add(e1_4);
Graph.Edge<Integer> e2_1 = new Graph.Edge<Integer>(6, v2, v1);
edges.add(e2_1);
Graph.Edge<Integer> e2_3 = new Graph.Edge<Integer>(3, v2, v3);
edges.add(e2_3);
Graph.Edge<Integer> e3_1 = new Graph.Edge<Integer>(4, v3, v1);
edges.add(e3_1);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(5, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e4_2 = new Graph.Edge<Integer>(-7, v4, v2);
edges.add(e4_2);
Graph.Edge<Integer> e4_3 = new Graph.Edge<Integer>(-3, v4, v3);
edges.add(e4_3);
Graph<Integer> directed = new Graph<Integer>(Graph.TYPE.DIRECTED, verticies, edges);
if (debug > 1)
System.out.println(directed.toString());
Graph.Vertex<Integer> start = v1;
if (debug > 1)
System.out.println("Bellman-Ford's shortest paths of the directed graph from " + start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map2 = BellmanFord
.getShortestPaths(directed, start);
if (debug > 1)
System.out.println(getPathMapString(start, map2));
Graph.Vertex<Integer> end = v3;
if (debug > 1)
System.out.println("Bellman-Ford's shortest path of the directed graph from " + start.getValue()
+ " to " + end.getValue());
Graph.CostPathPair<Integer> pair2 = BellmanFord.getShortestPath(directed, start, end);
if (debug > 1) {
if (pair2 != null)
System.out.println(pair2.toString());
else
System.out.println("No path from " + start.getValue() + " to " + end.getValue());
}
if (debug > 1)
System.out.println("Johnson's all-pairs shortest path of the directed graph.");
Map<Vertex<Integer>, Map<Vertex<Integer>, Set<Edge<Integer>>>> paths = Johnson
.getAllPairsShortestPaths(directed);
if (debug > 1) {
if (paths == null)
System.out.println("Directed graph contains a negative weight cycle.");
else
System.out.println(getPathMapString(paths));
}
if (debug > 1)
System.out.println("Floyd-Warshall's all-pairs shortest path weights of the directed graph.");
Map<Vertex<Integer>, Map<Vertex<Integer>, Integer>> pathWeights = FloydWarshall
.getAllPairsShortestPaths(directed);
if (debug > 1)
System.out.println(getWeightMapString(pathWeights));
if (debug > 1)
System.out.println();
}
{
// UNDIRECTED GRAPH
if (debug > 1)
System.out.println("Undirected Graph cycle check.");
java.util.List<Vertex<Integer>> cycledVerticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> cv1 = new Graph.Vertex<Integer>(1);
cycledVerticies.add(cv1);
Graph.Vertex<Integer> cv2 = new Graph.Vertex<Integer>(2);
cycledVerticies.add(cv2);
Graph.Vertex<Integer> cv3 = new Graph.Vertex<Integer>(3);
cycledVerticies.add(cv3);
Graph.Vertex<Integer> cv4 = new Graph.Vertex<Integer>(4);
cycledVerticies.add(cv4);
Graph.Vertex<Integer> cv5 = new Graph.Vertex<Integer>(5);
cycledVerticies.add(cv5);
Graph.Vertex<Integer> cv6 = new Graph.Vertex<Integer>(6);
cycledVerticies.add(cv6);
java.util.List<Edge<Integer>> cycledEdges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> ce1_2 = new Graph.Edge<Integer>(7, cv1, cv2);
cycledEdges.add(ce1_2);
Graph.Edge<Integer> ce2_4 = new Graph.Edge<Integer>(15, cv2, cv4);
cycledEdges.add(ce2_4);
Graph.Edge<Integer> ce3_4 = new Graph.Edge<Integer>(11, cv3, cv4);
cycledEdges.add(ce3_4);
Graph.Edge<Integer> ce3_6 = new Graph.Edge<Integer>(2, cv3, cv6);
cycledEdges.add(ce3_6);
Graph.Edge<Integer> ce5_6 = new Graph.Edge<Integer>(9, cv5, cv6);
cycledEdges.add(ce5_6);
Graph.Edge<Integer> ce4_5 = new Graph.Edge<Integer>(6, cv4, cv5);
cycledEdges.add(ce4_5);
Graph<Integer> undirectedWithCycle = new Graph<Integer>(cycledVerticies, cycledEdges);
if (debug > 1)
System.out.println(undirectedWithCycle.toString());
if (debug > 1) {
System.out.println("Cycle detection of the undirected graph.");
boolean result = CycleDetection.detect(undirectedWithCycle);
System.out.println("result=" + result);
System.out.println();
}
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
Graph.Vertex<Integer> v5 = new Graph.Vertex<Integer>(5);
verticies.add(v5);
Graph.Vertex<Integer> v6 = new Graph.Vertex<Integer>(6);
verticies.add(v6);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_2 = new Graph.Edge<Integer>(7, v1, v2);
edges.add(e1_2);
Graph.Edge<Integer> e2_4 = new Graph.Edge<Integer>(15, v2, v4);
edges.add(e2_4);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(11, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e3_6 = new Graph.Edge<Integer>(2, v3, v6);
edges.add(e3_6);
Graph.Edge<Integer> e4_5 = new Graph.Edge<Integer>(6, v4, v5);
edges.add(e4_5);
Graph<Integer> undirectedWithoutCycle = new Graph<Integer>(verticies, edges);
if (debug > 1)
System.out.println(undirectedWithoutCycle.toString());
if (debug > 1) {
System.out.println("Cycle detection of the undirected graph.");
boolean result = CycleDetection.detect(undirectedWithoutCycle);
System.out.println("result=" + result);
System.out.println();
}
}
{
// DIRECTED GRAPH
if (debug > 1)
System.out.println("Directed Graph topological sort.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> cv1 = new Graph.Vertex<Integer>(1);
verticies.add(cv1);
Graph.Vertex<Integer> cv2 = new Graph.Vertex<Integer>(2);
verticies.add(cv2);
Graph.Vertex<Integer> cv3 = new Graph.Vertex<Integer>(3);
verticies.add(cv3);
Graph.Vertex<Integer> cv4 = new Graph.Vertex<Integer>(4);
verticies.add(cv4);
Graph.Vertex<Integer> cv5 = new Graph.Vertex<Integer>(5);
verticies.add(cv5);
Graph.Vertex<Integer> cv6 = new Graph.Vertex<Integer>(6);
verticies.add(cv6);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> ce1_2 = new Graph.Edge<Integer>(1, cv1, cv2);
edges.add(ce1_2);
Graph.Edge<Integer> ce2_4 = new Graph.Edge<Integer>(2, cv2, cv4);
edges.add(ce2_4);
Graph.Edge<Integer> ce4_3 = new Graph.Edge<Integer>(3, cv4, cv3);
edges.add(ce4_3);
Graph.Edge<Integer> ce3_6 = new Graph.Edge<Integer>(4, cv3, cv6);
edges.add(ce3_6);
Graph.Edge<Integer> ce5_6 = new Graph.Edge<Integer>(5, cv5, cv6);
edges.add(ce5_6);
Graph.Edge<Integer> ce4_5 = new Graph.Edge<Integer>(6, cv4, cv5);
edges.add(ce4_5);
Graph<Integer> directed = new Graph<Integer>(Graph.TYPE.DIRECTED, verticies, edges);
if (debug > 1)
System.out.println(directed.toString());
if (debug > 1)
System.out.println("Topological sort of the directed graph.");
java.util.List<Graph.Vertex<Integer>> results = TopologicalSort.sort(directed);
if (debug > 1) {
System.out.println("result=" + results);
System.out.println();
}
}
return true;
}
private static boolean testHeap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Min-Heap [array]
if (debug > 1)
System.out.println("Min-Heap [array].");
testNames[testIndex] = "Min-Heap [array]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
BinaryHeap<Integer> minHeap = new BinaryHeap.BinaryHeapArray<Integer>(BinaryHeap.Type.MIN);
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Min-Heap [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Min-Heap [array] memory use = " + (memory / count) + " bytes");
}
boolean contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Min-Heap [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue() != null) {
System.err.println("YIKES!! Min-Heap [array] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Min-Heap [array] remove time = " + removeTime / count + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [array] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Min-Heap [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Min-Heap [array] memory use = " + (memory / count) + " bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Min-Heap [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue() != null) {
System.err.println("YIKES!! Min-Heap [array] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Min-Heap [array] remove time = " + removeTime / count + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [array] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Min-Heap [array] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Min-Heap [array] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Min-Heap [array] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Min-Heap [array] remove time = " + removeSortedTime + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [array] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Min-Heap [tree]
if (debug > 1)
System.out.println("Min-Heap [tree].");
testNames[testIndex] = "Min-Heap [tree]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
BinaryHeap<Integer> minHeap = new BinaryHeap.BinaryHeapTree<Integer>(BinaryHeap.Type.MIN);
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Min-Heap [tree] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Min-Heap [tree] memory use = " + (memory / count) + " bytes");
}
boolean contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [tree] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Min-Heap [tree] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue() != null) {
System.err.println("YIKES!! Min-Heap [tree] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Min-Heap [tree] remove time = " + removeTime / count + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [tree] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Min-Heap [tree] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Min-Heap [tree] memory use = " + (memory / count) + " bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [tree] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Min-Heap [tree] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue() != null) {
System.err.println("YIKES!! Min-Heap [tree] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Min-Heap [tree] remove time = " + removeTime / count + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [tree] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Min-Heap [tree] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Min-Heap [tree] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [tree] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Min-Heap [tree] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Min-Heap [tree] remove time = " + removeSortedTime + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Min-Heap [tree] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Max-Heap [array]
if (debug > 1)
System.out.println("Max-Heap [array].");
testNames[testIndex] = "Max-Heap [array]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
BinaryHeap<Integer> maxHeap = new BinaryHeap.BinaryHeapArray<Integer>(BinaryHeap.Type.MAX);
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Max-Heap [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Max-Heap [array] memory use = " + (memory / count) + " bytes");
}
boolean contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Max-Heap [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue() != null) {
System.err.println("YIKES!! Max-Heap [array] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Max-Heap [array] remove time = " + removeTime / count + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [array] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Max-Heap [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Max-Heap [array] memory use = " + (memory / count) + " bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Max-Heap [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue() != null) {
System.err.println("YIKES!! Max-Heap [array] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Max-Heap [array] remove time = " + removeTime / count + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [array] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Max-Heap [array] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Max-Heap [array] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Max-Heap [array] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Max-Heap [array] remove time = " + removeSortedTime + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [array] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Max-Heap [tree]
if (debug > 1)
System.out.println("Max-Heap [tree].");
testNames[testIndex] = "Max-Heap [tree]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
BinaryHeap<Integer> maxHeap = new BinaryHeap.BinaryHeapTree<Integer>(BinaryHeap.Type.MAX);
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Max-Heap [tree] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Max-Heap [tree] memory use = " + (memory / count) + " bytes");
}
boolean contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [tree] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Max-Heap [tree] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue() != null) {
System.err.println("YIKES!! Max-Heap [tree] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Max-Heap [tree] remove time = " + removeTime / count + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [tree] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Max-Heap [tree] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Max-Heap [tree] memory use = " + (memory / count) + " bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [tree] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Max-Heap [tree] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue() != null) {
System.err.println("YIKES!! Max-Heap [tree] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Max-Heap [tree] remove time = " + removeTime / count + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [tree] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Max-Heap [tree] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Max-Heap [tree] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [tree] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Max-Heap [tree] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Max-Heap [tree] remove time = " + removeSortedTime + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Max-Heap [tree] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testHashMap() {
int key = unsorted.length / 2;
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Hash Map
if (debug > 1)
System.out.println("Hash Map.");
testNames[testIndex] = "Hash Map";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
HashMap<Integer, String> hash = new HashMap<Integer, String>(key);
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item, string);
if (validateStructure && !(hash.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && !hash.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Hash Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Hash Map memory use = " + (memory / count) + " bytes");
}
boolean contains = hash.contains(INVALID);
boolean removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(hash.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Hash Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
hash.remove(item);
if (validateStructure && !(hash.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && hash.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Hash Map remove time = " + removeTime / count + " ms");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item, string);
if (validateStructure && !(hash.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && !hash.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Hash Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Hash Map memory use = " + (memory / count) + " bytes");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Hash Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
hash.remove(item);
if (validateStructure && !(hash.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && hash.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Hash Map remove time = " + removeTime / count + " ms");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
hash.put(item, string);
if (validateStructure && !(hash.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && !hash.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Hash Map add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Hash Map memory use = " + (memory / (count + 1)) + " bytes");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
hash.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Hash Map lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
hash.remove(item);
if (validateStructure && !(hash.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && hash.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Hash Map remove time = " + removeSortedTime + " ms");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Hash Map invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testIntervalTree() {
{
// Interval tree
if (debug > 1)
System.out.println("Interval Tree.");
java.util.List<IntervalTree.IntervalData<String>> intervals = new ArrayList<IntervalTree.IntervalData<String>>();
intervals.add((new IntervalTree.IntervalData<String>(2, 6, "RED")));
intervals.add((new IntervalTree.IntervalData<String>(3, 5, "ORANGE")));
intervals.add((new IntervalTree.IntervalData<String>(4, 11, "GREEN")));
intervals.add((new IntervalTree.IntervalData<String>(5, 10, "DARK_GREEN")));
intervals.add((new IntervalTree.IntervalData<String>(8, 12, "BLUE")));
intervals.add((new IntervalTree.IntervalData<String>(9, 14, "PURPLE")));
intervals.add((new IntervalTree.IntervalData<String>(13, 15, "BLACK")));
IntervalTree<String> tree = new IntervalTree<String>(intervals);
if (debug > 1)
System.out.println(tree);
IntervalTree.IntervalData<String> query = tree.query(2);
if (debug > 1)
System.out.println("2: " + query);
query = tree.query(4); // Stabbing query
if (debug > 1)
System.out.println("4: " + query);
query = tree.query(9); // Stabbing query
if (debug > 1)
System.out.println("9: " + query);
query = tree.query(1, 16); // Range query
if (debug > 1)
System.out.println("1->16: " + query);
query = tree.query(7, 14); // Range query
if (debug > 1)
System.out.println("7->14: " + query);
query = tree.query(14, 15); // Range query
if (debug > 1)
System.out.println("14->15: " + query);
if (debug > 1)
System.out.println();
}
{
// Lifespan Interval tree
if (debug > 1)
System.out.println("Lifespan Interval Tree.");
java.util.List<IntervalTree.IntervalData<String>> intervals = new ArrayList<IntervalTree.IntervalData<String>>();
intervals.add((new IntervalTree.IntervalData<String>(1888, 1971, "Stravinsky")));
intervals.add((new IntervalTree.IntervalData<String>(1874, 1951, "Schoenberg")));
intervals.add((new IntervalTree.IntervalData<String>(1843, 1907, "Grieg")));
intervals.add((new IntervalTree.IntervalData<String>(1779, 1828, "Schubert")));
intervals.add((new IntervalTree.IntervalData<String>(1756, 1791, "Mozart")));
intervals.add((new IntervalTree.IntervalData<String>(1585, 1672, "Schuetz")));
IntervalTree<String> tree = new IntervalTree<String>(intervals);
if (debug > 1)
System.out.println(tree);
IntervalTree.IntervalData<String> query = tree.query(1890);
if (debug > 1)
System.out.println("1890: " + query);
query = tree.query(1909); // Stabbing query
if (debug > 1)
System.out.println("1909: " + query);
query = tree.query(1792, 1903); // Range query
if (debug > 1)
System.out.println("1792->1903: " + query);
query = tree.query(1776, 1799); // Range query
if (debug > 1)
System.out.println("1776->1799: " + query);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testJavaHashMap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Hash Map
if (debug > 1)
System.out.println("Java's Hash Map.");
testNames[testIndex] = "Java's Hash Map";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.HashMap<Integer, String> hash = new java.util.HashMap<Integer, String>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item, string);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Hash Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Hash Map memory use = " + (memory / count) + " bytes");
}
boolean contains = hash.containsKey(INVALID);
String removed = hash.remove(INVALID);
if (contains || removed != null) {
System.err.println("Java's Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Hash Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (debug > 1)
System.out.println(hash.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.containsKey(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Hash Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
hash.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Hash Map remove time = " + removeTime / count + " ms");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed != null) {
System.err.println("Java's Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Hash Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item, string);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Hash Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Hash Map memory use = " + (memory / count) + " bytes");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed != null) {
System.err.println("Java's Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Hash Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (debug > 1)
System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.containsKey(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Hash Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
hash.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Hash Map remove time = " + removeTime / count + " ms");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed != null) {
System.err.println("Java's Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Hash Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
hash.put(item, string);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Hash Map add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Hash Map memory use = " + (memory / (count + 1)) + " bytes");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed != null) {
System.err.println("Java's Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Hash Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (debug > 1)
System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
hash.containsKey(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Hash Map lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
hash.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Hash Map remove time = " + removeSortedTime + " ms");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed != null) {
System.err.println("Java's Hash Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Hash Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testJavaHeap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// MIN-HEAP
if (debug > 1)
System.out.println("Java's Min-Heap.");
testNames[testIndex] = "Java's Min-Heap";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
java.util.PriorityQueue<Integer> minHeap = new java.util.PriorityQueue<Integer>(10,
new Comparator<Integer>() {
@Override
public int compare(Integer arg0, Integer arg1) {
if (arg0.compareTo(arg1) == -1)
return -1;
else if (arg1.compareTo(arg0) == -1)
return 1;
return 0;
}
});
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
minHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Min-Heap add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Min-Heap memory use = " + (memory / count) + " bytes");
}
boolean contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Min-Heap invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Min-Heap lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
minHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Min-Heap remove time = " + removeTime / count + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Min-Heap invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
minHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Min-Heap add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Min-Heap memory use = " + (memory / count) + " bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Min-Heap invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Min-Heap lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
minHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Min-Heap remove time = " + removeTime / count + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Min-Heap invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
minHeap.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Min-Heap add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Min-Heap memory use = " + (memory / (count + 1)) + " bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Min-Heap invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Min-Heap lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
minHeap.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Min-Heap remove time = " + removeSortedTime + " ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Min-Heap invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// MAX-HEAP
if (debug > 1)
System.out.println("Java's Max-Heap.");
testNames[testIndex] = "Java's Max-Heap";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.PriorityQueue<Integer> maxHeap = new java.util.PriorityQueue<Integer>(10,
new Comparator<Integer>() {
@Override
public int compare(Integer arg0, Integer arg1) {
if (arg0.compareTo(arg1) == 1)
return -1;
else if (arg1.compareTo(arg0) == 1)
return 1;
return 0;
}
});
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
maxHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Max-Heap add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Max-Heap memory use = " + (memory / count) + " bytes");
}
boolean contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Max-Heap invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Max-Heap lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
maxHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Max-Heap remove time = " + removeTime / count + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Max-Heap invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
maxHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Max-Heap add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Max-Heap memory use = " + (memory / count) + " bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Max-Heap invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Max-Heap lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
maxHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Max-Heap remove time = " + removeTime / count + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Max-Heap invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
maxHeap.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Max-Heap add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Max-Heap memory use = " + (memory / (count + 1)) + " bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Max-Heap invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Max-Heap lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
maxHeap.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Max-Heap remove time = " + removeSortedTime + " ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Max-Heap invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testJavaList() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's List [array]
if (debug > 1)
System.out.println("Java's List [array].");
testNames[testIndex] = "Java's List [array]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.List<Integer> list = new java.util.ArrayList<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's List [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's List [array] memory use = " + (memory / count) + " bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's List [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's List [array] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's List [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's List [array] memory use = " + (memory / count) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's List [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's List [array] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
list.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's List [array] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's List [array] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's List [array] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
Integer item = sorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's List [array] remove time = " + removeSortedTime + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out
.println("Java's List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's List [linked]
if (debug > 1)
System.out.println("Java's List [linked].");
testNames[testIndex] = "Java's List [linked]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.List<Integer> list = new java.util.LinkedList<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's List [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's List [linked] memory use = " + (memory / count) + " bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
if (debug > 1)
System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's List [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's List [linked] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's List [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's List [linked] memory use = " + (memory / count) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's List [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's List [linked] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
list.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's List [linked] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's List [linked] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's List [linked] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
Integer item = sorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's List [linked] remove time = " + removeSortedTime + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's List [linked] invalidity check. contains=" + contains + " removed="
+ removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testJavaQueue() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Queue [array]
if (debug > 1)
System.out.println("Java's Queue [array].");
testNames[testIndex] = "Java's Queue [array]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.Queue<Integer> queue = new java.util.ArrayDeque<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Queue [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Queue [array] memory use = " + (memory / count) + " bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Queue [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i = 0; i < size; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Queue [array] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [array] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Queue [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Queue [array] memory use = " + (memory / count) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Queue [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Queue [array] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [array] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
queue.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Queue [array] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Queue [array] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Queue [array] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
queue.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Queue [array] remove time = " + removeSortedTime + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [array] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// LinkedQueue
if (debug > 1)
System.out.println("Java's Queue [linked].");
testNames[testIndex] = "Java's Queue [linked]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.Queue<Integer> queue = new java.util.LinkedList<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Queue [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Queue [linked] memory use = " + (memory / count) + " bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Queue [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i = 0; i < size; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Queue [linked] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [linked] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Queue [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Queue [linked] memory use = " + (memory / count) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Queue [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Queue [linked] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [linked] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
queue.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Queue [linked] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Queue [linked] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Queue [linked] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
queue.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Queue [linked] remove time = " + removeSortedTime + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Queue [linked] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testJavaRedBlackTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Red-Black Tree
if (debug > 1)
System.out.println("Java's Red-Black Tree");
testNames[testIndex] = "Java's RedBlack Tree";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.TreeSet<Integer> tree = new java.util.TreeSet<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Red-Black Tree memory use = " + (memory / count) + " bytes");
}
boolean contains = tree.contains(INVALID);
boolean removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
if (debug > 1)
System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Red-Black lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree remove time = " + removeTime / count + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
tree.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Red-Black Tree memory use = " + (memory / count) + " bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree remove time = " + removeTime / count + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
tree.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Red-Black Tree memory use = " + (memory / (count + 1)) + " bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
tree.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Red-Black Tree remove time = " + removeSortedTime + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
return false;
} else
System.out.println("Java's Red-Black Tree invalidity check. contains=" + contains + " removed="
+ removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testJavaStack() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Stack [vector]
if (debug > 1)
System.out.println("Java's Stack [vector].");
testNames[testIndex] = "Java's Stack [vector]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.Stack<Integer> stack = new java.util.Stack<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Stack [vector] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Stack [vector] memory use = " + (memory / count) + " bytes");
}
boolean contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Stack [vector] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Stack [vector] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
int size = stack.size();
for (int i = 0; i < size; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Stack [vector] remove time = " + removeTime / count + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Stack [vector] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Stack [vector] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Stack [vector] memory use = " + (memory / count) + " bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Stack [vector] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Stack [vector] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Stack [vector] remove time = " + removeTime / count + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Stack [vector] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Stack [vector] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Stack [vector] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Stack [vector] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Stack [vector] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = stack.pop();
if (validateStructure && !(stack.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Stack [vector] remove time = " + removeSortedTime + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Java's Stack [vector] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testJavaTreeMap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Tree Map
if (debug > 1)
System.out.println("Java's Tree Map.");
testNames[testIndex] = "Java's Tree Map";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
java.util.TreeMap<String, Integer> trieMap = new java.util.TreeMap<String, Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Tree Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Tree Map memory use = " + (memory / count) + " bytes");
}
String invalid = INVALID.toString();
boolean contains = trieMap.containsKey(invalid);
Integer removed = trieMap.remove(invalid);
if (contains || removed != null) {
System.err.println("Java's Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Tree Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (debug > 1)
System.out.println(trieMap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.containsKey(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Tree Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Tree Map remove time = " + removeTime / count + " ms");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed != null) {
System.err.println("Java's Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Tree Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Java's Tree Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Tree Map memory use = " + (memory / count) + " bytes");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed != null) {
System.err.println("Java's Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Tree Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (debug > 1)
System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.containsKey(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Tree Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Java's Tree Map remove time = " + removeTime / count + " ms");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed != null) {
System.err.println("Java's Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Tree Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Java's Tree Map add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Java's Tree Map memory use = " + (memory / (count + 1)) + " bytes");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed != null) {
System.err.println("Java's Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Tree Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (debug > 1)
System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trieMap.containsKey(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Java's Tree Map lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Java's Tree Map remove time = " + removeSortedTime + " ms");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed != null) {
System.err.println("Java's Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Java's Tree Map invalidity check. contains=" + contains + " removed="
+ (removed != null));
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testKdTree() {
{
// K-D TREE
if (debug > 1)
System.out.println("k-d tree with node.");
java.util.List<KdTree.XYZPoint> points = new ArrayList<KdTree.XYZPoint>();
KdTree.XYZPoint p1 = new KdTree.XYZPoint(2, 3);
points.add(p1);
KdTree.XYZPoint p2 = new KdTree.XYZPoint(5, 4);
points.add(p2);
KdTree.XYZPoint p3 = new KdTree.XYZPoint(9, 6);
points.add(p3);
KdTree.XYZPoint p4 = new KdTree.XYZPoint(4, 7);
points.add(p4);
KdTree.XYZPoint p5 = new KdTree.XYZPoint(8, 1);
points.add(p5);
KdTree.XYZPoint p6 = new KdTree.XYZPoint(7, 2);
points.add(p6);
KdTree<KdTree.XYZPoint> kdTree = new KdTree<KdTree.XYZPoint>(points);
if (debug > 1)
System.out.println(kdTree.toString());
Collection<KdTree.XYZPoint> result = kdTree.nearestNeighbourSearch(1, p3);
if (debug > 1)
System.out.println("NNS for " + p3 + " result=" + result + "\n");
KdTree.XYZPoint search = new KdTree.XYZPoint(1, 4);
result = kdTree.nearestNeighbourSearch(4, search);
if (debug > 1)
System.out.println("NNS for " + search + " result=" + result + "\n");
kdTree.remove(p6);
if (debug > 1)
System.out.println("Removed " + p6 + "\n" + kdTree.toString());
kdTree.remove(p4);
if (debug > 1)
System.out.println("Removed " + p4 + "\n" + kdTree.toString());
kdTree.remove(p3);
if (debug > 1)
System.out.println("Removed " + p3 + "\n" + kdTree.toString());
kdTree.remove(p5);
if (debug > 1)
System.out.println("Removed " + p5 + "\n" + kdTree.toString());
kdTree.remove(p1);
if (debug > 1)
System.out.println("Removed " + p1 + "\n" + kdTree.toString());
kdTree.remove(p2);
if (debug > 1)
System.out.println("Removed " + p2 + "\n" + kdTree.toString());
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testList() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// List [array]
if (debug > 1)
System.out.println("List [array].");
testNames[testIndex] = "List [array]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
List<Integer> list = new List.ArrayList<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("List [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("List [array] memory use = " + (memory / count) + " bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("List [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("List [array] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("List [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("List [array] memory use = " + (memory / count) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("List [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("List [array] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("List [array] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("List [array] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("List [array] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("List [array] remove time = " + removeSortedTime + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [array] invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// List [linked]
if (debug > 1)
System.out.println("List [linked].");
testNames[testIndex] = "List [linked]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
List<Integer> list = new List.LinkedList<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("List [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("List [linked] memory use = " + (memory / count) + " bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("List [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("List [linked] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("List [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("List [linked] memory use = " + (memory / count) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("List [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("List [linked] remove time = " + removeTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("List [linked] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("List [linked] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("List [linked] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("List [linked] remove time = " + removeSortedTime + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("List [linked] invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testMatrix() {
{
// MATRIX
if (debug > 1)
System.out.println("Matrix.");
Matrix<Integer> matrix1 = new Matrix<Integer>(4, 3);
matrix1.set(0, 0, 14);
matrix1.set(0, 1, 9);
matrix1.set(0, 2, 3);
matrix1.set(1, 0, 2);
matrix1.set(1, 1, 11);
matrix1.set(1, 2, 15);
matrix1.set(2, 0, 0);
matrix1.set(2, 1, 12);
matrix1.set(2, 2, 17);
matrix1.set(3, 0, 5);
matrix1.set(3, 1, 2);
matrix1.set(3, 2, 3);
Matrix<Integer> matrix2 = new Matrix<Integer>(3, 2);
matrix2.set(0, 0, 12);
matrix2.set(0, 1, 25);
matrix2.set(1, 0, 9);
matrix2.set(1, 1, 10);
matrix2.set(2, 0, 8);
matrix2.set(2, 1, 5);
if (debug > 1)
System.out.println("Matrix multiplication.");
Matrix<Integer> matrix3 = matrix1.multiply(matrix2);
if (debug > 1)
System.out.println(matrix3);
int rows = 2;
int cols = 2;
int counter = 0;
Matrix<Integer> matrix4 = new Matrix<Integer>(rows, cols);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
matrix4.set(r, c, counter++);
}
}
if (debug > 1)
System.out.println("Matrix subtraction.");
Matrix<Integer> matrix5 = matrix4.subtract(matrix4);
if (debug > 1)
System.out.println(matrix5);
if (debug > 1)
System.out.println("Matrix addition.");
Matrix<Integer> matrix6 = matrix4.add(matrix4);
if (debug > 1)
System.out.println(matrix6);
Matrix<Integer> matrix7 = new Matrix<Integer>(2, 2);
matrix7.set(0, 0, 1);
matrix7.set(0, 1, 2);
matrix7.set(1, 0, 3);
matrix7.set(1, 1, 4);
Matrix<Integer> matrix8 = new Matrix<Integer>(2, 2);
matrix8.set(0, 0, 1);
matrix8.set(0, 1, 2);
matrix8.set(1, 0, 3);
matrix8.set(1, 1, 4);
if (debug > 1)
System.out.println("Matrix multiplication.");
Matrix<Integer> matrix9 = matrix7.multiply(matrix8);
if (debug > 1)
System.out.println(matrix9);
}
return true;
}
private static boolean testPatriciaTrie() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Patricia Trie
if (debug > 1)
System.out.println("Patricia Trie.");
testNames[testIndex] = "Patricia Trie";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
PatriciaTrie<String> trie = new PatriciaTrie<String>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Patricia Trie add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Patricia Trie memory use = " + (memory / count) + " bytes");
}
String invalid = INVALID.toString();
boolean contains = trie.contains(invalid);
boolean removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trie.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Patricia Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Patricia Trie remove time = " + removeTime / count + " ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + string + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Patricia Trie add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Patricia Trie memory use = " + (memory / count) + " bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Patricia Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + string + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Patricia Trie remove time = " + removeTime / count + " ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Patricia Tree add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Patricia Tree memory use = " + (memory / (count + 1)) + " bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Patricia Tree lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Patricia Tree remove time = " + removeSortedTime + " ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Patricia Trie invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
@SuppressWarnings("unchecked")
private static boolean testQuadTree() {
int listSize = 10;
int size = 16000;
java.util.List<QuadTree.XYPoint>[] lists = new java.util.List[listSize];
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> list = new java.util.ArrayList<QuadTree.XYPoint>(size);
for (int j=0; j<size; j++) {
float x = RANDOM.nextInt(size);
float y = RANDOM.nextInt(size);
QuadTree.XYPoint xyPoint = new QuadTree.XYPoint(x,y);
list.add(xyPoint);
}
lists[i] = list;
}
java.util.List<QuadTree.XYPoint>[] queries = new java.util.List[listSize];
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> query = new java.util.ArrayList<QuadTree.XYPoint>(size);
for (int j=0; j<size; j++) {
float x = RANDOM.nextInt(size);
float y = RANDOM.nextInt(size);
QuadTree.XYPoint xyPoint = new QuadTree.XYPoint(x,y);
query.add(xyPoint);
}
queries[i] = query;
}
long beforeInsert;
long beforeQuery;
long beforeMemory;
long beforeTreeQuery;
long afterInsert;
long afterQuery;
long afterMemory;
long afterTreeQuery;
long insertTime;
long queryTime;
long avgInsertTime;
long avgQueryTime;
long treeMemory;
long treeQuery;
// Point based quad tree
{
QuadTree.PointRegionQuadTree<QuadTree.XYPoint> tree = new QuadTree.PointRegionQuadTree<QuadTree.XYPoint>(0,0,size,size);
beforeMemory = DataStructures.getMemoryUse();
avgInsertTime = 0;
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> list = lists[i];
beforeInsert = System.currentTimeMillis();
for (QuadTree.XYPoint p : list) {
tree.insert(p.getX(), p.getY());
}
afterInsert = System.currentTimeMillis();
insertTime = afterInsert - beforeInsert;
System.out.println("insertTime="+insertTime);
avgInsertTime += insertTime;
}
System.out.println("avgInsertTime="+avgInsertTime/listSize);
afterMemory = DataStructures.getMemoryUse();
treeMemory = afterMemory - beforeMemory;
System.out.println("treeMemory="+treeMemory);
//System.out.println(tree);
// We should find all points here
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> list = lists[i];
for (QuadTree.XYPoint p : list) {
java.util.List<QuadTree.XYPoint> result = tree.queryRange(p.getX(), p.getY(), 1, 1);
if (result.size()<=0) return false;
}
}
// We should find all points here
avgQueryTime = 0;
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> query = queries[i];
beforeQuery = System.currentTimeMillis();
for (QuadTree.XYPoint p : query) {
tree.queryRange(p.getX(), p.getY(), 1, 1);
}
afterQuery = System.currentTimeMillis();
queryTime = afterQuery - beforeQuery;
System.out.println("queryTime="+queryTime);
avgQueryTime += queryTime;
}
System.out.println("avgQueryTime="+avgQueryTime/listSize);
// Result set should not contain duplicates
beforeTreeQuery = System.currentTimeMillis();
java.util.List<QuadTree.XYPoint> result = tree.queryRange(0, 0, size, size);
afterTreeQuery = System.currentTimeMillis();
treeQuery = afterTreeQuery - beforeTreeQuery;
System.out.println("treeQuery="+treeQuery);
Collections.sort(result);
QuadTree.XYPoint prev = null;
for (QuadTree.XYPoint p : result) {
if (prev!=null && prev.equals(p)) return false;
prev = p;
}
}
// Rectangle base quadtree
{
QuadTree.MxCifQuadTree<QuadTree.AxisAlignedBoundingBox> tree = new QuadTree.MxCifQuadTree<QuadTree.AxisAlignedBoundingBox>(0,0,size,size,20,20);
beforeMemory = DataStructures.getMemoryUse();
avgInsertTime = 0;
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> list = lists[i];
beforeInsert = System.currentTimeMillis();
for (QuadTree.XYPoint p : list) {
tree.insert(p.getX(), p.getY(), 1, 1);
}
afterInsert = System.currentTimeMillis();
insertTime = afterInsert - beforeInsert;
System.out.println("insertTime="+insertTime);
avgInsertTime += insertTime;
}
System.out.println("avgInsertTime="+avgInsertTime/listSize);
afterMemory = DataStructures.getMemoryUse();
treeMemory = afterMemory - beforeMemory;
System.out.println("treeMemory="+treeMemory);
//System.out.println(tree);
// We should find all points here
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> list = lists[i];
for (QuadTree.XYPoint p : list) {
java.util.List<QuadTree.AxisAlignedBoundingBox> result = tree.queryRange(p.getX(), p.getY(), 1, 1);
if (result.size()<=0) return false;
}
}
// We should find all points here
avgQueryTime = 0;
for (int i=0; i<listSize; i++) {
java.util.List<QuadTree.XYPoint> query = queries[i];
beforeQuery = System.currentTimeMillis();
for (QuadTree.XYPoint p : query) {
tree.queryRange(p.getX(), p.getY(), 1, 1);
}
afterQuery = System.currentTimeMillis();
queryTime = afterQuery - beforeQuery;
System.out.println("queryTime="+queryTime);
avgQueryTime += queryTime;
}
System.out.println("avgQueryTime="+avgQueryTime/listSize);
// Result set should not contain duplicates
beforeTreeQuery = System.currentTimeMillis();
java.util.List<QuadTree.AxisAlignedBoundingBox> result = tree.queryRange(0, 0, size, size);
afterTreeQuery = System.currentTimeMillis();
treeQuery = afterTreeQuery - beforeTreeQuery;
System.out.println("treeQuery="+treeQuery);
Collections.sort(result);
QuadTree.AxisAlignedBoundingBox prev = null;
for (QuadTree.AxisAlignedBoundingBox p : result) {
if (prev!=null && prev.equals(p)) {
System.out.println("prev==p. p="+p.toString()+" "+prev.toString());
return false;
}
prev = p;
}
}
return true;
}
private static boolean testQueue() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Queue [array]
if (debug > 1)
System.out.println("Queue [array].");
testNames[testIndex] = "Queue [array]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
Queue<Integer> queue = new Queue.ArrayQueue<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Queue [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Queue [array] memory use = " + (memory / count) + " bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Queue [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i = 0; i < size; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! " + item + " still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Queue [array] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [array] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Queue [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Queue [array] memory use = " + (memory / count) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Queue [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! " + item + " still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Queue [array] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [array] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Queue [array] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Queue [array] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Queue [array] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = queue.dequeue();
if (validateStructure && !(queue.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Queue [array] remove time = " + removeSortedTime + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [array] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// LinkedQueue
if (debug > 1)
System.out.println("Queue [linked].");
testNames[testIndex] = "Queue [linked]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
Queue<Integer> queue = new Queue.LinkedQueue<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Queue [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Queue [linked] memory use = " + (memory / count) + " bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Queue [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i = 0; i < size; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! " + item + " still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Queue [linked] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [linked] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Queue [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Queue [linked] memory use = " + (memory / count) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Queue [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! " + item + " still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Queue [linked] remove time = " + removeTime / count + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [linked] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Queue [linked] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Queue [linked] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Queue [linked] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = queue.dequeue();
if (validateStructure && !(queue.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Queue [linked] remove time = " + removeSortedTime + " ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Queue [linked] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testRadixTrie() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Radix Trie (map)
if (debug > 1)
System.out.println("Radix Trie (map).");
testNames[testIndex] = "Radix Trie (map)";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
RadixTrie<String, Integer> tree = new RadixTrie<String, Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
tree.put(string, item);
if (validateStructure && !(tree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Radix Trie add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Radix Trie memory use = " + (memory / count) + " bytes");
}
String invalid = INVALID.toString();
boolean contains = tree.contains(invalid);
boolean removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
tree.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Radix Trie lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
tree.remove(string);
if (validateStructure && !(tree.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Radix Trie remove time = " + removeTime / count + " ms");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
tree.put(string, item);
if (validateStructure && !(tree.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Radix Trie add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Radix Trie memory use = " + (memory / count) + " bytes");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
tree.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Radix Trie lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
tree.remove(string);
if (validateStructure && !(tree.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Radix Trie remove time = " + removeTime / count + " ms");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
tree.put(string, item);
if (validateStructure && !(tree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(string)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Radix Trie add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Radix Trie memory use = " + (memory / (count + 1)) + " bytes");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
tree.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Radix Trie lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
String string = String.valueOf(item);
tree.remove(string);
if (validateStructure && !(tree.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(string)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Radix Trie remove time = " + removeSortedTime + " ms");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Radix Trie invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testRedBlackTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Red-Black Tree
if (debug > 1)
System.out.println("Red-Black Tree");
testNames[testIndex] = "RedBlack Tree";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
RedBlackTree<Integer> tree = new RedBlackTree<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Red-Black Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Red-Black Tree memory use = " + (memory / count) + " bytes");
}
boolean contains = tree.contains(INVALID);
boolean removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Red-Black lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Red-Black Tree remove time = " + removeTime / count + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Red-Black Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Red-Black Tree memory use = " + (memory / count) + " bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Red-Black Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Red-Black Tree remove time = " + removeTime / count + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Red-Black Tree add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Red-Black Tree memory use = " + (memory / (count + 1)) + " bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Red-Black Tree lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Red-Black Tree remove time = " + removeSortedTime + " ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Red-Black Tree invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testSegmentTree() {
{
// Quadrant Segment tree
if (debug > 1)
System.out.println("Quadrant Segment Tree.");
java.util.List<SegmentTree.Data.QuadrantData> segments = new ArrayList<SegmentTree.Data.QuadrantData>();
segments.add(new SegmentTree.Data.QuadrantData(0, 1, 0, 0, 0)); // first
// point
// the
// 0th
// quadrant
segments.add(new SegmentTree.Data.QuadrantData(1, 0, 1, 0, 0)); // second
// point
// the
// 1st
// quadrant
segments.add(new SegmentTree.Data.QuadrantData(2, 0, 0, 1, 0)); // third
// point
// the
// 2nd
// quadrant
segments.add(new SegmentTree.Data.QuadrantData(3, 0, 0, 0, 1)); // fourth
// point
// the
// 3rd
// quadrant
FlatSegmentTree<SegmentTree.Data.QuadrantData> tree = new FlatSegmentTree<SegmentTree.Data.QuadrantData>(
segments);
if (debug > 1)
System.out.println(tree);
SegmentTree.Data.QuadrantData query = tree.query(0, 3);
if (debug > 1)
System.out.println("0->3: " + query + "\n");
query = tree.query(2, 3);
if (debug > 1)
System.out.println("2->3: " + query + "\n");
query = tree.query(0, 2);
if (debug > 1)
System.out.println("0->2: " + query + "\n");
if (debug > 1)
System.out.println();
}
{
// Range Maximum Segment tree
if (debug > 1)
System.out.println("Range Maximum Segment Tree.");
java.util.List<SegmentTree.Data.RangeMaximumData<Integer>> segments = new ArrayList<SegmentTree.Data.RangeMaximumData<Integer>>();
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(0, (Integer) 4));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(1, (Integer) 2));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(2, (Integer) 6));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(3, (Integer) 3));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(4, (Integer) 1));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(5, (Integer) 5));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(6, (Integer) 0));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(7, 17, (Integer) 7));
segments.add(new SegmentTree.Data.RangeMaximumData<Integer>(21, (Integer) 10));
FlatSegmentTree<SegmentTree.Data.RangeMaximumData<Integer>> tree = new FlatSegmentTree<SegmentTree.Data.RangeMaximumData<Integer>>(
segments, 3);
if (debug > 1)
System.out.println(tree);
SegmentTree.Data.RangeMaximumData<Integer> query = tree.query(0, 7);
if (debug > 1)
System.out.println("0->7: " + query + "\n");
query = tree.query(0, 21);
if (debug > 1)
System.out.println("0->21: " + query + "\n");
query = tree.query(2, 5);
if (debug > 1)
System.out.println("2->5: " + query + "\n");
query = tree.query(7);
if (debug > 1)
System.out.println("7: " + query + "\n");
if (debug > 1)
System.out.println();
}
{
// Range Minimum Segment tree
if (debug > 1)
System.out.println("Range Minimum Segment Tree.");
java.util.List<SegmentTree.Data.RangeMinimumData<Integer>> segments = new ArrayList<SegmentTree.Data.RangeMinimumData<Integer>>();
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(0, (Integer) 4));
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(1, (Integer) 2));
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(2, (Integer) 6));
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(3, (Integer) 3));
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(4, (Integer) 1));
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(5, (Integer) 5));
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(6, (Integer) 0));
segments.add(new SegmentTree.Data.RangeMinimumData<Integer>(17, (Integer) 7));
FlatSegmentTree<SegmentTree.Data.RangeMinimumData<Integer>> tree = new FlatSegmentTree<SegmentTree.Data.RangeMinimumData<Integer>>(
segments, 5);
if (debug > 1)
System.out.println(tree);
SegmentTree.Data.RangeMinimumData<Integer> query = tree.query(0, 7);
if (debug > 1)
System.out.println("0->7: " + query + "\n");
query = tree.query(0, 17);
if (debug > 1)
System.out.println("0->17: " + query + "\n");
query = tree.query(1, 3);
if (debug > 1)
System.out.println("1->3: " + query + "\n");
query = tree.query(7);
if (debug > 1)
System.out.println("7: " + query + "\n");
if (debug > 1)
System.out.println();
}
{
// Range Sum Segment tree
if (debug > 1)
System.out.println("Range Sum Segment Tree.");
java.util.List<SegmentTree.Data.RangeSumData<Integer>> segments = new ArrayList<SegmentTree.Data.RangeSumData<Integer>>();
segments.add(new SegmentTree.Data.RangeSumData<Integer>(0, (Integer) 4));
segments.add(new SegmentTree.Data.RangeSumData<Integer>(1, (Integer) 2));
segments.add(new SegmentTree.Data.RangeSumData<Integer>(2, (Integer) 6));
segments.add(new SegmentTree.Data.RangeSumData<Integer>(3, (Integer) 3));
segments.add(new SegmentTree.Data.RangeSumData<Integer>(4, (Integer) 1));
segments.add(new SegmentTree.Data.RangeSumData<Integer>(5, (Integer) 5));
segments.add(new SegmentTree.Data.RangeSumData<Integer>(6, (Integer) 0));
segments.add(new SegmentTree.Data.RangeSumData<Integer>(17, (Integer) 7));
FlatSegmentTree<SegmentTree.Data.RangeSumData<Integer>> tree = new FlatSegmentTree<SegmentTree.Data.RangeSumData<Integer>>(
segments, 10);
if (debug > 1)
System.out.println(tree);
SegmentTree.Data.RangeSumData<Integer> query = tree.query(0, 8);
if (debug > 1)
System.out.println("0->8: " + query + "\n");
query = tree.query(0, 17);
if (debug > 1)
System.out.println("0->17: " + query + "\n");
query = tree.query(2, 5);
if (debug > 1)
System.out.println("2->5: " + query + "\n");
query = tree.query(10, 17);
if (debug > 1)
System.out.println("10->17: " + query + "\n");
query = tree.query(16);
if (debug > 1)
System.out.println("16: " + query + "\n");
query = tree.query(17);
if (debug > 1)
System.out.println("17: " + query + "\n");
if (debug > 1)
System.out.println();
}
{
// Interval Segment tree
if (debug > 1)
System.out.println("Interval Segment Tree.");
java.util.List<SegmentTree.Data.IntervalData<String>> segments = new ArrayList<SegmentTree.Data.IntervalData<String>>();
segments.add((new SegmentTree.Data.IntervalData<String>(2, 6, "RED")));
segments.add((new SegmentTree.Data.IntervalData<String>(3, 5, "ORANGE")));
segments.add((new SegmentTree.Data.IntervalData<String>(4, 11, "GREEN")));
segments.add((new SegmentTree.Data.IntervalData<String>(5, 10, "DARK_GREEN")));
segments.add((new SegmentTree.Data.IntervalData<String>(8, 12, "BLUE")));
segments.add((new SegmentTree.Data.IntervalData<String>(9, 14, "PURPLE")));
segments.add((new SegmentTree.Data.IntervalData<String>(13, 15, "BLACK")));
DynamicSegmentTree<SegmentTree.Data.IntervalData<String>> tree = new DynamicSegmentTree<SegmentTree.Data.IntervalData<String>>(
segments);
if (debug > 1)
System.out.println(tree);
SegmentTree.Data.IntervalData<String> query = tree.query(2);
if (debug > 1)
System.out.println("2: " + query);
query = tree.query(4); // Stabbing query
if (debug > 1)
System.out.println("4: " + query);
query = tree.query(9); // Stabbing query
if (debug > 1)
System.out.println("9: " + query);
query = tree.query(1, 16); // Range query
if (debug > 1)
System.out.println("1->16: " + query);
query = tree.query(7, 14); // Range query
if (debug > 1)
System.out.println("7->14: " + query);
query = tree.query(14, 15); // Range query
if (debug > 1)
System.out.println("14->15: " + query);
if (debug > 1)
System.out.println();
}
{
// Lifespan Interval Segment tree
if (debug > 1)
System.out.println("Lifespan Interval Segment Tree.");
java.util.List<SegmentTree.Data.IntervalData<String>> segments = new ArrayList<SegmentTree.Data.IntervalData<String>>();
segments.add((new SegmentTree.Data.IntervalData<String>(1888, 1971, "Stravinsky")));
segments.add((new SegmentTree.Data.IntervalData<String>(1874, 1951, "Schoenberg")));
segments.add((new SegmentTree.Data.IntervalData<String>(1843, 1907, "Grieg")));
segments.add((new SegmentTree.Data.IntervalData<String>(1779, 1828, "Schubert")));
segments.add((new SegmentTree.Data.IntervalData<String>(1756, 1791, "Mozart")));
segments.add((new SegmentTree.Data.IntervalData<String>(1585, 1672, "Schuetz")));
DynamicSegmentTree<SegmentTree.Data.IntervalData<String>> tree = new DynamicSegmentTree<SegmentTree.Data.IntervalData<String>>(
segments, 25);
if (debug > 1)
System.out.println(tree);
SegmentTree.Data.IntervalData<String> query = tree.query(1890);
if (debug > 1)
System.out.println("1890: " + query);
query = tree.query(1909); // Stabbing query
if (debug > 1)
System.out.println("1909: " + query);
query = tree.query(1792, 1903); // Range query
if (debug > 1)
System.out.println("1792->1903: " + query);
query = tree.query(1776, 1799); // Range query
if (debug > 1)
System.out.println("1776->1799: " + query);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testSkipList() {
{
long count = 0;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
// SkipList only works with sorted items
if (debug > 1)
System.out.println("Skip List.");
testNames[testIndex] = "Skip List";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
SkipList<Integer> list = new SkipList<Integer>();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Skip List add time = " + (addSortedTime / count) + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Skip List memory use = " + (memory / count) + " bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Skip List lookup time = " + (lookupTime / count) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Skip List remove time = " + (removeSortedTime / count) + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Skip List add time = " + (addSortedTime / count) + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Skip List memory use = " + (memory / count) + " bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Skip List lookup time = " + (lookupTime / count) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size() == (sorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Skip List remove time = " + removeSortedTime / count + " ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Skip List invalidity check. contains=" + contains + " removed=" + removed);
testResults[testIndex] = new long[] { 0, 0, addSortedTime / count, removeSortedTime / count,
lookupTime / count, memory / count };
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testSplayTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Splay Tree
if (debug > 1)
System.out.println("Splay Tree.");
testNames[testIndex] = "Splay Tree";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
SplayTree<Integer> splay = new SplayTree<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
splay.add(item);
if (validateStructure && !(splay.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && !splay.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Splay Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Splay Tree memory use = " + (memory / count) + " bytes");
}
boolean contains = splay.contains(INVALID);
boolean removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(splay.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
splay.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Splay Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
splay.remove(item);
if (validateStructure && !(splay.size() == ((unsorted.length - 1) - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && splay.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Splay Tree remove time = " + removeTime / count + " ms");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
splay.add(item);
if (validateStructure && !(splay.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && !splay.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Splay Tree add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Splay Tree memory use = " + (memory / count) + " bytes");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(splay.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
splay.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Splay Tree lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
splay.remove(item);
if (validateStructure && !(splay.size() == ((unsorted.length - 1) - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && splay.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Splay Tree remove time = " + removeTime / count + " ms");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
splay.add(item);
if (validateStructure && !(splay.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && !splay.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Splay Tree add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Splay Tree memory use = " + (memory / (count + 1)) + " bytes");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(splay.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
splay.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Splay Tree lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
splay.remove(item);
if (validateStructure && !(splay.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && splay.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Splay Tree remove time = " + removeSortedTime + " ms");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Splay Tree invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testStack() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Stack [array]
if (debug > 1)
System.out.println("Stack [array].");
testNames[testIndex] = "Stack [array]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
Stack<Integer> stack = new Stack.ArrayStack<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Stack [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Stack [array] memory use = " + (memory / count) + " bytes");
}
boolean contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Stack [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
int size = stack.size();
for (int i = 0; i < size; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Stack [array] remove time = " + removeTime / count + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [array] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Stack [array] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Stack [array] memory use = " + (memory / count) + " bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Stack [array] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Stack [array] remove time = " + removeTime / count + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [array] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Stack [array] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Stack [array] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [array] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Stack [array] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = stack.pop();
if (validateStructure && !(stack.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Stack [array] remove time = " + removeSortedTime + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [array] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Stack [linked]
if (debug > 1)
System.out.println("Stack [linked].");
testNames[testIndex] = "Stack [linked]";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
Stack<Integer> stack = new Stack.LinkedStack<Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Stack [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Stack [linked] memory use = " + (memory / count) + " bytes");
}
boolean contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Stack [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
int size = stack.size();
for (int i = 0; i < size; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Stack [linked] remove time = " + removeTime / count + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [linked] invalidity check. contains=" + contains);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Stack [linked] add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Stack [linked] memory use = " + (memory / count) + " bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Stack [linked] lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Stack [linked] remove time = " + removeTime / count + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [linked] invalidity check. contains=" + contains);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
stack.push(item);
if (validateStructure && !(stack.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Stack [linked] add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Stack [linked] memory use = " + (memory / (count + 1)) + " bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [linked] invalidity check. contains=" + contains);
if (debug > 1)
System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Stack [linked] lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = stack.pop();
if (validateStructure && !(stack.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Stack [linked] remove time = " + removeSortedTime + " ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains=" + contains);
return false;
} else
System.out.println("Stack [linked] invalidity check. contains=" + contains);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testSuffixTree() {
{
// Suffix Tree
if (debug > 1)
System.out.println("Suffix Tree.");
String bookkeeper = "bookkeeper";
SuffixTree<String> tree = new SuffixTree<String>(bookkeeper);
if (debug > 1)
System.out.println(tree.toString());
if (debug > 1)
System.out.println(tree.getSuffixes());
boolean exists = tree.doesSubStringExist(bookkeeper);
if (!exists) {
System.err.println("YIKES!! " + bookkeeper + " doesn't exists.");
handleError(tree);
return false;
}
String failed = "booker";
exists = tree.doesSubStringExist(failed);
if (exists) {
System.err.println("YIKES!! " + failed + " exists.");
handleError(tree);
return false;
}
String pass = "kkee";
exists = tree.doesSubStringExist(pass);
if (!exists) {
System.err.println("YIKES!! " + pass + " doesn't exists.");
handleError(tree);
return false;
}
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testSuffixTrie() {
{
// Suffix Trie
if (debug > 1)
System.out.println("Suffix Trie.");
String bookkeeper = "bookkeeper";
SuffixTrie<String> trie = new SuffixTrie<String>(bookkeeper);
if (debug > 1)
System.out.println(trie.toString());
if (debug > 1)
System.out.println(trie.getSuffixes());
boolean exists = trie.doesSubStringExist(bookkeeper);
if (!exists) {
System.err.println("YIKES!! " + bookkeeper + " doesn't exists.");
handleError(trie);
return false;
}
String failed = "booker";
exists = trie.doesSubStringExist(failed);
if (exists) {
System.err.println("YIKES!! " + failed + " exists.");
handleError(trie);
return false;
}
String pass = "kkee";
exists = trie.doesSubStringExist(pass);
if (!exists) {
System.err.println("YIKES!! " + pass + " doesn't exists.");
handleError(trie);
return false;
}
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testTreap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Treap
if (debug > 1)
System.out.println("Treap.");
testNames[testIndex] = "Treap";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
Treap<Integer> treap = new Treap<Integer>(unsorted.length * 2);
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
treap.add(item);
if (validateStructure && !(treap.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.1");
handleError(treap);
return false;
}
if (validateContents && !treap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Treap add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Treap memory use = " + (memory / count) + " bytes");
}
boolean contains = treap.contains(INVALID);
boolean removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(treap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
treap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Treap lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
treap.remove(item);
if (validateStructure && !(treap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.2");
handleError(treap);
return false;
}
if (validateContents && treap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Treap remove time = " + removeTime / count + " ms");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
treap.add(item);
if (validateStructure && !(treap.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.3");
handleError(treap);
return false;
}
if (validateContents && !treap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Treap add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Treap memory use = " + (memory / count) + " bytes");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(treap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
treap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Treap lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
treap.remove(item);
if (validateStructure && !(treap.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.4");
handleError(treap);
return false;
}
if (validateContents && treap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Treap remove time = " + removeTime / count + " ms");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
treap.add(item);
if (validateStructure && !(treap.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(treap);
return false;
}
if (validateContents && !treap.contains(item)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Treap add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Treap memory use = " + (memory / (count + 1)) + " bytes");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(treap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
treap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Treap lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
treap.remove(item);
if (validateStructure && !(treap.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(treap);
return false;
}
if (validateContents && treap.contains(item)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Treap remove time = " + removeSortedTime + " ms");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Treap invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testTreeMap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Tree Map
if (debug > 1)
System.out.println("Tree Map.");
testNames[testIndex] = "Tree Map";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
TreeMap<String, Integer> TreeMap = new TreeMap<String, Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
TreeMap.put(string, item);
if (validateStructure && !(TreeMap.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(TreeMap);
return false;
}
if (validateContents && !TreeMap.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(TreeMap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Tree Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Tree Map memory use = " + (memory / count) + " bytes");
}
String invalid = INVALID.toString();
boolean contains = TreeMap.contains(invalid);
boolean removed = TreeMap.remove(invalid);
if (contains || removed) {
System.err.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(TreeMap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
TreeMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Tree Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
TreeMap.remove(string);
if (validateStructure && !(TreeMap.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(TreeMap);
return false;
}
if (validateContents && TreeMap.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(TreeMap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Tree Map remove time = " + removeTime / count + " ms");
}
contains = TreeMap.contains(invalid);
removed = TreeMap.remove(invalid);
if (contains || removed) {
System.err.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
TreeMap.put(string, item);
if (validateStructure && !(TreeMap.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(TreeMap);
return false;
}
if (validateContents && !TreeMap.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(TreeMap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Tree Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Tree Map memory use = " + (memory / count) + " bytes");
}
contains = TreeMap.contains(invalid);
removed = TreeMap.remove(invalid);
if (contains || removed) {
System.err.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(TreeMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
TreeMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Tree Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
TreeMap.remove(string);
if (validateStructure && !(TreeMap.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(TreeMap);
return false;
}
if (validateContents && TreeMap.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(TreeMap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Tree Map remove time = " + removeTime / count + " ms");
}
contains = TreeMap.contains(invalid);
removed = TreeMap.remove(invalid);
if (contains || removed) {
System.err.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
TreeMap.put(string, item);
if (validateStructure && !(TreeMap.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(TreeMap);
return false;
}
if (validateContents && !TreeMap.contains(string)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(TreeMap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Tree Map add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Tree Map memory use = " + (memory / (count + 1)) + " bytes");
}
contains = TreeMap.contains(invalid);
removed = TreeMap.remove(invalid);
if (contains || removed) {
System.err.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(TreeMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
TreeMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Tree Map lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
String string = String.valueOf(item);
TreeMap.remove(string);
if (validateStructure && !(TreeMap.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(TreeMap);
return false;
}
if (validateContents && TreeMap.contains(string)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(TreeMap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Tree Map remove time = " + removeSortedTime + " ms");
}
contains = TreeMap.contains(invalid);
removed = TreeMap.remove(invalid);
if (contains || removed) {
System.err.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Tree Map invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testTrie() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Trie.
if (debug > 1)
System.out.println("Trie.");
testNames[testIndex] = "Trie";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
Trie<String> trie = new Trie<String>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Trie add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Trie memory use = " + (memory / count) + " bytes");
}
String invalid = INVALID.toString();
boolean contains = trie.contains(invalid);
boolean removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trie.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Trie lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Trie remove time = " + removeTime / count + " ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size() == unsorted.length - i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Trie add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Trie memory use = " + (memory / count) + " bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Trie lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size() == unsorted.length - (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Trie remove time = " + removeTime / count + " ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Trie add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Trie memory use = " + (memory / (count + 1)) + " bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Trie lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Trie remove time = " + removeSortedTime + " ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static boolean testTrieMap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Trie Map
if (debug > 1)
System.out.println("Trie Map.");
testNames[testIndex] = "Trie Map";
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
TrieMap<String, Integer> trieMap = new TrieMap<String, Integer>();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
if (validateStructure && !(trieMap.size() == i + 1)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && !trieMap.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Trie Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Trie Map memory use = " + (memory / count) + " bytes");
}
String invalid = INVALID.toString();
boolean contains = trieMap.contains(invalid);
boolean removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trieMap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Trie Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
if (validateStructure && !(trieMap.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && trieMap.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Trie Map remove time = " + removeTime / count + " ms");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
count++;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddTime = System.currentTimeMillis();
for (int i = unsorted.length - 1; i >= 0; i
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
if (validateStructure && !(trieMap.size() == (unsorted.length - i))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && !trieMap.contains(string)) {
System.err.println("YIKES!! " + string + " doesn't exist.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime - beforeAddTime;
if (debug > 0)
System.out.println("Trie Map add time = " + addTime / count + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Trie Map memory use = " + (memory / count) + " bytes");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Trie Map lookup time = " + lookupTime / count + " ms");
}
if (debugTime)
beforeRemoveTime = System.currentTimeMillis();
for (int i = 0; i < unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
if (validateStructure && !(trieMap.size() == (unsorted.length - (i + 1)))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && trieMap.contains(string)) {
System.err.println("YIKES!! " + string + " still exists.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime - beforeRemoveTime;
if (debug > 0)
System.out.println("Trie Map remove time = " + removeTime / count + " ms");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
// sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory)
beforeMemory = DataStructures.getMemoryUse();
if (debugTime)
beforeAddSortedTime = System.currentTimeMillis();
for (int i = 0; i < sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
if (validateStructure && !(trieMap.size() == (i + 1))) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && !trieMap.contains(string)) {
System.err.println("YIKES!! " + item + " doesn't exist.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime - beforeAddSortedTime;
if (debug > 0)
System.out.println("Trie Map add time = " + addSortedTime + " ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory - beforeMemory;
if (debug > 0)
System.out.println("Trie Map memory use = " + (memory / (count + 1)) + " bytes");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
if (debug > 1)
System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime)
beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trieMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime - beforeLookupTime;
if (debug > 0)
System.out.println("Trie Map lookup time = " + lookupTime / (count + 1) + " ms");
}
if (debugTime)
beforeRemoveSortedTime = System.currentTimeMillis();
for (int i = sorted.length - 1; i >= 0; i
int item = sorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
if (validateStructure && !(trieMap.size() == i)) {
System.err.println("YIKES!! " + item + " caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && trieMap.contains(string)) {
System.err.println("YIKES!! " + item + " still exists.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime - beforeRemoveSortedTime;
if (debug > 0)
System.out.println("Trie Map remove time = " + removeSortedTime + " ms");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
return false;
} else
System.out.println("Trie Map invalidity check. contains=" + contains + " removed=" + removed);
if (testResults[testIndex] == null)
testResults[testIndex] = new long[6];
testResults[testIndex][0] += addTime / count;
testResults[testIndex][1] += removeTime / count;
testResults[testIndex][2] += addSortedTime;
testResults[testIndex][3] += removeSortedTime;
testResults[testIndex][4] += lookupTime / (count + 1);
testResults[testIndex++][5] += memory / (count + 1);
if (debug > 1)
System.out.println();
}
return true;
}
private static final String getTestResults(int testNumber, String[] names, long[][] results) {
StringBuilder resultsBuilder = new StringBuilder();
String format = "%-25s %-10s %-15s %-15s %-20s %-15s %-15s\n";
Formatter formatter = new Formatter(resultsBuilder, Locale.US);
formatter = formatter.format(format, "Data Structure", "Add time", "Remove time", "Sorted add time", "Sorted remove time", "Lookup time", "Size");
double KB = 1000;
double MB = 1000 * KB;
double SECOND = 1000;
double MINUTES = 60 * SECOND;
for (int i = 0; i < TESTS; i++) {
String name = names[i];
long[] result = results[i];
if (name != null && result != null) {
double addTime = result[0];
addTime /= testNumber;
String addTimeString = null;
if (addTime > MINUTES) {
addTime /= MINUTES;
addTimeString = FORMAT.format(addTime) + " m";
} else if (addTime > SECOND) {
addTime /= SECOND;
addTimeString = FORMAT.format(addTime) + " s";
} else {
addTimeString = FORMAT.format(addTime) + " ms";
}
double removeTime = result[1];
removeTime /= testNumber;
String removeTimeString = null;
if (removeTime > MINUTES) {
removeTime /= MINUTES;
removeTimeString = FORMAT.format(removeTime) + " m";
} else if (removeTime > SECOND) {
removeTime /= SECOND;
removeTimeString = FORMAT.format(removeTime) + " s";
} else {
removeTimeString = FORMAT.format(removeTime) + " ms";
}
// sorted
double addSortedTime = result[2];
addSortedTime /= testNumber;
String sortedAddTimeString = null;
if (addSortedTime > MINUTES) {
addSortedTime /= MINUTES;
sortedAddTimeString = FORMAT.format(addSortedTime) + " m";
} else if (addSortedTime > SECOND) {
addSortedTime /= SECOND;
sortedAddTimeString = FORMAT.format(addSortedTime) + " s";
} else {
sortedAddTimeString = FORMAT.format(addSortedTime) + " ms";
}
double removeSortedTime = result[3];
removeSortedTime /= testNumber;
String sortedRemoveTimeString = null;
if (removeSortedTime > MINUTES) {
removeSortedTime /= MINUTES;
sortedRemoveTimeString = FORMAT.format(removeSortedTime) + " m";
} else if (removeSortedTime > SECOND) {
removeSortedTime /= SECOND;
sortedRemoveTimeString = FORMAT.format(removeSortedTime) + " s";
} else {
sortedRemoveTimeString = FORMAT.format(removeSortedTime) + " ms";
}
double lookupTime = result[4];
lookupTime /= testNumber;
String lookupTimeString = null;
if (lookupTime > MINUTES) {
lookupTime /= MINUTES;
lookupTimeString = FORMAT.format(lookupTime) + " m";
} else if (lookupTime > SECOND) {
lookupTime /= SECOND;
lookupTimeString = FORMAT.format(lookupTime) + " s";
} else {
lookupTimeString = FORMAT.format(lookupTime) + " ms";
}
double size = result[5];
size /= testNumber;
String sizeString = null;
if (size > MB) {
size = size / MB;
sizeString = FORMAT.format(size) + " MB";
} else if (size > KB) {
size = size / KB;
sizeString = FORMAT.format(size) + " KB";
} else {
sizeString = FORMAT.format(size) + " Bytes";
}
formatter = formatter.format(format, name, addTimeString, removeTimeString, sortedAddTimeString,
sortedRemoveTimeString, lookupTimeString, sizeString);
}
}
return resultsBuilder.toString();
}
private static final String getPathMapString(Graph.Vertex<Integer> start, Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map) {
StringBuilder builder = new StringBuilder();
for (Graph.Vertex<Integer> v : map.keySet()) {
Graph.CostPathPair<Integer> pair = map.get(v);
builder.append("From ").append(start.getValue()).append(" to vertex=").append(v.getValue()).append("\n");
if (pair != null)
builder.append(pair.toString()).append("\n");
}
return builder.toString();
}
private static final String getPathMapString(Map<Vertex<Integer>, Map<Vertex<Integer>, Set<Edge<Integer>>>> paths) {
StringBuilder builder = new StringBuilder();
for (Graph.Vertex<Integer> v : paths.keySet()) {
Map<Vertex<Integer>, Set<Edge<Integer>>> map = paths.get(v);
for (Graph.Vertex<Integer> v2 : map.keySet()) {
builder.append("From=").append(v.getValue()).append(" to=").append(v2.getValue()).append("\n");
Set<Graph.Edge<Integer>> path = map.get(v2);
builder.append(path).append("\n");
}
}
return builder.toString();
}
private static final String getWeightMapString(Map<Vertex<Integer>, Map<Vertex<Integer>, Integer>> paths) {
StringBuilder builder = new StringBuilder();
for (Graph.Vertex<Integer> v : paths.keySet()) {
Map<Vertex<Integer>, Integer> map = paths.get(v);
for (Graph.Vertex<Integer> v2 : map.keySet()) {
builder.append("From=").append(v.getValue()).append(" to=").append(v2.getValue()).append("\n");
Integer weight = map.get(v2);
builder.append(weight).append("\n");
}
}
return builder.toString();
}
private static final long getMemoryUse() {
putOutTheGarbage();
long totalMemory = Runtime.getRuntime().totalMemory();
putOutTheGarbage();
long freeMemory = Runtime.getRuntime().freeMemory();
return (totalMemory - freeMemory);
}
private static final void putOutTheGarbage() {
collectGarbage();
collectGarbage();
}
private static final long fSLEEP_INTERVAL = 75;
private static final void collectGarbage() {
try {
System.gc();
Thread.sleep(fSLEEP_INTERVAL);
System.runFinalization();
Thread.sleep(fSLEEP_INTERVAL);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
|
package aid.lib.myshows;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.security.MessageDigest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class MyshowsAPI {
final protected String URL_API_LOGIN="http://api.myshows.ru/profile/login?login=%1$s&password=%2$s";
final protected String URL_API_SHOWS="http://api.myshows.ru/profile/shows/";
final protected String URL_API_EPISODES_UNWATCHED="http://api.myshows.ru/profile/episodes/unwatched/";
final protected String URL_API_EPISODES_NEXT="http://api.myshows.ru/profile/episodes/next/";
final protected String URL_API_EPISODES_SEEN="http://api.myshows.ru/profile/shows/%1$d/";
final protected String URL_API_EPISODE_CHECK="http://api.myshows.ru/profile/episodes/check/%1$d";
final protected String URL_API_EPISODE_CHECK_RATIO="http://api.myshows.ru/profile/episodes/check/%1$d?rating=%2$d";
final protected String URL_API_EPISODE_UNCHECK="http://api.myshows.ru/profile/episodes/uncheck/%1$d";
protected String user=null;
protected String password=null;
protected HttpClient httpClient=null;
public MyshowsAPI(String _user, String _password) {
user=_user;
// get md5 hash of password
try {
MessageDigest algorithm=MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(_password.getBytes());
byte[] hashDigest=algorithm.digest();
StringBuffer hexString=new StringBuffer();
for ( int i=0; i<hashDigest.length; i++ ) {
String hex=Integer.toHexString( 0xFF & hashDigest[i] );
if ( hex.length()==1 ) {
hex="0"+hex;
}
hexString.append(hex);
}
password=hexString.toString();
// password="57da8c667d17b1b98b6c203cb1fc3d62";
// debug
System.out.println("password: "+password);
httpClient = new DefaultHttpClient();
} catch (Exception e) {
System.err.println("--- oops: "+e.toString());
e.printStackTrace();
password=null;
}
}
public boolean login() {
if ( httpClient==null ) {
// debug
System.err.println("--- password=null");
return false;
}
String URLs=String.format(URL_API_LOGIN, user, password);
try {
HttpGet request = new HttpGet(URLs);
HttpResponse response = httpClient.execute(request);
// TODO: rewrite checking logged in (?)
if ( response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK ) {
request.abort(); // ~ close connection (?)
return true;
} else {
HttpEntity entity=response.getEntity();
if ( entity!=null ) {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader( entity.getContent() )
);
String answer = "";
String line;
while ( (line = inputStream.readLine()) != null ) {
answer += (line + "\n");
}
request.abort(); // ~ close connection (?)
System.out.println("answer: >>>\n" + answer + "<<<");
}
}
} catch (Exception e) {
System.err.println("--- oops: "+e.getMessage());
e.printStackTrace();
}
return false;
}
public String getShows() {
if ( httpClient==null ) {
return null;
}
try {
HttpGet request=new HttpGet(URL_API_SHOWS);
HttpResponse response=httpClient.execute(request);
HttpEntity entity=response.getEntity();
if ( entity!=null ) {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader( entity.getContent() )
);
String answer = "";
String line;
while ( (line = inputStream.readLine()) != null ) {
answer += (line + "\n");
}
request.abort(); // ~ close connection (?)
// debug
System.out.println("answer: >>>\n" + answer + "<<<");
if ( response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK ) {
return answer;
} else {
return null;
}
}
} catch (Exception e) {
System.err.println("--- oops: "+e.getMessage());
e.printStackTrace();
}
return null;
}
public String getUnwatchedEpisodes() {
if ( httpClient==null ) {
return null;
}
try {
HttpGet request=new HttpGet(URL_API_EPISODES_UNWATCHED);
HttpResponse response=httpClient.execute(request);
HttpEntity entity=response.getEntity();
if ( entity!=null ) {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader( entity.getContent() )
);
String answer = "";
String line;
while ( (line = inputStream.readLine()) != null ) {
answer += (line + "\n");
}
request.abort(); // ~ close connection (?)
// debug
System.out.println("answer: >>>\n" + answer + "<<<");
if ( response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK ) {
return answer;
} else {
return null;
}
}
} catch (Exception e) {
System.err.println("--- oops: "+e.getMessage());
e.printStackTrace();
}
return null;
}
public String getNextEpisodes() {
if ( httpClient==null ) {
return null;
}
try {
HttpGet request=new HttpGet(URL_API_EPISODES_NEXT);
HttpResponse response=httpClient.execute(request);
HttpEntity entity=response.getEntity();
if ( entity!=null ) {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader( entity.getContent() )
);
String answer = "";
String line;
while ( (line = inputStream.readLine()) != null ) {
answer += (line + "\n");
}
request.abort(); // ~ close connection (?)
// debug
System.out.println("answer: >>>\n" + answer + "<<<");
if ( response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK ) {
return answer;
} else {
return null;
}
}
} catch (Exception e) {
System.err.println("--- oops: "+e.getMessage());
e.printStackTrace();
}
return null;
}
public String getSeenEpisodes(int _show) {
if ( httpClient==null || _show<0 ) {
return null;
}
try {
String URLs=String.format(URL_API_EPISODES_SEEN, _show);
HttpGet request=new HttpGet(URLs);
HttpResponse response=httpClient.execute(request);
HttpEntity entity=response.getEntity();
if ( entity!=null ) {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader( entity.getContent() )
);
String answer = "";
String line;
while ( (line = inputStream.readLine()) != null ) {
answer += (line + "\n");
}
request.abort(); // ~ close connection (?)
// debug
System.out.println("answer: >>>\n" + answer + "<<<");
if ( response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK ) {
return answer;
} else {
return null;
}
}
} catch (Exception e) {
System.err.println("--- oops: "+e.getMessage());
e.printStackTrace();
}
return null;
}
public boolean checkEpisode(int _episode) {
return checkEpisode(_episode, -1);
}
/**
*
* @param _episode
* @param _ratio if ( _ratio<0 ) { no ratio using }
* @return true anyway :( except unauthorized
*/
public boolean checkEpisode(int _episode, int _ratio) {
if ( httpClient==null || _episode<0 ) {
// debug
System.err.println("--- no httpClient || episode");
return false;
}
String URLs=null;
if ( _ratio<0 || _ratio>5 ) {
URLs=String.format(URL_API_EPISODE_CHECK, _episode);
} else {
URLs=String.format(URL_API_EPISODE_CHECK_RATIO, _episode, _ratio); // TODO: check if ratio appears @ msh.ru
}
try {
HttpGet request = new HttpGet(URLs);
HttpResponse response = httpClient.execute(request);
if ( response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK ) {
request.abort(); // ~ close connection (?)
return true;
} else {
HttpEntity entity=response.getEntity();
if ( entity!=null ) {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader( entity.getContent() )
);
String answer = "";
String line;
while ( (line = inputStream.readLine()) != null ) {
answer += (line + "\n");
}
request.abort(); // ~ close connection (?)
System.out.println("answer: >>>\n" + answer + "<<<");
}
}
} catch (Exception e) {
System.err.println("--- oops: "+e.getMessage());
e.printStackTrace();
}
return false;
}
public boolean unCheckEpisode(int _episode) {
if ( httpClient==null || _episode<0 ) {
// debug
System.err.println("--- no httpClient || episode");
return false;
}
try {
HttpGet request = new HttpGet( String.format(URL_API_EPISODE_UNCHECK, _episode) );
HttpResponse response = httpClient.execute(request);
if ( response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK ) {
request.abort(); // ~ close connection (?)
return true;
} else {
HttpEntity entity=response.getEntity();
if ( entity!=null ) {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader( entity.getContent() )
);
String answer = "";
String line;
while ( (line = inputStream.readLine()) != null ) {
answer += (line + "\n");
}
request.abort(); // ~ close connection (?)
System.out.println("answer: >>>\n" + answer + "<<<");
}
}
} catch (Exception e) {
System.err.println("--- oops: "+e.getMessage());
e.printStackTrace();
}
return false;
}
}
|
package com.bridgewalkerapp.androidclient;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.bridgewalkerapp.androidclient.SendConfirmationDialogFragment.SendConfirmationDialogListener;
import com.bridgewalkerapp.androidclient.apidata.RequestQuote;
import com.bridgewalkerapp.androidclient.apidata.SendPayment;
import com.bridgewalkerapp.androidclient.apidata.WSQuote;
import com.bridgewalkerapp.androidclient.apidata.WSQuoteUnavailable;
import com.bridgewalkerapp.androidclient.apidata.WSSendFailed;
import com.bridgewalkerapp.androidclient.apidata.WebsocketReply;
import com.bridgewalkerapp.androidclient.apidata.WebsocketRequest.AmountType;
import com.bridgewalkerapp.androidclient.data.ParameterizedRunnable;
import com.bridgewalkerapp.androidclient.data.SendPaymentCheck;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class SendFragment extends BalanceFragment implements SendConfirmationDialogListener {
// only send new requests when either this time has
// passed or the previous result has been received
private static int REPEAT_REQUEST_QUOTE_INTERVAL = 3 * 1000;
private EditText recipientAddressEditText = null;
private EditText amountEditText = null;
private Button scanButton = null;
private RadioButton btcRadioButton = null;
private RadioGroup currencyRadioGroup = null;
private CheckBox feesOnTop = null;
private TextView infoTextView = null;
private Button sendPaymentButton = null;
private TextView sendPaymentHintTextView = null;
private Resources resources;
private long nextRequestId = 0;
private long lastRequestQuoteTimestamp = 0;
private RequestQuote lastSuccessfulRequestQuote = null;
private WSQuote lastSuccessfulQuote = null;
private SendPayment lastSendPayment = null;
private List<RequestQuote> pendingRequests = new ArrayList<RequestQuote>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_send, container, false);
this.progressBar = (ProgressBar)view.findViewById(R.id.send_fragment_progressbar);
this.contentLinearLayout = (LinearLayout)view.findViewById(R.id.send_fragment_content_linearlayout);
this.usdBalanceTextView = (TextView)view.findViewById(R.id.send_fragment_usd_balance_textview);
this.pendingEventsTextView = (TextView)view.findViewById(R.id.send_fragment_pending_events_textview);
this.recipientAddressEditText = (EditText)view.findViewById(R.id.recipient_address_edittext);
this.amountEditText = (EditText)view.findViewById(R.id.amount_edittext);
this.scanButton = (Button)view.findViewById(R.id.scan_button);
this.btcRadioButton = (RadioButton)view.findViewById(R.id.btc_radiobutton);
this.currencyRadioGroup = (RadioGroup)view.findViewById(R.id.currency_radiogroup);
this.feesOnTop = (CheckBox)view.findViewById(R.id.fees_on_top_checkbox);
this.infoTextView = (TextView)view.findViewById(R.id.info_textview);
this.sendPaymentButton = (Button)view.findViewById(R.id.send_payment_button);
this.sendPaymentHintTextView = (TextView)view.findViewById(R.id.send_payment_hint_textview);
this.scanButton.setOnClickListener(this.scanButtonOnClickListener);
this.recipientAddressEditText.addTextChangedListener(this.recipientAddressTextWatcher);
this.amountEditText.addTextChangedListener(this.amountTextWatcher);
this.currencyRadioGroup.setOnCheckedChangeListener(this.currencyOnCheckedChangeListener);
this.feesOnTop.setOnCheckedChangeListener(this.feesOnTopOnCheckedChangeListener);
this.sendPaymentButton.setOnClickListener(this.sendPaymentButtonOnClickListener);
this.resources = getResources();
return view;
}
@Override
protected void displayStatusHook() {
/* do nothing */
}
private double parseAmount() {
String amountStr = this.amountEditText.getText().toString();
double amount = 0;
try {
amount = Double.parseDouble(amountStr);
} catch (NumberFormatException e) { /* ignore */ }
return amount;
}
private RequestQuote compileRequestQuote() {
double amount = parseAmount();
long adjustedAmount = 0;
AmountType type = getAmountType();
if (type == AmountType.AMOUNT_BASED_ON_BTC) {
adjustedAmount = Math.round(amount * BackendService.BTC_BASE_AMOUNT);
} else {
adjustedAmount = Math.round(amount * BackendService.USD_BASE_AMOUNT);
}
return new RequestQuote(this.nextRequestId, type, adjustedAmount);
}
private void displayAndOrRequestQuote() {
RequestQuote rq = compileRequestQuote();
long adjustedAmount = rq.getAmount();
// display old data, if available
if (rq.isSameRequest(this.lastSuccessfulRequestQuote)) {
displayQuote(this.lastSuccessfulQuote);
}
// do not send any requests, if we are not yet fully resumed
if (!isResumed())
return;
// do not send requests too fast
if (System.currentTimeMillis() - this.lastRequestQuoteTimestamp
< REPEAT_REQUEST_QUOTE_INTERVAL)
return;
// do not send the same request again
if (rq.isSameRequest(this.lastSuccessfulRequestQuote))
return;
// do not send requests for 0
if (adjustedAmount == 0) {
return;
}
// add to pending requests
this.pendingRequests.add(rq);
this.lastRequestQuoteTimestamp = System.currentTimeMillis();
this.nextRequestId++;
this.parentActivity.getServiceUtils().sendCommand(rq, new ParameterizedRunnable() {
@Override
public void run(WebsocketReply reply) {
lastRequestQuoteTimestamp = 0;
if (reply.getReplyType() == WebsocketReply.TYPE_WS_QUOTE_UNAVAILABLE) {
WSQuoteUnavailable qu = (WSQuoteUnavailable)reply;
removePendingRequests(qu.getId(), null);
infoTextView.setText("Sorry, I was unable to get a quote.");
updateSendPaymentButton();
}
if (reply.getReplyType() == WebsocketReply.TYPE_WS_QUOTE) {
WSQuote quote = (WSQuote)reply;
removePendingRequests(quote.getId(), quote);
displayQuote(quote);
}
displayAndOrRequestQuote(); // see if we need to fire of a new request,
// as the user might have entered new
// input in the meantime
}
});
}
private void displayQuote(WSQuote quote) {
double actualFee =
(double)(quote.getUsdAccount() - quote.getUsdRecipient())
/ (double)quote.getUsdRecipient();
String infoText = resources.getString(
R.string.quote_info_text
, formatBTC(quote.getBtc())
, formatUSD(quote.getUsdRecipient())
, formatUSD(quote.getUsdAccount())
, actualFee * 100);
infoTextView.setText(infoText);
updateSendPaymentButton();
}
private SendPaymentCheck isReadyToSendPayment() {
if (parseAmount() == 0)
return new SendPaymentCheck(false, "");
String address = recipientAddressEditText.getText().toString();
if (address.equalsIgnoreCase(""))
return new SendPaymentCheck(false, "");
// see if we have quote data to do some additional checks
RequestQuote rq = compileRequestQuote();
if (rq.isSameRequest(this.lastSuccessfulRequestQuote)) {
if (!this.lastSuccessfulQuote.hasSufficientBalance()) {
String hint = this.resources.getString(R.string.insufficient_balance);
return new SendPaymentCheck(false, hint);
}
if (this.lastSuccessfulQuote.getBtc() < BackendService.MINIMUM_BTC_AMOUNT) {
String hint = this.resources.getString(R.string.minimum_amount,
formatBTC(BackendService.MINIMUM_BTC_AMOUNT));
return new SendPaymentCheck(false, hint);
}
}
return new SendPaymentCheck(true, "");
}
private void updateSendPaymentButton() {
SendPaymentCheck check = isReadyToSendPayment();
if (check.isReady()) {
this.sendPaymentButton.setEnabled(true);
this.sendPaymentHintTextView.setText("");
} else {
this.sendPaymentButton.setEnabled(false);
this.sendPaymentHintTextView.setText(check.getHint());
}
}
private AmountType getAmountType() {
if (this.currencyRadioGroup.getCheckedRadioButtonId() == R.id.usd_radiobutton) {
if (this.feesOnTop.isChecked())
return AmountType.AMOUNT_BASED_ON_USD_BEFORE_FEES;
else
return AmountType.AMOUNT_BASED_ON_USD_AFTER_FEES;
} else {
return AmountType.AMOUNT_BASED_ON_BTC;
}
}
/*
* Delete matching requests and also remove any
* older requests as their answers might have gotten lost.
* Sets the provided quote as the last successful answer.
*/
private void removePendingRequests(long id, WSQuote answer) {
Iterator<RequestQuote> it = pendingRequests.iterator();
while (it.hasNext()) {
RequestQuote prq = it.next();
if (prq.getId() == id) {
lastSuccessfulRequestQuote = prq;
lastSuccessfulQuote = answer;
}
// delete matching requests and also remove any
// older requests as their answers might have
// gotten lost
if (prq.getId() <= id)
it.remove();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult == null || scanResult.getContents() == null)
return;
BitcoinURI btcURI = BitcoinURI.parse(scanResult.getContents());
if (btcURI != null) {
this.recipientAddressEditText.setText(btcURI.getAddress());
if (btcURI.getAmount() > 0) {
this.amountEditText.setText(formatBTCForEditText(btcURI.getAmount()));
this.btcRadioButton.setChecked(true);
}
}
}
private android.widget.CompoundButton.OnCheckedChangeListener feesOnTopOnCheckedChangeListener = new android.widget.CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
displayAndOrRequestQuote();
updateSendPaymentButton();
}
};
private android.widget.RadioGroup.OnCheckedChangeListener currencyOnCheckedChangeListener = new android.widget.RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
feesOnTop.setEnabled(checkedId == R.id.usd_radiobutton);
if (checkedId == R.id.btc_radiobutton)
feesOnTop.setChecked(true);
displayAndOrRequestQuote();
updateSendPaymentButton();
}
};
private TextWatcher recipientAddressTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
updateSendPaymentButton();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
/* do nothing */
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
/* do nothing */
}
};
private TextWatcher amountTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (parseAmount() == 0)
infoTextView.setText("");
displayAndOrRequestQuote();
updateSendPaymentButton();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
/* do nothing */
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
/* do nothing */
}
};
private OnClickListener scanButtonOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(getSherlockActivity());
integrator.initiateScan();
}
};
private OnClickListener sendPaymentButtonOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// SharedPreferences settings =
// getActivity().getSharedPreferences(BackendService.BRIDGEWALKER_PREFERENCES_FILE, 0);
// SharedPreferences.Editor editor = settings.edit();
// editor.clear();
// editor.commit();
String address = recipientAddressEditText.getText().toString();
double amount = parseAmount();
long adjustedAmount = 0;
AmountType type = getAmountType();
if (type == AmountType.AMOUNT_BASED_ON_BTC) {
adjustedAmount = Math.round(amount * BackendService.BTC_BASE_AMOUNT);
} else {
adjustedAmount = Math.round(amount * BackendService.USD_BASE_AMOUNT);
}
// double check; should not be necessary
// though, as the button should be disabled then
if (!isReadyToSendPayment().isReady())
return;
// always use 0 as request id; we will not track it
SendPayment sp = new SendPayment(0, address, type, adjustedAmount);
// prepare confirmation text
String message = "";
WSQuote quote = null;
if (lastSuccessfulRequestQuote != null
&& lastSuccessfulRequestQuote.isSimilarRequest(sp)) {
quote = lastSuccessfulQuote;
}
switch (type) {
case AMOUNT_BASED_ON_BTC:
if (quote == null)
message = resources.getString(
R.string.send_payment_confirmation_text_based_on_btc
, formatBTC(adjustedAmount), address);
else
message = resources.getString(
R.string.send_payment_confirmation_text_based_on_btc_with_quote
, formatBTC(adjustedAmount)
, formatUSD(quote.getUsdRecipient()), address);
break;
case AMOUNT_BASED_ON_USD_BEFORE_FEES:
if (quote == null)
message = resources.getString(
R.string.send_payment_confirmation_text_based_on_usd_before_fees
, formatBTC(adjustedAmount), address);
else
message = resources.getString(
R.string.send_payment_confirmation_text_based_on_usd_before_fees_with_quote
, formatUSD(adjustedAmount)
, formatBTC(quote.getBtc()), address);
break;
case AMOUNT_BASED_ON_USD_AFTER_FEES:
if (quote == null)
message = resources.getString(
R.string.send_payment_confirmation_text_based_on_usd_after_fees
, formatBTC(adjustedAmount), address);
else
message = resources.getString(
R.string.send_payment_confirmation_text_based_on_usd_after_fees_with_quote
, formatUSD(adjustedAmount)
, formatBTC(quote.getBtc()), address);
break;
}
lastSendPayment = sp;
SherlockDialogFragment dialog = SendConfirmationDialogFragment.newInstance(message);
dialog.show(getActivity().getSupportFragmentManager(), "sendconfirmation");
}
};
@Override
public void onDialogPositiveClick() {
this.parentActivity.getServiceUtils().sendCommand(lastSendPayment, new ParameterizedRunnable() {
@Override
public void run(WebsocketReply reply) {
if (reply.getReplyType() == WebsocketReply.TYPE_WS_SEND_FAILED) {
WSSendFailed wsSF = (WSSendFailed)reply;
String message = resources.getString(R.string.send_payment_error)
+ " " + wsSF.getReason();
SherlockDialogFragment dialog = ErrorMessageDialogFragment.newInstance(message);
dialog.show(getActivity().getSupportFragmentManager(), "errormessage");
}
if (reply.getReplyType() == WebsocketReply.TYPE_WS_SEND_SUCCESSFUL) {
Toast.makeText(getActivity()
, R.string.send_payment_success, Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
*
* Represents the view for the grid
* @author Charlotte Dye, Humaira Orchee, Sehr Sethi
*
*/
public class GridView extends JPanel{
//The height of the grid
private static final int GRID_HEIGHT = 600;
//The width of the grid
private static final int GRID_WIDTH = 600;
//The width of each cell
private int cellWidth;
//The height of each cell
private int cellHeight;
//The array of cell data
private GridCell[][] gridCells;
/**
* Create a new GridView object
* @param gridCells The cells that will be in the grid
*/
public GridView(GridCell[][] gridCells){
this.gridCells = gridCells;
cellWidth = GRID_WIDTH / EstimationGrid.NUM_COLS;
cellHeight = GRID_HEIGHT / EstimationGrid.NUM_ROWS;
}
public void paintComponent(Graphics g){
//First we draw the grid lines
drawGridLines(g);
//Now we draw each cell
for (int i = 0; i < EstimationGrid.NUM_ROWS; i++){
for (int j = 0; j < EstimationGrid.NUM_COLS; j++){
drawCell(gridCells[i][j],i,j, g);
}
}
//We should make sure that the blocking is on top of the trees
//and the grid lines are on top of everything else
}
/**
* Draw the specified cell
* @param toDraw Cell data for drawing
* @param row The row this cell is in
* @param col The column this cell is in
*/
private void drawCell(GridCell toDraw, int row, int col, Graphics g){
//We need to calculate the boundaries of the cell
int startX = row * cellWidth;
int startY = col * cellHeight;
//First we see if it is blocked
if (toDraw.isBlocked()){
//In this case, we just block out the cell by filling it with gray
g.setColor(Color.GRAY);
g.fillRect(startX, startY, cellWidth, cellHeight);
}
else {
//Otherwise, we need to draw the trees.
//We need it to be at least 50% in this cell. I -think- this
//will be satisfied as long as the center is in the cell, but
//I'm not sure. Also, we want it to be clear enough
//that the tree is mostly in the cell--a tree that is 51% in
//this cell and 49% in another cell will be hard to figure out
//Also, should trees be able to overlap?
//What size will the trees be? All the same size or different sizes?
//Basically, we need to figure out what the constraints are
//on how the trees look/are placed in the grid and then figure
//out how to satisfy those constraints.
//Additionally, does it matter if we put all green trees down
//before red trees? If so, what do we do to make sure this
//doesn't cause issues
if (toDraw.getNumGreenTrees() > 0){
//Draw green trees
}
if (toDraw.getNumRedTrees() > 0){
//Draw red trees
}
}
}
/**
* Draws the vertical and horizontal lines for the grid
* @param g The graphics to use to draw
*/
private void drawGridLines(Graphics g) {
//This will draw the vertical lines
for (int i = 0; i <= EstimationGrid.NUM_COLS; i++){
g.drawLine(i*cellWidth,0,i*cellWidth, GRID_HEIGHT);
}
//This will draw the horizontal lines
for (int i = 0; i <= EstimationGrid.NUM_ROWS; i++){
g.drawLine(0,i*cellHeight,GRID_WIDTH, i*cellHeight);
}
}
}
|
package com.kduda.battleships.models.board;
import com.kduda.battleships.models.units.GroundLevelUnit;
import com.kduda.battleships.models.units.Plane;
import com.kduda.battleships.models.units.Unit;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.Parent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.List;
public class Board extends Parent {
public int units = 19;
private VBox column = new VBox();
private boolean isEnemyBoard = false;
public Board(boolean isEnemyBoard, EventHandler<? super MouseEvent> mouseClickHandler,
EventHandler<? super MouseEvent> mouseEnteredHandler,
EventHandler<? super MouseEvent> mouseExitedHandler) {
this.isEnemyBoard = isEnemyBoard;
for (int y = 0; y < 22; y++) {
HBox row = new HBox();
for (int x = 0; x < 14; x++) {
Cell cell = new Cell(x, y, this);
cell.setOnMouseClicked(mouseClickHandler);
cell.setOnMouseEntered(mouseEnteredHandler);
cell.setOnMouseExited(mouseExitedHandler);
row.getChildren().add(cell);
}
column.getChildren().add(row);
}
getChildren().add(column);
}
public boolean placeUnit(Unit unit, Position cellPosition) {
boolean wasUnitPlaced;
if (unit instanceof GroundLevelUnit)
wasUnitPlaced = placeGroundLevelUnit((GroundLevelUnit) unit, cellPosition);
else
wasUnitPlaced = placePlane((Plane) unit, cellPosition);
return wasUnitPlaced;
}
private boolean placeGroundLevelUnit(GroundLevelUnit unit, Position cellPosition) {
if (unit.getOrientation() == Orientation.VERTICAL) {
if (isVerticalLocationValid(unit, cellPosition)) placeVerticalUnit(unit, cellPosition);
else return false;
} else {
if (isHorizontalLocationValid(unit, cellPosition)) placeHorizontalUnit(unit, cellPosition);
else return false;
}
return true;
}
private boolean isVerticalLocationValid(Unit unit, Position cellPosition) {
int unitLength = unit.getLength();
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
for (int i = yPosition; i < yPosition + unitLength; i++) {
if (!isValidPoint(xPosition, i)) return false;
Cell cell = getCell(xPosition, i);
if (!cell.isSurfaceValid(unit)) return false;
if (!cell.isEmpty()) return false;
for (Cell neighbor : getAdjacentCells(xPosition, i))
if (!neighbor.isEmpty()) return false;
}
return true;
}
private boolean isHorizontalLocationValid(Unit unit, Position cellPosition) {
int unitLength = unit.getLength();
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
for (int i = xPosition; i < xPosition + unitLength; i++) {
if (!isValidPoint(i, yPosition)) return false;
Cell cell = getCell(i, yPosition);
if (!cell.isSurfaceValid(unit)) return false;
if (!cell.isEmpty()) return false;
for (Cell neighbor : getAdjacentCells(i, yPosition))
if (!neighbor.isEmpty()) return false;
}
return true;
}
private void placeVerticalUnit(Unit unit, Position cellPosition) {
int unitLength = unit.getLength();
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
for (int i = yPosition; i < yPosition + unitLength; i++) {
Cell cell = getCell(xPosition, i);
placeUnitInCell(unit,cell);
}
}
private void placeHorizontalUnit(Unit unit, Position cellPosition) {
int unitLength = unit.getLength();
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
for (int i = xPosition; i < xPosition + unitLength; i++) {
Cell cell = getCell(i, yPosition);
placeUnitInCell(unit,cell);
}
}
private boolean placePlane(Plane plane, Position cellPosition) {
switch (plane.getDirection()) {
case North:
if (isNorthLocationValid(plane, cellPosition)) placePlaneNorth(plane, cellPosition);
else return false;
break;
case East:
if (isEastLocationValid(plane, cellPosition)) placePlaneEast(plane, cellPosition);
else return false;
break;
case South:
if (isSouthLocationValid(plane, cellPosition)) placePlaneSouth(plane, cellPosition);
else return false;
break;
case West:
if (isWestLocationValid(plane, cellPosition)) placePlaneWest(plane, cellPosition);
else return false;
break;
}
return true;
}
private boolean isNorthLocationValid(Plane plane, Position cellPosition) {
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
int length = plane.getLength();
if (!isVerticalLocationPlaneValid(xPosition, yPosition, length)) return false;
//noinspection RedundantIfStatement
if (!areHorizontalNeighborsValid(xPosition, yPosition)) return false;
return true;
}
private boolean isEastLocationValid(Plane plane, Position cellPosition) {
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
if (!isHorizontalLocationValid(plane, cellPosition)) return false;
//noinspection RedundantIfStatement
if (!areVerticalNeighborsValid(xPosition, yPosition)) return false;
return true;
}
private boolean isSouthLocationValid(Plane plane, Position cellPosition) {
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
if (!isVerticalLocationValid(plane, cellPosition)) return false;
//noinspection RedundantIfStatement
if (!areHorizontalNeighborsValid(xPosition, yPosition)) return false;
return true;
}
private boolean isWestLocationValid(Plane plane, Position cellPosition) {
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
int length = plane.getLength();
if (!isHorizontalLocationPlaneValid(xPosition, yPosition, length)) return false;
//noinspection RedundantIfStatement
if (!areVerticalNeighborsValid(xPosition, yPosition)) return false;
return true;
}
private boolean isVerticalLocationPlaneValid(int xPosition, int yPosition, int length) {
for (int i = yPosition; i > yPosition - length; i
if (!isValidPoint(xPosition, i)) return false;
Cell cell = getCell(xPosition, i);
if (!cell.isEmpty()) return false;
for (Cell neighbor : getAdjacentCells(xPosition, i))
if (!neighbor.isEmpty()) return false;
}
return true;
}
private boolean isHorizontalLocationPlaneValid(int xPosition, int yPosition, int length) {
for (int i = xPosition; i > xPosition - length; i
if (!isValidPoint(i, yPosition)) return false;
Cell cell = getCell(i, yPosition);
if (!cell.isEmpty()) return false;
for (Cell neighbor : getAdjacentCells(i, yPosition))
if (!neighbor.isEmpty()) return false;
}
return true;
}
private boolean areHorizontalNeighborsValid(int xPosition, int yPosition) {
if (!isValidPlacementCell(xPosition - 1, yPosition)) return false;
//noinspection RedundantIfStatement
if (!isValidPlacementCell(xPosition + 1, yPosition)) return false;
return true;
}
private boolean areVerticalNeighborsValid(int xPosition, int yPosition) {
if (!isValidPlacementCell(xPosition, yPosition - 1)) return false;
//noinspection RedundantIfStatement
if (!isValidPlacementCell(xPosition, yPosition + 1)) return false;
return true;
}
private boolean isValidPlacementCell(int xPosition, int yPosition) {
if (!isValidPoint(xPosition, yPosition)) return false;
Cell cell = getCell(xPosition, yPosition);
if (!cell.isEmpty()) return false;
for (Cell neighbor : getAdjacentCells(xPosition, yPosition))
if (!neighbor.isEmpty()) return false;
return true;
}
private void placePlaneNorth(Plane plane, Position cellPosition) {
int unitLength = plane.getLength();
int xPosition = cellPosition.getX();
int yPosition = cellPosition.getY();
placeVerticalPlaneBody(plane, unitLength, xPosition, yPosition);
placeHorizontalPlaneWings(plane, xPosition, yPosition);
}
private void placeVerticalPlaneBody(Plane plane, int unitLength, int xPosition, int yPosition) {
for (int i = yPosition; i > yPosition - unitLength; i
Cell cell = getCell(xPosition, i);
placeUnitInCell(plane, cell);
}
}
private void placePlaneEast(Plane plane, Position cellPosition) {
//TODO: implement
throw new UnsupportedOperationException();
}
private void placePlaneSouth(Plane plane, Position cellPosition) {
//TODO: implement
throw new UnsupportedOperationException();
}
private void placePlaneWest(Plane plane, Position cellPosition) {
//TODO: implement
throw new UnsupportedOperationException();
}
private void placeHorizontalPlaneWings(Plane plane, int xPosition, int yPosition) {
Cell cell = getCell(xPosition - 1, yPosition);
placeUnitInCell(plane, cell);
cell = getCell(xPosition + 1, yPosition);
placeUnitInCell(plane, cell);
}
private void placeUnitInCell(Unit unit, Cell cell) {
cell.setUnit(unit);
if (!this.isEnemyBoard) {
//TODO: rozne kolory dla roznych jednostek
cell.setColors(Color.WHITE, Color.GREEN);
cell.saveCurrentColors();
}
}
private boolean isValidPoint(int x, int y) {
return x >= 0 && x < 14 && y >= 0 && y < 22;
}
public Cell getCell(int x, int y) {
HBox row = (HBox) column.getChildren().get(y);
return (Cell) row.getChildren().get(x);
}
private Cell[] getAdjacentCells(int x, int y) {
Position[] positions = new Position[]{
new Position(x, y - 1),
new Position(x + 1, y - 1),
new Position(x + 1, y),
new Position(x + 1, y + 1),
new Position(x, y + 1),
new Position(x - 1, y + 1),
new Position(x - 1, y),
new Position(x - 1, y - 1)
};
List<Cell> neighbors = new ArrayList<>();
for (Position position : positions) {
int xPosition = position.getX();
int yPosition = position.getY();
if (isValidPoint(xPosition, yPosition))
neighbors.add(getCell(xPosition, yPosition));
}
//noinspection ToArrayCallWithZeroLengthArrayArgument
return neighbors.toArray(new Cell[0]);
}
public void showPlacementHint(Unit unit, Cell cell) {
Position cellPosition = new Position(cell.POSITION.getX(), cell.POSITION.getY());
if (unit instanceof GroundLevelUnit) {
GroundLevelUnit currentUnit = (GroundLevelUnit) unit;
if (currentUnit.getOrientation() == Orientation.VERTICAL) {
if (isVerticalLocationValid(currentUnit, cellPosition)) {
changeColorsVertical(cell, currentUnit.getLength(), Color.GREEN, Color.GREEN);
} else {
changeColorsVertical(cell, currentUnit.getLength(), Color.RED, Color.RED);
}
} else {
if (isHorizontalLocationValid(currentUnit, cellPosition)) {
changeColorsHorizontal(cell, currentUnit.getLength(), Color.GREEN, Color.GREEN);
} else {
changeColorsHorizontal(cell, currentUnit.getLength(), Color.RED, Color.RED);
}
}
} else {
//TODO: hint dla samolotu
return;
}
}
private void changeColorsVertical(Cell cell, int length, Color fillColor, Color strokeColor) {
int xPosition = cell.POSITION.getX();
int yPosition = cell.POSITION.getY();
for (int i = yPosition; i < yPosition + length; i++) {
Cell currCell = getCell(xPosition, i);
currCell.saveCurrentColors();
currCell.setColors(fillColor, strokeColor);
}
}
private void changeColorsHorizontal(Cell cell, int length, Color fillColor, Color strokeColor) {
int xPosition = cell.POSITION.getX();
int yPosition = cell.POSITION.getY();
for (int i = xPosition; i < xPosition + length; i++) {
Cell currCell = getCell(i, yPosition);
currCell.saveCurrentColors();
currCell.setColors(fillColor, strokeColor);
}
}
public void removePlacementHint(Unit unit, Cell cell) {
if (unit instanceof GroundLevelUnit) {
GroundLevelUnit currentUnit = (GroundLevelUnit) unit;
if (currentUnit.getOrientation() == Orientation.VERTICAL) {
restoreColorsVertical(cell, currentUnit.getLength());
} else {
restoreColorsHorizontal(cell, currentUnit.getLength());
}
} else {
//TODO: restore dla samolotow
return;
}
}
private void restoreColorsVertical(Cell cell, int length) {
int xPosition = cell.POSITION.getX();
int yPosition = cell.POSITION.getY();
for (int i = yPosition; i < yPosition + length; i++) {
Cell currCell = getCell(xPosition, i);
currCell.loadSavedColors();
}
}
private void restoreColorsHorizontal(Cell cell, int length) {
int xPosition = cell.POSITION.getX();
int yPosition = cell.POSITION.getY();
for (int i = xPosition; i < xPosition + length; i++) {
Cell currCell = getCell(i, yPosition);
currCell.loadSavedColors();
}
}
}
|
package dynamake.models;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import dynamake.caching.Memoizer1;
import dynamake.commands.Command;
import dynamake.commands.DualCommand;
import dynamake.commands.DualCommandPair;
import dynamake.commands.UnwrapTransaction;
import dynamake.commands.WrapTransaction;
import dynamake.delegates.Action1;
import dynamake.delegates.Func1;
import dynamake.delegates.Runner;
import dynamake.menubuilders.CompositeMenuBuilder;
import dynamake.models.LiveModel.LivePanel;
import dynamake.models.factories.AsIsFactory;
import dynamake.models.factories.Factory;
import dynamake.numbers.Fraction;
import dynamake.transcription.DualCommandFactory;
import dynamake.transcription.DualCommandFactory2;
import dynamake.transcription.IsolatingCollector;
import dynamake.transcription.Collector;
import dynamake.transcription.Trigger;
public class CanvasModel extends Model {
private static final long serialVersionUID = 1L;
private ArrayList<Model> models;
public CanvasModel() {
models = new ArrayList<Model>();
}
public CanvasModel(ArrayList<Model> models) {
this.models = models;
}
public static class AddedModelChange {
public final int index;
public final Model model;
public AddedModelChange(int index, Model model) {
this.index = index;
this.model = model;
}
}
@Override
protected void modelScale(Fraction hChange, Fraction vChange, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
for(Model model: models)
model.scale(hChange, vChange, propCtx, propDistance, collector);
}
@Override
protected void modelAppendScale(ModelLocation location, Fraction hChange, Fraction vChange, List<DualCommand<Model>> dualCommands) {
for(Model model: models) {
int indexOfModel = indexOfModel(model);
ModelLocation childLocation = new CompositeModelLocation(location, new IndexLocation(indexOfModel));
model.appendScale(childLocation, hChange, vChange, dualCommands);
}
}
@Override
public Model modelCloneIsolated() {
ArrayList<Model> clonedModels = new ArrayList<Model>();
for(Model model: models) {
Model clone = model.cloneIsolated();
clonedModels.add(clone);
}
return new CanvasModel(clonedModels);
}
@Override
protected void modelAddContent(HashSet<Model> contained) {
for(Model model: models) {
model.addContent(contained);
}
}
@Override
protected void modelBeRemoved() {
for(Model model: models) {
model.beRemoved();
}
}
public int getModelCount() {
return models.size();
}
@Override
protected void cloneAndMap(Hashtable<Model, Model> sourceToCloneMap) {
CanvasModel clone = new CanvasModel();
clone.properties = new Hashtable<String, Object>();
// Assumed that cloning is not necessary for properties
// I.e., all property values are immutable
clone.properties.putAll(this.properties);
sourceToCloneMap.put(this, clone);
for(Model model: models) {
model.cloneAndMap(sourceToCloneMap);
Model modelClone = sourceToCloneMap.get(model);
clone.models.add(modelClone);
}
}
public static class RemovedModelChange {
public final int index;
public final Model model;
public RemovedModelChange(int index, Model model) {
this.index = index;
this.model = model;
}
}
public static class MoveModelTransaction implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location canvasSourceLocation;
private Location canvasTargetLocation;
private int indexInSource;
private int indexInTarget;
public MoveModelTransaction(Location canvasSourceLocation, Location canvasTargetLocation, int indexInSource, int indexInTarget) {
this.canvasSourceLocation = canvasSourceLocation;
this.canvasTargetLocation = canvasTargetLocation;
this.indexInSource = indexInSource;
this.indexInTarget = indexInTarget;
}
@Override
public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, Collector<Model> collector) {
CanvasModel canvasSource = (CanvasModel)canvasSourceLocation.getChild(prevalentSystem);
CanvasModel canvasTarget = (CanvasModel)canvasTargetLocation.getChild(prevalentSystem);
Model model = (Model)canvasSource.getModel(indexInSource);
int indexOfModel = canvasSource.indexOfModel(model);
canvasSource.removeModel(indexOfModel, propCtx, 0, collector);
canvasTarget.addModel(indexInTarget, model, propCtx, 0, collector);
}
}
public static class AddModelTransaction implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location canvasLocation;
private Rectangle creationBounds;
private Factory factory;
public AddModelTransaction(Location canvasLocation, Rectangle creationBounds, Factory factory) {
this.canvasLocation = canvasLocation;
this.creationBounds = creationBounds;
this.factory = factory;
}
@Override
public void executeOn(PropogationContext propCtx, Model rootPrevalentSystem, Date executionTime, Collector<Model> collector) {
CanvasModel canvas = (CanvasModel)canvasLocation.getChild(rootPrevalentSystem);
Model model = (Model)factory.create(rootPrevalentSystem, creationBounds, propCtx, 0, collector);
IsolatingCollector<Model> isolatedCollector = new IsolatingCollector<Model>(collector);
model.setProperty("X", new Fraction(creationBounds.x), propCtx, 0, isolatedCollector);
model.setProperty("Y", new Fraction(creationBounds.y), propCtx, 0, isolatedCollector);
model.setProperty("Width", new Fraction(creationBounds.width), propCtx, 0, isolatedCollector);
model.setProperty("Height", new Fraction(creationBounds.height), propCtx, 0, isolatedCollector);
canvas.addModel(model, new PropogationContext(), 0, collector);
}
}
public static class AddModelAtTransaction implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location canvasLocation;
private Rectangle creationBounds;
private Factory factory;
private int index;
public AddModelAtTransaction(Location canvasLocation, Rectangle creationBounds, Factory factory, int index) {
this.canvasLocation = canvasLocation;
this.creationBounds = creationBounds;
this.factory = factory;
this.index = index;
}
@Override
public void executeOn(PropogationContext propCtx, Model rootPrevalentSystem, Date executionTime, Collector<Model> collector) {
CanvasModel canvas = (CanvasModel)canvasLocation.getChild(rootPrevalentSystem);
Model model = (Model)factory.create(rootPrevalentSystem, creationBounds, propCtx, 0, collector);
IsolatingCollector<Model> isolatingCollector = new IsolatingCollector<>(collector);
model.setProperty("X", new Fraction(creationBounds.x), propCtx, 0, isolatingCollector);
model.setProperty("Y", new Fraction(creationBounds.y), propCtx, 0, isolatingCollector);
model.setProperty("Width", new Fraction(creationBounds.width), propCtx, 0, isolatingCollector);
model.setProperty("Height", new Fraction(creationBounds.height), propCtx, 0, isolatingCollector);
canvas.addModel(index, model, new PropogationContext(), 0, collector);
}
}
public static class AddModelNoCreationBoundsTransaction implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location canvasLocation;
private int index;
private Factory factory;
public AddModelNoCreationBoundsTransaction(Location canvasLocation, int index, Factory factory) {
this.canvasLocation = canvasLocation;
this.index = index;
this.factory = factory;
}
@Override
public void executeOn(PropogationContext propCtx, Model rootPrevalentSystem, Date executionTime, Collector<Model> collector) {
CanvasModel canvas = (CanvasModel)canvasLocation.getChild(rootPrevalentSystem);
Model model = (Model)factory.create(rootPrevalentSystem, null, propCtx, 0, collector);
canvas.addModel(index, model, new PropogationContext(), 0, collector);
}
}
public static class RemoveModelTransaction implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location canvasLocation;
private int index;
public RemoveModelTransaction(Location canvasLocation, int index) {
if(index < 0)
new String();
this.canvasLocation = canvasLocation;
this.index = index;
}
@Override
public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, Collector<Model> collector) {
CanvasModel canvas = (CanvasModel)canvasLocation.getChild(prevalentSystem);
Model modelToRemove = canvas.getModel(index);
canvas.removeModel(index, propCtx, 0, collector);
modelToRemove.beRemoved();
}
}
public void addModel(Model model, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
addModel(models.size(), model, propCtx, propDistance, collector);
}
public Model getModel(int index) {
return models.get(index);
}
public void addModel(int index, Model model, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
models.add(index, model);
collector.registerAffectedModel(this);
sendChanged(new AddedModelChange(index, model), propCtx, propDistance, 0, collector);
}
public void removeModel(Model model, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
int indexOfModel = indexOfModel(model);
removeModel(indexOfModel, propCtx, propDistance, collector);
}
public void removeModel(int index, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
Model model = models.get(index);
models.remove(index);
collector.registerAffectedModel(this);
sendChanged(new RemovedModelChange(index, model), propCtx, propDistance, 0, collector);
}
public static void move(CanvasModel canvasSource, CanvasModel canvasTarget, Model model, int indexInTarget, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
int indexOfModel = canvasSource.indexOfModel(model);
canvasSource.models.remove(indexOfModel);
canvasSource.sendChanged(new RemovedModelChange(indexOfModel, model), propCtx, propDistance, 0, collector);
canvasTarget.models.add(indexInTarget, model);
canvasTarget.sendChanged(new AddedModelChange(indexInTarget, model), propCtx, propDistance, 0, collector);
}
public int indexOfModel(Model model) {
return models.indexOf(model);
}
public ModelLocation getLocationOf(Model model) {
int indexOfModel = indexOfModel(model);
return new IndexLocation(indexOfModel);
}
private static class CanvasPanel extends JLayeredPane implements ModelComponent {
private static final long serialVersionUID = 1L;
private CanvasModel model;
private ModelTranscriber modelTranscriber;
private HashSet<Model> shownModels = new HashSet<Model>();
private Memoizer1<Model, Binding<ModelComponent>> modelToModelComponentMap;
public CanvasPanel(final ModelComponent rootView, CanvasModel model, final ModelTranscriber modelTranscriber, final ViewManager viewManager) {
this.model = model;
this.modelTranscriber = modelTranscriber;
setLayout(null);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setOpaque(true);
modelToModelComponentMap = new Memoizer1<Model, Binding<ModelComponent>>(new Func1<Model, Binding<ModelComponent>>() {
@Override
public Binding<ModelComponent> call(Model model) {
final Binding<ModelComponent> modelView = model.createView(rootView, viewManager, modelTranscriber.extend(new IndexLocator(CanvasPanel.this.model, model)));
Rectangle bounds = new Rectangle(
((Fraction)model.getProperty("X")).intValue(),
((Fraction)model.getProperty("Y")).intValue(),
((Fraction)model.getProperty("Width")).intValue(),
((Fraction)model.getProperty("Height")).intValue()
);
((JComponent)modelView.getBindingTarget()).setBounds(bounds);
return modelView;
}
});
}
@Override
public Model getModelBehind() {
return model;
}
@Override
public void appendContainerTransactions(
final LivePanel livePanel, CompositeMenuBuilder menuBuilder, final ModelComponent child) {
menuBuilder.addMenuBuilder("Remove", new Trigger<Model>() {
@Override
public void run(Collector<Model> collector) {
collector.execute(new DualCommandFactory<Model>() {
@Override
public void createDualCommands(List<DualCommand<Model>> dualCommands) {
Location canvasLocation = modelTranscriber.getModelLocation();
CanvasModel.appendRemoveTransaction(dualCommands, livePanel, child, canvasLocation, model);
}
});
}
});
}
@Override
public void appendTransactions(ModelComponent livePanel, CompositeMenuBuilder menuBuilder) {
Model.appendComponentPropertyChangeTransactions(livePanel, model, modelTranscriber, menuBuilder);
// The canvas model can be unwrap only if all the following cases are true:
// - It has one ore more models contained in itself
// - Its parent is a canvas model; i.e. canvases can only be unwrapped into other canvases
if(model.models.size() > 0 && ModelComponent.Util.getParent(this).getModelBehind() instanceof CanvasModel) {
menuBuilder.addMenuBuilder("Unwrap", new Trigger<Model>() {
@Override
public void run(Collector<Model> collector) {
collector.execute(new DualCommandFactory<Model>() {
@Override
public void createDualCommands(List<DualCommand<Model>> dualCommands) {
CanvasModel.appendUnwrapTransaction(dualCommands, CanvasPanel.this);
}
});
}
});
}
}
@Override
public void appendDroppedTransactions(ModelComponent livePanel, ModelComponent target, Rectangle droppedBounds, CompositeMenuBuilder menuBuilder) {
Model.appendGeneralDroppedTransactions(livePanel, this, target, droppedBounds, menuBuilder);
}
@Override
public void appendDropTargetTransactions(final ModelComponent livePanel,
final ModelComponent dropped, final Rectangle droppedBounds, final Point dropPoint, CompositeMenuBuilder menuBuilder) {
if(dropped.getModelTranscriber().getParent() != null &&
dropped.getModelTranscriber().getParent() != CanvasPanel.this.modelTranscriber &&
!isContainerOf(dropped.getModelTranscriber(), this.modelTranscriber) /*Dropee cannot be child of dropped*/) {
menuBuilder.addMenuBuilder("Move", new Trigger<Model>() {
@Override
public void run(Collector<Model> collector) {
final ModelComponent modelToMove = dropped;
// Reference is closest common ancestor
collector.execute(new DualCommandFactory2<Model>() {
ModelComponent source;
ModelComponent targetOver;
ModelComponent referenceMC;
@Override
public Model getReference() {
ModelComponent.Util.getParent(modelToMove);
targetOver = CanvasPanel.this;
referenceMC = ModelComponent.Util.closestCommonAncestor(source, targetOver);
return referenceMC.getModelBehind();
}
@Override
public void createDualCommands(Location location, List<DualCommand<Model>> dualCommands) {
ModelLocation locationOfSource = new CompositeModelLocation(
(ModelLocation)location,
ModelComponent.Util.locationFromAncestor(referenceMC, source)
);
ModelLocation locationOfTarget = new CompositeModelLocation(
(ModelLocation)location,
ModelComponent.Util.locationFromAncestor(referenceMC, targetOver)
);
CanvasModel.appendMoveTransaction(dualCommands, (LivePanel)livePanel, source, modelToMove, targetOver, droppedBounds.getLocation(), locationOfSource, locationOfTarget);
}
});
}
});
}
}
private boolean isContainerOf(ModelTranscriber container, ModelTranscriber item) {
ModelTranscriber parent = item.getParent();
if(parent != null) {
if(parent == container)
return true;
return isContainerOf(container, parent);
}
return false;
}
@Override
public ModelTranscriber getModelTranscriber() {
return modelTranscriber;
}
@Override
public DualCommandFactory<Model> getImplicitDropAction(ModelComponent target) {
return null;
}
@Override
public void initialize() {
}
@Override
public void visitTree(Action1<ModelComponent> visitAction) {
for(Component child: getComponents())
((ModelComponent)child).visitTree(visitAction);
visitAction.run(this);
}
}
public static void appendUnwrapTransaction(List<DualCommand<Model>> dualCommands, ModelComponent toUnwrap) {
ModelComponent parent = ModelComponent.Util.getParent(toUnwrap);
CanvasModel target = (CanvasModel)parent.getModelBehind();
CanvasModel modelToBeUnwrapped = (CanvasModel)toUnwrap.getModelBehind();
Location targetLocation = parent.getModelTranscriber().getModelLocation();
int indexOfWrapper = target.indexOfModel(modelToBeUnwrapped);
ModelLocation wrapperLocationInTarget = new CanvasModel.IndexLocation(indexOfWrapper);
Rectangle creationBoundsInSelection = new Rectangle(
((Number)modelToBeUnwrapped.getProperty("X")).intValue(),
((Number)modelToBeUnwrapped.getProperty("Y")).intValue(),
((Number)modelToBeUnwrapped.getProperty("Width")).intValue(),
((Number)modelToBeUnwrapped.getProperty("Height")).intValue()
);
// Each of the model locations should be moved from target to wrapper
Location[] modelLocations = new Location[modelToBeUnwrapped.models.size()];
for(int i = 0; i < modelLocations.length; i++) {
ModelComponent view = (ModelComponent)((JComponent)toUnwrap).getComponent(i);
modelLocations[i] = view.getModelTranscriber().getModelLocation();
}
dualCommands.add(new DualCommandPair<Model>(
new UnwrapTransaction(targetLocation, wrapperLocationInTarget, creationBoundsInSelection),
new WrapTransaction(targetLocation, creationBoundsInSelection, modelLocations)
));
}
public static void appendRemoveTransaction(List<DualCommand<Model>> dualCommands, LivePanel livePanel, ModelComponent child, Location canvasLocation, CanvasModel model) {
int indexOfModel = model.indexOfModel(child.getModelBehind());
// TODO: Make the backward transaction
// The removed model should probably be reconstructed
// The direct structure (clone isolated) (without observers and observees) could probably be used
// where this direct structure should, afterwards, be decorated with any missing relations to observers and observees
Model childClone = child.getModelBehind().cloneDeep(); // TODO: Fix this: Not a perfect clone
Command<Model> backward = new AddModelNoCreationBoundsTransaction(canvasLocation, indexOfModel, new AsIsFactory(childClone));
dualCommands.add(new DualCommandPair<Model>(
new RemoveModelTransaction(canvasLocation, indexOfModel),
backward
));
}
public static void appendMoveTransaction(List<DualCommand<Model>> dualCommands, LivePanel livePanel, ModelComponent source, ModelComponent modelToMove, ModelComponent target, final Point moveLocation, ModelLocation canvasSourceLocation, ModelLocation canvasTargetLocation) {
int indexTarget = ((CanvasModel)target.getModelBehind()).getModelCount();
CanvasModel sourceCanvas = (CanvasModel)source.getModelBehind();
int indexSource = sourceCanvas.indexOfModel(modelToMove.getModelBehind());
CanvasModel targetCanvas = (CanvasModel)target.getModelBehind();
ModelLocation canvasTargetLocationAfter;
int indexOfTargetCanvasInSource = sourceCanvas.indexOfModel(targetCanvas);
if(indexOfTargetCanvasInSource != -1 && indexSource < indexOfTargetCanvasInSource) {
// If target canvas is contained with the source canvas, then special care needs to be taken as
// to predicting the location of target canvas after the move has taken place:
// - If index of target canvas > index of model to be moved, then the predicated index of target canvas should 1 less
int predictedIndexOfTargetCanvasInSource = indexOfTargetCanvasInSource - 1;
canvasTargetLocationAfter = new CompositeModelLocation(canvasSourceLocation, new CanvasModel.IndexLocation(predictedIndexOfTargetCanvasInSource));
} else {
canvasTargetLocationAfter = canvasTargetLocation;
}
Location modelLocationAfterMove = new CompositeModelLocation(canvasTargetLocationAfter, new CanvasModel.IndexLocation(indexTarget));
dualCommands.add(new DualCommandPair<Model>(
new CanvasModel.MoveModelTransaction(canvasSourceLocation, canvasTargetLocation, indexSource, indexTarget),
new CanvasModel.MoveModelTransaction(canvasTargetLocationAfter, canvasSourceLocation, indexTarget, indexSource)
));
dualCommands.add(new DualCommandPair<Model>(
new Model.SetPropertyTransaction(modelLocationAfterMove, "X", new Fraction(moveLocation.x)),
new Model.SetPropertyTransaction(modelLocationAfterMove, "X", modelToMove.getModelBehind().getProperty("X"))
));
dualCommands.add(new DualCommandPair<Model>(
new Model.SetPropertyTransaction(modelLocationAfterMove, "Y", new Fraction(moveLocation.y)),
new Model.SetPropertyTransaction(modelLocationAfterMove, "Y", modelToMove.getModelBehind().getProperty("Y"))
));
}
public static void appendMoveTransaction(List<DualCommand<Model>> dualCommands, LivePanel livePanel, ModelComponent source, ModelComponent modelToMove, ModelComponent target, final Point moveLocation) {
Location canvasSourceLocation = modelToMove.getModelTranscriber().getParent().getModelLocation();
ModelLocation canvasTargetLocation = target.getModelTranscriber().getModelLocation();
int indexTarget = ((CanvasModel)target.getModelBehind()).getModelCount();
CanvasModel sourceCanvas = (CanvasModel)source.getModelBehind();
int indexSource = sourceCanvas.indexOfModel(modelToMove.getModelBehind());
CanvasModel targetCanvas = (CanvasModel)target.getModelBehind();
ModelLocation canvasTargetLocationAfter;
int indexOfTargetCanvasInSource = sourceCanvas.indexOfModel(targetCanvas);
if(indexOfTargetCanvasInSource != -1 && indexSource < indexOfTargetCanvasInSource) {
// If target canvas is contained with the source canvas, then special care needs to be taken as
// to predicting the location of target canvas after the move has taken place:
// - If index of target canvas > index of model to be moved, then the predicated index of target canvas should 1 less
int predictedIndexOfTargetCanvasInSource = indexOfTargetCanvasInSource - 1;
canvasTargetLocationAfter = modelToMove.getModelTranscriber().getParent().extendLocation(new CanvasModel.IndexLocation(predictedIndexOfTargetCanvasInSource));
} else {
canvasTargetLocationAfter = canvasTargetLocation;
}
Location modelLocationAfterMove = new CompositeModelLocation(canvasTargetLocationAfter, new CanvasModel.IndexLocation(indexTarget));
dualCommands.add(new DualCommandPair<Model>(
new CanvasModel.MoveModelTransaction(canvasSourceLocation, canvasTargetLocation, indexSource, indexTarget),
new CanvasModel.MoveModelTransaction(canvasTargetLocationAfter, canvasSourceLocation, indexTarget, indexSource)
));
dualCommands.add(new DualCommandPair<Model>(
new Model.SetPropertyTransaction(modelLocationAfterMove, "X", new Fraction(moveLocation.x)),
new Model.SetPropertyTransaction(modelLocationAfterMove, "X", modelToMove.getModelBehind().getProperty("X"))
));
dualCommands.add(new DualCommandPair<Model>(
new Model.SetPropertyTransaction(modelLocationAfterMove, "Y", new Fraction(moveLocation.y)),
new Model.SetPropertyTransaction(modelLocationAfterMove, "Y", modelToMove.getModelBehind().getProperty("Y"))
));
}
public static class IndexLocator implements ModelLocator {
private CanvasModel canvasModel;
private Model model;
public IndexLocator(CanvasModel canvasModel, Model model) {
this.canvasModel = canvasModel;
this.model = model;
}
@Override
public ModelLocation locate() {
int index = canvasModel.indexOfModel(model);
return new IndexLocation(index);
}
}
public static class IndexLocation implements ModelLocation {
private static final long serialVersionUID = 1L;
private int index;
public IndexLocation(int index) {
this.index = index;
}
@Override
public Object getChild(Object holder) {
/*
Instead of using indexes to locate models, id's relative to the canvas should be used.
This is not so much due to the potential efficiency gains in complex canvases, but
more due to effectiveness. More specifically, it is due to models being moved across
canvases meaning the index-lookup quickly becomes ineffective from an identity viewpoint.
By using id's, which are unique to canvases, it may be possible to track down models, by
keeping of the models moved out of canvases (their id's) and where to and their id in the
target canvases.
If the index is coupled with a particular version of the canvas, it may function as a
unique identifier, though.
*/
return ((CanvasModel)holder).models.get(index);
}
@Override
public Location getModelComponentLocation() {
return new ViewIndexLocation(index);
}
}
private static class ViewIndexLocation implements Location {
private int index;
public ViewIndexLocation(int index) {
this.index = index;
}
@Override
public Object getChild(Object holder) {
// Is the model at index visible? If so, then return the corresponding model. If not, then return null.
Model model = ((CanvasPanel)holder).model.models.get(index);
return ((CanvasPanel)holder).modelToModelComponentMap.get(model).getBindingTarget();
}
}
private void addModelComponent(
final ModelComponent rootView,
final CanvasPanel view, final ModelTranscriber modelTranscriber,
final ViewManager viewManager,
Hashtable<Model, Model.RemovableListener> modelToRemovableListenerMap, final Model model,
final Runner viewChangeRunner) {
Integer viewModel2 = (Integer)model.getProperty(Model.PROPERTY_VIEW);
if(viewModel2 == null)
viewModel2 = 1;
if(view.model.conformsToView(viewModel2)) {
view.shownModels.add(model);
final Binding<ModelComponent> modelView = view.modelToModelComponentMap.call(model);
viewChangeRunner.run(new Runnable() {
@Override
public void run() {
view.add((JComponent)modelView.getBindingTarget());
view.setComponentZOrder((JComponent)modelView.getBindingTarget(), 0);
}
});
}
Model.RemovableListener removableListener = Model.RemovableListener.addObserver(model, new Observer() {
@Override
public void removeObservee(Observer observee) { }
@Override
public void changed(Model sender, Object change,
PropogationContext propCtx, int propDistance, int changeDistance, Collector<Model> collector) {
if(change instanceof PropertyChanged) {
PropertyChanged propertyChanged = (PropertyChanged)change;
if(propertyChanged.name.equals(Model.PROPERTY_VIEW)) {
int modelView2 = (int)propertyChanged.value;
if(view.model.conformsToView(modelView2)) {
// Should be shown
if(!view.shownModels.contains(sender)) {
final Binding<ModelComponent> modelView = view.modelToModelComponentMap.call(model);
view.shownModels.add(sender);
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.add((JComponent)modelView.getBindingTarget());
}
});
ArrayList<Model> shownModelsSequence = new ArrayList<Model>();
for(int i = 0; i < models.size(); i++) {
Model m = models.get(i);
if(view.shownModels.contains(m))
shownModelsSequence.add(m);
}
int zOrder = shownModelsSequence.size();
for(int i = 0; i < shownModelsSequence.size(); i++) {
zOrder
Model m = shownModelsSequence.get(i);
if(m == sender)
break;
}
final int localZOrder = zOrder;
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.setComponentZOrder((JComponent)modelView.getBindingTarget(), localZOrder);
}
});
}
} else {
// Should be hidden
if(view.shownModels.contains(sender)) {
final Binding<ModelComponent> modelView = view.modelToModelComponentMap.call(model);
view.shownModels.remove(sender);
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.remove((JComponent)modelView.getBindingTarget());
}
});
}
}
}
}
}
@Override
public void addObservee(Observer observee) { }
});
modelToRemovableListenerMap.put(model, removableListener);
}
@Override
public Binding<ModelComponent> createView(final ModelComponent rootView, final ViewManager viewManager, final ModelTranscriber modelTranscriber) {
this.setLocator(modelTranscriber.getModelLocator());
final CanvasPanel view = new CanvasPanel(rootView, this, modelTranscriber, viewManager);
final RemovableListener removableListenerForBoundsChanges = Model.wrapForBoundsChanges(this, view, viewManager);
Model.loadComponentProperties(this, view, Model.COMPONENT_COLOR_BACKGROUND);
final Model.RemovableListener removableListenerForComponentPropertyChanges = Model.wrapForComponentColorChanges(this, view, view, viewManager, Model.COMPONENT_COLOR_BACKGROUND);
Model.wrapForComponentGUIEvents(this, view, view, viewManager);
final HashSet<Model> shownModels = new HashSet<Model>();
final Hashtable<Model, Model.RemovableListener> modelToRemovableListenerMap = new Hashtable<Model, Model.RemovableListener>();
for(final Model model: models) {
addModelComponent(
rootView, view, modelTranscriber, viewManager,
modelToRemovableListenerMap, model,
new Runner() {
@Override
public void run(Runnable runnable) {
runnable.run();
}
}
);
}
final Model.RemovableListener removableListener = Model.RemovableListener.addObserver(this, new ObserverAdapter() {
@Override
public void changed(Model sender, Object change, final PropogationContext propCtx, int propDistance, int changeDistance, final Collector<Model> collector) {
if(change instanceof CanvasModel.AddedModelChange) {
CanvasModel.AddedModelChange addedChange = (CanvasModel.AddedModelChange)change;
final Model model = addedChange.model;
addModelComponent(
rootView, view, modelTranscriber, viewManager,
modelToRemovableListenerMap, model,
new Runner() {
@Override
public void run(final Runnable runnable) {
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
runnable.run();
}
});
}
}
);
} else if(change instanceof CanvasModel.RemovedModelChange) {
Model removedModel = ((CanvasModel.RemovedModelChange)change).model;
Binding<ModelComponent> removedMCBinding = view.modelToModelComponentMap.get(removedModel);
removedMCBinding.releaseBinding();
view.modelToModelComponentMap.clear(removedModel);
final ModelComponent removedMC = removedMCBinding.getBindingTarget();
// Mark the model physically non-existent at this point in the current branch
// (this may change before committing the branch)
removedMC.getModelBehind().setLocator(null);
Model.RemovableListener removableListener = modelToRemovableListenerMap.get(removedModel);
removableListener.releaseBinding();
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.remove((JComponent)removedMC);
}
});
} else if(change instanceof Model.PropertyChanged && propDistance == 1) {
PropertyChanged propertyChanged = (PropertyChanged)change;
if(propertyChanged.name.equals(Model.PROPERTY_VIEW)) {
Hashtable<Integer, Model> invisibles = new Hashtable<Integer, Model>();
for(int i = 0; i < view.model.models.size(); i++) {
Model m = view.model.models.get(i);
boolean wasFound = false;
for(Component mc: view.getComponents()) {
if(m == ((ModelComponent)mc).getModelBehind()) {
wasFound = true;
break;
}
}
if(!wasFound)
invisibles.put(i, m);
}
Hashtable<Integer, Model> newVisibles = new Hashtable<Integer, Model>();
for(Map.Entry<Integer, Model> entry: invisibles.entrySet()) {
Model invisible = entry.getValue();
if(invisible.viewConformsTo((int)propertyChanged.value)) {
newVisibles.put(entry.getKey(), invisible);
}
}
ArrayList<Component> newInvisibles = new ArrayList<Component>();
for(Component mc: view.getComponents()) {
if(!((ModelComponent)mc).getModelBehind().viewConformsTo((int)propertyChanged.value)) {
newInvisibles.add(mc);
}
}
for(final Component newInvisible: newInvisibles) {
shownModels.remove(((ModelComponent)newInvisible).getModelBehind());
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.remove(newInvisible);
}
});
}
Object[] visibles = new Object[view.model.models.size()];
for(Component mc: view.getComponents()) {
boolean isVisible = shownModels.contains(mc);
if(isVisible) {
int indexOfVisible = view.model.indexOfModel(((ModelComponent)mc).getModelBehind());
visibles[indexOfVisible] = mc;
}
}
// Add the new visibles at each their respective index at model into visibles
for(Map.Entry<Integer, Model> entry: newVisibles.entrySet()) {
visibles[entry.getKey()] = entry.getValue();
}
for(int i = 0; i < visibles.length; i++) {
Object visible = visibles[i];
if(visible != null) {
if(visible instanceof Model) {
// Model to add
Model model = (Model)visible;
shownModels.add(model);
final Binding<ModelComponent> modelView = view.modelToModelComponentMap.call(model);
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.add((JComponent)modelView.getBindingTarget());
}
});
}
}
}
int zOrder = shownModels.size();
for(int i = 0; i < visibles.length; i++) {
Object visible = visibles[i];
if(visible != null) {
zOrder
if(visible instanceof Model) {
// Model to add
Model model = (Model)visible;
final Binding<ModelComponent> modelView = view.modelToModelComponentMap.call(model);
final int localZOrder = zOrder;
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.setComponentZOrder((JComponent)modelView.getBindingTarget(), localZOrder);
}
});
} else {
final JComponent component = (JComponent)visibles[i];
final int localZOrder = zOrder;
collector.afterNextTrigger(new Runnable() {
@Override
public void run() {
view.setComponentZOrder(component, localZOrder);
}
});
}
}
}
}
}
}
});
return new Binding<ModelComponent>() {
@Override
public void releaseBinding() {
removableListenerForComponentPropertyChanges.releaseBinding();
removableListenerForBoundsChanges.releaseBinding();
removableListener.releaseBinding();
}
@Override
public ModelComponent getBindingTarget() {
return view;
}
};
}
}
|
package api.products;
import java.util.List;
import api.son.MySon;
public class ProductSearch {
private Number currentItemCount;
private String etag;
private String id;
private List<Items> items;
private Number itemsPerPage;
private String kind;
private String nextLink;
private String requestId;
private String selfLink;
private Number startIndex;
private Number totalItems;
private static final String KEY = "AIzaSyDOPEJep1GSxaWylXm7Tvdytozve8odmuo";
public static ProductSearch ProductSearchFromUPC(String upc) {
String url =
"https:
+ "&alt=json";
ProductSearch ps = (ProductSearch) MySon.toObjectOther(url, ProductSearch.class);
return ps;
}
public boolean hasItems() {
if (totalItems.intValue() > 0)
return true;
return false;
}
public Number getCurrentItemCount() {
return this.currentItemCount;
}
public void setCurrentItemCount(Number currentItemCount) {
this.currentItemCount = currentItemCount;
}
public String getEtag() {
return this.etag;
}
public void setEtag(String etag) {
this.etag = etag;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public List<Items> getItems() {
return this.items;
}
public void setItems(List<Items> items) {
this.items = items;
}
public Number getItemsPerPage() {
return this.itemsPerPage;
}
public void setItemsPerPage(Number itemsPerPage) {
this.itemsPerPage = itemsPerPage;
}
public String getKind() {
return this.kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getNextLink() {
return this.nextLink;
}
public void setNextLink(String nextLink) {
this.nextLink = nextLink;
}
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getSelfLink() {
return this.selfLink;
}
public void setSelfLink(String selfLink) {
this.selfLink = selfLink;
}
public Number getStartIndex() {
return this.startIndex;
}
public void setStartIndex(Number startIndex) {
this.startIndex = startIndex;
}
public Number getTotalItems() {
return this.totalItems;
}
public void setTotalItems(Number totalItems) {
this.totalItems = totalItems;
}
}
|
package com.legit2.Demigods.Utilities;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map.Entry;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import com.legit2.Demigods.Utilities.DMiscUtil;
public class DDeityUtil
{
/*
* getDeityClass() : Returns the string of the (String)deity's classpath.
*/
public static String getDeityClass(String deity)
{
return DDataUtil.getPluginData("temp_deity_classes", deity).toString();
}
/*
* invokeDeityMethod() : Invokes a static method (with no paramaters) from inside a deity class.
*/
@SuppressWarnings("rawtypes")
public static Object invokeDeityMethod(String deityClass, String method) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
// No Paramaters
Class noparams[] = {};
// Creates a new instance of the deity class
Object obj = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).newInstance();
// Load everything else for the Deity (Listener, etc.)
Method toInvoke = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).getMethod(method, noparams);
return toInvoke.invoke(obj, (Object[])null);
}
/*
* invokeDeityMethodWithString() : Invokes a static method, with a String, from inside a deity class.
*/
public static Object invokeDeityMethodWithString(String deityClass, String method, String paramater) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
// Creates a new instance of the deity class
Object obj = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).newInstance();
// Load everything else for the Deity (Listener, etc.)
Method toInvoke = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).getMethod(method, String.class);
return toInvoke.invoke(obj, paramater);
}
/*
* invokeDeityMethodWithStringArray() : Invokes a static method, with an ArrayList, from inside a deity class.
*/
public static Object invokeDeityMethodWithStringArray(String deityClass, String method, String[] paramater) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
// Creates a new instance of the deity class
Object obj = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).newInstance();
// Load everything else for the Deity (Listener, etc.)
Method toInvoke = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).getMethod(method, String[].class);
return toInvoke.invoke(obj, (Object[]) paramater);
}
/*
* invokeDeityMethodWithPlayer() : Invokes a static method, with a Player, from inside a deity class.
*/
public static Object invokeDeityMethodWithPlayer(String deityClass, String method, Player paramater) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
// Creates a new instance of the deity class
Object obj = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).newInstance();
// Load everything else for the Deity (Listener, etc.)
Method toInvoke = Class.forName(deityClass, true, DMiscUtil.getPlugin().getClass().getClassLoader()).getMethod(method, Player.class);
return toInvoke.invoke(obj, paramater);
}
/*
* invokeDeityCommand : Invokes a deity command.
*/
@SuppressWarnings("unchecked")
public static boolean invokeDeityCommand(Player player, String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
String deity = null;
String command = args[0];
for(Entry<String, Object> entry : DDataUtil.getAllPluginData().get("temp_deity_commands").entrySet())
{
if(((ArrayList<String>) entry.getValue()).contains(command.toLowerCase()))
{
deity = entry.getKey();
break;
}
}
if(deity == null) return false;
String deityClass = getDeityClass(deity);
invokeDeityMethodWithStringArray(deityClass, command + "Command", args);
return true;
}
/*
* getLoadedDeityNames() : Returns a ArrayList<String> of all the loaded deities' names.
*/
public static ArrayList<String> getLoadedDeityNames()
{
ArrayList<String> toReturn = new ArrayList<String>();
for(String deity : DDataUtil.getAllPluginData().get("temp_deity_alliances").keySet())
{
toReturn.add(deity);
}
return toReturn;
}
/*
* getLoadedDeityAlliances() : Returns a ArrayList<String> of all the loaded deities' alliances.
*/
public static ArrayList<String> getLoadedDeityAlliances()
{
ArrayList<String> toReturn = new ArrayList<String>();
for(Object alliance : DDataUtil.getAllPluginData().get("temp_deity_alliances").values().toArray())
{
if(toReturn.contains((String) alliance)) continue;
toReturn.add((String) alliance);
}
return toReturn;
}
/*
* getDeityAlliance() : Returns a String of a loaded (String)deity's alliance.
*/
public static String getDeityAlliance(String deity)
{
String toReturn = (String) DDataUtil.getPluginData("temp_deity_alliances", deity);
return toReturn;
}
/*
* getDeityClaimItems() : Returns an ArrayList<Material> of a loaded (String)deity's claim items.
*/
@SuppressWarnings("unchecked")
public static ArrayList<Material> getDeityClaimItems(String deity)
{
ArrayList<Material> toReturn = (ArrayList<Material>) DDataUtil.getPluginData("temp_deity_claim_items", deity);
return toReturn;
}
/*
* getAllDeitiesInAlliance() : Returns a ArrayList<String> of all the loaded deities' names.
*/
public static ArrayList<String> getAllDeitiesInAlliance(String alliance)
{
ArrayList<String> toReturn = new ArrayList<String>();
for(String deity : DDataUtil.getAllPluginData().get("temp_deity_alliances").keySet())
{
if(!(getDeityAlliance(deity)).equalsIgnoreCase(alliance)) continue;
toReturn.add(deity);
}
return toReturn;
}
/*
* getAllDeityCommands() : Returns a ArrayList<String> of all the loaded deities' commands.
*/
public static ArrayList<String> getAllDeityCommands()
{
ArrayList<String> toReturn = new ArrayList<String>();
for(Entry<String, Object> deityCommands : DDataUtil.getAllPluginData().get("temp_deity_commands").entrySet())
{
toReturn.add(deityCommands.getValue().toString());
}
return toReturn;
}
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorMouseAdapter;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.Argument;
import com.maddyhome.idea.vim.command.Command;
import com.maddyhome.idea.vim.command.CommandState;
import com.maddyhome.idea.vim.common.Register;
import com.maddyhome.idea.vim.helper.CharacterHelper;
import com.maddyhome.idea.vim.helper.EditorData;
import com.maddyhome.idea.vim.helper.EditorHelper;
import com.maddyhome.idea.vim.helper.SearchHelper;
import com.maddyhome.idea.vim.key.KeyParser;
import com.maddyhome.idea.vim.undo.UndoManager;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.KeyStroke;
/**
* Provides all the insert/replace related functionality
* TODO - change cursor for the different modes
*/
public class ChangeGroup extends AbstractActionGroup
{
/**
* Creates the group
*/
public ChangeGroup()
{
// We want to know when a user clicks the mouse somewhere in the editor so we can clear any
// saved text for the current insert mode.
EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {
public void editorCreated(EditorFactoryEvent event)
{
Editor editor = event.getEditor();
editor.addEditorMouseListener(new EditorMouseAdapter() {
public void mouseClicked(EditorMouseEvent event)
{
if (!VimPlugin.isEnabled()) return;
if (CommandState.getInstance().getMode() == CommandState.MODE_INSERT ||
CommandState.getInstance().getMode() == CommandState.MODE_REPLACE)
{
clearStrokes(event.getEditor());
}
}
});
editor.getSettings().setBlockCursor(!CommandState.inInsertMode());
}
});
}
/**
* Begin insert before the cursor position
* @param editor The editor to insert into
* @param context The data context
*/
public void insertBeforeCursor(Editor editor, DataContext context)
{
initInsert(editor, context, CommandState.MODE_INSERT);
}
/**
* Begin insert before the first non-blank on the current line
* @param editor The editor to insert into
* @param context The data context
*/
public void insertBeforeFirstNonBlank(Editor editor, DataContext context)
{
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretToLineStartSkipLeading(editor));
initInsert(editor, context, CommandState.MODE_INSERT);
}
/**
* Begin insert before the start of the current line
* @param editor The editor to insert into
* @param context The data context
*/
public void insertLineStart(Editor editor, DataContext context)
{
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretToLineStart(editor));
initInsert(editor, context, CommandState.MODE_INSERT);
}
/**
* Begin insert after the cursor position
* @param editor The editor to insert into
* @param context The data context
*/
public void insertAfterCursor(Editor editor, DataContext context)
{
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretHorizontal(editor, 1, true));
initInsert(editor, context, CommandState.MODE_INSERT);
}
/**
* Begin insert after the end of the current line
* @param editor The editor to insert into
* @param context The data context
*/
public void insertAfterLineEnd(Editor editor, DataContext context)
{
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretToLineEnd(editor, true));
initInsert(editor, context, CommandState.MODE_INSERT);
}
/**
* Begin insert before the current line by creating a new blank line above the current line
* @param editor The editor to insert into
* @param context The data context
*/
public void insertNewLineAbove(Editor editor, DataContext context)
{
if (EditorHelper.getCurrentVisualLine(editor) == 0)
{
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretToLineStart(editor));
initInsert(editor, context, CommandState.MODE_INSERT);
KeyHandler.executeAction("VimEditorEnter", context);
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretVertical(editor, -1));
}
else
{
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretVertical(editor, -1));
insertNewLineBelow(editor, context);
}
}
/**
* Begin insert after the current line by creating a new blank line below the current line
* @param editor The editor to insert into
* @param context The data context
*/
public void insertNewLineBelow(Editor editor, DataContext context)
{
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretToLineEnd(editor, true));
initInsert(editor, context, CommandState.MODE_INSERT);
KeyHandler.executeAction("VimEditorEnter", context);
}
/**
* Begin insert at the location of the previous insert
* @param editor The editor to insert into
* @param context The data context
*/
public void insertAtPreviousInsert(Editor editor, DataContext context)
{
int offset = CommandGroups.getInstance().getMotion().moveCaretToFileMarkLine(editor, context, '^');
if (offset != -1)
{
MotionGroup.moveCaret(editor, context, offset);
}
insertBeforeCursor(editor, context);
}
/**
* Inserts the previously inserted text
* @param editor The editor to insert into
* @param context The data context
* @param exit true if insert mode should be exited after the insert, false should stay in insert mode
*/
public void insertPreviousInsert(Editor editor, DataContext context, boolean exit)
{
repeatInsertText(editor, context, 1);
if (exit)
{
processEscape(editor, context);
}
}
/**
* Exits insert mode and brings up the help system
* @param editor The editor to exit insert mode in
* @param context The data context
*/
public void insertHelp(Editor editor, DataContext context)
{
processEscape(editor, context);
KeyHandler.executeAction("HelpTopics", context);
}
/**
* Inserts the contents of the specified register
* @param editor The editor to insert the text into
* @param context The data context
* @param key The register name
* @return true if able to insert the register contents, false if not
*/
public boolean insertRegister(Editor editor, DataContext context, char key)
{
Register register = CommandGroups.getInstance().getRegister().getRegister(key);
if (register != null)
{
String text = register.getText();
for (int i = 0; i < text.length(); i++)
{
processKey(editor, context, KeyStroke.getKeyStroke(text.charAt(i)));
}
return true;
}
return false;
}
/**
* Inserts the character above/below the cursor at the cursor location
* @param editor The editor to insert into
* @param context The data context
* @param dir 1 for getting from line below cursor, -1 for getting from line aboe cursor
* @return true if able to get the character and insert it, false if not
*/
public boolean insertCharacterAroundCursor(Editor editor, DataContext context, int dir)
{
boolean res = false;
VisualPosition vp = editor.getCaretModel().getVisualPosition();
vp = new VisualPosition(vp.line + dir, vp.column);
int len = EditorHelper.getLineLength(editor, EditorHelper.visualLineToLogicalLine(editor, vp.line));
if (vp.column < len)
{
int offset = EditorHelper.visualPostionToOffset(editor, vp);
char ch = editor.getDocument().getChars()[offset];
processKey(editor, context, KeyStroke.getKeyStroke(ch));
res = true;
}
return res;
}
/**
* If the cursor is currently after the start of the current insert this deletes all the newly inserted text.
* Otherwise it deletes all text from the cursor back to the first non-blank in the line.
* @param editor The editor to delete the text from
* @param context The data context
* @return true if able to delete the text, false if not
*/
public boolean insertDeleteInsertedText(Editor editor, DataContext context)
{
int deleteTo = insertStart;
int offset = editor.getCaretModel().getOffset();
if (offset == insertStart)
{
deleteTo = CommandGroups.getInstance().getMotion().moveCaretToLineStartSkipLeading(editor);
}
if (deleteTo != -1)
{
deleteRange(editor, context, new TextRange(deleteTo, offset), Command.FLAG_MOT_EXCLUSIVE);
return true;
}
return false;
}
/**
* Deletes the text from the cursor to the start of the previous word
* @param editor The editor to delete the text from
* @param context The data context
* @return true if able to delete text, false if not
*/
public boolean insertDeletePreviousWord(Editor editor, DataContext context)
{
int deleteTo = insertStart;
int offset = editor.getCaretModel().getOffset();
if (offset == insertStart)
{
deleteTo = CommandGroups.getInstance().getMotion().moveCaretToNextWord(editor, -1, false);
}
if (deleteTo != -1)
{
deleteRange(editor, context, new TextRange(deleteTo, offset), Command.FLAG_MOT_EXCLUSIVE);
return true;
}
return false;
}
/**
* Begin insert/replace mode
* @param editor The editor to insert into
* @param context The data context
* @param mode The mode - inidicate insert or replace
*/
private void initInsert(Editor editor, DataContext context, int mode)
{
CommandState state = CommandState.getInstance();
insertStart = editor.getCaretModel().getOffset();
CommandGroups.getInstance().getMark().setMark(editor, context, '[', insertStart);
// If we are repeating the last insert/replace
if (state.getMode() == CommandState.MODE_REPEAT)
{
if (mode == CommandState.MODE_REPLACE)
{
processInsert(editor, context);
}
// If this command doesn't allow repeating, set the count to 1
if ((state.getCommand().getFlags() & Command.FLAG_NO_REPEAT) != 0)
{
repeatInsert(editor, context, 1);
}
else
{
repeatInsert(editor, context, state.getCommand().getCount());
}
if (mode == CommandState.MODE_REPLACE)
{
processInsert(editor, context);
}
}
// Here we begin insert/replace mode
else
{
lastInsert = state.getCommand();
strokes.clear();
inInsert = true;
if (mode == CommandState.MODE_REPLACE)
{
processInsert(editor, context);
}
state.pushState(mode, 0, KeyParser.MAPPING_INSERT);
resetCursor(editor, true);
}
}
/**
* This repeats the previous insert count times
* @param editor The editor to insert into
* @param context The data context
* @param count The number of times to repeat the previous insert
*/
private void repeatInsert(Editor editor, DataContext context, int count)
{
repeatInsertText(editor, context, count);
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretHorizontal(editor, -1, false));
}
/**
* This repeats the previous insert count times
* @param editor The editor to insert into
* @param context The data context
* @param count The number of times to repeat the previous insert
*/
private void repeatInsertText(Editor editor, DataContext context, int count)
{
for (int i = 0; i < count; i++)
{
// Treat other keys special by performing the appropriate action they represent in insert/replace mode
for (int k = 0; k < lastStrokes.size(); k++)
{
Object obj = lastStrokes.get(k);
if (obj instanceof AnAction)
{
KeyHandler.executeAction((AnAction)obj, context);
strokes.add(obj);
}
else if (obj instanceof Character)
{
processKey(editor, context, KeyStroke.getKeyStroke(((Character)obj).charValue()));
}
}
}
}
/**
* Terminate insert/replace mode after the user presses Escape or Ctrl-C
* @param editor The editor that was being edited
* @param context The data context
*/
public void processEscape(Editor editor, DataContext context)
{
logger.debug("processing escape");
int cnt = lastInsert.getCount();
// Turn off overwrite mode if we were in replace mode
if (CommandState.getInstance().getMode() == CommandState.MODE_REPLACE)
{
KeyHandler.executeAction("VimInsertReplaceToggle", context);
}
// If this command doesn't allow repeats, set count to 1
if ((lastInsert.getFlags() & Command.FLAG_NO_REPEAT) != 0)
{
cnt = 1;
}
// Save off current list of keystrokes
lastStrokes = new ArrayList(strokes);
// TODO - support . register
//CommandGroups.getInstance().getRegister().storeKeys(lastStrokes, Command.FLAG_MOT_CHARACTERWISE, '.');
// If the insert/replace command was preceded by a count, repeat again N - 1 times
repeatInsert(editor, context, cnt - 1);
CommandGroups.getInstance().getMark().setMark(editor, context, '^', editor.getCaretModel().getOffset());
CommandGroups.getInstance().getMark().setMark(editor, context, ']', editor.getCaretModel().getOffset());
CommandState.getInstance().popState();
if (!CommandState.inInsertMode())
{
resetCursor(editor, false);
}
UndoManager.getInstance().endCommand(editor);
UndoManager.getInstance().beginCommand(editor);
}
/**
* Processes the user pressing the Enter key. If this is REPLACE mode we need to turn off OVERWRITE before and
* then turn OVERWRITE back on after sending the "Enter" key.
* @param editor The editor to press "Enter" in
* @param context The data context
*/
public void processEnter(Editor editor, DataContext context)
{
if (CommandState.getInstance().getMode() == CommandState.MODE_REPLACE)
{
KeyHandler.executeAction("VimEditorToggleInsertState", context);
}
KeyHandler.executeAction("VimEditorEnter", context);
if (CommandState.getInstance().getMode() == CommandState.MODE_REPLACE)
{
KeyHandler.executeAction("VimEditorToggleInsertState", context);
}
}
/**
* Processes the user pressing the Insert key while in INSERT or REPLACE mode. This simply toggles the
* Insert/Overwrite state which updates the status bar.
* @param editor The editor to toggle the state in
* @param context The data context
*/
public void processInsert(Editor editor, DataContext context)
{
KeyHandler.executeAction("VimEditorToggleInsertState", context);
CommandState.getInstance().toggleInsertOverwrite();
inInsert = !inInsert;
}
/**
* While in INSERT or REPLACE mode the user can enter a single NORMAL mode command and then automatically
* return to INSERT or REPLACE mode.
* @param editor The editor to put into NORMAL mode for one command
* @param context The data context
*/
public void processSingleCommand(Editor editor, DataContext context)
{
CommandState.getInstance().pushState(CommandState.MODE_COMMAND, CommandState.SUBMODE_SINGLE_COMMAND,
KeyParser.MAPPING_NORMAL);
clearStrokes(editor);
}
/**
* This processes all "regular" keystrokes entered while in insert/replace mode
* @param editor The editor the character was typed into
* @param context The data context
* @param key The user entered keystroke
* @return true if this was a regular character, false if not
*/
public boolean processKey(Editor editor, DataContext context, KeyStroke key)
{
logger.debug("processKey(" + key + ")");
if (key.getKeyChar() != KeyEvent.CHAR_UNDEFINED)
{
// Regular characters are not handled by us, pass them back to Idea. We just keep track of the keystroke
// for repeating later.
strokes.add(new Character(key.getKeyChar()));
KeyHandler.getInstance().getOriginalHandler().execute(editor, key.getKeyChar(), context);
return true;
}
return false;
}
/**
* This processes all keystrokes in Insert/Replace mode that were converted into Commands. Some of these
* commands need to be saved off so the inserted/replaced text can be repeated properly later if needed.
* @param editor The editor the command was executed in
* @param context The data context
* @param cmd The command that was executed
* @return true if the command was stored for later repeat, false if not
*/
public boolean processCommand(Editor editor, DataContext context, Command cmd)
{
if ((cmd.getFlags() & Command.FLAG_SAVE_STROKE) != 0)
{
strokes.add(cmd.getAction());
return true;
}
else if ((cmd.getFlags() & Command.FLAG_CLEAR_STROKES) != 0)
{
clearStrokes(editor);
return false;
}
else
{
return false;
}
}
/**
* Clears all the keystrokes from the current insert command
* @param editor
*/
private void clearStrokes(Editor editor)
{
strokes.clear();
insertStart = editor.getCaretModel().getOffset();
}
/**
* Deletes count characters from the editor
* @param editor The editor to remove the characters from
* @param context The data context
* @param count The number of characters to delete
* @return true if able to delete, false if not
*/
public boolean deleteCharacter(Editor editor, DataContext context, int count)
{
int offset = CommandGroups.getInstance().getMotion().moveCaretHorizontal(editor, count, true);
if (offset != -1)
{
boolean res = deleteText(editor, context, editor.getCaretModel().getOffset(), offset, Command.FLAG_MOT_INCLUSIVE);
int pos = editor.getCaretModel().getOffset();
int norm = EditorHelper.normalizeOffset(editor, EditorHelper.getCurrentLogicalLine(editor), pos, false);
if (norm != pos)
{
MotionGroup.moveCaret(editor, context, norm);
}
return res;
}
return false;
}
/**
* Deletes count lines including the current line
* @param editor The editor to remove the lines from
* @param context The data context
* @param count The number of lines to delete
* @return true if able to delete the lines, false if not
*/
public boolean deleteLine(Editor editor, DataContext context, int count)
{
int start = CommandGroups.getInstance().getMotion().moveCaretToLineStart(editor);
int offset = Math.min(CommandGroups.getInstance().getMotion().moveCaretToLineEndOffset(editor,
count - 1, true) + 1, EditorHelper.getFileSize(editor));
if (offset != -1)
{
boolean res = deleteText(editor, context, start, offset, Command.FLAG_MOT_LINEWISE);
if (res && editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) &&
editor.getCaretModel().getOffset() != 0)
{
MotionGroup.moveCaret(editor, context,
CommandGroups.getInstance().getMotion().moveCaretToLineStartSkipLeadingOffset(editor, -1));
}
return res;
}
return false;
}
/**
* Delete from the cursor to the end of count - 1 lines down
* @param editor The editor to delete from
* @param context The data context
* @param count The number of lines affected
* @return true if able to delete the text, false if not
*/
public boolean deleteEndOfLine(Editor editor, DataContext context, int count)
{
int offset = CommandGroups.getInstance().getMotion().moveCaretToLineEndOffset(editor, count - 1, true);
if (offset != -1)
{
boolean res = deleteText(editor, context, editor.getCaretModel().getOffset(), offset, Command.FLAG_MOT_INCLUSIVE);
int pos = CommandGroups.getInstance().getMotion().moveCaretHorizontal(editor, -1, false);
if (pos != -1)
{
MotionGroup.moveCaret(editor, context, pos);
}
return res;
}
return false;
}
/**
* Joins count lines togetheri starting at the cursor. No count or a count of one still joins two lines.
* @param editor The editor to join the lines in
* @param context The data context
* @param count The number of lines to join
* @param spaces If true the joined lines will have one space between them and any leading space on the second line
* will be removed. If false, only the newline is removed to join the lines.
* @return true if able to join the lines, false if not
*/
public boolean deleteJoinLines(Editor editor, DataContext context, int count, boolean spaces)
{
if (count < 2) count = 2;
int lline = EditorHelper.getCurrentLogicalLine(editor);
int total = EditorHelper.getLineCount(editor);
if (lline + count > total)
{
return false;
}
return deleteJoinNLines(editor, context, lline, count, spaces);
}
/**
* Joins all the lines selected by the current visual selection.
* @param editor The editor to join the lines in
* @param context The data context
* @param range The range of the visual selection
* @param spaces If true the joined lines will have one space between them and any leading space on the second line
* will be removed. If false, only the newline is removed to join the lines.
* @return true if able to join the lines, false if not
*/
public boolean deleteJoinRange(Editor editor, DataContext context, TextRange range, boolean spaces)
{
int startLine = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int endLine = editor.offsetToLogicalPosition(range.getEndOffset()).line;
int count = endLine - startLine + 1;
if (count < 2) count = 2;
return deleteJoinNLines(editor, context, startLine, count, spaces);
}
/**
* This does the actual joining of the lines
* @param editor The editor to join the lines in
* @param context The data context
* @param startLine The starting logical line
* @param count The number of lines to join including startLine
* @param spaces If true the joined lines will have one space between them and any leading space on the second line
* will be removed. If false, only the newline is removed to join the lines.
* @return true if able to join the lines, false if not
*/
private boolean deleteJoinNLines(Editor editor, DataContext context, int startLine, int count, boolean spaces)
{
// start my moving the cursor to the very end of the first line
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretToLineEnd(editor, startLine, true));
for (int i = 1; i < count; i++)
{
int start = CommandGroups.getInstance().getMotion().moveCaretToLineEnd(editor, true);
MotionGroup.moveCaret(editor, context, start);
int offset;
if (spaces)
{
offset = CommandGroups.getInstance().getMotion().moveCaretToLineStartSkipLeadingOffset(editor, 1);
}
else
{
offset = CommandGroups.getInstance().getMotion().moveCaretToLineStartOffset(editor, 1);
}
deleteText(editor, context, editor.getCaretModel().getOffset(), offset, Command.FLAG_MOT_INCLUSIVE);
if (spaces)
{
insertText(editor, context, start, " ");
MotionGroup.moveCaret(editor, context, CommandGroups.getInstance().getMotion().moveCaretHorizontal(editor, -1, false));
}
}
return true;
}
/**
* Delete all text moved over by the supplied motion command argument.
* @param editor The editor to delete the text from
* @param context The data context
* @param count The number of times to repear the deletion
* @param rawCount The actual count entered by the user
* @param argument The motion command
* @return true if able to delete the text, false if not
*/
public boolean deleteMotion(Editor editor, DataContext context, int count, int rawCount, Argument argument, boolean isChange)
{
TextRange range = MotionGroup.getMotionRange(editor, context, count, rawCount, argument, true, false);
if (range == null && EditorHelper.getFileSize(editor) == 0)
{
return true;
}
// Delete motion commands that are not linewise become linewise if all the following are true:
// 1) The range is across multiple lines
// 2) There is only whitespace before the start of the range
// 3) There is only whitespace after the end of the range
if (!isChange && (argument.getMotion().getFlags() & Command.FLAG_MOT_LINEWISE) == 0)
{
LogicalPosition start = editor.offsetToLogicalPosition(range.getStartOffset());
LogicalPosition end = editor.offsetToLogicalPosition(range.getEndOffset());
if (start.line != end.line)
{
if (!SearchHelper.anyNonWhitespace(editor, range.getStartOffset(), -1) &&
!SearchHelper.anyNonWhitespace(editor, range.getEndOffset(), 1))
{
int flags = argument.getMotion().getFlags();
flags &= ~Command.FLAG_MOT_EXCLUSIVE;
flags &= ~Command.FLAG_MOT_INCLUSIVE;
flags |= Command.FLAG_MOT_LINEWISE;
argument.getMotion().setFlags(flags);
}
}
}
return deleteRange(editor, context, range, argument.getMotion().getFlags());
}
/**
* Delete the range of text.
* @param editor The editor to delete the text from
* @param context The data context
* @param range The range to delete
* @param type The type of deletion (FLAG_MOT_LINEWISE, FLAG_MOT_EXCLUSIVE, or FLAG_MOT_INCLUSIVE)
* @return true if able to delete the text, false if not
*/
public boolean deleteRange(Editor editor, DataContext context, TextRange range, int type)
{
if (range == null)
{
return false;
}
else
{
boolean res = deleteText(editor, context, range.getStartOffset(), range.getEndOffset(), type);
if (res && editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) &&
editor.getCaretModel().getOffset() != 0)
{
MotionGroup.moveCaret(editor, context,
CommandGroups.getInstance().getMotion().moveCaretToLineStartSkipLeadingOffset(editor, -1));
}
return res;
}
}
/**
* Begin Replace mode
* @param editor The editor to replace in
* @param context The data context
* @return true
*/
public boolean changeReplace(Editor editor, DataContext context)
{
initInsert(editor, context, CommandState.MODE_REPLACE);
return true;
}
/**
* Replace each of the next count characters with the charcter ch
* @param editor The editor to chage
* @param context The data context
* @param count The number of characters to change
* @param ch The character to change to
* @return true if able to change count characters, false if not
*/
public boolean changeCharacter(Editor editor, DataContext context, int count, char ch)
{
int col = EditorHelper.getCurrentLogicalColumn(editor);
int len = EditorHelper.getLineLength(editor);
int offset = editor.getCaretModel().getOffset();
if (len - col < count)
{
return false;
}
// Special case - if char is newline, only add one despite count
int num = count;
if (ch == '\n')
{
num = 1;
}
StringBuffer repl = new StringBuffer(count);
for (int i = 0; i < num; i++)
{
repl.append(ch);
}
replaceText(editor, context, offset, offset + count, repl.toString());
//TODO - move cursor and indent line of new char was newline
return true;
}
/**
* Each character in the supplied range gets replaced with the character ch
* @param editor The editor to change
* @param context The data context
* @param range The range to change
* @param ch The replacing character
* @return true if able to change the range, false if not
*/
public boolean changeCharacterRange(Editor editor, DataContext context, TextRange range, char ch)
{
char[] chars = editor.getDocument().getChars();
for (int i = range.getStartOffset(); i < range.getEndOffset(); i++)
{
if (i < chars.length && '\n' != chars[i])
{
replaceText(editor, context, i, i + 1, Character.toString(ch));
}
}
return true;
}
/**
* Delete count characters and then enter insert mode
* @param editor The editor to change
* @param context The data context
* @param count The number of characters to change
* @return true if able to delete count characters, false if not
*/
public boolean changeCharacters(Editor editor, DataContext context, int count)
{
boolean res = deleteCharacter(editor, context, count);
if (res)
{
initInsert(editor, context, CommandState.MODE_INSERT);
}
return res;
}
/**
* Delete count lines and then enter insert mode
* @param editor The editor to change
* @param context The data context
* @param count The number of lines to change
* @return true if able to delete count lines, false if not
*/
public boolean changeLine(Editor editor, DataContext context, int count)
{
boolean res = deleteLine(editor, context, count);
if (res)
{
insertNewLineAbove(editor, context);
}
return res;
}
/**
* Delete from the cursor to the end of count - 1 lines down and enter insert mode
* @param editor The editor to change
* @param context The data context
* @param count The number of lines to change
* @return true if able to delete count lines, false if not
*/
public boolean changeEndOfLine(Editor editor, DataContext context, int count)
{
boolean res = deleteEndOfLine(editor, context, count);
if (res)
{
insertAfterLineEnd(editor, context);
}
return res;
}
/**
* Delete the text covered by the motion command argument and enter insert mode
* @param editor The editor to change
* @param context The data context
* @param count The number of time to repeat the change
* @param rawCount The actual count entered by the user
* @param argument The motion command
* @return true if able to delete the text, false if not
*/
public boolean changeMotion(Editor editor, DataContext context, int count, int rawCount, Argument argument)
{
// TODO: Hack - find better way to do this exceptional case - at least make constants out of these strings
// Vim treats cw as ce and cW as cE if cursor is on a non-blank character
String id = ActionManager.getInstance().getId(argument.getMotion().getAction());
if (id.equals("VimMotionWordRight"))
{
if (EditorHelper.getFileSize(editor) > 0 &&
!Character.isWhitespace(editor.getDocument().getChars()[editor.getCaretModel().getOffset()]))
{
argument.getMotion().setAction(ActionManager.getInstance().getAction("VimMotionWordEndRight"));
argument.getMotion().setFlags(Command.FLAG_MOT_INCLUSIVE);
}
}
else if (id.equals("VimMotionWORDRight"))
{
if (EditorHelper.getFileSize(editor) > 0 &&
!Character.isWhitespace(editor.getDocument().getChars()[editor.getCaretModel().getOffset()]))
{
argument.getMotion().setAction(ActionManager.getInstance().getAction("VimMotionWORDEndRight"));
argument.getMotion().setFlags(Command.FLAG_MOT_INCLUSIVE);
}
}
else if (id.equals("VimMotionCamelRight"))
{
if (EditorHelper.getFileSize(editor) > 0 &&
!Character.isWhitespace(editor.getDocument().getChars()[editor.getCaretModel().getOffset()]))
{
argument.getMotion().setAction(ActionManager.getInstance().getAction("VimMotionCamelEndRight"));
argument.getMotion().setFlags(Command.FLAG_MOT_INCLUSIVE);
}
}
boolean res = deleteMotion(editor, context, count, rawCount, argument, true);
if (res)
{
insertBeforeCursor(editor, context);
}
return res;
}
/**
* Deletes the range of text and enters insert mode
* @param editor The editor to change
* @param context The data context
* @param range The range to change
* @param type The type of the range (FLAG_MOT_LINEWISE, FLAG_MOT_CHARACTERWISE)
* @return true if able to delete the range, false if not
*/
public boolean changeRange(Editor editor, DataContext context, TextRange range, int type)
{
boolean after = range.getEndOffset() >= EditorHelper.getFileSize(editor);
boolean res = deleteRange(editor, context, range, type);
if (res)
{
if (type == Command.FLAG_MOT_LINEWISE)
{
if (after)
{
insertNewLineBelow(editor, context);
}
else
{
insertNewLineAbove(editor, context);
}
}
else
{
insertBeforeCursor(editor, context);
}
}
return res;
}
/**
* Toggles the case of count characters
* @param editor The editor to change
* @param context The data context
* @param count The number of characters to change
* @return true if able to change count characters
*/
public boolean changeCaseToggleCharacter(Editor editor, DataContext context, int count)
{
int offset = CommandGroups.getInstance().getMotion().moveCaretHorizontal(editor, count, true);
if (offset == -1)
{
return false;
}
else
{
changeCase(editor, context, editor.getCaretModel().getOffset(), offset, CharacterHelper.CASE_TOGGLE);
offset = EditorHelper.normalizeOffset(editor, offset, false);
MotionGroup.moveCaret(editor, context, offset);
return true;
}
}
/**
* Changes the case of all the character moved over by the motion argument.
* @param editor The editor to change
* @param context The data context
* @param count The number of times to repeat the change
* @param rawCount The actual count entered by the user
* @param type The case change type (TOGGLE, UPPER, LOWER)
* @param argument The motion command
* @return true if able to delete the text, false if not
*/
public boolean changeCaseMotion(Editor editor, DataContext context, int count, int rawCount, char type, Argument argument)
{
TextRange range = MotionGroup.getMotionRange(editor, context, count, rawCount, argument, true, false);
return changeCaseRange(editor, context, range, type);
}
/**
* Changes the case of all the characters in the range
* @param editor The editor to change
* @param context The data context
* @param range The range to change
* @param type The case change type (TOGGLE, UPPER, LOWER)
* @return true if able to delete the text, false if not
*/
public boolean changeCaseRange(Editor editor, DataContext context, TextRange range, char type)
{
if (range == null)
{
return false;
}
else
{
changeCase(editor, context, range.getStartOffset(), range.getEndOffset(), type);
MotionGroup.moveCaret(editor, context, range.getStartOffset());
return true;
}
}
/**
* This performs the actual case change.
* @param editor The editor to change
* @param context The data context
* @param start The start offset to change
* @param end The end offset to change
* @param type The type of change (TOGGLE, UPPER, LOWER)
*/
private void changeCase(Editor editor, DataContext context, int start, int end, char type)
{
if (start > end)
{
int t = end;
end = start;
start = t;
}
char[] chars = editor.getDocument().getChars();
for (int i = start; i < end; i++)
{
if (i >= chars.length)
{
break;
}
char ch = CharacterHelper.changeCase(chars[i], type);
if (ch != chars[i])
{
replaceText(editor, context, i, i + 1, Character.toString(ch));
}
}
}
public void autoIndentLines(Editor editor, DataContext context, int lines)
{
KeyHandler.executeAction("AutoIndentLines", context);
}
public void indentLines(Editor editor, DataContext context, int lines, int dir)
{
int cnt = 1;
if (CommandState.getInstance().getMode() == CommandState.MODE_INSERT ||
CommandState.getInstance().getMode() == CommandState.MODE_REPLACE)
{
if (strokes.size() > 0)
{
Object stroke = strokes.get(strokes.size() - 1);
if (stroke instanceof Character)
{
Character key = (Character)stroke;
if (key.charValue() == '0')
{
deleteCharacter(editor, context, -1);
cnt = 99;
}
}
}
}
int start = editor.getCaretModel().getOffset();
int end = CommandGroups.getInstance().getMotion().moveCaretToLineEndOffset(editor, lines - 1, false);
indentRange(editor, context, new TextRange(start, end), cnt, dir);
}
public void indentMotion(Editor editor, DataContext context, int count, int rawCount, Argument argument, int dir)
{
TextRange range = MotionGroup.getMotionRange(editor, context, count, rawCount, argument, false, false);
indentRange(editor, context, range, 1, dir);
}
public void indentRange(Editor editor, DataContext context, TextRange range, int count, int dir)
{
if (range == null) return;
Project proj = (Project)context.getData(DataConstants.PROJECT);
int tabSize = editor.getSettings().getTabSize(proj);
boolean useTabs = editor.getSettings().isUseTabCharacter(proj);
int sline = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int eline = editor.offsetToLogicalPosition(range.getEndOffset()).line;
int eoff = EditorHelper.getLineStartForOffset(editor, range.getEndOffset());
if (eoff == range.getEndOffset())
{
eline
}
for (int l = sline; l <= eline; l++)
{
int soff = EditorHelper.getLineStartOffset(editor, l);
int woff = CommandGroups.getInstance().getMotion().moveCaretToLineStartSkipLeading(editor, l);
int col = editor.offsetToVisualPosition(woff).column;
int newCol = Math.max(0, col + dir * tabSize * count);
if (dir == 1 || col > 0)
{
StringBuffer space = new StringBuffer();
int tabCnt = 0;
int spcCnt = 0;
if (useTabs)
{
tabCnt = newCol / tabSize;
spcCnt = newCol % tabSize;
}
else
{
spcCnt = newCol;
}
for (int i = 0; i < tabCnt; i++)
{
space.append('\t');
}
for (int i = 0; i < spcCnt; i++)
{
space.append(' ');
}
replaceText(editor, context, soff, woff, space.toString());
}
}
if (CommandState.getInstance().getMode() != CommandState.MODE_INSERT &&
CommandState.getInstance().getMode() != CommandState.MODE_REPLACE)
{
MotionGroup.moveCaret(editor, context,
CommandGroups.getInstance().getMotion().moveCaretToLineStartSkipLeading(editor, sline));
}
EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column);
}
/**
* Insert text into the document
* @param editor The editor to insert into
* @param context The data context
* @param start The starting offset to insert at
* @param str The text to insert
*/
public void insertText(Editor editor, DataContext context, int start, String str)
{
editor.getDocument().insertString(start, str);
editor.getCaretModel().moveToOffset(start + str.length());
CommandGroups.getInstance().getMark().setMark(editor, context, '.', start);
//CommandGroups.getInstance().getMark().setMark(editor, context, '[', start);
//CommandGroups.getInstance().getMark().setMark(editor, context, ']', start + str.length());
}
/**
* Delete text from the document. This will fail if being asked to store the deleted text into a read-only
* register.
* @param editor The editor to delete from
* @param context The data context
* @param start The start offset to delete
* @param end The end offset to delete
* @param type The type of deletion (FLAG_MOT_LINEWISE, FLAG_MOT_CHARACTERWISE)
* @return true if able to delete the text, false if not
*/
private boolean deleteText(Editor editor, DataContext context, int start, int end, int type)
{
if (start > end)
{
int t = start;
start = end;
end = t;
}
start = Math.max(0, Math.min(start, EditorHelper.getFileSize(editor)));
end = Math.max(0, Math.min(end, EditorHelper.getFileSize(editor)));
if (CommandGroups.getInstance().getRegister().storeText(editor, context, start, end, type, true, false))
{
editor.getDocument().deleteString(start, end);
CommandGroups.getInstance().getMark().setMark(editor, context, '.', start);
CommandGroups.getInstance().getMark().setMark(editor, context, '[', start);
CommandGroups.getInstance().getMark().setMark(editor, context, ']', start);
return true;
}
return false;
}
/**
* Replace text in the editor
* @param editor The editor to replace text in
* @param context The data context
* @param start The start offset to change
* @param end The end offset to change
* @param str The new text
*/
private void replaceText(Editor editor, DataContext context, int start, int end, String str)
{
editor.getDocument().replaceString(start, end, str);
CommandGroups.getInstance().getMark().setMark(editor, context, '[', start);
CommandGroups.getInstance().getMark().setMark(editor, context, ']', start + str.length());
CommandGroups.getInstance().getMark().setMark(editor, context, '.', start + str.length());
}
private static void resetCursor(Editor editor, boolean insert)
{
Document doc = editor.getDocument();
VirtualFile vf = FileDocumentManager.getInstance().getFile(doc);
if (vf != null)
{
resetCursor(vf, EditorData.getProject(editor), insert);
}
else
{
editor.getSettings().setBlockCursor(!insert);
}
}
private static void resetCursor(VirtualFile virtualFile, Project proj, boolean insert)
{
logger.debug("resetCursor");
Document doc = FileDocumentManager.getInstance().getDocument(virtualFile);
Editor[] editors = EditorFactory.getInstance().getEditors(doc, proj);
logger.debug("There are " + editors.length + " editors for virtual file " + virtualFile.getName());
for (int i = 0; i < editors.length; i++)
{
editors[i].getSettings().setBlockCursor(!insert);
}
}
/**
* This class listens for editor tab changes so any insert/replace modes that need to be reset can be
*/
public static class InsertCheck extends FileEditorManagerAdapter
{
/**
* Ensure that all open editors get a block cursor for command mode.
* @param fileEditorManager
* @param virtualFile
*/
public void fileOpened(FileEditorManager fileEditorManager, VirtualFile virtualFile)
{
resetCursor(virtualFile, EditorData.getProject(fileEditorManager), false);
}
/**
* The user has changed the editor they are working with - exit insert/replace mode, and complete any
* appropriate repeat.
* @param event
*/
public void selectionChanged(FileEditorManagerEvent event)
{
if (!VimPlugin.isEnabled()) return;
logger.debug("selected file changed");
CommandState.getInstance().reset();
KeyHandler.getInstance().fullReset();
VirtualFile virtualFile = event.getOldFile();
if (virtualFile != null)
{
resetCursor(virtualFile, EditorData.getProject(event.getManager()), false);
}
}
}
private ArrayList strokes = new ArrayList();
private ArrayList lastStrokes;
private int insertStart;
private Command lastInsert;
private boolean inInsert;
private static Logger logger = Logger.getInstance(ChangeGroup.class.getName());
}
|
package com.github.yuukis.businessmap.app;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import com.github.yuukis.businessmap.R;
import com.github.yuukis.businessmap.data.GeocodingCacheDatabase;
import com.github.yuukis.businessmap.model.ContactsGroup;
import com.github.yuukis.businessmap.model.ContactsItem;
import com.github.yuukis.businessmap.utils.CursorJoinerWithIntKey;
import com.github.yuukis.businessmap.utils.ContactsItemComparator;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ArrayAdapter;
public class MainActivity extends Activity implements
ActionBar.OnNavigationListener {
private static final String KEY_NAVIGATION_INDEX = "navigation_index";
private static final String KEY_CONTACTSLIST = "contacts_list";
private static final long ID_GROUP_ALL_CONTACTS = -1;
private List<ContactsGroup> mGroupList;
private List<ContactsItem> mContactsList;
private List<ContactsItem> mCurrentGroupContactsList;
private Map<String, Double[]> mGeocodingResultCache;
private ContactsMapFragment mMapFragment;
private ContactsListFragment mListFragment;
private ProgressDialog mProgressDialog;
private Handler mHandler = new Handler();
private GeocodingThread mThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
setProgressBarVisibility(false);
FragmentManager fm = getFragmentManager();
mMapFragment = (ContactsMapFragment) fm
.findFragmentById(R.id.contacts_map);
mListFragment = (ContactsListFragment) fm
.findFragmentById(R.id.contacts_list);
mGroupList = getContactsGroupList();
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle(R.string.title_geocoding);
mProgressDialog.setMessage(getString(R.string.message_geocoding));
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
ArrayAdapter<ContactsGroup> adapter = new ArrayAdapter<ContactsGroup>(
this, android.R.layout.simple_spinner_dropdown_item, mGroupList);
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, this);
if (savedInstanceState != null) {
actionBar.setSelectedNavigationItem(savedInstanceState
.getInt(KEY_NAVIGATION_INDEX));
mContactsList = (List<ContactsItem>) savedInstanceState
.getSerializable(KEY_CONTACTSLIST);
}
mCurrentGroupContactsList = new ArrayList<ContactsItem>();
mGeocodingResultCache = new HashMap<String, Double[]>();
if (mContactsList == null) {
mContactsList = new ArrayList<ContactsItem>();
mThread = new GeocodingThread();
mThread.start();
}
}
@Override
protected void onDestroy() {
if (mThread != null) {
mThread.halt();
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
AboutDialogFragment.showDialog(this);
return true;
}
return false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(KEY_NAVIGATION_INDEX, getActionBar()
.getSelectedNavigationIndex());
outState.putSerializable(KEY_CONTACTSLIST, (Serializable) mContactsList);
super.onSaveInstanceState(outState);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (mGroupList.size() <= itemPosition) {
return false;
}
ContactsGroup group = mGroupList.get(itemPosition);
long groupId = group.getId();
mCurrentGroupContactsList.clear();
for (ContactsItem contact : mContactsList) {
if (contact.getGroupId() == groupId) {
mCurrentGroupContactsList.add(contact);
}
}
mMapFragment.notifyDataSetChanged();
mListFragment.notifyDataSetChanged();
return true;
}
public List<ContactsItem> getCurrentContactsList() {
return mCurrentGroupContactsList;
}
public List<ContactsGroup> getContactsGroupList() {
Cursor groupCursor = getContentResolver().query(Groups.CONTENT_URI,
new String[] { Groups._ID, Groups.TITLE, Groups.ACCOUNT_NAME },
Groups.DELETED + "=0", null, null);
List<ContactsGroup> list = new ArrayList<ContactsGroup>();
ContactsGroup all = new ContactsGroup(ID_GROUP_ALL_CONTACTS, "", "");
list.add(all);
while (groupCursor.moveToNext()) {
long _id = groupCursor.getLong(0);
String title = groupCursor.getString(1);
String accountName = groupCursor.getString(2);
ContactsGroup group = new ContactsGroup(_id, title, accountName);
list.add(group);
}
return list;
}
private void loadAllContacts() {
mGeocodingResultCache.clear();
Cursor groupCursor = getContentResolver().query(
Data.CONTENT_URI,
new String[] {
GroupMembership.RAW_CONTACT_ID,
GroupMembership.CONTACT_ID,
GroupMembership.DISPLAY_NAME,
GroupMembership.PHONETIC_NAME,
GroupMembership.GROUP_ROW_ID },
Data.MIMETYPE + "=?",
new String[] {
GroupMembership.CONTENT_ITEM_TYPE },
Data.RAW_CONTACT_ID);
Cursor postalCursor = getContentResolver().query(
StructuredPostal.CONTENT_URI,
new String[] {
StructuredPostal.RAW_CONTACT_ID,
StructuredPostal.FORMATTED_ADDRESS },
null,
null,
StructuredPostal.RAW_CONTACT_ID);
CursorJoinerWithIntKey joiner = new CursorJoinerWithIntKey(
groupCursor, new String[] { Data.RAW_CONTACT_ID },
postalCursor, new String[] { Data.RAW_CONTACT_ID });
final GeocodingCacheDatabase db = new GeocodingCacheDatabase(this);
List<ContactsItem> contactsList = new ArrayList<ContactsItem>();
long _rowId = -1, _cid = -1;
String _name = null, _phonetic = null;
List<Long> _groupIds = new ArrayList<Long>();
List<String> _address = new ArrayList<String>();
for (CursorJoinerWithIntKey.Result result : joiner) {
long rowId, cid, groupId;
String name, phonetic, address;
switch (result) {
case LEFT:
rowId = groupCursor.getLong(0);
cid = groupCursor.getLong(1);
name = groupCursor.getString(2);
phonetic = groupCursor.getString(3);
groupId = groupCursor.getLong(4);
address = null;
break;
case RIGHT:
rowId = groupCursor.getLong(0);
cid = groupCursor.getLong(1);
name = groupCursor.getString(2);
phonetic = groupCursor.getString(3);
groupId = ID_GROUP_ALL_CONTACTS;
address = postalCursor.getString(1);
break;
case BOTH:
rowId = groupCursor.getLong(0);
cid = groupCursor.getLong(1);
name = groupCursor.getString(2);
phonetic = groupCursor.getString(3);
groupId = groupCursor.getLong(4);
address = postalCursor.getString(1);
break;
default:
continue;
}
if (_rowId != rowId) {
for (long gid : _groupIds) {
if (_address.isEmpty()) {
contactsList.add(new ContactsItem(_cid, _name,
_phonetic, gid, null));
continue;
}
for (String addr : _address) {
ContactsItem contact = new ContactsItem(_cid, _name,
_phonetic, gid, addr);
double[] latlng = db.get(addr);
if (latlng != null && latlng.length == 2) {
contact.setLat(latlng[0]);
contact.setLng(latlng[1]);
} else {
if (!mGeocodingResultCache.containsKey(addr)) {
mGeocodingResultCache.put(addr, null);
}
}
contactsList.add(contact);
}
}
_rowId = rowId;
_cid = cid;
_name = name;
_phonetic = phonetic;
_groupIds.clear();
_groupIds.add(ID_GROUP_ALL_CONTACTS);
_address.clear();
}
if (_groupIds.indexOf(groupId) < 0) {
_groupIds.add(groupId);
}
if (address != null && _address.indexOf(address) < 0) {
_address.add(address);
}
}
for (long gid : _groupIds) {
if (_address.isEmpty()) {
contactsList.add(new ContactsItem(_cid, _name, _phonetic, gid,
null));
continue;
}
for (String addr : _address) {
contactsList.add(new ContactsItem(_cid, _name, _phonetic, gid,
addr));
}
}
db.close();
groupCursor.close();
postalCursor.close();
Collections.sort(contactsList, new ContactsItemComparator());
mContactsList = contactsList;
}
private class GeocodingThread extends Thread {
private boolean halt;
public GeocodingThread() {
halt = false;
}
@Override
public void run() {
loadAllContacts();
if (!mGeocodingResultCache.isEmpty()) {
geocoding();
}
mHandler.post(new Runnable() {
@Override
public void run() {
if (!halt) {
mMapFragment.notifyDataSetChanged();
mListFragment.notifyDataSetChanged();
}
}
});
}
public void halt() {
halt = true;
interrupt();
}
private void geocoding() {
// final Map<String, Double[]> map = mGeocodingResultCache;
mProgressDialog.setMax(mGeocodingResultCache.size());
mHandler.post(new Runnable() {
@Override
public void run() {
mProgressDialog.show();
}
});
final GeocodingCacheDatabase db = new GeocodingCacheDatabase(
MainActivity.this);
int count = 0;
for (Iterator<Entry<String, Double[]>> it = mGeocodingResultCache.entrySet()
.iterator(); it.hasNext();) {
Entry<String, Double[]> entry = it.next();
String address = entry.getKey();
List<Address> list;
try {
list = new Geocoder(MainActivity.this, Locale.getDefault())
.getFromLocationName(address, 1);
} catch (IOException e) {
continue;
}
double lat = Double.NaN;
double lng = Double.NaN;
if (list.size() != 0) {
Address addr = list.get(0);
lat = addr.getLatitude();
lng = addr.getLongitude();
}
db.put(address, new double[] { lat, lng });
entry.setValue(new Double[] { lat, lng });
count++;
final int progress = count;
mHandler.post(new Runnable() {
@Override
public void run() {
mProgressDialog.setProgress(progress);
}
});
if (halt) {
db.close();
return;
}
}
db.close();
for (int j = 0; j < mContactsList.size(); j++) {
ContactsItem contact = mContactsList.get(j);
String address = contact.getAddress();
if (address == null) {
continue;
}
if (contact.getLat() != null && contact.getLng() != null) {
continue;
}
if (!mGeocodingResultCache.containsKey(address)) {
continue;
}
Double[] latlng = mGeocodingResultCache.get(address);
if (latlng != null && latlng.length == 2) {
contact.setLat(latlng[0]);
contact.setLng(latlng[1]);
mContactsList.set(j, contact);
}
}
mHandler.post(new Runnable() {
@Override
public void run() {
mProgressDialog.setProgress(mProgressDialog.getMax());
mProgressDialog.dismiss();
}
});
}
}
}
|
package com.mcbans.firestar.mcbans.api;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.mcbans.firestar.mcbans.BanType;
import com.mcbans.firestar.mcbans.MCBans;
import com.mcbans.firestar.mcbans.callBacks.AltLookupCallback;
import com.mcbans.firestar.mcbans.callBacks.BanLookupCallback;
import com.mcbans.firestar.mcbans.callBacks.LookupCallback;
import com.mcbans.firestar.mcbans.request.AltLookupRequest;
import com.mcbans.firestar.mcbans.request.Ban;
import com.mcbans.firestar.mcbans.request.BanLookupRequest;
import com.mcbans.firestar.mcbans.request.Kick;
import com.mcbans.firestar.mcbans.request.LookupRequest;
import com.mcbans.firestar.mcbans.util.Util;
public class MCBansAPI {
private final MCBans plugin;
private final String pname;
private MCBansAPI(final MCBans plugin, final String pname) {
plugin.getLog().info("MCBans API linked with: " + pname);
this.plugin = plugin;
this.pname = pname;
}
private void ban(BanType type, String targetName, String senderName, String reason, String duration, String measure){
// check null
if (targetName == null || senderName == null){
return;
}
String targetIP = "";
if (type != BanType.UNBAN){
final Player target = Bukkit.getPlayerExact(targetName);
targetIP = (target != null) ? target.getAddress().getAddress().getHostAddress() : "";
}
Ban banControl = new Ban(plugin, type.getActionName(), targetName, targetIP, senderName, reason, duration, measure);
Thread triggerThread = new Thread(banControl);
triggerThread.start();
}
/**
* Add Locally BAN
* @param targetName BAN target player's name
* @param senderName BAN issued admin's name
* @param reason BAN reason
*/
public void localBan(String targetName, String senderName, String reason){
plugin.getLog().info("Plugin " + pname + " tried to local ban player " + targetName);
reason = (reason == null || reason == "") ? plugin.getConfigs().getDefaultLocal() : reason;
this.ban(BanType.LOCAL, targetName, senderName, reason, "", "");
}
/**
* Add Globally BAN
* @param targetName BAN target player's name
* @param senderName BAN issued admin's name
* @param reason BAN reason
*/
public void globalBan(String targetName, String senderName, String reason){
plugin.getLog().info("Plugin " + pname + " tried to global ban player " + targetName);
if (reason == null || reason == "") return;
this.ban(BanType.GLOBAL, targetName, senderName, reason, "", "");
}
/**
* Add Temporary BAN
* @param targetName BAN target player's name
* @param senderName BAN issued admin's name
* @param reason BAN reason
* @param duration Banning length duration (intValue)
* @param measure Banning length measure (m(minute), h(hour), d(day), w(week))
*/
public void tempBan(String targetName, String senderName, String reason, String duration, String measure){
plugin.getLog().info("Plugin " + pname + " tried to temp ban player " + targetName);
reason = (reason == null || reason == "") ? plugin.getConfigs().getDefaultTemp() : reason;
duration = (duration == null) ? "" : duration;
measure = (measure == null) ? "" : measure;
this.ban(BanType.TEMP, targetName, senderName, reason, duration, measure);
}
/**
* Remove BAN
* @param targetName UnBan target player's name
* @param senderName UnBan issued admin's name
*/
public void unBan(String targetName, String senderName){
plugin.getLog().info("Plugin " + pname + " tried to unban player " + targetName);
this.ban(BanType.UNBAN, targetName, senderName, "", "", "");
}
/**
* Kick Player
* @param targetName Kick target player's name
* @param senderName Kick issued admin's name
* @param reason Kick reason
*/
public void kick(String targetName, String senderName, String reason){
//plugin.getLog().info("Plugin " + pname + " tried to kick player " + targetName);
reason = (reason == null || reason == "") ? plugin.getConfigs().getDefaultKick() : reason;
// Start
Kick kickPlayer = new Kick(plugin, targetName, senderName, reason, true);
Thread triggerThread = new Thread(kickPlayer);
triggerThread.start();
}
/**
* Lookup Player
* @param targetName Lookup target player name
* @param senderName Lookup issued admin name
* @param callback LookupCallback LookupCallback
*/
public void lookupPlayer(String targetName, String senderName, LookupCallback callback){
plugin.getLog().info("Plugin " + pname + " tried to lookup player " + targetName);
if (targetName == null || callback == null){
plugin.getLog().info("Invalid usage (null): lookupPlayer");
return;
}
if (!Util.isValidName(targetName)){
callback.error("Invalid lookup target name!");
}
LookupRequest request = new LookupRequest(plugin, callback, targetName, senderName);
Thread triggerThread = new Thread(request);
triggerThread.start();
}
/**
* Lookup Ban
* @param banID Lookup target ban ID
* @param callback BanLookupCallback BanLookupCallback
*/
public void lookupBan(int banID, BanLookupCallback callback){
plugin.getLog().info("Plugin " + pname + " tried to ban lookup " + banID);
if (banID < 0 || callback == null){
plugin.getLog().info("Invalid usage (null): lookupBan");
return;
}
BanLookupRequest request = new BanLookupRequest(plugin, callback, banID);
Thread triggerThread = new Thread(request);
triggerThread.start();
}
/**
* Lookup Alt Accounts
* @param playerName Lookup target player name
* @param callback BanLookupCallback BanLookupCallback
*/
public void lookupAlt(String playerName, AltLookupCallback callback){
plugin.getLog().info("Plugin " + pname + " tried to alt lookup " + playerName);
if (playerName == null || callback == null){
plugin.getLog().info("Invalid usage (null): lookupAlt");
return;
}
if (!Util.isValidName(playerName)){
callback.error("Invalid alt lookup target name!");
}
AltLookupRequest request = new AltLookupRequest(plugin, callback, playerName);
Thread triggerThread = new Thread(request);
triggerThread.start();
}
/**
* Get MCBans plugin version
* @return plugin version
*/
public String getVersion(){
return plugin.getDescription().getVersion();
}
private static HashMap<Plugin, MCBansAPI> apiHandles = new HashMap<Plugin, MCBansAPI>();
public static MCBansAPI getHandle(final MCBans plugin, final Plugin otherPlugin){
if (otherPlugin == null) return null;
MCBansAPI api = apiHandles.get(otherPlugin);
if (api == null){
// get new api
api = new MCBansAPI(plugin, otherPlugin.getName());
apiHandles.put(otherPlugin, api);
}
return api;
}
}
|
package com.namelessmc.plugin.common;
import java.util.Optional;
import com.namelessmc.java_api.ApiError;
import com.namelessmc.java_api.NamelessAPI;
import com.namelessmc.java_api.NamelessException;
import com.namelessmc.java_api.Website;
public abstract class ApiProvider {
private static final String USER_AGENT = "Nameless-Plugin";
private Optional<NamelessAPI> cachedApi; // null if not cached
public ApiProvider() {
}
public Optional<NamelessAPI> getNamelessApi() {
if (this.cachedApi != null) {
return this.cachedApi;
}
final NamelessAPI api = NamelessAPI.builder()
.apiUrl(this.getApiUrl())
.userAgent(USER_AGENT)
.debug(this.getDebug())
.build();
try {
final Website info = api.getWebsite();
if (GlobalConstants.SUPPORTED_WEBSITE_VERSIONS.contains(info.getParsedVersion())) {
this.cachedApi = Optional.of(api);
} else {
// TODO Use proper logger
System.err.println("Your website runs a version of NamelessMC (" + info.getVersion() + ") that is not supported by this version of the plugin.");
this.cachedApi = Optional.empty();
}
} catch (final ApiError e) {
if (e.getError() == ApiError.INVALID_API_KEY) {
// TODO Use proper logger
System.err.println("You have entered an invalid API key. Please get an up-to-date API URL from StaffCP > Configuration > API and reload the plugin.");
} else {
System.err.println("Encountered an unexpected error code " + e.getError() + " while trying to connect to your website. Enable api debug mode in the config file for more details. When you think you've fixed the problem, reload the plugin to attempt connecting again.");
}
this.cachedApi = Optional.empty();
} catch (final NamelessException e) {
System.err.println("Encounted an error when connecting to the website. This message is expected if your site is down temporarily and can be ignored if the plugin works fine otherwise. If the plugin doesn't work as expected, please enable api-debug-mode in the config and run /nlpl reload to get more information.");
// Do not cache so it immediately tries again the next time. These types of errors may fix on their
// own, so we don't want to break the plugin until the administrator reloads.
this.cachedApi = null;
return Optional.empty();
}
return this.cachedApi;
}
protected void clearCachedApi() {
this.cachedApi = null;
}
protected abstract String getApiUrl();
protected abstract boolean getDebug();
}
|
package com.nisoft.instools;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
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 com.google.gson.Gson;
import com.nisoft.instools.bean.ImageRecode;
import com.nisoft.instools.bean.ProblemDataPackage;
import com.nisoft.instools.bean.ProblemRecode;
import com.nisoft.instools.bean.Recode;
import com.nisoft.instools.gson.ProblemListDataPackage;
import com.nisoft.instools.jdbc.JDBCUtil;
import com.nisoft.instools.strings.RecodeDbSchema.RecodeTable;
import com.nisoft.instools.utils.FileUtils;
import com.nisoft.instools.utils.GsonUtil;
import com.nisoft.instools.utils.StringsUtil;
/**
* Servlet implementation class ProblemRecodeServlet
*/
@WebServlet("/ProblemRecodeServlet")
public class ProblemRecodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PROBLEM_DATA_PATH = "C:\\apache-tomcat-8.5.15\\webapps\\InspectorToolsServer\\recode\\JXCZ\\problem\\";
/**
* @see HttpServlet#HttpServlet()
*/
public ProblemRecodeServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* +
*
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String intent = request.getParameter("intent");
switch (intent) {
case "new_problem":
String newProblemId = getRecodeId();
if (newProblemId != null) {
// String problemImagesDirPath = request.getSession().getServletContext()
// .getRealPath("/recode/JXCZ/problem/" + newProblemId + "/problem/");
String problemImagesDirPath = PROBLEM_DATA_PATH+ newProblemId + "\\problem\\";
System.out.println(problemImagesDirPath);
// String resultImagesDirPath = request.getSession().getServletContext()
// .getRealPath("/recode/JXCZ/problem/" + newProblemId + "/result/");
String resultImagesDirPath = PROBLEM_DATA_PATH+ newProblemId + "\\result\\";
ProblemDataPackage data = new ProblemDataPackage(newProblemId, problemImagesDirPath,
resultImagesDirPath);
boolean isUpdated = update(data);
if (isUpdated) {
out.write(newProblemId);
} else {
out.write(newProblemId);
}
} else {
out.write("false");
}
break;
case "recoding":
String problemId = request.getParameter("problem_id");
ProblemDataPackage problem = queryProblemById(problemId);
if (problem != null) {
Gson gson = GsonUtil.getDateFormatGson();
String recodeResult = gson.toJson(problem);
out.write(recodeResult);
} else {
out.write("error");
}
break;
case "list":
ArrayList<ProblemRecode> allRecodes = queryAll();
if (allRecodes == null || allRecodes.size() == 0) {
out.write("zero");
} else {
ProblemListDataPackage data = new ProblemListDataPackage();
data.setProblemRecodes(allRecodes);
Gson gson = GsonUtil.getDateFormatGson();
out.write(gson.toJson(data));
}
break;
case "update":
String json = request.getParameter("job_json");
Gson gson = GsonUtil.getDateFormatGson();
ProblemDataPackage problemRecode = gson.fromJson(json, ProblemDataPackage.class);
boolean isSuccess = update(problemRecode);
if (isSuccess) {
out.write("OK");
} else {
out.write("");
}
break;
}
out.close();
}
private String getRecodeId() {
String sql = "select *from problem order by problem_id";
Connection conn = JDBCUtil.getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
rs.last();
int row = rs.getRow();
Date date = new Date();
String dateFormat = StringsUtil.dateFormatForNum(date);
if (row == 0) {
return dateFormat + "-" + 1;
} else {
String lastId = rs.getString("problem_id");
String[] strs = lastId.split("-");
String[] dateStrs = dateFormat.split("-");
if (strs[0].equals(dateStrs[0]) || strs[1].equals(dateStrs[1])) {
int num = Integer.parseInt(strs[strs.length - 1]) + 1;
return dateFormat + "-" + num;
} else {
return dateFormat + "-" + 1;
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
private int update(String table, Recode recode) {
String job_id = recode.getRecodeId();
if (job_id == null || job_id.equals("")) {
return -1;
}
Date date = recode.getDate();
if (date == null) {
date = new Date();
}
String updateSql = updateSql(table, recode);
System.out.println(updateSql);
Connection conn = JDBCUtil.getConnection();
Statement st = null;
int row = -1;
try {
st = conn.createStatement();
row = st.executeUpdate(updateSql);
System.out.println(table+" update row:" + row);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("");
} finally {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return row;
}
private boolean update(ProblemDataPackage data) {
int a = update(RecodeTable.PROBLEM_NAME, data.getProblem());
int b = update(RecodeTable.ANALYSIS_NAME, data.getAnalysis());
int c = update(RecodeTable.PROGRAM_NAME, data.getProgram());
int d = update(RecodeTable.RESULT_NAME, data.getResultRecode());
if (a >=0 && b >= 0 && c >= 0 && d >= 0) {
return true;
}
return false;
}
private String updateSql(String table, Recode recode) {
String sql = null;
Date date = recode.getDate();
if (date == null) {
date = new Date();
}
long dateTime = date.getTime();
long update_time = recode.getUpdateTime();
if (table.equals(RecodeTable.ANALYSIS_NAME) || table.equals(RecodeTable.PROGRAM_NAME)) {
sql = "insert into " + table + "(" + RecodeTable.Cols.PROBLEM_ID + "," + RecodeTable.Cols.TYPE + ","
+ RecodeTable.Cols.AUTHOR + "," + RecodeTable.Cols.DATE + "," + RecodeTable.Cols.UPDATE_TIME + ","
+ RecodeTable.Cols.DESCRIPTION_TEXT + ")values('" + recode.getRecodeId() + "','" + recode.getType()
+ "','" + recode.getAuthor() + "','" + dateTime + "','" + update_time + "','"
+ recode.getDescription() + "') on duplicate key update " + RecodeTable.Cols.TYPE + "= values("
+ RecodeTable.Cols.TYPE + ")," + RecodeTable.Cols.AUTHOR + "= values(" + RecodeTable.Cols.AUTHOR
+ ")," + RecodeTable.Cols.DATE + "= values(" + RecodeTable.Cols.DATE + "),"
+ RecodeTable.Cols.UPDATE_TIME + "= values(" + RecodeTable.Cols.UPDATE_TIME + "),"
+ RecodeTable.Cols.DESCRIPTION_TEXT + "= values(" + RecodeTable.Cols.DESCRIPTION_TEXT + ")";
} else if (table.equals(RecodeTable.RESULT_NAME)) {
sql = "insert into " + table + "(" + RecodeTable.Cols.PROBLEM_ID + "," + RecodeTable.Cols.TYPE + ","
+ RecodeTable.Cols.AUTHOR + "," + RecodeTable.Cols.DATE + "," + RecodeTable.Cols.UPDATE_TIME + ","
+ RecodeTable.Cols.DESCRIPTION_TEXT + "," + RecodeTable.Cols.IMAGES_NAME + ")values('"
+ recode.getRecodeId() + "','" + recode.getType() + "','" + recode.getAuthor() + "','" + dateTime
+ "','" + update_time + "','" + recode.getDescription() + "','"
+ ((ImageRecode) recode).getImagesNameOnServer() + "') on duplicate key update "
+ RecodeTable.Cols.TYPE + "= values(" + RecodeTable.Cols.TYPE + ")," + RecodeTable.Cols.AUTHOR
+ "= values(" + RecodeTable.Cols.AUTHOR + ")," + RecodeTable.Cols.DATE + "= values("
+ RecodeTable.Cols.DATE + ")," + RecodeTable.Cols.UPDATE_TIME + "= values("
+ RecodeTable.Cols.UPDATE_TIME + ")," + RecodeTable.Cols.DESCRIPTION_TEXT + "= values("
+ RecodeTable.Cols.DESCRIPTION_TEXT + ")," + RecodeTable.Cols.IMAGES_NAME + "= values("
+ RecodeTable.Cols.IMAGES_NAME + ")";
} else if (table.equals(RecodeTable.PROBLEM_NAME)) {
sql = "insert into " + table + "(" + RecodeTable.Cols.PROBLEM_ID + "," + RecodeTable.Cols.TYPE + ","
+ RecodeTable.Cols.AUTHOR + "," + RecodeTable.Cols.DATE + "," + RecodeTable.Cols.SUSPECTS + ","
+ RecodeTable.Cols.UPDATE_TIME + "," + RecodeTable.Cols.DESCRIPTION_TEXT + ","
+ RecodeTable.Cols.IMAGES_NAME + "," + RecodeTable.Cols.TITLE + "," + RecodeTable.Cols.ADDRESS
+ ")values('" + recode.getRecodeId() + "','" + recode.getType() + "','" + recode.getAuthor() + "','"
+ dateTime + "','" + "" + "','" + recode.getUpdateTime() + "','" + recode.getDescription() + "','"
+ ((ProblemRecode) recode).getImagesNameOnServer() + "','" + ((ProblemRecode) recode).getTitle()
+ "','" + ((ProblemRecode) recode).getAddress() + "') on duplicate key update "
+ RecodeTable.Cols.TYPE + "= values(" + RecodeTable.Cols.TYPE + ")," + RecodeTable.Cols.AUTHOR
+ "= values(" + RecodeTable.Cols.AUTHOR + ")," + RecodeTable.Cols.DATE + "= values("
+ RecodeTable.Cols.DATE + ")," + RecodeTable.Cols.SUSPECTS + "= values(" + RecodeTable.Cols.SUSPECTS
+ ")," + RecodeTable.Cols.UPDATE_TIME + "= values(" + RecodeTable.Cols.UPDATE_TIME + "),"
+ RecodeTable.Cols.DESCRIPTION_TEXT + "= values(" + RecodeTable.Cols.DESCRIPTION_TEXT + "),"
+ RecodeTable.Cols.IMAGES_NAME + "= values(" + RecodeTable.Cols.IMAGES_NAME + "),"
+ RecodeTable.Cols.TITLE + "= values(" + RecodeTable.Cols.TITLE + ")," + RecodeTable.Cols.ADDRESS
+ "= values(" + RecodeTable.Cols.ADDRESS + ")";
}
return sql;
}
private ArrayList<ProblemRecode> queryAll() {
String sql = "select * from problem";
Connection conn = JDBCUtil.getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
rs.last();
int row = rs.getRow();
if (row > 0) {
ArrayList<ProblemRecode> allRecodes = new ArrayList<>();
rs.beforeFirst();
while (rs.next()) {
String problemId = rs.getString(RecodeTable.Cols.PROBLEM_ID);
String authorId = rs.getString(RecodeTable.Cols.AUTHOR);
String description = rs.getString(RecodeTable.Cols.DESCRIPTION_TEXT);
String address = rs.getString(RecodeTable.Cols.ADDRESS);
String suspectsString = rs.getString(RecodeTable.Cols.SUSPECTS);
ArrayList<String> suspects = StringsUtil.getStrings(suspectsString);
String problemImagesDirPath = PROBLEM_DATA_PATH+ problemId + "\\problem\\";
ArrayList<String> images_name = FileUtils.getAllImagesName(problemImagesDirPath);
String title = rs.getString(RecodeTable.Cols.TITLE);
String type = rs.getString(RecodeTable.Cols.TYPE);
long dateTime = rs.getLong(RecodeTable.Cols.DATE);
long updateTime = rs.getLong(RecodeTable.Cols.UPDATE_TIME);
Date date = new Date(dateTime);
ProblemRecode recode = new ProblemRecode(problemId);
recode.setAuthor(authorId);
recode.setTitle(title);
recode.setAddress(address);
recode.setDate(date);
recode.setDescription(description);
recode.setType(type);
recode.setUpdateTime(updateTime);
recode.setSuspects(suspects);
recode.setImagesNameOnserver(images_name);
allRecodes.add(recode);
}
return allRecodes;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
private ProblemDataPackage queryProblemById(String problemId) {
System.out.println(RecodeTable.PROGRAM_NAME);
Recode program = queryRecodeById(RecodeTable.PROGRAM_NAME, problemId);
System.out.println(RecodeTable.PROBLEM_NAME);
ProblemRecode problemRecode = (ProblemRecode) queryRecodeById(RecodeTable.PROBLEM_NAME, problemId);
System.out.println(RecodeTable.ANALYSIS_NAME);
Recode analysis = queryRecodeById(RecodeTable.ANALYSIS_NAME, problemId);
System.out.println(RecodeTable.RESULT_NAME);
ImageRecode result = (ImageRecode) queryRecodeById(RecodeTable.RESULT_NAME, problemId);
ProblemDataPackage problem = new ProblemDataPackage();
problem.setAnalysis(analysis);
problem.setProblem(problemRecode);
problem.setProgram(program);
problem.setResultRecode(result);
return problem;
}
private Recode queryRecodeById(String table, String problemId) {
String sql = "select * from " + table + " where " + RecodeTable.Cols.PROBLEM_ID + " = '" + problemId+"'";
System.out.println("queryRecodeById:"+sql);
Connection conn = JDBCUtil.getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
rs.last();
int row = rs.getRow();
System.out.println(table+":"+row);
if (row > 0) {
rs.first();
String authorId = rs.getString(RecodeTable.Cols.AUTHOR);
String description = rs.getString(RecodeTable.Cols.DESCRIPTION_TEXT);
String type = rs.getString(RecodeTable.Cols.TYPE);
long dateTime = rs.getLong(RecodeTable.Cols.DATE);
long updateTime = rs.getLong(RecodeTable.Cols.UPDATE_TIME);
Date date = new Date(dateTime);
if (table.equals(RecodeTable.ANALYSIS_NAME) || table.equals(RecodeTable.PROGRAM_NAME)) {
return new Recode(problemId, type, authorId, date, description, updateTime);
} else if (table.equals(RecodeTable.RESULT_NAME)) {
// String resultImagesDirPath = request.getSession().getServletContext()
// .getRealPath("/recode/JXCZ/problem/" + problemId + "/result/");
String resultImagesDirPath = PROBLEM_DATA_PATH+ problemId + "\\result\\";
ArrayList<String> resultImagesName = FileUtils.getAllImagesName(resultImagesDirPath);
return new ImageRecode(problemId, type, authorId, date, description, updateTime, resultImagesName);
} else if (table.equals(RecodeTable.PROBLEM_NAME)) {
System.out.println(RecodeTable.PROBLEM_NAME);
// String problemImagesDirPath = request.getSession().getServletContext()
// .getRealPath("/recode/JXCZ/problem/" + problemId + "/problem/");
String problemImagesDirPath = PROBLEM_DATA_PATH+ problemId + "\\problem\\";
System.out.println(problemImagesDirPath);
ArrayList<String> problemImagesName = FileUtils.getAllImagesName(problemImagesDirPath);
System.out.println("problemImagesName:"+problemImagesName.toString());
String address = rs.getString(RecodeTable.Cols.ADDRESS);
String suspectsString = rs.getString(RecodeTable.Cols.SUSPECTS);
ArrayList<String> suspects = StringsUtil.getStrings(suspectsString);
String title = rs.getString(RecodeTable.Cols.TITLE);
return new ProblemRecode(problemId, type, authorId, date, description, updateTime,
problemImagesName, address, suspects, title);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
}
|
package com.irccloud.androidnative;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
public class BuffersListFragment extends SherlockListFragment {
private static final int TYPE_SERVER = 0;
private static final int TYPE_CHANNEL = 1;
private static final int TYPE_CONVERSATION = 2;
private static final int TYPE_ARCHIVES_HEADER = 3;
NetworkConnection conn;
BufferListAdapter adapter;
OnBufferSelectedListener mListener;
View view;
TextView errorMsg;
ListView listView = null;
RelativeLayout connecting = null;
LinearLayout topUnreadIndicator = null;
LinearLayout topUnreadIndicatorColor = null;
LinearLayout bottomUnreadIndicator = null;
LinearLayout bottomUnreadIndicatorColor = null;
String error = null;
private Timer countdownTimer = null;
int firstUnreadPosition = -1;
int lastUnreadPosition= -1;
int firstHighlightPosition = -1;
int lastHighlightPosition= -1;
SparseBooleanArray mExpandArchives = new SparseBooleanArray();
private static class BufferListEntry implements Serializable {
private static final long serialVersionUID = 1848168221883194027L;
int cid;
int bid;
int type;
int unread;
int highlights;
int key;
long last_seen_eid;
long min_eid;
int joined;
int archived;
String name;
String status;
}
private class BufferListAdapter extends BaseAdapter {
ArrayList<BufferListEntry> data;
private SherlockListFragment ctx;
int progressRow = -1;
private class ViewHolder {
int type;
TextView label;
TextView highlights;
LinearLayout unread;
LinearLayout groupbg;
LinearLayout bufferbg;
ImageView key;
ProgressBar progress;
ImageButton addBtn;
}
public void showProgress(int row) {
progressRow = row;
notifyDataSetChanged();
}
public BufferListAdapter(SherlockListFragment context) {
ctx = context;
data = new ArrayList<BufferListEntry>();
}
public void setItems(ArrayList<BufferListEntry> items) {
data = items;
}
int unreadPositionAbove(int pos) {
for(int i = pos-1; i >= 0; i
BufferListEntry e = data.get(i);
if(e.unread > 0)
return i;
}
return 0;
}
int unreadPositionBelow(int pos) {
for(int i = pos; i < data.size(); i++) {
BufferListEntry e = data.get(i);
if(e.unread > 0)
return i;
}
return data.size() - 1;
}
public BufferListEntry buildItem(int cid, int bid, int type, String name, int key, int unread, int highlights, long last_seen_eid, long min_eid, int joined, int archived, String status) {
BufferListEntry e = new BufferListEntry();
e.cid = cid;
e.bid = bid;
e.type = type;
e.name = name;
e.key = key;
e.unread = unread;
e.highlights = highlights;
e.last_seen_eid = last_seen_eid;
e.min_eid = min_eid;
e.joined = joined;
e.archived = archived;
e.status = status;
return e;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
BufferListEntry e = data.get(position);
return e.bid;
}
@SuppressWarnings("deprecation")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
BufferListEntry e = data.get(position);
View row = convertView;
ViewHolder holder;
if(row != null && ((ViewHolder)row.getTag()).type != e.type)
row = null;
if (row == null) {
LayoutInflater inflater = ctx.getLayoutInflater(null);
if(e.type == TYPE_SERVER)
row = inflater.inflate(R.layout.row_buffergroup, null);
else
row = inflater.inflate(R.layout.row_buffer, null);
holder = new ViewHolder();
holder.label = (TextView) row.findViewById(R.id.label);
holder.highlights = (TextView) row.findViewById(R.id.highlights);
holder.unread = (LinearLayout) row.findViewById(R.id.unread);
holder.groupbg = (LinearLayout) row.findViewById(R.id.groupbg);
holder.bufferbg = (LinearLayout) row.findViewById(R.id.bufferbg);
holder.key = (ImageView) row.findViewById(R.id.key);
holder.progress = (ProgressBar) row.findViewById(R.id.progressBar);
holder.addBtn = (ImageButton) row.findViewById(R.id.addBtn);
holder.type = e.type;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.label.setText(e.name);
if(e.type == TYPE_ARCHIVES_HEADER) {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_archives_heading));
holder.unread.setBackgroundDrawable(null);
if(mExpandArchives.get(e.cid, false)) {
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg_archived);
holder.bufferbg.setSelected(true);
} else {
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg);
holder.bufferbg.setSelected(false);
}
} else if(e.archived == 1 && holder.bufferbg != null) {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_archived));
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg_archived);
holder.unread.setBackgroundDrawable(null);
} else if((e.type == TYPE_CHANNEL && e.joined == 0) || !e.status.equals("connected_ready")) {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_inactive));
holder.unread.setBackgroundDrawable(null);
if(holder.bufferbg != null)
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg);
} else if(e.unread > 0) {
holder.label.setTypeface(null, Typeface.BOLD);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_unread));
holder.unread.setBackgroundResource(R.drawable.selected_blue);
if(holder.bufferbg != null)
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg);
} else {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label));
holder.unread.setBackgroundDrawable(null);
if(holder.bufferbg != null)
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg);
}
if(conn.getState() != NetworkConnection.STATE_CONNECTED)
row.setBackgroundResource(R.drawable.disconnected_yellow);
else
row.setBackgroundResource(R.drawable.bg);
if(holder.key != null) {
if(e.key > 0) {
holder.key.setVisibility(View.VISIBLE);
} else {
holder.key.setVisibility(View.INVISIBLE);
}
}
if(holder.progress != null) {
if(progressRow == position || (e.type == TYPE_SERVER && !(e.status.equals("connected_ready") || e.status.equals("quitting") || e.status.equals("disconnected")))) {
holder.progress.setVisibility(View.VISIBLE);
} else {
holder.progress.setVisibility(View.GONE);
}
}
if(holder.groupbg != null) {
if(e.status.equals("waiting_to_retry") || e.status.equals("pool_unavailable")) {
holder.groupbg.setBackgroundResource(R.drawable.operator_bg_red);
holder.label.setTextColor(getResources().getColorStateList(R.color.heading_operators));
} else {
holder.groupbg.setBackgroundResource(R.drawable.row_buffergroup_bg);
}
}
if(holder.highlights != null) {
if(e.highlights > 0) {
holder.highlights.setVisibility(View.VISIBLE);
holder.highlights.setText("(" + e.highlights + ")");
} else {
holder.highlights.setVisibility(View.GONE);
holder.highlights.setText("");
}
}
if(holder.addBtn != null) {
holder.addBtn.setTag(e);
holder.addBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
BufferListEntry e = (BufferListEntry)v.getTag();
AddChannelFragment newFragment = new AddChannelFragment();
newFragment.setDefaultCid(e.cid);
newFragment.show(getActivity().getSupportFragmentManager(), "dialog");
}
});
}
return row;
}
}
private class RefreshTask extends AsyncTask<Void, Void, Void> {
ArrayList<BufferListEntry> entries = new ArrayList<BufferListEntry>();
@Override
protected Void doInBackground(Void... params) {
ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers();
if(adapter == null) {
adapter = new BufferListAdapter(BuffersListFragment.this);
}
firstUnreadPosition = -1;
lastUnreadPosition = -1;
firstHighlightPosition = -1;
lastHighlightPosition = -1;
int position = 0;
for(int i = 0; i < servers.size(); i++) {
int archiveCount = 0;
ServersDataSource.Server s = servers.get(i);
ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid);
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
if(b.type.equalsIgnoreCase("console")) {
int unread = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
int highlights = EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid);
if(s.name.length() == 0)
s.name = s.hostname;
entries.add(adapter.buildItem(b.cid, b.bid, TYPE_SERVER, s.name, 0, unread, highlights, b.last_seen_eid, b.min_eid, 1, b.archived, s.status));
if(unread > 0 && firstUnreadPosition == -1)
firstUnreadPosition = position;
if(unread > 0 && (lastUnreadPosition == -1 || lastUnreadPosition < position))
lastUnreadPosition = position;
if(highlights > 0 && firstHighlightPosition == -1)
firstHighlightPosition = position;
if(highlights > 0 && (lastHighlightPosition == -1 || lastHighlightPosition < position))
lastHighlightPosition = position;
position++;
break;
}
}
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
int type = -1;
int key = 0;
int joined = 1;
if(b.type.equalsIgnoreCase("channel")) {
type = TYPE_CHANNEL;
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid);
if(c == null)
joined = 0;
if(c != null && c.mode != null && c.mode.contains("k"))
key = 1;
}
else if(b.type.equalsIgnoreCase("conversation"))
type = TYPE_CONVERSATION;
if(type > 0 && b.archived == 0) {
int unread = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
int highlights = EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid);
if(conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) {
try {
JSONObject disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
if(disabledMap.has(String.valueOf(b.bid)) && disabledMap.getBoolean(String.valueOf(b.bid)))
unread = 0;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
entries.add(adapter.buildItem(b.cid, b.bid, type, b.name, key, unread, highlights, b.last_seen_eid, b.min_eid, joined, b.archived, s.status));
if(unread > 0 && firstUnreadPosition == -1)
firstUnreadPosition = position;
if(unread > 0 && (lastUnreadPosition == -1 || lastUnreadPosition < position))
lastUnreadPosition = position;
if(highlights > 0 && firstHighlightPosition == -1)
firstHighlightPosition = position;
if(highlights > 0 && (lastHighlightPosition == -1 || lastHighlightPosition < position))
lastHighlightPosition = position;
position++;
}
if(type > 0 && b.archived > 0) {
archiveCount++;
}
}
if(archiveCount > 0) {
entries.add(adapter.buildItem(s.cid, 0, TYPE_ARCHIVES_HEADER, "Archives", 0, 0, 0, 0, 0, 0, 1, s.status));
position++;
if(mExpandArchives.get(s.cid, false)) {
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
int type = -1;
if(b.archived == 1) {
if(b.type.equalsIgnoreCase("channel"))
type = TYPE_CHANNEL;
else if(b.type.equalsIgnoreCase("conversation"))
type = TYPE_CONVERSATION;
if(type > 0) {
entries.add(adapter.buildItem(b.cid, b.bid, type, b.name, 0, 0, 0, b.last_seen_eid, b.min_eid, 0, b.archived, s.status));
position++;
}
}
}
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
adapter.setItems(entries);
if(getListAdapter() == null && entries.size() > 0)
setListAdapter(adapter);
else
adapter.notifyDataSetChanged();
if(entries.size() > 0 && connecting != null) {
connecting.setVisibility(View.GONE);
}
if(listView != null)
updateUnreadIndicators(listView.getFirstVisiblePosition(), listView.getLastVisiblePosition());
else //The activity view isn't ready yet, try again
new RefreshTask().execute((Void)null);
}
}
private void updateUnreadIndicators(int first, int last) {
if(topUnreadIndicator != null) {
if(firstUnreadPosition != -1 && first >= firstUnreadPosition) {
topUnreadIndicator.setVisibility(View.VISIBLE);
topUnreadIndicatorColor.setBackgroundResource(R.drawable.selected_blue);
} else {
topUnreadIndicator.setVisibility(View.GONE);
}
if((lastHighlightPosition != -1 && first >= lastHighlightPosition) ||
(firstHighlightPosition != -1 && first >= firstHighlightPosition)) {
topUnreadIndicator.setVisibility(View.VISIBLE);
topUnreadIndicatorColor.setBackgroundResource(R.drawable.highlight_red);
}
}
if(bottomUnreadIndicator != null) {
if(lastUnreadPosition != -1 && last <= lastUnreadPosition) {
bottomUnreadIndicator.setVisibility(View.VISIBLE);
bottomUnreadIndicatorColor.setBackgroundResource(R.drawable.selected_blue);
} else {
bottomUnreadIndicator.setVisibility(View.GONE);
}
if((firstHighlightPosition != -1 && last <= firstHighlightPosition) ||
(lastHighlightPosition != -1 && last <= lastHighlightPosition)) {
bottomUnreadIndicator.setVisibility(View.VISIBLE);
bottomUnreadIndicatorColor.setBackgroundResource(R.drawable.highlight_red);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.bufferslist, null);
errorMsg = (TextView)view.findViewById(R.id.errorMsg);
connecting = (RelativeLayout)view.findViewById(R.id.connecting);
topUnreadIndicator = (LinearLayout)view.findViewById(R.id.topUnreadIndicator);
topUnreadIndicator.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int scrollTo = adapter.unreadPositionAbove(getListView().getFirstVisiblePosition());
if(scrollTo > 0)
getListView().setSelection(scrollTo-1);
else
getListView().setSelection(0);
updateUnreadIndicators(getListView().getFirstVisiblePosition(), getListView().getLastVisiblePosition());
}
});
topUnreadIndicatorColor = (LinearLayout)view.findViewById(R.id.topUnreadIndicatorColor);
bottomUnreadIndicator = (LinearLayout)view.findViewById(R.id.bottomUnreadIndicator);
bottomUnreadIndicator.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int offset = getListView().getLastVisiblePosition() - getListView().getFirstVisiblePosition();
int scrollTo = adapter.unreadPositionBelow(getListView().getLastVisiblePosition()) - offset + 2;
if(scrollTo < adapter.getCount())
getListView().setSelection(scrollTo);
else
getListView().setSelection(adapter.getCount() - 1);
updateUnreadIndicators(getListView().getFirstVisiblePosition(), getListView().getLastVisiblePosition());
}
});
bottomUnreadIndicatorColor = (LinearLayout)view.findViewById(R.id.bottomUnreadIndicatorColor);
listView = (ListView)view.findViewById(android.R.id.list);
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
updateUnreadIndicators(firstVisibleItem, firstVisibleItem+visibleItemCount-1);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
});
if(savedInstanceState != null && savedInstanceState.containsKey("data")) {
ArrayList<Integer> expandedArchives = savedInstanceState.getIntegerArrayList("expandedArchives");
Iterator<Integer> i = expandedArchives.iterator();
while(i.hasNext()) {
Integer cid = i.next();
mExpandArchives.put(cid, true);
}
adapter = new BufferListAdapter(this);
adapter.setItems((ArrayList<BufferListEntry>) savedInstanceState.getSerializable("data"));
setListAdapter(adapter);
listView.setSelection(savedInstanceState.getInt("scrollPosition"));
}
return view;
}
@Override
public void onSaveInstanceState(Bundle state) {
if(adapter != null && adapter.data != null && adapter.data.size() > 0) {
ArrayList<Integer> expandedArchives = new ArrayList<Integer>();
ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers();
Iterator<ServersDataSource.Server> i = servers.iterator();
while(i.hasNext()) {
ServersDataSource.Server s = i.next();
if(mExpandArchives.get(s.cid, false))
expandedArchives.add(s.cid);
}
state.putSerializable("data", adapter.data);
state.putIntegerArrayList("expandedArchives", expandedArchives);
if(listView != null)
state.putInt("scrollPosition", listView.getFirstVisiblePosition());
}
}
public void onResume() {
super.onResume();
conn = NetworkConnection.getInstance();
conn.addHandler(mHandler);
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
view.setBackgroundResource(R.drawable.disconnected_yellow);
} else {
view.setBackgroundResource(R.drawable.background_blue);
connecting.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
if(adapter != null)
adapter.showProgress(-1);
new RefreshTask().execute((Void)null);
}
@Override
public void onPause() {
super.onPause();
if(conn != null)
conn.removeHandler(mHandler);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnBufferSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnBufferSelectedListener");
}
}
public void onListItemClick(ListView l, View v, int position, long id) {
BufferListEntry e = (BufferListEntry)adapter.getItem(position);
String type = null;
switch(e.type) {
case TYPE_ARCHIVES_HEADER:
mExpandArchives.put(e.cid, !mExpandArchives.get(e.cid, false));
new RefreshTask().execute((Void)null);
return;
case TYPE_SERVER:
type = "console";
break;
case TYPE_CHANNEL:
type = "channel";
break;
case TYPE_CONVERSATION:
type = "conversation";
break;
}
adapter.showProgress(position);
mListener.onBufferSelected(e.cid, e.bid, e.name, e.last_seen_eid, e.min_eid, type, e.joined, e.archived, e.status);
}
private void updateReconnecting() {
if(conn.getReconnectTimestamp() > 0) {
String plural = "";
int seconds = (int)((conn.getReconnectTimestamp() - System.currentTimeMillis()) / 1000);
if(seconds != 1)
plural = "s";
if(seconds < 1)
errorMsg.setText("Connecting");
else if(seconds > 10 && error != null)
errorMsg.setText(error +"\n\nReconnecting in\n" + seconds + " second" + plural);
else
errorMsg.setText("Reconnecting in\n" + seconds + " second" + plural);
if(countdownTimer != null)
countdownTimer.cancel();
countdownTimer = new Timer();
countdownTimer.schedule( new TimerTask(){
public void run() {
if(conn.getState() == NetworkConnection.STATE_DISCONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
updateReconnecting();
}
});
}
countdownTimer = null;
}
}, 1000);
} else {
errorMsg.setText("Offline");
}
}
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case NetworkConnection.EVENT_CONNECTIVITY:
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
view.setBackgroundResource(R.drawable.disconnected_yellow);
} else {
view.setBackgroundResource(R.drawable.background_blue);
errorMsg.setText("Loading");
error = null;
}
if(conn.getState() == NetworkConnection.STATE_CONNECTING) {
errorMsg.setText("Connecting");
error = null;
}
else if(conn.getState() == NetworkConnection.STATE_DISCONNECTED)
updateReconnecting();
if(adapter != null)
adapter.notifyDataSetChanged();
break;
case NetworkConnection.EVENT_FAILURE_MSG:
IRCCloudJSONObject o = (IRCCloudJSONObject)msg.obj;
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
try {
error = o.getString("message");
if(error.equals("temp_unavailable"))
error = "Your account is temporarily unavailable";
updateReconnecting();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_BACKLOG_END:
case NetworkConnection.EVENT_USERINFO:
case NetworkConnection.EVENT_MAKESERVER:
case NetworkConnection.EVENT_STATUSCHANGED:
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_MAKEBUFFER:
case NetworkConnection.EVENT_DELETEBUFFER:
case NetworkConnection.EVENT_BUFFERMSG:
case NetworkConnection.EVENT_HEARTBEATECHO:
case NetworkConnection.EVENT_BUFFERARCHIVED:
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
case NetworkConnection.EVENT_RENAMECONVERSATION:
case NetworkConnection.EVENT_PART:
new RefreshTask().execute((Void)null);
break;
default:
break;
}
}
};
@SuppressLint("NewApi")
public void scrollToTop() {
if(listView != null) {
if(Build.VERSION.SDK_INT >= 11)
listView.smoothScrollToPositionFromTop(0, 0, 200);
else
listView.setSelection(0);
}
}
public interface OnBufferSelectedListener {
public void onBufferSelected(int cid, int bid, String name, long last_seen_eid, long min_eid, String type, int joined, int archived, String status);
}
}
|
package com.simplenote.android.ui;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.widget.EditText;
import com.simplenote.android.Constants;
import com.simplenote.android.R;
import com.simplenote.android.model.Note;
import com.simplenote.android.persistence.SimpleNoteDao;
/**
* Handle the note editing
* @author bryanjswift
*/
public class SimpleNoteEdit extends Activity {
private static final String LOGGING_TAG = Constants.TAG + "SimpleNoteEdit";
// Final variables
private final SimpleNoteDao dao;
// Mutable instance variables
private long mNoteId = 0L;
private String mOriginalBody = "";
private boolean mActivityStateSaved = false;
/**
* Default constructor to setup final fields
*/
public SimpleNoteEdit() {
this.dao = new SimpleNoteDao(this);
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOGGING_TAG, "Running creating new SimpleNoteEdit Activity");
setContentView(R.layout.edit_note);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
mNoteId = extras.getLong(BaseColumns._ID);
mOriginalBody = extras.getString(SimpleNoteDao.BODY);
} else {
mNoteId = savedInstanceState.getLong(BaseColumns._ID);
}
final Note dbNote = dao.retrieve(mNoteId);
if (savedInstanceState == null && mOriginalBody == null) {
mOriginalBody = dbNote.getBody();
} else if (savedInstanceState != null && mOriginalBody == null) {
mOriginalBody = savedInstanceState.getString(SimpleNoteDao.BODY);
}
setTitle(getString(R.string.app_name) + " - " + dbNote.getTitle());
((EditText) findViewById(R.id.body)).setText(dbNote.getBody());
}
/**
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.d(LOGGING_TAG, "Resuming SimpleNoteEdit");
mActivityStateSaved = false;
}
/**
* Called before on pause, save data here so SimpleEditNote can be relaunched
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(LOGGING_TAG, "Saving instance state");
mActivityStateSaved = true;
// Make sure the note id is set in the saved state
outState.putLong(BaseColumns._ID, mNoteId);
outState.putString(SimpleNoteDao.BODY, mOriginalBody);
}
/**
* When user leaves this view save the note and set a result
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.d(LOGGING_TAG, "Firing onPause and handling note saving if needed");
// if text is unchanged send a CANCELLED result, otherwise save and send an OK result
if (needsSave() && !mActivityStateSaved) {
save();
} else {
Intent intent = getIntent();
setResult(RESULT_CANCELED, intent);
}
}
/**
* @see android.app.Activity#onBackPressed()
*/
@Override
public void onBackPressed() {
//super.onBackPressed();
Log.d(LOGGING_TAG, "Back button pressed");
if (needsSave()) {
// save finishes the Activity with an OK result
save();
} else {
// supr.onBackPressed finishes the Activity with a CANCELLED result
super.onBackPressed();
}
}
/**
* Checks if the body of the note has been updated compared to what was in the DB
* when this Activity was created
* @return whether or note the note body has changed
*/
private boolean needsSave() {
final String body = ((EditText) findViewById(R.id.body)).getText().toString();
return !mOriginalBody.equals(body);
}
/**
* Saves the note with data from the view and finishes this Activity with an OK result
*/
private void save() {
Log.d(LOGGING_TAG, "Save the note with updated values");
final String body = ((EditText) findViewById(R.id.body)).getText().toString();
final String now = Constants.serverDateFormat.format(new Date());
final Intent intent = getIntent();
// get the note as it is from the db, set new fields values and save it
final Note note = dao.save(dao.retrieve(mNoteId).setBody(body).setDateModified(now));
intent.putExtra(BaseColumns._ID, note.getId());
intent.putExtra(SimpleNoteDao.BODY, note.getBody());
intent.putExtra(SimpleNoteDao.MODIFY, note.getDateModified());
setResult(RESULT_OK, intent);
finish();
}
}
|
package com.iskrembilen.quasseldroid.gui;
import android.*;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.iskrembilen.quasseldroid.*;
import com.iskrembilen.quasseldroid.R;
import com.iskrembilen.quasseldroid.service.CoreConnService;
import com.iskrembilen.quasseldroid.util.ThemeUtil;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
public class NicksActivity extends Activity{
private static final String TAG = NicksActivity.class.getSimpleName();
private ResultReceiver statusReceiver;
private NicksAdapter adapter;
private ExpandableListView list;
private int bufferId;
private int currentTheme;
private static final int[] EXPANDED_STATE = {android.R.attr.state_expanded};
private static final int[] NOT_EXPANDED_STATE = {android.R.attr.state_empty};
SharedPreferences preferences;
OnSharedPreferenceChangeListener sharedPreferenceChangeListener;
private Boolean showLag = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
setTheme(ThemeUtil.theme);
super.onCreate(savedInstanceState);
currentTheme = ThemeUtil.theme;
setContentView(R.layout.nick_layout);
initActionBar();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
showLag = preferences.getBoolean(getString(R.string.preference_show_lag), false);
Intent intent = getIntent();
if(intent.hasExtra(ChatActivity.BUFFER_ID)) {
bufferId = intent.getIntExtra(ChatActivity.BUFFER_ID, 0);
Log.d(TAG, "Intent has bufferid" + bufferId);
}
adapter = new NicksAdapter(this);
list = (ExpandableListView)findViewById(R.id.userList);
list.setAdapter(adapter);
statusReceiver = new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode==CoreConnService.CONNECTION_DISCONNECTED) {
finish();
} else if(resultCode==CoreConnService.LATENCY_CORE) {
if (resultData.getInt(CoreConnService.LATENCY_CORE_KEY) > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setActionBarSubtitle(String.format(getResources().getString(R.string.title_lag), resultData.getInt(CoreConnService.LATENCY_CORE_KEY)));
} else {
setTitle(getResources().getString(R.string.app_name) + " - "
+ String.format(getResources().getString(R.string.title_lag), resultData.getInt(CoreConnService.LATENCY_CORE_KEY)));
}
}
}
super.onReceiveResult(resultCode, resultData);
}
};
sharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(getResources().getString(R.string.preference_show_lag))){
showLag = preferences.getBoolean(getString(R.string.preference_show_lag), false);
if(!showLag) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setActionBarSubtitle("");
} else {
setTitle(getResources().getString(R.string.app_name));
}
}
}
}
};
preferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); //To avoid GC issues
}
@TargetApi(11)
private void setActionBarSubtitle(String subtitle) {
getActionBar().setSubtitle(subtitle);
}
@TargetApi(14)
private void initActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
protected void onStart() {
super.onStart();
if(ThemeUtil.theme != currentTheme) {
Intent intent = new Intent(this, BufferActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
doBindService();
}
@Override
protected void onStop() {
super.onStop();
doUnbindService();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, ChatActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(ChatActivity.BUFFER_ID, bufferId);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public class NicksAdapter extends BaseExpandableListAdapter implements Observer{
private LayoutInflater inflater;
private UserCollection users;
public NicksAdapter(Context context) {
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.users = null;
}
public void setUsers(UserCollection users) {
users.addObserver(this);
this.users = users;
notifyDataSetChanged();
for(int i=0; i<getGroupCount();i++) {
list.expandGroup(i);
}
}
@Override
public void update(Observable observable, Object data) {
if(data == null) {
return;
}
switch ((Integer)data) {
case R.id.BUFFERUPDATE_USERSCHANGED:
notifyDataSetChanged();
break;
}
}
public void stopObserving() {
users.deleteObserver(this);
}
@Override
public IrcUser getChild(int groupPosition, int childPosition) {
return getGroup(groupPosition).second.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
//TODO: This will cause bugs when you have more than 99 children in a group
return groupPosition*100 + childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ViewHolderChild holder = null;
if (convertView==null) {
convertView = inflater.inflate(R.layout.nicklist_item, null);
holder = new ViewHolderChild();
holder.nickView = (TextView)convertView.findViewById(R.id.nicklist_nick_view);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild)convertView.getTag();
}
IrcUser entry = getChild(groupPosition, childPosition);
holder.nickView.setText(entry.nick);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
if (this.users==null) return 0;
return getGroup(groupPosition).second.size();
}
@Override
public Pair<IrcMode,List<IrcUser>> getGroup(int groupPosition) {
int counter = 0;
for(IrcMode mode: IrcMode.values()){
if (counter == groupPosition){
return new Pair<IrcMode, List<IrcUser>>(mode,users.getUniqueUsersWithMode(mode));
} else {
counter++;
}
}
return null;
}
@Override
public int getGroupCount() {
return IrcMode.values().length;
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ViewHolderGroup holder = null;
if (convertView==null) {
convertView = inflater.inflate(R.layout.nicklist_group_item, null);
holder = new ViewHolderGroup();
holder.nameView = (TextView)convertView.findViewById(R.id.nicklist_group_name_view);
holder.imageView = (ImageView)convertView.findViewById(R.id.nicklist_group_image_view);
holder.expanderView = (ImageView)convertView.findViewById(R.id.nicklist_expander_image_view);
holder.groupHolderView = (LinearLayout)convertView.findViewById(R.id.nicklist_holder_view);
convertView.setTag(holder);
} else {
holder = (ViewHolderGroup)convertView.getTag();
}
Pair<IrcMode, List<IrcUser>> group = getGroup(groupPosition);
if(group.second.size()<1){
holder.nameView.setVisibility(View.GONE);
holder.imageView.setVisibility(View.GONE);
holder.expanderView.setVisibility(View.GONE);
holder.groupHolderView.setPadding(0,0,0,0);
}else{
if(group.second.size()>1){
holder.nameView.setText(group.second.size() + " "+group.first.modeName+group.first.pluralization);
} else {
holder.nameView.setText(group.second.size() + " "+group.first.modeName);
}
holder.nameView.setVisibility(View.VISIBLE);
holder.imageView.setVisibility(View.VISIBLE);
holder.expanderView.setVisibility(View.VISIBLE);
holder.imageView.setImageResource(group.first.iconResource);
holder.groupHolderView.setPadding(5,2,2,2);
holder.expanderView.getDrawable().setState(list.isGroupExpanded(groupPosition)? EXPANDED_STATE : NOT_EXPANDED_STATE);
}
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
public static class ViewHolderChild {
public TextView nickView;
}
public static class ViewHolderGroup {
public TextView nameView;
public ImageView imageView;
public ImageView expanderView;
public LinearLayout groupHolderView;
}
/**
* Code for service binding:
*/
private CoreConnService boundConnService;
private Boolean isBound;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
Log.d(TAG, "BINDING ON SERVICE DONE");
boundConnService = ((CoreConnService.LocalBinder)service).getService();
Buffer buffer = boundConnService.getBuffer(bufferId, null);
adapter.setUsers(buffer.getUsers());
boundConnService.registerStatusReceiver(statusReceiver);
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
boundConnService = null;
}
};
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(NicksActivity.this, CoreConnService.class), mConnection, Context.BIND_AUTO_CREATE);
isBound = true;
Log.i(TAG, "BINDING");
}
void doUnbindService() {
if (isBound) {
Log.i(TAG, "Unbinding service");
// Detach our existing connection.
adapter.stopObserving();
boundConnService.unregisterStatusReceiver(statusReceiver);
unbindService(mConnection);
isBound = false;
}
}
}
|
package com.stuffwithstuff.magpie.parser;
import java.util.HashSet;
import java.util.Set;
public class Grammar {
public Grammar() {
prefix(TokenType.BOOL, new LiteralParser());
prefix(TokenType.INT, new LiteralParser());
prefix(TokenType.NOTHING, new LiteralParser());
prefix(TokenType.STRING, new LiteralParser());
prefix(TokenType.LEFT_PAREN, new ParenthesisPrefixParser());
prefix(TokenType.LEFT_BRACKET, new BracketPrefixParser());
prefix(TokenType.NAME, new NameParser());
prefix(TokenType.FIELD, new FieldParser());
prefix("break", new BreakParser());
prefix("def", new DefParser());
prefix("defclass", new ClassParser());
prefix("do", new DoParser());
prefix("fn", new FnParser());
prefix("for", new LoopParser());
prefix("if", new IfParser());
prefix("import", new ImportParser());
prefix("match", new MatchParser());
prefix("return", new ReturnParser());
prefix("throw", new ThrowParser());
prefix("var", new VarParser());
prefix("while", new LoopParser());
infix(TokenType.NAME, new NameParser());
infix(TokenType.COMMA, new CommaParser());
infix(TokenType.EQUALS, new EqualsParser());
infix(TokenType.LEFT_BRACKET, new BracketInfixParser());
infix("*", Precedence.PRODUCT);
infix("/", Precedence.PRODUCT);
infix("%", Precedence.PRODUCT);
infix("+", Precedence.TERM);
infix("-", Precedence.TERM);
infix("<", Precedence.COMPARISON);
infix(">", Precedence.COMPARISON);
infix("<=", Precedence.COMPARISON);
infix(">=", Precedence.COMPARISON);
infix("==", Precedence.ASSIGNMENT);
infix("!=", Precedence.ASSIGNMENT);
reserve("-> case catch else end then");
reserve("break def defclass do fn for if import match nothing return throw val var while");
}
public PrefixParser getPrefixParser(Token token) {
return mPrefixParsers.get(token);
}
public InfixParser getInfixParser(Token token) {
return mInfixParsers.get(token);
}
/**
* Gets whether or not this token is a reserved word. Reserved words like
* "else" and "then" are claimed for special use by mixfix parsers, so can't
* be parsed on their own.
*
* @param token The token to test
* @return True if the token is a reserved name token.
*/
public boolean isReserved(String name) {
return mReservedWords.contains(name);
}
/**
* Gets whether or not this token is a reserved word. Reserved words like
* "else" and "then" are claimed for special use by mixfix parsers, so can't
* be parsed on their own.
*
* @param token The token to test
* @return True if the token is a reserved name token.
*/
public boolean isReserved(Token token) {
return (token.getType() == TokenType.NAME) &&
isReserved(token.getString());
}
public int getStickiness(Token token) {
int stickiness = 0;
// A reserved word can't start an infix expression. Prevents us from
// parsing a keyword as an identifier.
if (isReserved(token)) return 0;
// If we have a prefix parser for this token's name, then that takes
// precedence. Prevents us from parsing a keyword as an identifier.
if ((token.getValue() instanceof String) &&
mPrefixParsers.isReserved(token.getString())) return 0;
InfixParser parser = mInfixParsers.get(token);
if (parser != null) {
stickiness = parser.getStickiness();
}
return stickiness;
}
private void prefix(TokenType type, PrefixParser parser) {
mPrefixParsers.define(type, parser);
}
private void prefix(String keyword, PrefixParser parser) {
mPrefixParsers.define(keyword, parser);
}
private void infix(TokenType type, InfixParser parser) {
mInfixParsers.define(type, parser);
}
private void infix(String keyword, InfixParser parser) {
mInfixParsers.define(keyword, parser);
}
private void infix(String keyword, int stickiness) {
infix(keyword, new InfixOperatorParser(stickiness, false));
}
private void reserve(String wordString) {
String[] words = wordString.split(" ");
for (int i = 0; i < words.length; i++) {
mReservedWords.add(words[i]);
}
}
private final ParserTable<PrefixParser> mPrefixParsers =
new ParserTable<PrefixParser>();
private final ParserTable<InfixParser> mInfixParsers =
new ParserTable<InfixParser>();
private final Set<String> mReservedWords = new HashSet<String>();
}
|
package com.jcwhatever.arborianprotect;
import com.jcwhatever.arborianprotect.commands.Dispatcher;
import com.jcwhatever.arborianprotect.listeners.BlockListener;
import com.jcwhatever.arborianprotect.listeners.MobSpawnListener;
import com.jcwhatever.arborianprotect.listeners.PlayerListener;
import com.jcwhatever.arborianprotect.regions.ProtectedRegionManager;
import com.jcwhatever.arborianprotect.worlds.ProtectedWorldManager;
import com.jcwhatever.nucleus.NucleusPlugin;
import com.jcwhatever.nucleus.storage.DataPath;
import com.jcwhatever.nucleus.storage.DataStorage;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.utils.text.TextColor;
/**
* A lightweight world and region protection plugin.
*/
public class ArborianProtect extends NucleusPlugin {
private static ArborianProtect _instance;
private ProtectedWorldManager _worldManager;
private ProtectedRegionManager _regionManager;
/**
* Get the current plugin instance.
*/
public static ArborianProtect getPlugin() {
return _instance;
}
/**
* Get the world manager.
*/
public static ProtectedWorldManager getWorldManager() {
return _instance._worldManager;
}
/**
* Get the region manager.
*/
public static ProtectedRegionManager getRegionManager() {
return _instance._regionManager;
}
@Override
public String getChatPrefix() {
return TextColor.WHITE + "[" + TextColor.GREEN + "Protect" + TextColor.WHITE + "] ";
}
@Override
public String getConsolePrefix() {
return "[ArborianProtect] ";
}
@Override
protected void onPreEnable() {
_instance = this;
}
@Override
protected void onPostPreEnable() {
IDataNode worldNode = DataStorage.get(this, new DataPath("worlds"));
worldNode.load();
IDataNode regionNode = DataStorage.get(this, new DataPath("regions"));
regionNode.load();
_worldManager = new ProtectedWorldManager(worldNode);
_regionManager = new ProtectedRegionManager(regionNode);
// setup listeners in post pre-enable to ensure they
// are running when server first starts
registerEventListeners(
new BlockListener(),
new MobSpawnListener(),
new PlayerListener());
}
@Override
protected void onEnablePlugin() {
registerCommands(new Dispatcher(this));
}
@Override
protected void onDisablePlugin() {
_instance = null;
}
}
|
package com.vaadin.terminal.gwt.client.ui;
import java.util.Set;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.DomEvent.Type;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderInformation;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
public class VPanel extends SimplePanel implements Container {
public static final String CLICK_EVENT_IDENTIFIER = "click";
public static final String CLASSNAME = "v-panel";
ApplicationConnection client;
String id;
private final Element captionNode = DOM.createDiv();
private final Element captionText = DOM.createSpan();
private Icon icon;
private final Element bottomDecoration = DOM.createDiv();
private final Element contentNode = DOM.createDiv();
private Element errorIndicatorElement;
private String height;
private Paintable layout;
ShortcutActionHandler shortcutHandler;
private String width = "";
private Element geckoCaptionMeter;
private int scrollTop;
private int scrollLeft;
private RenderInformation renderInformation = new RenderInformation();
private int borderPaddingHorizontal = -1;
private int borderPaddingVertical = -1;
private int captionPaddingHorizontal = -1;
private int captionMarginLeft = -1;
private boolean rendering;
private int contentMarginLeft = -1;
private String previousStyleName;
private ClickEventHandler clickEventHandler = new ClickEventHandler(this,
CLICK_EVENT_IDENTIFIER) {
@Override
protected <H extends EventHandler> HandlerRegistration registerHandler(
H handler, Type<H> type) {
return addDomHandler(handler, type);
}
};
public VPanel() {
super();
DivElement captionWrap = Document.get().createDivElement();
captionWrap.appendChild(captionNode);
captionNode.appendChild(captionText);
captionWrap.setClassName(CLASSNAME + "-captionwrap");
captionNode.setClassName(CLASSNAME + "-caption");
contentNode.setClassName(CLASSNAME + "-content");
bottomDecoration.setClassName(CLASSNAME + "-deco");
getElement().appendChild(captionWrap);
getElement().appendChild(contentNode);
getElement().appendChild(bottomDecoration);
setStyleName(CLASSNAME);
DOM.sinkEvents(getElement(), Event.ONKEYDOWN);
DOM.sinkEvents(contentNode, Event.ONSCROLL);
contentNode.getStyle().setProperty("position", "relative");
getElement().getStyle().setProperty("overflow", "hidden");
}
@Override
protected Element getContainerElement() {
return contentNode;
}
private void setCaption(String text) {
DOM.setInnerHTML(captionText, text);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
if (!uidl.hasAttribute("cached")) {
// Handle caption displaying and style names, prior generics.
// Affects size
// calculations
// Restore default stylenames
contentNode.setClassName(CLASSNAME + "-content");
bottomDecoration.setClassName(CLASSNAME + "-deco");
captionNode.setClassName(CLASSNAME + "-caption");
boolean hasCaption = false;
if (uidl.hasAttribute("caption")
&& !uidl.getStringAttribute("caption").equals("")) {
setCaption(uidl.getStringAttribute("caption"));
hasCaption = true;
} else {
setCaption("");
captionNode.setClassName(CLASSNAME + "-nocaption");
}
// Add proper stylenames for all elements. This way we can prevent
// unwanted CSS selector inheritance.
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(
" ");
final String captionBaseClass = CLASSNAME
+ (hasCaption ? "-caption" : "-nocaption");
final String contentBaseClass = CLASSNAME + "-content";
final String decoBaseClass = CLASSNAME + "-deco";
String captionClass = captionBaseClass;
String contentClass = contentBaseClass;
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
captionClass += " " + captionBaseClass + "-" + styles[i];
contentClass += " " + contentBaseClass + "-" + styles[i];
decoClass += " " + decoBaseClass + "-" + styles[i];
}
captionNode.setClassName(captionClass);
contentNode.setClassName(contentClass);
bottomDecoration.setClassName(decoClass);
}
}
// Ensure correct implementation
if (client.updateComponent(this, uidl, false)) {
rendering = false;
return;
}
clickEventHandler.handleEventHandlerRegistration(client);
this.client = client;
id = uidl.getId();
setIconUri(uidl, client);
handleError(uidl);
// Render content
final UIDL layoutUidl = uidl.getChildUIDL(0);
final Paintable newLayout = client.getPaintable(layoutUidl);
if (newLayout != layout) {
if (layout != null) {
client.unregisterPaintable(layout);
}
setWidget((Widget) newLayout);
layout = newLayout;
}
layout.updateFromUIDL(layoutUidl, client);
runHacks(false);
// We may have actions attached to this panel
if (uidl.getChildCount() > 1) {
final int cnt = uidl.getChildCount();
for (int i = 1; i < cnt; i++) {
UIDL childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
}
}
}
if (uidl.hasVariable("scrollTop")
&& uidl.getIntVariable("scrollTop") != scrollTop) {
scrollTop = uidl.getIntVariable("scrollTop");
contentNode.setScrollTop(scrollTop);
// re-read the actual scrollTop in case invalid value was set
// (scrollTop != 0 when no scrollbar exists, other values would be
// caught by scroll listener), see #3784
scrollTop = contentNode.getScrollTop();
}
if (uidl.hasVariable("scrollLeft")
&& uidl.getIntVariable("scrollLeft") != scrollLeft) {
scrollLeft = uidl.getIntVariable("scrollLeft");
contentNode.setScrollLeft(scrollLeft);
// re-read the actual scrollTop in case invalid value was set
// (scrollTop != 0 when no scrollbar exists, other values would be
// caught by scroll listener), see #3784
scrollLeft = contentNode.getScrollLeft();
}
rendering = false;
}
@Override
public void setStyleName(String style) {
if (!style.equals(previousStyleName)) {
super.setStyleName(style);
detectContainerBorders();
previousStyleName = style;
}
}
private void handleError(UIDL uidl) {
if (uidl.hasAttribute("error")) {
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createSpan();
DOM.setElementProperty(errorIndicatorElement, "className",
"v-errorindicator");
DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
sinkEvents(Event.MOUSEEVENTS);
}
DOM.insertBefore(captionNode, errorIndicatorElement, captionText);
} else if (errorIndicatorElement != null) {
DOM.removeChild(captionNode, errorIndicatorElement);
errorIndicatorElement = null;
}
}
private void setIconUri(UIDL uidl, ApplicationConnection client) {
final String iconUri = uidl.hasAttribute("icon") ? uidl
.getStringAttribute("icon") : null;
if (iconUri == null) {
if (icon != null) {
DOM.removeChild(captionNode, icon.getElement());
icon = null;
}
} else {
if (icon == null) {
icon = new Icon(client);
DOM.insertChild(captionNode, icon.getElement(), 0);
}
icon.setUri(iconUri);
}
}
public void runHacks(boolean runGeckoFix) {
if (BrowserInfo.get().isIE6() && width != null && !width.equals("")) {
/*
* IE6 requires overflow-hidden elements to have a width specified
* so we calculate the width of the content and caption nodes when
* no width has been specified.
*/
/*
* Fixes #1923 VPanel: Horizontal scrollbar does not appear in IE6
* with wide content
*/
/*
* Caption must be shrunk for parent measurements to return correct
* result in IE6
*/
DOM.setStyleAttribute(captionNode, "width", "1px");
int parentPadding = Util.measureHorizontalPaddingAndBorder(
getElement(), 0);
int parentWidthExcludingPadding = getElement().getOffsetWidth()
- parentPadding;
Util.setWidthExcludingPaddingAndBorder(captionNode,
parentWidthExcludingPadding - getCaptionMarginLeft(), 26,
false);
int contentMarginLeft = getContentMarginLeft();
Util.setWidthExcludingPaddingAndBorder(contentNode,
parentWidthExcludingPadding - contentMarginLeft, 2, false);
}
if ((BrowserInfo.get().isIE() || BrowserInfo.get().isFF2())
&& (width == null || width.equals(""))) {
/*
* IE and FF2 needs width to be specified for the root DIV so we
* calculate that from the sizes of the caption and layout
*/
int captionWidth = captionText.getOffsetWidth()
+ getCaptionMarginLeft() + getCaptionPaddingHorizontal();
int layoutWidth = ((Widget) layout).getOffsetWidth()
+ getContainerBorderWidth();
int width = layoutWidth;
if (captionWidth > width) {
width = captionWidth;
}
if (BrowserInfo.get().isIE7()) {
Util.setWidthExcludingPaddingAndBorder(captionNode, width
- getCaptionMarginLeft(), 26, false);
}
super.setWidth(width + "px");
}
if (runGeckoFix && BrowserInfo.get().isGecko()) {
// workaround for #1764
if (width == null || width.equals("")) {
if (geckoCaptionMeter == null) {
geckoCaptionMeter = DOM.createDiv();
DOM.appendChild(captionNode, geckoCaptionMeter);
}
int captionWidth = DOM.getElementPropertyInt(captionText,
"offsetWidth");
int availWidth = DOM.getElementPropertyInt(geckoCaptionMeter,
"offsetWidth");
if (captionWidth == availWidth) {
/*
* Caption width defines panel width -> Gecko based browsers
* somehow fails to float things right, without the
* "noncode" below
*/
setWidth(getOffsetWidth() + "px");
} else {
DOM.setStyleAttribute(captionNode, "width", "");
}
}
}
client.runDescendentsLayout(this);
Util.runWebkitOverflowAutoFix(contentNode);
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
final Element target = DOM.eventGetTarget(event);
final int type = DOM.eventGetType(event);
if (type == Event.ONKEYDOWN && shortcutHandler != null) {
shortcutHandler.handleKeyboardEvent(event);
return;
}
if (type == Event.ONSCROLL) {
int newscrollTop = DOM.getElementPropertyInt(contentNode,
"scrollTop");
int newscrollLeft = DOM.getElementPropertyInt(contentNode,
"scrollLeft");
if (client != null
&& (newscrollLeft != scrollLeft || newscrollTop != scrollTop)) {
scrollLeft = newscrollLeft;
scrollTop = newscrollTop;
client.updateVariable(id, "scrollTop", scrollTop, false);
client.updateVariable(id, "scrollLeft", scrollLeft, false);
}
} else if (captionNode.isOrHasChild(target)) {
if (client != null) {
client.handleTooltipEvent(event, this);
}
}
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
if (height != null && height != "") {
final int targetHeight = getOffsetHeight();
int containerHeight = targetHeight - captionNode.getOffsetHeight()
- bottomDecoration.getOffsetHeight()
- getContainerBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
DOM
.setStyleAttribute(contentNode, "height", containerHeight
+ "px");
} else {
DOM.setStyleAttribute(contentNode, "height", "");
}
if (!rendering) {
runHacks(true);
}
}
private int getCaptionMarginLeft() {
if (captionMarginLeft < 0) {
detectContainerBorders();
}
return captionMarginLeft;
}
private int getContentMarginLeft() {
if (contentMarginLeft < 0) {
detectContainerBorders();
}
return contentMarginLeft;
}
private int getCaptionPaddingHorizontal() {
if (captionPaddingHorizontal < 0) {
detectContainerBorders();
}
return captionPaddingHorizontal;
}
private int getContainerBorderHeight() {
if (borderPaddingVertical < 0) {
detectContainerBorders();
}
return borderPaddingVertical;
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
this.width = width;
super.setWidth(width);
if (!rendering) {
runHacks(true);
if (height.equals("")) {
// Width change may affect height
Util.updateRelativeChildrenAndSendSizeUpdateEvent(client, this);
}
}
}
private int getContainerBorderWidth() {
if (borderPaddingHorizontal < 0) {
detectContainerBorders();
}
return borderPaddingHorizontal;
}
private void detectContainerBorders() {
DOM.setStyleAttribute(contentNode, "overflow", "hidden");
borderPaddingHorizontal = Util.measureHorizontalBorder(contentNode);
borderPaddingVertical = Util.measureVerticalBorder(contentNode);
DOM.setStyleAttribute(contentNode, "overflow", "auto");
captionPaddingHorizontal = Util.measureHorizontalPaddingAndBorder(
captionNode, 26);
captionMarginLeft = Util.measureMarginLeft(captionNode);
contentMarginLeft = Util.measureMarginLeft(contentNode);
}
public boolean hasChildComponent(Widget component) {
if (component != null && component == layout) {
return true;
} else {
return false;
}
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
// TODO This is untested as no layouts require this
if (oldComponent != layout) {
return;
}
setWidget(newComponent);
layout = (Paintable) newComponent;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int h = 0;
if (width != null && !width.equals("")) {
w = getOffsetWidth() - getContainerBorderWidth();
if (w < 0) {
w = 0;
}
}
if (height != null && !height.equals("")) {
h = contentNode.getOffsetHeight() - getContainerBorderHeight();
if (h < 0) {
h = 0;
}
}
return new RenderSpace(w, h, true);
}
public boolean requestLayout(Set<Paintable> child) {
// content size change might cause change to its available space
// (scrollbars)
client.handleComponentRelativeSize((Widget) layout);
if (height != null && height != "" && width != null && width != "") {
/*
* If the height and width has been specified the child components
* cannot make the size of the layout change
*/
return true;
}
runHacks(false);
return !renderInformation.updateSize(getElement());
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP: layouts caption, errors etc not rendered in Panel
}
@Override
protected void onAttach() {
super.onAttach();
detectContainerBorders();
}
}
|
package com.markupartist.sthlmtraveling;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.markupartist.sthlmtraveling.SectionedAdapter.Section;
public class RoutesActivity extends ListActivity {
private final String TAG = "RoutesActivity";
private static final int DIALOG_NO_ROUTE_DETAILS_FOUND = 0;
private final int SECTION_EARLIER_ROUTES = 1;
private final int SECTION_ROUTES = 2;
private final int SECTION_LATER_ROUTES = 3;
private final Handler mHandler = new Handler();
private ArrayAdapter<Route> mRouteAdapter;
private TextView mFromView;
private TextView mToView;
/**
* Holds the current selected route, this is referenced by
* RouteDetailActivity.
*/
public static Route route;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.routes_list);
createSections();
mFromView = (TextView) findViewById(R.id.route_from);
mToView = (TextView) findViewById(R.id.route_to);
Bundle extras = getIntent().getExtras();
mFromView.setText(extras.getString("com.markupartist.sthlmtraveling.startPoint"));
mToView.setText(extras.getString("com.markupartist.sthlmtraveling.endPoint"));
}
private void createSections() {
// Earlier routes
ArrayAdapter<String> earlierAdapter =
new ArrayAdapter<String>(this, R.layout.simple_list_row);
earlierAdapter.add("Show earlier routes");
mSectionedAdapter.addSection(SECTION_EARLIER_ROUTES, "Earlier routes", earlierAdapter);
// Routes
ArrayList<Route> routes = Planner.getInstance().lastFoundRoutes();
mRouteAdapter = new ArrayAdapter<Route>(this, R.layout.routes_row, routes);
mRouteAdapter.setNotifyOnChange(true);
mSectionedAdapter.addSection(SECTION_ROUTES, "Routes", mRouteAdapter);
// Later routes
ArrayAdapter<String> laterAdapter =
new ArrayAdapter<String>(this, R.layout.simple_list_row);
laterAdapter.add("Show later routes");
mSectionedAdapter.addSection(SECTION_LATER_ROUTES, "Later routes", laterAdapter);
setListAdapter(mSectionedAdapter);
}
SectionedAdapter mSectionedAdapter = new SectionedAdapter() {
protected View getHeaderView(Section section, int index,
View convertView, ViewGroup parent) {
TextView result = (TextView) convertView;
if (convertView == null) {
result = (TextView) getLayoutInflater().inflate(R.layout.header, null);
}
result.setText(section.caption);
return (result);
}
};
/**
* Updates routes in the UI after a search.
*/
final Runnable mUpdateRoutes = new Runnable() {
@Override public void run() {
final ArrayList<Route> routes = Planner.getInstance().lastFoundRoutes();
//TODO: Should find a better way than resetting the adapter like this.
mRouteAdapter = new ArrayAdapter<Route>(RoutesActivity.this, R.layout.routes_row, routes);
mSectionedAdapter.notifyDataSetChanged();
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object item = mSectionedAdapter.getItem(position);
if (item instanceof Route) {
route = (Route) item;
findRouteDetails(route);
} else {
Section section = mSectionedAdapter.getSection(position);
Log.d(TAG, "section.id=" + section.id);
if (section.id == SECTION_EARLIER_ROUTES) {
final ProgressDialog earlierProgress = ProgressDialog.show(RoutesActivity.this, "", getText(R.string.loading), true);
earlierProgress.setCancelable(true);
new Thread() {
public void run() {
try {
Planner.getInstance().findEarlierRoutes();
mHandler.post(mUpdateRoutes);
earlierProgress.dismiss();
} catch (Exception e) {
earlierProgress.dismiss();
}
}
}.start();
} else if (section.id == SECTION_LATER_ROUTES) {
final ProgressDialog laterProgress = ProgressDialog.show(RoutesActivity.this, "", getText(R.string.loading), true);
new Thread() {
public void run() {
try {
Planner.getInstance().findLaterRoutes();
mHandler.post(mUpdateRoutes);
laterProgress.dismiss();
} catch (Exception e) {
laterProgress.dismiss();
}
}
}.start();
}
}
}
/**
* Find route details. Calls onSearchRouteDetailsResult when done.
* @param route the route to find details for
*/
private void findRouteDetails(final Route route) {
final ProgressDialog progressDialog =
ProgressDialog.show(this, "", getText(R.string.loading), true);
new Thread() {
public void run() {
try {
Planner.getInstance().findRouteDetails(route);
mHandler.post(new Runnable() {
@Override public void run() {
onSearchRouteDetailsResult();
}
});
progressDialog.dismiss();
} catch (Exception e) {
progressDialog.dismiss();
}
}
}.start();
}
/**
* Called when we got a route details search result.
*/
private void onSearchRouteDetailsResult() {
if (Planner.getInstance().lastFoundRouteDetail() != null
&& !Planner.getInstance().lastFoundRoutes().isEmpty()) {
Intent i = new Intent(RoutesActivity.this, RouteDetailActivity.class);
startActivity(i);
} else {
showDialog(DIALOG_NO_ROUTE_DETAILS_FOUND);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_search :
final Intent intent = new Intent(this, SearchActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_NO_ROUTE_DETAILS_FOUND:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
dialog = builder.setTitle("Unfortunately no route details was found")
.setMessage("Most likely your session has timed out.")
.setCancelable(true)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create();
break;
}
return dialog;
}
}
|
package ru.job4j;
public class Max {
public int max(int first, int second) {
int max = 0;
(first > second) ? max = first : max = second;
return max;
}
public int max(int first, int second, int third) {
(third > max.max()) ? max = third : max = max;
return max;
}
}
|
package com.opengamma.transport;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeFieldContainer;
import org.fudgemsg.FudgeMsgEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.util.ArgumentChecker;
/**
* Allows synchronous RPC-style semantics to be applied over a {@link FudgeRequestSender}.
* This class also supports multiplexing different clients over the same
* underlying transport channel using correlation IDs to multiplex the requests
* and responses.
*/
public abstract class FudgeSynchronousClient implements FudgeMessageReceiver {
/** Logger. */
private static final Logger s_logger = LoggerFactory.getLogger(FudgeSynchronousClient.class);
/**
* The default timeout.
*/
private static final long DEFAULT_TIMEOUT_IN_MILLISECONDS = 30 * 1000L;
/**
* The generator of correlation ids.
*/
private final AtomicLong _nextCorrelationId = new AtomicLong();
/**
* The Fudge request sender.
*/
private final FudgeRequestSender _requestSender;
/**
* The map of pending requests keyed by correlation id.
*/
private final Map<Long, ClientRequestHolder> _pendingRequests = new ConcurrentHashMap<Long, ClientRequestHolder>();
/**
* The timeout.
*/
private long _timeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MILLISECONDS;
/**
* Creates the client.
* @param requestSender the sender, not null
*/
protected FudgeSynchronousClient(final FudgeRequestSender requestSender) {
ArgumentChecker.notNull(requestSender, "requestSender");
_requestSender = requestSender;
}
/**
* Gets the request sender.
* @return the request sender, not null
*/
public FudgeRequestSender getRequestSender() {
return _requestSender;
}
/**
* Gets the timeout in milliseconds.
* @return the timeout
*/
public long getTimeoutInMilliseconds() {
return _timeoutInMilliseconds;
}
public void setTimeoutInMilliseconds(final long timeoutMilliseconds) {
_timeoutInMilliseconds = timeoutMilliseconds;
}
/**
* Gets the next id.
* @return the next numeric id
*/
protected long getNextCorrelationId() {
return _nextCorrelationId.incrementAndGet();
}
/**
* Sends the message.
* @param requestMsg the message, not null
* @param correlationId the message id
* @return the result
*/
protected FudgeFieldContainer sendRequestAndWaitForResponse(FudgeFieldContainer requestMsg, long correlationId) {
ClientRequestHolder requestHolder = new ClientRequestHolder();
_pendingRequests.put(correlationId, requestHolder);
try {
synchronized (getRequestSender()) {
getRequestSender().sendRequest(requestMsg, this);
}
try {
requestHolder.latch.await(getTimeoutInMilliseconds(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.interrupted();
s_logger.warn("Didn't get response to {} in {}ms", correlationId, getTimeoutInMilliseconds());
}
if (requestHolder.resultValue == null) {
throw new OpenGammaRuntimeException("Didn't receive a response message to " + correlationId + " in " + getTimeoutInMilliseconds() + "ms");
}
assert getCorrelationIdFromReply(requestHolder.resultValue) == correlationId;
return requestHolder.resultValue;
} finally {
_pendingRequests.remove(correlationId);
}
}
/**
* Receives a message from Fudge.
* @param fudgeContext the Fudge context, not null
* @param msgEnvelope the message, not null
*/
@Override
public void messageReceived(FudgeContext fudgeContext, FudgeMsgEnvelope msgEnvelope) {
final FudgeFieldContainer reply = msgEnvelope.getMessage();
final long correlationId = getCorrelationIdFromReply(reply);
final ClientRequestHolder requestHolder = _pendingRequests.remove(correlationId);
if (requestHolder == null) {
s_logger.warn("Got a response on non-pending correlation Id {}", correlationId);
return;
}
requestHolder.resultValue = reply;
requestHolder.latch.countDown();
}
/**
* Extracts the correlation id from the reply object.
* @param reply the reply
* @return the id
*/
protected abstract long getCorrelationIdFromReply(FudgeFieldContainer reply);
/**
* Data holder.
*/
private static final class ClientRequestHolder {
public FudgeFieldContainer resultValue; // CSIGNORE: simple holder object
public final CountDownLatch latch = new CountDownLatch(1); // CSIGNORE: simple holder object
}
}
|
package com.qmetry.qaf.automation.rest;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.annotations.SerializedName;
import com.qmetry.qaf.automation.data.BaseDataBean;
import com.qmetry.qaf.automation.keys.ApplicationProperties;
import com.qmetry.qaf.automation.util.StringUtil;
/**
* @author chirag.jayswal
*/
public class RestRequestBean extends BaseDataBean {
private String method = "GET";
private String baseUrl = "";
private String endPoint = "";
private Map<String, Object> headers = new HashMap<String, Object>();
private String[] accept = {};
private String schema = "";;
private String body = "";;
@SerializedName("query-parameters")
private Map<String, Object> queryParameters = new HashMap<String, Object>();
@SerializedName("form-parameters")
private Map<String, Object> formParameters = new HashMap<String, Object>();
public String getBaseUrl() {
return StringUtil.isNotBlank(baseUrl) ? baseUrl
: ApplicationProperties.SELENIUM_BASE_URL.getStringVal("");
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, Object> getHeaders() {
return headers;
}
public void setHeaders(Map<String, Object> headers) {
this.headers = headers;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Map<String, Object> getQueryParameters() {
return queryParameters;
}
public void setQueryParameters(Map<String, Object> parameters) {
this.queryParameters = parameters;
}
public String getEndPoint() {
return endPoint;
}
public void setEndPoint(String endpoint) {
this.endPoint = endpoint;
}
public String[] getAccept() {
return accept;
}
public void setAccept(String[] accept) {
this.accept = accept;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public Map<String, Object> getFormParameters() {
return formParameters;
}
public void setFormParameters(Map<String, Object> formParameters) {
this.formParameters = formParameters;
}
}
|
package com.relteq.sirius.db.exporter;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.validation.SchemaFactory;
import org.apache.torque.NoRowsException;
import org.apache.torque.TorqueException;
import org.apache.torque.util.Criteria;
import org.xml.sax.SAXException;
import com.relteq.sirius.om.*;
import com.relteq.sirius.simulator.SiriusErrorLog;
import com.relteq.sirius.simulator.SiriusException;
/**
* Loads a scenario from the database
*/
public class ScenarioRestorer {
public static void export(long id, String filename) throws SiriusException, JAXBException, SAXException {
com.relteq.sirius.simulator.Scenario scenario = ScenarioRestorer.getScenario(id);
scenario.setSchemaVersion(com.relteq.sirius.Version.get().getSchemaVersion());
JAXBContext jaxbc = JAXBContext.newInstance("com.relteq.sirius.jaxb");
Marshaller mrsh = jaxbc.createMarshaller();
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
mrsh.setSchema(sf.newSchema(ScenarioRestorer.class.getClassLoader().getResource("sirius.xsd")));
mrsh.marshal(scenario, new File(filename));
}
/**
* Load a scenario from the database
* @param id a scenario id
* @return the scenario
* @throws SiriusException
*/
public static com.relteq.sirius.simulator.Scenario getScenario(long id) throws SiriusException {
com.relteq.sirius.simulator.Scenario scenario = com.relteq.sirius.simulator.ObjectFactory.process(new ScenarioRestorer().restore(id));
if (null == scenario)
throw new SiriusException("Could not load scenario " + id + " from the database. See error log for details.");
return scenario;
}
com.relteq.sirius.simulator.JaxbObjectFactory factory = null;
private ScenarioRestorer() {
factory = new com.relteq.sirius.simulator.JaxbObjectFactory();
}
private com.relteq.sirius.simulator.Scenario restore(long id) throws SiriusException {
com.relteq.sirius.db.Service.ensureInit();
Scenarios db_scenario = null;
try {
db_scenario = ScenariosPeer.retrieveByPK(id);
} catch (NoRowsException exc) {
throw new SiriusException("Scenario " + id + " does not exist", exc);
} catch (TorqueException exc) {
throw new SiriusException(exc);
}
return (com.relteq.sirius.simulator.Scenario) restoreScenario(db_scenario);
}
/**
* Converts a numeric ID to a string
* @param id
* @return String
*/
private static String id2str(Long id) {
return id.toString();
}
private com.relteq.sirius.jaxb.Scenario restoreScenario(Scenarios db_scenario) throws SiriusException {
if (null == db_scenario) return null;
com.relteq.sirius.jaxb.Scenario scenario = factory.createScenario();
scenario.setId(id2str(db_scenario.getId()));
scenario.setName(db_scenario.getName());
scenario.setDescription(db_scenario.getDescription());
try{
scenario.setSettings(restoreSettings(db_scenario));
scenario.setNetworkList(restoreNetworkList(db_scenario));
scenario.setSignalList(restoreSignalList(db_scenario.getSignalSets()));
scenario.setSensorList(restoreSensorList(db_scenario.getSensorSets()));
scenario.setInitialDensitySet(restoreInitialDensitySet(db_scenario.getInitialDensitySets()));
scenario.setWeavingFactorSet(restoreWeavingFactorSet(db_scenario.getWeavingFactorSets()));
scenario.setSplitRatioProfileSet(restoreSplitRatioProfileSet(db_scenario.getSplitRatioProfileSets()));
scenario.setDownstreamBoundaryCapacityProfileSet(restoreDownstreamBoundaryCapacity(db_scenario.getDownstreamBoundaryCapacityProfileSets()));
scenario.setEventSet(restoreEventSet(db_scenario.getEventSets()));
scenario.setDemandProfileSet(restoreDemandProfileSet(db_scenario.getDemandProfileSets()));
scenario.setControllerSet(restoreControllerSet(db_scenario.getControllerSets()));
scenario.setFundamentalDiagramProfileSet(restoreFundamentalDiagramProfileSet(db_scenario.getFundamentalDiagramProfileSets()));
scenario.setNetworkConnections(restoreNetworkConnections(db_scenario.getNetworkConnectionSets()));
scenario.setDestinationNetworks(restoreDestinationNetworks(db_scenario));
} catch (TorqueException exc) {
throw new SiriusException(exc);
}
return scenario;
}
private com.relteq.sirius.jaxb.Settings restoreSettings(Scenarios db_scenario) throws TorqueException {
com.relteq.sirius.jaxb.Settings settings = factory.createSettings();
settings.setUnits("US");
settings.setVehicleTypes(restoreVehicleTypes(db_scenario.getVehicleTypeSets()));
return settings;
}
private com.relteq.sirius.jaxb.VehicleTypes restoreVehicleTypes(VehicleTypeSets db_vtsets) throws TorqueException {
if (null == db_vtsets) return null;
Criteria crit = new Criteria();
crit.addJoin(VehicleTypesInSetsPeer.VEHICLE_TYPE_ID, VehicleTypesPeer.VEHICLE_TYPE_ID);
crit.add(VehicleTypesInSetsPeer.VEHICLE_TYPE_SET_ID, db_vtsets.getId());
crit.add(VehicleTypesPeer.PROJECT_ID, db_vtsets.getProjectId());
crit.addAscendingOrderByColumn(VehicleTypesPeer.VEHICLE_TYPE_ID);
@SuppressWarnings("unchecked")
List<VehicleTypes> db_vt_l = VehicleTypesPeer.doSelect(crit);
if (0 == db_vt_l.size()) return null;
com.relteq.sirius.jaxb.VehicleTypes vtypes = factory.createVehicleTypes();
for (VehicleTypes db_vt : db_vt_l)
vtypes.getVehicleType().add(restoreVehicleType(db_vt));
return vtypes;
}
private com.relteq.sirius.jaxb.VehicleType restoreVehicleType(VehicleTypes db_vt) {
com.relteq.sirius.jaxb.VehicleType vt = factory.createVehicleType();
vt.setName(db_vt.getName());
vt.setWeight(db_vt.getWeight());
return vt;
}
private com.relteq.sirius.jaxb.NetworkList restoreNetworkList(Scenarios db_scenario) {
try {
@SuppressWarnings("unchecked")
List<NetworkSets> db_nets_l = db_scenario.getNetworkSetss();
if (0 < db_nets_l.size()) {
com.relteq.sirius.jaxb.NetworkList nets = factory.createNetworkList();
for (NetworkSets db_nets : db_nets_l)
nets.getNetwork().add(restoreNetwork(db_nets.getNetworks()));
return nets;
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return null;
}
private com.relteq.sirius.jaxb.Network restoreNetwork(Networks db_net) {
com.relteq.sirius.jaxb.Network net = factory.createNetwork();
net.setId(id2str(db_net.getId()));
net.setName(db_net.getName());
net.setDescription(db_net.getDescription());
net.setDt(new BigDecimal(1)); // TODO change this when the DB schema is updated
net.setNodeList(restoreNodeList(db_net));
net.setLinkList(restoreLinkList(db_net));
return net;
}
private com.relteq.sirius.jaxb.NodeList restoreNodeList(Networks db_net) {
try {
@SuppressWarnings("unchecked")
List<Nodes> db_nl = db_net.getNodess();
if (0 < db_nl.size()) {
com.relteq.sirius.jaxb.NodeList nl = factory.createNodeList();
for (Nodes db_node : db_nl)
nl.getNode().add(restoreNode(db_node));
return nl;
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return null;
}
private com.relteq.sirius.jaxb.Node restoreNode(Nodes db_node) {
com.relteq.sirius.jaxb.Node node = factory.createNode();
node.setId(id2str(db_node.getId()));
try {
// TODO revise and uncomment
/*
@SuppressWarnings("unchecked")
List<NodeName> db_nname_l = db_node.getNodeNames();
if (0 < db_nname_l.size()) {
node.setName(db_nname_l.get(0).getName());
if (1 < db_nname_l.size())
SiriusErrorLog.addWarning("Node " + db_node.getId() + " has " + db_nname_l.size() + " values for @name");
}
*/
@SuppressWarnings("unchecked")
List<NodeType> db_ntype_l = db_node.getNodeTypes();
if (0 < db_ntype_l.size()) {
node.setType(db_ntype_l.get(0).getType());
if (1 < db_ntype_l.size())
SiriusErrorLog.addWarning("Node " + db_node.getId() + " has " + db_ntype_l.size() + " values for @type");
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
// TODO node.setDescription();
// TODO node.setType();
// TODO db_node.getGeometry() -> node.setPosition();
// TODO node.setPostmile();
node.setInputs(restoreInputs(db_node));
node.setOutputs(restoreOutputs(db_node));
return node;
}
private com.relteq.sirius.jaxb.Inputs restoreInputs(Nodes db_node) {
com.relteq.sirius.jaxb.Inputs inputs = factory.createInputs();
Criteria crit = new Criteria();
crit.add(LinksPeer.NETWORK_ID, db_node.getNetworkId());
crit.add(LinksPeer.END_NODE_ID, db_node.getId());
try {
@SuppressWarnings("unchecked")
List<Links> db_link_l = LinksPeer.doSelect(crit);
for (Links db_link : db_link_l)
inputs.getInput().add(restoreInput(db_link));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return inputs;
}
private com.relteq.sirius.jaxb.Input restoreInput(Links db_link) {
com.relteq.sirius.jaxb.Input input = factory.createInput();
input.setLinkId(id2str(db_link.getId()));
return input;
}
private com.relteq.sirius.jaxb.Outputs restoreOutputs(Nodes db_node) {
com.relteq.sirius.jaxb.Outputs outputs = factory.createOutputs();
Criteria crit = new Criteria();
crit.add(LinksPeer.NETWORK_ID, db_node.getNetworkId());
crit.add(LinksPeer.BEG_NODE_ID, db_node.getId());
try {
@SuppressWarnings("unchecked")
List<Links> db_link_l = LinksPeer.doSelect(crit);
for (Links db_link : db_link_l)
outputs.getOutput().add(restoreOutput(db_link));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return outputs;
}
private com.relteq.sirius.jaxb.Output restoreOutput(Links db_link) {
com.relteq.sirius.jaxb.Output output = factory.createOutput();
output.setLinkId(id2str(db_link.getId()));
return output;
}
private com.relteq.sirius.jaxb.LinkList restoreLinkList(Networks db_net) {
try {
@SuppressWarnings("unchecked")
List<Links> db_ll = db_net.getLinkss();
if (0 < db_ll.size()) {
com.relteq.sirius.jaxb.LinkList ll = factory.createLinkList();
for (Links db_link : db_ll) {
ll.getLink().add(restoreLink(db_link));
}
return ll;
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return null;
}
private com.relteq.sirius.jaxb.Link restoreLink(Links db_link) {
com.relteq.sirius.jaxb.Link link = factory.createLink();
link.setId(id2str(db_link.getId()));
// TODO link.setName();
// TODO link.setRoadName();
// TODO link.setDescription();
// TODO link.setType();
// TODO revise: geometry -> shape
link.setShape(db_link.getGeom());
try {
@SuppressWarnings("unchecked")
List<LinkLanes> db_llanes_l = db_link.getLinkLaness();
if (0 < db_llanes_l.size()) {
link.setLanes(db_llanes_l.get(0).getLanes());
if (1 < db_llanes_l.size())
SiriusErrorLog.addWarning("Link " + db_link.getId() + " has " + db_llanes_l.size() + " values for @lanes");
}
@SuppressWarnings("unchecked")
List<LinkType> db_ltype_l = db_link.getLinkTypes();
if (0 < db_ltype_l.size()) {
link.setType(db_ltype_l.get(0).getType());
if (1 < db_ltype_l.size())
SiriusErrorLog.addWarning("Link " + db_link.getId() + " has " + db_ltype_l.size() + " values for @type");
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
link.setLength(db_link.getLength());
// TODO link.setDynamics();
// TODO link.setLaneOffset();
if (null != db_link.getBegNodeId()) {
com.relteq.sirius.jaxb.Begin begin = factory.createBegin();
begin.setNodeId(id2str(db_link.getBegNodeId()));
link.setBegin(begin);
}
if (null != db_link.getEndNodeId()) {
com.relteq.sirius.jaxb.End end = factory.createEnd();
end.setNodeId(id2str(db_link.getEndNodeId()));
link.setEnd(end);
}
return link;
}
private com.relteq.sirius.jaxb.InitialDensitySet restoreInitialDensitySet(InitialDensitySets db_idset) {
if (null == db_idset) return null;
com.relteq.sirius.jaxb.InitialDensitySet idset = factory.createInitialDensitySet();
idset.setId(id2str(db_idset.getId()));
idset.setName(db_idset.getName());
idset.setDescription(db_idset.getDescription());
// TODO idset.setTstamp();
Criteria crit = new Criteria();
crit.addAscendingOrderByColumn(InitialDensitiesPeer.LINK_ID);
crit.addAscendingOrderByColumn(InitialDensitiesPeer.VEHICLE_TYPE_ID);
try {
@SuppressWarnings("unchecked")
List<InitialDensities> db_idl = db_idset.getInitialDensitiess(crit);
com.relteq.sirius.jaxb.Density density = null;
StringBuilder sb = new StringBuilder();
for (InitialDensities db_id : db_idl) {
if (null != density && !density.getLinkId().equals(id2str(db_id.getLinkId()))) {
density.setContent(sb.toString());
idset.getDensity().add(density);
density = null;
}
if (null == density) { // new link
density = factory.createDensity();
density.setLinkId(id2str(db_id.getLinkId()));
// TODO density.setNetworkId();
sb.setLength(0);
} else { // same link, different vehicle type
sb.append(":");
}
sb.append(db_id.getDensity().toPlainString());
}
// last link
if (null != density) {
density.setContent(sb.toString());
idset.getDensity().add(density);
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return idset;
}
private com.relteq.sirius.jaxb.WeavingFactorSet restoreWeavingFactorSet(WeavingFactorSets db_wfset) {
if (null == db_wfset) return null;
com.relteq.sirius.jaxb.WeavingFactorSet wfset = factory.createWeavingFactorSet();
wfset.setId(id2str(db_wfset.getId()));
wfset.setName(db_wfset.getName());
wfset.setDescription(db_wfset.getDescription());
Criteria crit = new Criteria();
crit.addAscendingOrderByColumn(WeavingFactorsPeer.IN_LINK_ID);
crit.addAscendingOrderByColumn(WeavingFactorsPeer.OUT_LINK_ID);
crit.addAscendingOrderByColumn(WeavingFactorsPeer.VEHICLE_TYPE_ID);
try {
@SuppressWarnings("unchecked")
List<WeavingFactors> db_wf_l = db_wfset.getWeavingFactorss();
com.relteq.sirius.jaxb.Weavingfactors wf = null;
StringBuilder sb = new StringBuilder();
for (WeavingFactors db_wf : db_wf_l) {
if (null != wf && !(wf.getLinkIn().equals(id2str(db_wf.getInLinkId())) && wf.getLinkOut().equals(id2str(db_wf.getOutLinkId())))) {
wf.setContent(sb.toString());
wfset.getWeavingfactors().add(wf);
wf = null;
}
if (null == wf) { // new weaving factor
wf = factory.createWeavingfactors();
wf.setLinkIn(id2str(db_wf.getInLinkId()));
wf.setLinkOut(id2str(db_wf.getOutLinkId()));
sb.setLength(0);
} else { // same weaving factor, different vehicle type
sb.append(':');
}
sb.append(db_wf.getFactor().toPlainString());
}
if (null != wf) {
wf.setContent(sb.toString());
wfset.getWeavingfactors().add(wf);
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return wfset;
}
private com.relteq.sirius.jaxb.SplitRatioProfileSet restoreSplitRatioProfileSet(SplitRatioProfileSets db_srps) {
if (null == db_srps) return null;
com.relteq.sirius.jaxb.SplitRatioProfileSet srps = factory.createSplitRatioProfileSet();
srps.setId(id2str(db_srps.getId()));
srps.setName(db_srps.getName());
srps.setDescription(db_srps.getDescription());
try {
@SuppressWarnings("unchecked")
List<SplitRatioProfiles> db_srp_l = db_srps.getSplitRatioProfiless();
for (SplitRatioProfiles db_srp : db_srp_l)
srps.getSplitratioProfile().add(restoreSplitRatioProfile(db_srp));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return srps;
}
private com.relteq.sirius.jaxb.SplitratioProfile restoreSplitRatioProfile(SplitRatioProfiles db_srp) {
com.relteq.sirius.jaxb.SplitratioProfile srp = factory.createSplitratioProfile();
srp.setNodeId(id2str(db_srp.getNodeId()));
srp.setDt(db_srp.getDt());
srp.setStartTime(db_srp.getStartTime());
Criteria crit = new Criteria();
crit.addAscendingOrderByColumn(SplitRatiosPeer.IN_LINK_ID);
crit.addAscendingOrderByColumn(SplitRatiosPeer.OUT_LINK_ID);
crit.addAscendingOrderByColumn(SplitRatiosPeer.ORDINAL);
crit.addAscendingOrderByColumn(SplitRatiosPeer.VEHICLE_TYPE_ID);
try {
@SuppressWarnings("unchecked")
List<SplitRatios> db_sr_l = db_srp.getSplitRatioss(crit);
com.relteq.sirius.jaxb.Splitratio sr = null;
Integer ordinal = null;
StringBuilder sb = new StringBuilder();
for (SplitRatios db_sr : db_sr_l) {
if (null != sr && !(sr.getLinkIn().equals(id2str(db_sr.getInLinkId())) && sr.getLinkOut().equals(id2str(db_sr.getOutLinkId())))) {
sr.setContent(sb.toString());
srp.getSplitratio().add(sr);
sr = null;
}
if (null == sr) { // new split ratio
sr = factory.createSplitratio();
sr.setLinkIn(id2str(db_sr.getInLinkId()));
sr.setLinkOut(id2str(db_sr.getOutLinkId()));
sb.setLength(0);
} else { // same split ratio, different time stamp (',') or vehicle type (':')
sb.append(db_sr.getOrdinal().equals(ordinal) ? ':' : ',');
}
ordinal = db_sr.getOrdinal();
sb.append(db_sr.getSplitRatio().toPlainString());
}
if (null != sr) {
sr.setContent(sb.toString());
srp.getSplitratio().add(sr);
}
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return srp;
}
com.relteq.sirius.jaxb.FundamentalDiagramProfileSet restoreFundamentalDiagramProfileSet(FundamentalDiagramProfileSets db_fdps) {
if (null == db_fdps) return null;
com.relteq.sirius.jaxb.FundamentalDiagramProfileSet fdps = factory.createFundamentalDiagramProfileSet();
fdps.setId(id2str(db_fdps.getId()));
fdps.setName(db_fdps.getName());
fdps.setDescription(db_fdps.getDescription());
try {
@SuppressWarnings("unchecked")
List<FundamentalDiagramProfiles> db_fdprofile_l = db_fdps.getFundamentalDiagramProfiless();
for (FundamentalDiagramProfiles db_fdprofile : db_fdprofile_l)
fdps.getFundamentalDiagramProfile().add(restoreFundamentalDiagramProfile(db_fdprofile));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return fdps;
}
com.relteq.sirius.jaxb.FundamentalDiagramProfile restoreFundamentalDiagramProfile(FundamentalDiagramProfiles db_fdprofile) {
com.relteq.sirius.jaxb.FundamentalDiagramProfile fdprofile = factory.createFundamentalDiagramProfile();
fdprofile.setLinkId(id2str(db_fdprofile.getLinkId()));
fdprofile.setDt(db_fdprofile.getDt());
fdprofile.setStartTime(db_fdprofile.getStartTime());
Criteria crit = new Criteria();
crit.addAscendingOrderByColumn(FundamentalDiagramsPeer.NUMBER);
try {
@SuppressWarnings("unchecked")
List<FundamentalDiagrams> db_fd_l = db_fdprofile.getFundamentalDiagramss(crit);
for (FundamentalDiagrams db_fd : db_fd_l)
fdprofile.getFundamentalDiagram().add(restoreFundamentalDiagram(db_fd));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return fdprofile;
}
com.relteq.sirius.jaxb.FundamentalDiagram restoreFundamentalDiagram(FundamentalDiagrams db_fd) {
com.relteq.sirius.jaxb.FundamentalDiagram fd = factory.createFundamentalDiagram();
fd.setFreeFlowSpeed(db_fd.getFreeFlowSpeed());
fd.setCongestionSpeed(db_fd.getCongestionWaveSpeed());
fd.setCapacity(db_fd.getCapacity());
fd.setJamDensity(db_fd.getJamDensity());
fd.setCapacityDrop(db_fd.getCapacityDrop());
fd.setStdDevCapacity(db_fd.getCapacityStd());
return fd;
}
private com.relteq.sirius.jaxb.DemandProfileSet restoreDemandProfileSet(DemandProfileSets db_dpset) {
if (null == db_dpset) return null;
com.relteq.sirius.jaxb.DemandProfileSet dpset = factory.createDemandProfileSet();
dpset.setId(id2str(db_dpset.getId()));
dpset.setName(db_dpset.getName());
dpset.setDescription(db_dpset.getDescription());
try {
@SuppressWarnings("unchecked")
List<DemandProfiles> db_dp_l = db_dpset.getDemandProfiless();
for (DemandProfiles db_dp : db_dp_l)
dpset.getDemandProfile().add(restoreDemandProfile(db_dp));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return dpset;
}
private com.relteq.sirius.jaxb.DemandProfile restoreDemandProfile(DemandProfiles db_dp) {
com.relteq.sirius.jaxb.DemandProfile dp = factory.createDemandProfile();
dp.setLinkIdOrigin(id2str(db_dp.getOriginLinkId()));
dp.setDt(db_dp.getDt());
dp.setStartTime(db_dp.getStartTime());
dp.setKnob(db_dp.getKnob());
dp.setStdDevAdd(db_dp.getStdDeviationAdditive());
dp.setStdDevMult(db_dp.getStdDeviationMultiplicative());
Criteria crit = new Criteria();
crit.addAscendingOrderByColumn(DemandsPeer.NUMBER);
crit.addAscendingOrderByColumn(DemandsPeer.VEHICLE_TYPE_ID);
try {
@SuppressWarnings("unchecked")
List<Demands> db_demand_l = db_dp.getDemandss(crit);
StringBuilder sb = null;
Integer number = null;
for (Demands db_demand : db_demand_l) {
if (null == sb) sb = new StringBuilder();
else sb.append(db_demand.getNumber().equals(number) ? ':' : ',');
number = db_demand.getNumber();
sb.append(db_demand.getDemand().toPlainString());
}
if (null != sb) dp.setContent(sb.toString());
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return dp;
}
private com.relteq.sirius.jaxb.NetworkConnections restoreNetworkConnections(NetworkConnectionSets db_ncs) {
if (null == db_ncs) return null;
com.relteq.sirius.jaxb.NetworkConnections nc = factory.createNetworkConnections();
nc.setId(id2str(db_ncs.getId()));
nc.setName(db_ncs.getName());
nc.setDescription(db_ncs.getDescription());
Criteria crit = new Criteria();
crit.addAscendingOrderByColumn(NetworkConnectionsPeer.FROM_NETWORK_ID);
crit.addAscendingOrderByColumn(NetworkConnectionsPeer.TO_NETWORK_ID);
try {
@SuppressWarnings("unchecked")
List<NetworkConnections> db_nc_l = db_ncs.getNetworkConnectionss(crit);
com.relteq.sirius.jaxb.Networkpair np = null;
for (NetworkConnections db_nc : db_nc_l) {
if (null != np && (!np.getNetworkA().equals(db_nc.getFromNetworkId()) || !np.getNetworkB().equals(db_nc.getToNetworkId()))) {
nc.getNetworkpair().add(np);
np = null;
}
if (null == np) {
np = factory.createNetworkpair();
np.setNetworkA(id2str(db_nc.getFromNetworkId()));
np.setNetworkB(id2str(db_nc.getToNetworkId()));
}
com.relteq.sirius.jaxb.Linkpair lp = factory.createLinkpair();
lp.setLinkA(id2str(db_nc.getFromLinkId()));
lp.setLinkB(id2str(db_nc.getToLinkId()));
np.getLinkpair().add(lp);
}
if (null != np) nc.getNetworkpair().add(np);
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return nc;
}
private com.relteq.sirius.jaxb.SignalList restoreSignalList(SignalSets db_ss) {
if (null == db_ss) return null;
com.relteq.sirius.jaxb.SignalList sl = factory.createSignalList();
// TODO sl.setName(db_sl.getName());
// TODO sl.setDescription(db_sl.getDescription());
try {
@SuppressWarnings("unchecked")
List<Signals> db_signal_l = db_ss.getSignalss();
for (Signals db_signal : db_signal_l)
sl.getSignal().add(restoreSignal(db_signal));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return sl;
}
private com.relteq.sirius.jaxb.Signal restoreSignal(Signals db_signal) {
com.relteq.sirius.jaxb.Signal signal = factory.createSignal();
signal.setId(id2str(db_signal.getId()));
signal.setNodeId(id2str(db_signal.getNodeId()));
try {
@SuppressWarnings("unchecked")
List<Phases> db_ph_l = db_signal.getPhasess();
for (Phases db_ph : db_ph_l)
signal.getPhase().add(restorePhase(db_ph));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return signal;
}
private com.relteq.sirius.jaxb.Phase restorePhase(Phases db_ph) {
com.relteq.sirius.jaxb.Phase phase = factory.createPhase();
phase.setNema(BigInteger.valueOf(db_ph.getNema()));
phase.setProtected(db_ph.getIsProtected());
phase.setPermissive(db_ph.getPermissive());
phase.setLag(db_ph.getLag());
phase.setRecall(db_ph.getRecall());
phase.setMinGreenTime(db_ph.getMinGreenTime());
phase.setYellowTime(db_ph.getYellowTime());
phase.setRedClearTime(db_ph.getRedClearTime());
try {
@SuppressWarnings("unchecked")
List<PhaseLinks> db_phl_l = db_ph.getPhaseLinkss();
com.relteq.sirius.jaxb.LinkReferences linkrefs = factory.createLinkReferences();
for (PhaseLinks db_phl : db_phl_l)
linkrefs.getLinkReference().add(restorePhaseLink(db_phl));
phase.setLinkReferences(linkrefs);
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return phase;
}
private com.relteq.sirius.jaxb.LinkReference restorePhaseLink(PhaseLinks db_phl) {
com.relteq.sirius.jaxb.LinkReference lr = factory.createLinkReference();
lr.setId(id2str(db_phl.getLinkId()));
return lr;
}
private com.relteq.sirius.jaxb.SensorList restoreSensorList(SensorSets db_ss) {
if (null == db_ss) return null;
com.relteq.sirius.jaxb.SensorList sl = factory.createSensorList();
// TODO sl.getSensor().add();
return sl;
}
private com.relteq.sirius.jaxb.DownstreamBoundaryCapacityProfileSet restoreDownstreamBoundaryCapacity(DownstreamBoundaryCapacityProfileSets db_dbcps) {
if (null == db_dbcps) return null;
com.relteq.sirius.jaxb.DownstreamBoundaryCapacityProfileSet dbcps = factory.createDownstreamBoundaryCapacityProfileSet();
dbcps.setId(id2str(db_dbcps.getId()));
dbcps.setName(db_dbcps.getName());
dbcps.setDescription(db_dbcps.getDescription());
try {
@SuppressWarnings("unchecked")
List<DownstreamBoundaryCapacityProfiles> db_dbcp_l = db_dbcps.getDownstreamBoundaryCapacityProfiless();
for (DownstreamBoundaryCapacityProfiles db_dbcp : db_dbcp_l)
dbcps.getCapacityProfile().add(restoreCapacityProfile(db_dbcp));
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return dbcps;
}
private com.relteq.sirius.jaxb.CapacityProfile restoreCapacityProfile(DownstreamBoundaryCapacityProfiles db_dbcp) {
com.relteq.sirius.jaxb.CapacityProfile cprofile = factory.createCapacityProfile();
cprofile.setLinkId(id2str(db_dbcp.getLinkId()));
cprofile.setDt(db_dbcp.getDt());
cprofile.setStartTime(db_dbcp.getStartTime());
Criteria crit = new Criteria();
crit.addAscendingOrderByColumn(DownstreamBoundaryCapacitiesPeer.NUMBER);
try {
@SuppressWarnings("unchecked")
List<DownstreamBoundaryCapacities> db_dbc_l = db_dbcp.getDownstreamBoundaryCapacitiess(crit);
StringBuilder sb = null;
for (DownstreamBoundaryCapacities db_dbc : db_dbc_l) {
// TODO delimiter = ',' or ':'?
if (null == sb) sb = new StringBuilder();
else sb.append(',');
sb.append(db_dbc.getDownstreamBoundaryCapacity().toPlainString());
}
if (null != sb) cprofile.setContent(sb.toString());
} catch (TorqueException exc) {
SiriusErrorLog.addError(exc.getMessage());
}
return cprofile;
}
private com.relteq.sirius.jaxb.ControllerSet restoreControllerSet(ControllerSets db_cs) {
if (null == db_cs) return null;
com.relteq.sirius.jaxb.ControllerSet cset = factory.createControllerSet();
cset.setId(id2str(db_cs.getId()));
// TODO cset.setName();
// TODO cset.setDescription();
// TODO cset.getController().add();
return cset;
}
private com.relteq.sirius.jaxb.EventSet restoreEventSet(EventSets db_es) {
if (null == db_es) return null;
com.relteq.sirius.jaxb.EventSet eset = factory.createEventSet();
eset.setId(id2str(db_es.getId()));
// TODO eset.setName();
// TODO eset.setDescription();
// TODO eset.getEvent().add();
return eset;
}
private com.relteq.sirius.jaxb.DestinationNetworks restoreDestinationNetworks(Scenarios db_scenario) throws TorqueException {
@SuppressWarnings("unchecked")
List<DestinationNetworkSets> db_dns_l = db_scenario.getDestinationNetworkSetss();
if (0 == db_dns_l.size()) return null;
com.relteq.sirius.jaxb.DestinationNetworks dns = factory.createDestinationNetworks();
for (DestinationNetworkSets db_dns : db_dns_l)
dns.getDestinationNetwork().add(restoreDestinationNetwork(db_dns.getDestinationNetworks()));
return dns;
}
private com.relteq.sirius.jaxb.DestinationNetwork restoreDestinationNetwork(DestinationNetworks db_destnet) throws TorqueException {
com.relteq.sirius.jaxb.DestinationNetwork destnet = factory.createDestinationNetwork();
destnet.setId(id2str(db_destnet.getId()));
destnet.setLinkIdDestination(id2str(db_destnet.getDestinationLinkId()));
com.relteq.sirius.jaxb.LinkReferences linkrefs = factory.createLinkReferences();
@SuppressWarnings("unchecked")
List<DestinationNetworkLinks> db_dnl_l = db_destnet.getDestinationNetworkLinkss();
for (DestinationNetworkLinks db_dnl : db_dnl_l)
linkrefs.getLinkReference().add(restoreDestinationNetworkLinks(db_dnl));
destnet.setLinkReferences(linkrefs);
return destnet;
}
private com.relteq.sirius.jaxb.LinkReference restoreDestinationNetworkLinks(DestinationNetworkLinks db_dnl) {
com.relteq.sirius.jaxb.LinkReference linkref = factory.createLinkReference();
linkref.setId(id2str(db_dnl.getLinkId()));
return linkref;
}
}
|
package com.jme3.animation;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.InputCapsule;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.math.Matrix3f;
import com.jme3.math.Matrix4f;
import com.jme3.math.Quaternion;
import com.jme3.math.Transform;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.util.ArrayList;
/**
* <code>Bone</code> describes a bone in the bone-weight skeletal animation
* system. A bone contains a name and an index, as well as relevant
* transformation data.
*
* @author Kirill Vainer
*/
public final class Bone implements Savable {
private String name;
private Bone parent;
private final ArrayList<Bone> children = new ArrayList<Bone>();
/**
* If enabled, user can control bone transform with setUserTransforms.
* Animation transforms are not applied to this bone when enabled.
*/
private boolean userControl = false;
/**
* The attachment node.
*/
private Node attachNode;
/**
* Initial transform is the local bind transform of this bone.
* PARENT SPACE -> BONE SPACE
*/
private Vector3f initialPos;
private Quaternion initialRot;
private Vector3f initialScale;
/**
* The inverse world bind transform.
* BONE SPACE -> MODEL SPACE
*/
private Vector3f worldBindInversePos;
private Quaternion worldBindInverseRot;
private Vector3f worldBindInverseScale;
/**
* The local animated transform combined with the local bind transform and parent world transform
*/
private Vector3f localPos = new Vector3f();
private Quaternion localRot = new Quaternion();
private Vector3f localScale = new Vector3f(1.0f, 1.0f, 1.0f);
/**
* MODEL SPACE -> BONE SPACE (in animated state)
*/
private Vector3f worldPos = new Vector3f();
private Quaternion worldRot = new Quaternion();
private Vector3f worldScale = new Vector3f();
//used for getCombinedTransform
private Transform tmpTransform = new Transform();
/**
* Creates a new bone with the given name.
*
* @param name Name to give to this bone
*/
public Bone(String name) {
this.name = name;
initialPos = new Vector3f();
initialRot = new Quaternion();
initialScale = new Vector3f(1, 1, 1);
worldBindInversePos = new Vector3f();
worldBindInverseRot = new Quaternion();
worldBindInverseScale = new Vector3f();
}
/**
* Special-purpose copy constructor.
* <p>
* Only copies the name and bind pose from the original.
* <p>
* WARNING: Local bind pose and world inverse bind pose transforms shallow
* copied. Modifying that data on the original bone will cause it to
* be recomputed on any cloned bones.
* <p>
* The rest of the data is <em>NOT</em> copied, as it will be
* generated automatically when the bone is animated.
*
* @param source The bone from which to copy the data.
*/
Bone(Bone source) {
this.name = source.name;
userControl = source.userControl;
initialPos = source.initialPos;
initialRot = source.initialRot;
initialScale = source.initialScale;
worldBindInversePos = source.worldBindInversePos;
worldBindInverseRot = source.worldBindInverseRot;
worldBindInverseScale = source.worldBindInverseScale;
// parent and children will be assigned manually..
}
/**
* Serialization only. Do not use.
*/
public Bone() {
}
/**
* Returns the name of the bone, set in the constructor.
*
* @return The name of the bone, set in the constructor.
*/
public String getName() {
return name;
}
/**
* Returns parent bone of this bone, or null if it is a root bone.
* @return The parent bone of this bone, or null if it is a root bone.
*/
public Bone getParent() {
return parent;
}
/**
* Returns all the children bones of this bone.
*
* @return All the children bones of this bone.
*/
public ArrayList<Bone> getChildren() {
return children;
}
/**
* Returns the local position of the bone, relative to the parent bone.
*
* @return The local position of the bone, relative to the parent bone.
*/
public Vector3f getLocalPosition() {
return localPos;
}
/**
* Returns the local rotation of the bone, relative to the parent bone.
*
* @return The local rotation of the bone, relative to the parent bone.
*/
public Quaternion getLocalRotation() {
return localRot;
}
/**
* Returns the local scale of the bone, relative to the parent bone.
*
* @return The local scale of the bone, relative to the parent bone.
*/
public Vector3f getLocalScale() {
return localScale;
}
/**
* Returns the position of the bone in model space.
*
* @return The position of the bone in model space.
*/
public Vector3f getModelSpacePosition() {
return worldPos;
}
/**
* Returns the rotation of the bone in model space.
*
* @return The rotation of the bone in model space.
*/
public Quaternion getModelSpaceRotation() {
return worldRot;
}
/**
* Returns the scale of the bone in model space.
*
* @return The scale of the bone in model space.
*/
public Vector3f getModelSpaceScale() {
return worldScale;
}
/**
* Returns the inverse world bind pose position.
* <p>
* The bind pose transform of the bone is its "default"
* transform with no animation applied.
*
* @return the inverse world bind pose position.
*/
public Vector3f getWorldBindInversePosition() {
return worldBindInversePos;
}
/**
* Returns the inverse world bind pose rotation.
* <p>
* The bind pose transform of the bone is its "default"
* transform with no animation applied.
*
* @return the inverse world bind pose rotation.
*/
public Quaternion getWorldBindInverseRotation() {
return worldBindInverseRot;
}
/**
* Returns the inverse world bind pose scale.
* <p>
* The bind pose transform of the bone is its "default"
* transform with no animation applied.
*
* @return the inverse world bind pose scale.
*/
public Vector3f getWorldBindInverseScale() {
return worldBindInverseScale;
}
/**
* Returns the world bind pose position.
* <p>
* The bind pose transform of the bone is its "default"
* transform with no animation applied.
*
* @return the world bind pose position.
*/
public Vector3f getWorldBindPosition() {
return initialPos;
}
/**
* Returns the world bind pose rotation.
* <p>
* The bind pose transform of the bone is its "default"
* transform with no animation applied.
*
* @return the world bind pose rotation.
*/
public Quaternion getWorldBindRotation() {
return initialRot;
}
/**
* Returns the world bind pose scale.
* <p>
* The bind pose transform of the bone is its "default"
* transform with no animation applied.
*
* @return the world bind pose scale.
*/
public Vector3f getWorldBindScale() {
return initialScale;
}
/**
* If enabled, user can control bone transform with setUserTransforms.
* Animation transforms are not applied to this bone when enabled.
*/
public void setUserControl(boolean enable) {
userControl = enable;
}
/**
* Add a new child to this bone. Shouldn't be used by user code.
* Can corrupt skeleton.
*
* @param bone The bone to add
*/
public void addChild(Bone bone) {
children.add(bone);
bone.parent = this;
}
/**
* Updates the world transforms for this bone, and, possibly the attach node
* if not null.
* <p>
* The world transform of this bone is computed by combining the parent's
* world transform with this bones' local transform.
*/
public final void updateWorldVectors() {
if (parent != null) {
//rotation
parent.worldRot.mult(localRot, worldRot);
//scale
//For scale parent scale is not taken into account!
// worldScale.set(localScale);
parent.worldScale.mult(localScale, worldScale);
//translation
//scale and rotation of parent affect bone position
parent.worldRot.mult(localPos, worldPos);
worldPos.multLocal(parent.worldScale);
worldPos.addLocal(parent.worldPos);
} else {
worldRot.set(localRot);
worldPos.set(localPos);
worldScale.set(localScale);
}
if (attachNode != null) {
attachNode.setLocalTranslation(worldPos);
attachNode.setLocalRotation(worldRot);
attachNode.setLocalScale(worldScale);
}
}
/**
* Updates world transforms for this bone and it's children.
*/
final void update() {
this.updateWorldVectors();
for (int i = children.size() - 1; i >= 0; i
children.get(i).update();
}
}
/**
* Saves the current bone state as its binding pose, including its children.
*/
void setBindingPose() {
initialPos.set(localPos);
initialRot.set(localRot);
initialScale.set(localScale);
if (worldBindInversePos == null) {
worldBindInversePos = new Vector3f();
worldBindInverseRot = new Quaternion();
worldBindInverseScale = new Vector3f();
}
// Save inverse derived position/scale/orientation, used for calculate offset transform later
worldBindInversePos.set(worldPos);
worldBindInversePos.negateLocal();
worldBindInverseRot.set(worldRot);
worldBindInverseRot.inverseLocal();
worldBindInverseScale.set(Vector3f.UNIT_XYZ);
worldBindInverseScale.divideLocal(worldScale);
for (Bone b : children) {
b.setBindingPose();
}
}
/**
* Reset the bone and it's children to bind pose.
*/
final void reset() {
if (!userControl) {
localPos.set(initialPos);
localRot.set(initialRot);
localScale.set(initialScale);
}
for (int i = children.size() - 1; i >= 0; i
children.get(i).reset();
}
}
/**
* Stores the skinning transform in the specified Matrix4f.
* The skinning transform applies the animation of the bone to a vertex.
* @param m
*/
void getOffsetTransform(Matrix4f m, Quaternion tmp1, Vector3f tmp2, Vector3f tmp3, Matrix3f rotMat) {
//Computing scale
Vector3f scale = worldScale.mult(worldBindInverseScale, tmp3);
//computing rotation
Quaternion rotate = worldRot.mult(worldBindInverseRot, tmp1);
//computing translation
//translation depend on rotation and scale
Vector3f translate = worldPos.add(rotate.mult(scale.mult(worldBindInversePos, tmp2), tmp2), tmp2);
//populating the matrix
m.loadIdentity();
m.setTransform(translate, scale, rotate.toRotationMatrix(rotMat));
}
/**
* Sets user transform.
*/
public void setUserTransforms(Vector3f translation, Quaternion rotation, Vector3f scale) {
if (!userControl) {
throw new IllegalStateException("User control must be on bone to allow user transforms");
}
localPos.set(initialPos);
localRot.set(initialRot);
localScale.set(initialScale);
localPos.addLocal(translation);
localRot = localRot.mult(rotation);
localScale.multLocal(scale);
}
/**
* Must update all bones in skeleton for this to work.
* @param translation
* @param rotation
*/
public void setUserTransformsWorld(Vector3f translation, Quaternion rotation) {
if (!userControl) {
throw new IllegalStateException("User control must be on bone to allow user transforms");
}
// TODO: add scale here ???
worldPos.set(translation);
worldRot.set(rotation);
}
/**
* Returns the local transform of this bone combined with the given position and rotation
* @param position a position
* @param rotation a rotation
*/
public Transform getCombinedTransform(Vector3f position, Quaternion rotation) {
rotation.mult(localPos, tmpTransform.getTranslation()).addLocal(position);
tmpTransform.setRotation(rotation).getRotation().multLocal(localRot);
return tmpTransform;
}
/**
* Returns the attachment node.
* Attach models and effects to this node to make
* them follow this bone's motions.
*/
public Node getAttachmentsNode() {
if (attachNode == null) {
attachNode = new Node(name + "_attachnode");
attachNode.setUserData("AttachedBone", this);
}
return attachNode;
}
/**
* Used internally after model cloning.
* @param attachNode
*/
void setAttachmentsNode(Node attachNode) {
this.attachNode = attachNode;
}
/**
* Sets the local animation transform of this bone.
* Bone is assumed to be in bind pose when this is called.
*/
void setAnimTransforms(Vector3f translation, Quaternion rotation, Vector3f scale) {
if (userControl) {
return;
}
// localPos.addLocal(translation);
// localRot.multLocal(rotation);
//localRot = localRot.mult(rotation);
localPos.set(initialPos).addLocal(translation);
localRot.set(initialRot).multLocal(rotation);
if (scale != null) {
localScale.set(initialScale).multLocal(scale);
}
}
void blendAnimTransforms(Vector3f translation, Quaternion rotation, Vector3f scale, float weight) {
if (userControl) {
return;
}
TempVars vars = TempVars.get();
assert vars.lock();
Vector3f tmpV = vars.vect1;
Vector3f tmpV2 = vars.vect2;
Quaternion tmpQ = vars.quat1;
//location
tmpV.set(initialPos).addLocal(translation);
localPos.interpolate(tmpV, weight);
//rotation
tmpQ.set(initialRot).multLocal(rotation);
localRot.nlerp(tmpQ, weight);
//scale
if (scale != null) {
tmpV2.set(initialScale).multLocal(scale);
localScale.interpolate(tmpV2, weight);
}
assert vars.unlock();
}
/**
* Sets local bind transform for bone.
* Call setBindingPose() after all of the skeleton bones' bind transforms are set to save them.
*/
public void setBindTransforms(Vector3f translation, Quaternion rotation, Vector3f scale) {
initialPos.set(translation);
initialRot.set(rotation);
//ogre.xml can have null scale values breaking this if the check is removed
if (scale != null) {
initialScale.set(scale);
}
localPos.set(translation);
localRot.set(rotation);
if (scale != null) {
localScale.set(scale);
}
}
private String toString(int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append('-');
}
sb.append(name).append(" bone\n");
for (Bone child : children) {
sb.append(child.toString(depth + 1));
}
return sb.toString();
}
@Override
public String toString() {
return this.toString(0);
}
@Override
@SuppressWarnings("unchecked")
public void read(JmeImporter im) throws IOException {
InputCapsule input = im.getCapsule(this);
name = input.readString("name", null);
initialPos = (Vector3f) input.readSavable("initialPos", null);
initialRot = (Quaternion) input.readSavable("initialRot", null);
initialScale = (Vector3f) input.readSavable("initialScale", new Vector3f(1.0f, 1.0f, 1.0f));
attachNode = (Node) input.readSavable("attachNode", null);
localPos.set(initialPos);
localRot.set(initialRot);
ArrayList<Bone> childList = input.readSavableArrayList("children", null);
for (int i = childList.size() - 1; i >= 0; i
this.addChild(childList.get(i));
}
// NOTE: Parent skeleton will call update() then setBindingPose()
// after Skeleton has been de-serialized.
// Therefore, worldBindInversePos and worldBindInverseRot
// will be reconstructed based on that information.
}
@Override
public void write(JmeExporter ex) throws IOException {
OutputCapsule output = ex.getCapsule(this);
output.write(name, "name", null);
output.write(attachNode, "attachNode", null);
output.write(initialPos, "initialPos", null);
output.write(initialRot, "initialRot", null);
output.write(initialScale, "initialScale", new Vector3f(1.0f, 1.0f, 1.0f));
output.writeSavableArrayList(children, "children", null);
}
}
|
package com.techjar.ledcm.gui.screen;
import com.techjar.ledcm.LEDCubeManager;
import com.techjar.ledcm.RenderHelper;
import com.techjar.ledcm.gui.GUIAlignment;
import com.techjar.ledcm.gui.GUIBackground;
import com.techjar.ledcm.gui.GUIButton;
import com.techjar.ledcm.gui.GUICallback;
import com.techjar.ledcm.gui.GUICheckBox;
import com.techjar.ledcm.gui.GUIComboBox;
import com.techjar.ledcm.gui.GUIComboButton;
import com.techjar.ledcm.gui.GUILabel;
import com.techjar.ledcm.gui.GUIRadioButton;
import com.techjar.ledcm.gui.GUIScrollBox;
import com.techjar.ledcm.gui.GUISlider;
import com.techjar.ledcm.gui.GUISpinner;
import com.techjar.ledcm.gui.GUITabbed;
import com.techjar.ledcm.gui.GUITextField;
import com.techjar.ledcm.gui.GUIWindow;
import com.techjar.ledcm.hardware.LEDManager;
import com.techjar.ledcm.hardware.animation.Animation;
import com.techjar.ledcm.hardware.animation.AnimationSequence;
import com.techjar.ledcm.util.Constants;
import com.techjar.ledcm.util.Dimension3D;
import com.techjar.ledcm.util.PrintStreamRelayer;
import com.techjar.ledcm.util.Vector3;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.util.Color;
import org.lwjgl.util.Dimension;
import org.lwjgl.util.ReadableColor;
import org.newdawn.slick.UnicodeFont;
/**
*
* @author Techjar
*/
public class ScreenMainControl extends Screen {
public final UnicodeFont font;
public final UnicodeFont fontTabbed;
public final GUISlider progressSlider;
public final GUIWindow layersWindow;
public final GUIWindow sequenceWindow;
public final GUIWindow animOptionsWindow;
public final GUIWindow settingsWindow;
public final GUIWindow controlsWindow;
public final GUIWindow transformWindow;
public final GUIScrollBox animOptionsScrollBox;
public final GUIScrollBox settingsScrollBox;
public final GUITabbed controlsTabbed;
public final GUIButton animOptionsBtn;
public final GUIButton settingsBtn;
public final GUIButton audioInputBtn;
public final GUIBackground audioInputBtnBg;
public final GUISlider mixerGainSlider;
public final GUISlider layerSlider;
public final GUIComboBox animComboBox;
public final GUIComboBox resolutionComboBox;
public final GUIComboBox audioInputComboBox;
public final GUIComboButton antiAliasingComboBtn;
public final GUISlider redColorSlider;
public final GUISlider greenColorSlider;
public final GUISlider blueColorSlider;
public final GUIButton chooseFileBtn;
public final GUIButton playBtn;
public final GUIButton pauseBtn;
public final GUIButton stopBtn;
public final GUISlider volumeSlider;
public final GUIButton togglePortBtn;
public final GUISlider xScaleSlider;
public final GUILabel xScaleLabel;
public final GUISlider yScaleSlider;
public final GUILabel yScaleLabel;
public final GUISlider zScaleSlider;
public final GUILabel zScaleLabel;
public final GUIButton layersBtn;
public final GUIRadioButton radioOff;
public final GUILabel radioOffLabel;
public final GUIRadioButton radioX;
public final GUILabel radioXLabel;
public final GUIRadioButton radioY;
public final GUILabel radioYLabel;
public final GUIRadioButton radioZ;
public final GUILabel radioZLabel;
public final GUIComboBox sequenceComboBox;
public final GUIButton sequenceLoadBtn;
public final GUIButton sequencePlayBtn;
public final GUIButton sequenceStopBtn;
public final GUIButton settingsApplyBtn;
public final GUIButton controlsBtn;
public final GUIButton transformBtn;
public final GUILabel mirrorLabel;
public final GUICheckBox mirrorX;
public final GUILabel mirrorXLabel;
public final GUICheckBox mirrorY;
public final GUILabel mirrorYLabel;
public final GUICheckBox mirrorZ;
public final GUILabel mirrorZLabel;
public final GUILabel rotateLabel;
public final GUISpinner rotateXSpinner;
public final GUIButton rotateXButton;
public final GUILabel rotateXLabel;
public final GUISpinner rotateYSpinner;
public final GUIButton rotateYButton;
public final GUILabel rotateYLabel;
public final GUISpinner rotateZSpinner;
public final GUIButton rotateZButton;
public final GUILabel rotateZLabel;
public final GUICheckBox previewTransform;
public final GUILabel previewTransformLabel;
public ScreenMainControl() {
super();
final LEDManager ledManager = LEDCubeManager.getLEDManager();
final Dimension3D ledDim = ledManager.getDimensions();
font = LEDCubeManager.getFontManager().getFont("chemrea", 30, false, false).getUnicodeFont();
fontTabbed = LEDCubeManager.getFontManager().getFont("chemrea", 22, false, false).getUnicodeFont();
playBtn = new GUIButton(font, new Color(255, 255, 255), "Play", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
playBtn.setParentAlignment(GUIAlignment.BOTTOM_LEFT);
playBtn.setDimension(100, 40);
playBtn.setPosition(5, -5);
playBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().play();
}
});
container.addComponent(playBtn);
pauseBtn = new GUIButton(font, new Color(255, 255, 255), "Pause", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
pauseBtn.setParentAlignment(GUIAlignment.BOTTOM_LEFT);
pauseBtn.setDimension(100, 40);
pauseBtn.setPosition(110, -5);
pauseBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().pause();
}
});
container.addComponent(pauseBtn);
stopBtn = new GUIButton(font, new Color(255, 255, 255), "Stop", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
stopBtn.setParentAlignment(GUIAlignment.BOTTOM_LEFT);
stopBtn.setDimension(100, 40);
stopBtn.setPosition(215, -5);
stopBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().stop();
}
});
container.addComponent(stopBtn);
chooseFileBtn = new GUIButton(font, new Color(255, 255, 255), "Choose File...", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
chooseFileBtn.setParentAlignment(GUIAlignment.BOTTOM_LEFT);
chooseFileBtn.setDimension(200, 40);
chooseFileBtn.setPosition(320, -5);
chooseFileBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
if (LEDCubeManager.isConvertingAudio()) return;
int option = LEDCubeManager.getFileChooser().showOpenDialog(LEDCubeManager.getFrame());
if (option == JFileChooser.APPROVE_OPTION) {
try {
File file = LEDCubeManager.getFileChooser().getSelectedFile();
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().loadFile(file);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}, "File Chooser").start();
}
});
container.addComponent(chooseFileBtn);
volumeSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
volumeSlider.setParentAlignment(GUIAlignment.BOTTOM_LEFT);
volumeSlider.setDimension(150, 30);
volumeSlider.setPosition(525, -10);
volumeSlider.setValue(1);
volumeSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().setVolume(volumeSlider.getValue());
}
});
container.addComponent(volumeSlider);
progressSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
progressSlider.setParentAlignment(GUIAlignment.BOTTOM_LEFT);
progressSlider.setDimension(310, 30);
progressSlider.setPosition(5, -55);
progressSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().setPosition(progressSlider.getValue());
}
});
container.addComponent(progressSlider);
togglePortBtn = new GUIButton(font, new Color(255, 255, 255), "Toggle Port", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
togglePortBtn.setParentAlignment(GUIAlignment.TOP_RIGHT);
togglePortBtn.setDimension(190, 35);
togglePortBtn.setPosition(-410, 5);
togglePortBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
if (LEDCubeManager.getLEDCube().getCommThread().isPortOpen()) LEDCubeManager.getLEDCube().getCommThread().closePort();
else LEDCubeManager.getLEDCube().getCommThread().openPort();
}
});
container.addComponent(togglePortBtn);
/*GUIButton openPortBtn = new GUIButton(font, new Color(255, 255, 255), "Open", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
openPortBtn.setParentAlignment(GUIAlignment.TOP_RIGHT);
openPortBtn.setDimension(100, 35);
openPortBtn.setPosition(-515, 5);
openPortBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
CubeDesigner.getSerialThread().openPort();
}
});
container.addComponent(openPortBtn);*/
redColorSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
redColorSlider.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
redColorSlider.setDimension(30, 150);
redColorSlider.setPosition(-125, -10);
redColorSlider.setIncrement(1F / 255F);
redColorSlider.setValue(1);
redColorSlider.setVertical(true);
redColorSlider.setShowNotches(false);
redColorSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getPaintColor().setRed(Math.round(255 * redColorSlider.getValue()));
}
});
container.addComponent(redColorSlider);
greenColorSlider = new GUISlider(new Color(0, 255, 0), new Color(50, 50, 50));
greenColorSlider.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
greenColorSlider.setDimension(30, 150);
greenColorSlider.setPosition(-90, -10);
greenColorSlider.setIncrement(1F / 255F);
greenColorSlider.setValue(1);
greenColorSlider.setVertical(true);
greenColorSlider.setShowNotches(false);
greenColorSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getPaintColor().setGreen(Math.round(255 * greenColorSlider.getValue()));
}
});
container.addComponent(greenColorSlider);
blueColorSlider = new GUISlider(new Color(0, 0, 255), new Color(50, 50, 50));
blueColorSlider.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
blueColorSlider.setDimension(30, 150);
blueColorSlider.setPosition(-55, -10);
blueColorSlider.setIncrement(1F / 255F);
blueColorSlider.setValue(1);
blueColorSlider.setVertical(true);
blueColorSlider.setShowNotches(false);
blueColorSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
if (LEDCubeManager.getLEDCube().getLEDManager().isMonochrome()) {
Color color = LEDCubeManager.getLEDCube().getLEDManager().getMonochromeColor();
LEDCubeManager.getPaintColor().setRed(Math.round(color.getRed() * blueColorSlider.getValue()));
LEDCubeManager.getPaintColor().setGreen(Math.round(color.getGreen() * blueColorSlider.getValue()));
LEDCubeManager.getPaintColor().setBlue(Math.round(color.getBlue() * blueColorSlider.getValue()));
} else {
LEDCubeManager.getPaintColor().setBlue(Math.round(255 * blueColorSlider.getValue()));
}
}
});
container.addComponent(blueColorSlider);
if (LEDCubeManager.getLEDCube().getLEDManager().isMonochrome()) {
Color color = LEDCubeManager.getLEDCube().getLEDManager().getMonochromeColor();
LEDCubeManager.getPaintColor().setColor(color);
redColorSlider.setVisible(false);
greenColorSlider.setVisible(false);
blueColorSlider.setColor(color);
}
xScaleSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
xScaleSlider.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
xScaleSlider.setDimension(120, 30);
xScaleSlider.setPosition(-10, -240);
xScaleSlider.setIncrement(1F / (ledDim.x - 1));
xScaleSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getPaintSize().setX(Math.round((ledDim.x - 1) * xScaleSlider.getValue()));
}
});
container.addComponent(xScaleSlider);
xScaleLabel = new GUILabel(font, new Color(255, 255, 255), "X");
xScaleLabel.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
xScaleLabel.setDimension(20, 30);
xScaleLabel.setPosition(-135, -240);
container.addComponent(xScaleLabel);
yScaleSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
yScaleSlider.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
yScaleSlider.setDimension(120, 30);
yScaleSlider.setPosition(-10, -205);
yScaleSlider.setIncrement(1F / (ledDim.y - 1));
yScaleSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getPaintSize().setY(Math.round((ledDim.y - 1) * yScaleSlider.getValue()));
}
});
container.addComponent(yScaleSlider);
yScaleLabel = new GUILabel(font, new Color(255, 255, 255), "Y");
yScaleLabel.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
yScaleLabel.setDimension(20, 30);
yScaleLabel.setPosition(-135, -205);
container.addComponent(yScaleLabel);
zScaleSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
zScaleSlider.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
zScaleSlider.setDimension(120, 30);
zScaleSlider.setPosition(-10, -170);
zScaleSlider.setIncrement(1F / (ledDim.z - 1));
zScaleSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getPaintSize().setZ(Math.round((ledDim.z - 1) * zScaleSlider.getValue()));
}
});
container.addComponent(zScaleSlider);
zScaleLabel = new GUILabel(font, new Color(255, 255, 255), "Z");
zScaleLabel.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
zScaleLabel.setDimension(20, 30);
zScaleLabel.setPosition(-135, -170);
container.addComponent(zScaleLabel);
layersBtn = new GUIButton(font, new Color(255, 255, 255), "Layers", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
layersBtn.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
layersBtn.setDimension(120, 35);
layersBtn.setPosition(-10, -275);
layersBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
layersWindow.setVisible(!layersWindow.isVisible());
if (layersWindow.isVisible()) layersWindow.setToBePutOnTop(true);
}
});
container.addComponent(layersBtn);
layersWindow = new GUIWindow(new GUIBackground(new Color(10, 10, 10), new Color(255, 0, 0), 2));
layersWindow.setDimension(150, 167);
layersWindow.setPosition(container.getWidth() - layersWindow.getWidth() - 10, container.getHeight() - layersWindow.getHeight() - 360);
layersWindow.setResizable(false);
layersWindow.setCloseAction(GUIWindow.HIDE_ON_CLOSE);
layersWindow.setVisible(false);
container.addComponent(layersWindow);
radioOff = new GUIRadioButton(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
radioOff.setDimension(30, 30);
radioOff.setPosition(5, 5);
radioOff.setSelected(true);
radioOff.setSelectHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setLayerIsolation(0);
layerSlider.setEnabled(false);
layerSlider.setValue(0);
layerSlider.setIncrement(0);
}
});
radioOffLabel = new GUILabel(font, new Color(255, 255, 255), "Off");
radioOffLabel.setDimension(60, 30);
radioOffLabel.setPosition(40, 5);
radioOff.setLabel(radioOffLabel);
layersWindow.addComponent(radioOffLabel);
layersWindow.addComponent(radioOff);
radioX = new GUIRadioButton(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
radioX.setDimension(30, 30);
radioX.setPosition(5, 40);
radioX.setSelectHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setLayerIsolation(1);
layerSlider.setEnabled(true);
layerSlider.setValue(0);
layerSlider.setIncrement(1F / (ledDim.x - 1));
layerSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setSelectedLayer(Math.round((ledDim.x - 1) * layerSlider.getValue()));
}
});
}
});
radioXLabel = new GUILabel(font, new Color(255, 255, 255), "X");
radioXLabel.setDimension(20, 30);
radioXLabel.setPosition(40, 40);
radioX.setLabel(radioXLabel);
layersWindow.addComponent(radioXLabel);
layersWindow.addComponent(radioX);
radioY = new GUIRadioButton(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
radioY.setDimension(30, 30);
radioY.setPosition(5, 75);
radioY.setSelectHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setLayerIsolation(2);
layerSlider.setEnabled(true);
layerSlider.setValue(0);
layerSlider.setIncrement(1F / (ledDim.y - 1));
layerSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setSelectedLayer(Math.round((ledDim.y - 1) * layerSlider.getValue()));
}
});
}
});
radioYLabel = new GUILabel(font, new Color(255, 255, 255), "Y");
radioYLabel.setDimension(20, 30);
radioYLabel.setPosition(40, 75);
radioY.setLabel(radioYLabel);
layersWindow.addComponent(radioYLabel);
layersWindow.addComponent(radioY);
radioZ = new GUIRadioButton(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
radioZ.setDimension(30, 30);
radioZ.setPosition(5, 110);
radioZ.setSelectHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setLayerIsolation(3);
layerSlider.setEnabled(true);
layerSlider.setValue(0);
layerSlider.setIncrement(1F / (ledDim.z - 1));
layerSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setSelectedLayer(Math.round((ledDim.z - 1) * layerSlider.getValue()));
}
});
}
});
radioZLabel = new GUILabel(font, new Color(255, 255, 255), "Z");
radioZLabel.setDimension(20, 30);
radioZLabel.setPosition(40, 110);
radioZ.setLabel(radioZLabel);
layersWindow.addComponent(radioZLabel);
layersWindow.addComponent(radioZ);
layerSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
layerSlider.setDimension(30, 125);
layerSlider.setPosition(105, 10);
//layerSlider.setIncrement(1F / 7F);
layerSlider.setVertical(true);
layerSlider.setEnabled(false);
/*layerSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
CubeDesigner.setSelectedLayer(Math.round(7 * layerSlider.getValue()));
}
});*/
layersWindow.addComponent(layerSlider);
sequenceComboBox = new GUIComboBox(font, new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
sequenceComboBox.setParentAlignment(GUIAlignment.TOP_CENTER);
sequenceComboBox.setDimension(300, 35);
sequenceComboBox.setPosition(0, 10);
sequenceComboBox.setVisibleItems(2);
sequenceLoadBtn = new GUIButton(font, new Color(255, 255, 255), "Sequence", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
sequenceLoadBtn.setParentAlignment(GUIAlignment.BOTTOM_LEFT);
sequenceLoadBtn.setDimension(200, 40);
sequenceLoadBtn.setPosition(320, -50);
sequenceLoadBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
sequenceWindow.setVisible(!sequenceWindow.isVisible());
if (sequenceWindow.isVisible()) {
sequenceWindow.setToBePutOnTop(true);
sequenceComboBox.setSelectedItem(-1);
sequenceComboBox.clearItems();
File dir = new File("resources/sequences/");
for (File file : dir.listFiles()) {
String name = file.getName();
if (name.toLowerCase().endsWith(".sequence")) {
sequenceComboBox.addItem(name.substring(0, name.lastIndexOf('.')));
}
}
}
}
});
container.addComponent(sequenceLoadBtn);
sequenceWindow = new GUIWindow(new GUIBackground(new Color(10, 10, 10), new Color(255, 0, 0), 2));
sequenceWindow.setDimension(350, 150);
sequenceWindow.setPosition(container.getWidth() / 2 - sequenceWindow.getWidth() / 2, container.getHeight() / 2 - sequenceWindow.getHeight() / 2);
sequenceWindow.setResizable(false);
sequenceWindow.setCloseAction(GUIWindow.HIDE_ON_CLOSE);
sequenceWindow.setVisible(false);
container.addComponent(sequenceWindow);
sequencePlayBtn = new GUIButton(font, new Color(255, 255, 255), "Start", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
sequencePlayBtn.setParentAlignment(GUIAlignment.TOP_CENTER);
sequencePlayBtn.setDimension(100, 40);
sequencePlayBtn.setPosition(-55, 65);
sequencePlayBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
Object item = sequenceComboBox.getSelectedItem();
if (item != null) {
try {
File file = new File("resources/sequences/" + item.toString() + ".sequence");
AnimationSequence sequence = AnimationSequence.loadFromFile(file);
LEDCubeManager.getLEDCube().getCommThread().setCurrentSequence(sequence);
sequenceWindow.setVisible(false);
chooseFileBtn.setEnabled(!sequence.isMusicSynced());
progressSlider.setEnabled(!sequence.isMusicSynced());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
sequenceWindow.addComponent(sequencePlayBtn);
sequenceStopBtn = new GUIButton(font, new Color(255, 255, 255), "Stop", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
sequenceStopBtn.setParentAlignment(GUIAlignment.TOP_CENTER);
sequenceStopBtn.setDimension(100, 40);
sequenceStopBtn.setPosition(55, 65);
sequenceStopBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getCommThread().setCurrentSequence(null);
chooseFileBtn.setEnabled(true);
progressSlider.setEnabled(true);
}
});
sequenceWindow.addComponent(sequenceStopBtn);
sequenceWindow.addComponent(sequenceComboBox);
animOptionsWindow = new GUIWindow(new GUIBackground(new Color(10, 10, 10), new Color(255, 0, 0), 2));
animOptionsWindow.setDimension(500, 300);
animOptionsWindow.setPosition(container.getWidth() / 2 - animOptionsWindow.getWidth() / 2, container.getHeight() / 2 - animOptionsWindow.getHeight() / 2);
animOptionsWindow.setResizable(false, true);
animOptionsWindow.setCloseAction(GUIWindow.HIDE_ON_CLOSE);
animOptionsWindow.setVisible(false);
container.addComponent(animOptionsWindow);
animOptionsScrollBox = new GUIScrollBox(new Color(255, 0, 0));
animOptionsScrollBox.setDimension((int)animOptionsWindow.getContainerBox().getWidth(), (int)animOptionsWindow.getContainerBox().getHeight());
animOptionsScrollBox.setScrollXMode(GUIScrollBox.ScrollMode.DISABLED);
animOptionsScrollBox.setScrollYMode(GUIScrollBox.ScrollMode.AUTOMATIC);
animOptionsWindow.setDimensionChangeHandler(new GUICallback() {
@Override
public void run() {
animOptionsScrollBox.setDimension((int)animOptionsWindow.getContainerBox().getWidth(), (int)animOptionsWindow.getContainerBox().getHeight());
}
});
animOptionsWindow.addComponent(animOptionsScrollBox);
animOptionsBtn = new GUIButton(font, new Color(255, 255, 255), "Options", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
animOptionsBtn.setParentAlignment(GUIAlignment.TOP_RIGHT);
animOptionsBtn.setDimension(140, 35);
animOptionsBtn.setPosition(-605, 5);
animOptionsBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
animOptionsWindow.setVisible(!animOptionsWindow.isVisible());
if (animOptionsWindow.isVisible()) animOptionsWindow.setToBePutOnTop(true);
}
});
container.addComponent(animOptionsBtn);
animComboBox = new GUIComboBox(font, new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
animComboBox.setParentAlignment(GUIAlignment.TOP_RIGHT);
animComboBox.setDimension(400, 35);
animComboBox.setPosition(-5, 5);
animComboBox.setVisibleItems(8);
animComboBox.setChangeHandler(new GUICallback() {
@Override
public void run() {
if (animComboBox.getSelectedItem() != null) {
Animation animation = LEDCubeManager.getLEDCube().getAnimations().get(animComboBox.getSelectedItem().toString());
LEDCubeManager.getLEDCube().getCommThread().setCurrentAnimation(animation);
}
}
});
//populateAnimationList();
container.addComponent(animComboBox);
settingsWindow = new GUIWindow(new GUIBackground(new Color(10, 10, 10), new Color(255, 0, 0), 2));
settingsWindow.setDimension(450, 450);
settingsWindow.setPosition(container.getWidth() / 2 - settingsWindow.getWidth() / 2, container.getHeight() / 2 - settingsWindow.getHeight() / 2);
settingsWindow.setResizable(false, true);
settingsWindow.setCloseAction(GUIWindow.HIDE_ON_CLOSE);
settingsWindow.setMinimumSize(new Dimension(50, 150));
settingsWindow.setVisible(false);
container.addComponent(settingsWindow);
settingsScrollBox = new GUIScrollBox(new Color(255, 0, 0));
settingsScrollBox.setDimension((int)settingsWindow.getContainerBox().getWidth(), (int)settingsWindow.getContainerBox().getHeight() - 60);
settingsScrollBox.setScrollXMode(GUIScrollBox.ScrollMode.DISABLED);
settingsScrollBox.setScrollYMode(GUIScrollBox.ScrollMode.AUTOMATIC);
settingsWindow.setDimensionChangeHandler(new GUICallback() {
@Override
public void run() {
settingsScrollBox.setDimension((int)settingsWindow.getContainerBox().getWidth(), (int)settingsWindow.getContainerBox().getHeight() - 60);
}
});
settingsWindow.addComponent(settingsScrollBox);
settingsApplyBtn = new GUIButton(font, new Color(255, 255, 255), "Apply", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
settingsApplyBtn.setParentAlignment(GUIAlignment.BOTTOM_CENTER);
settingsApplyBtn.setDimension(200, 40);
settingsApplyBtn.setPosition(-105, -30);
settingsApplyBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
settingsWindow.setVisible(false);
Object item = resolutionComboBox.getSelectedItem();
if (item != null) {
String[] split = item.toString().split("x");
if (split.length == 2) {
LEDCubeManager.getInstance().setDisplayMode(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
}
}
item = audioInputComboBox.getSelectedItem();
if (item != null) {
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().setMixer(item.toString());
}
item = antiAliasingComboBtn.getSelectedItem();
if (item != null) {
switch (item.toString()) {
case "Off":
LEDCubeManager.getInstance().setAntiAliasing(false, 2);
break;
default:
LEDCubeManager.getInstance().setAntiAliasing(true, Integer.parseInt(Character.toString(item.toString().charAt(0))));
break;
}
}
}
});
settingsWindow.addComponent(settingsApplyBtn);
controlsBtn = new GUIButton(font, new Color(255, 255, 255), "Controls", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
controlsBtn.setParentAlignment(GUIAlignment.BOTTOM_CENTER);
controlsBtn.setDimension(200, 40);
controlsBtn.setPosition(105, -30);
controlsBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
controlsWindow.setVisible(!controlsWindow.isVisible());
if (controlsWindow.isVisible()) controlsWindow.setToBePutOnTop(true);
}
});
settingsWindow.addComponent(controlsBtn);
settingsBtn = new GUIButton(font, new Color(255, 255, 255), "Settings", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
settingsBtn.setParentAlignment(GUIAlignment.TOP_RIGHT);
settingsBtn.setDimension(160, 35);
settingsBtn.setPosition(-5, 45);
settingsBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
settingsWindow.setVisible(!settingsWindow.isVisible());
if (settingsWindow.isVisible()) settingsWindow.setToBePutOnTop(true);
}
});
container.addComponent(settingsBtn);
resolutionComboBox = new GUIComboBox(font, new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
resolutionComboBox.setParentAlignment(GUIAlignment.TOP_CENTER);
resolutionComboBox.setDimension(400, 35);
resolutionComboBox.setPosition(0, 10);
resolutionComboBox.setVisibleItems(5);
for (DisplayMode displayMode : LEDCubeManager.getInstance().getDisplayModeList()) {
resolutionComboBox.addItem(displayMode.getWidth() + "x" + displayMode.getHeight());
}
resolutionComboBox.setSelectedItem(LEDCubeManager.getWidth() + "x" + LEDCubeManager.getHeight());
settingsScrollBox.addComponent(resolutionComboBox);
audioInputComboBox = new GUIComboBox(font, new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
audioInputComboBox.setParentAlignment(GUIAlignment.TOP_CENTER);
audioInputComboBox.setDimension(400, 35);
audioInputComboBox.setPosition(0, 55);
audioInputComboBox.setVisibleItems(5);
audioInputComboBox.addAllItems(LEDCubeManager.getLEDCube().getSpectrumAnalyzer().getMixers().keySet());
audioInputComboBox.setSelectedItem(LEDCubeManager.getLEDCube().getSpectrumAnalyzer().getCurrentMixerName());
settingsScrollBox.addComponent(audioInputComboBox);
antiAliasingComboBtn = new GUIComboButton(font, new Color(255, 255, 255), new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
antiAliasingComboBtn.setParentAlignment(GUIAlignment.TOP_CENTER);
antiAliasingComboBtn.setDimension(400, 35);
antiAliasingComboBtn.setPosition(0, 100);
antiAliasingComboBtn.addItem("Off");
for (int i = 2; i <= LEDCubeManager.getInstance().antiAliasingMaxSamples; i *= 2) {
antiAliasingComboBtn.addItem(i + "x");
}
antiAliasingComboBtn.setSelectedItem(LEDCubeManager.getInstance().isAntiAliasing() ? LEDCubeManager.getInstance().getAntiAliasingSamples() + "x" : "Off");
settingsScrollBox.addComponent(antiAliasingComboBtn);
controlsWindow = new GUIWindow(new GUIBackground(new Color(10, 10, 10), new Color(255, 0, 0), 2));
controlsWindow.setDimension(500, 450);
controlsWindow.setPosition(container.getWidth() / 2 - controlsWindow.getWidth() / 2, container.getHeight() / 2 - controlsWindow.getHeight() / 2);
controlsWindow.setResizable(false, true);
controlsWindow.setCloseAction(GUIWindow.HIDE_ON_CLOSE);
controlsWindow.setMinimumSize(new Dimension(50, 150));
controlsWindow.setVisible(false);
container.addComponent(controlsWindow);
controlsTabbed = new GUITabbed(fontTabbed, new Color(255, 255, 255), new GUIBackground(new Color(50, 50, 50), new Color(255, 0, 0), 2));
controlsTabbed.setDimension((int)controlsWindow.getContainerBox().getWidth(), (int)controlsWindow.getContainerBox().getHeight());
controlsWindow.setDimensionChangeHandler(new GUICallback() {
@Override
public void run() {
controlsTabbed.setDimension((int)controlsWindow.getContainerBox().getWidth(), (int)controlsWindow.getContainerBox().getHeight());
}
});
controlsWindow.addComponent(controlsTabbed);
audioInputBtnBg = new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2);
audioInputBtn = new GUIButton(font, new Color(255, 255, 255), "Audio Input", audioInputBtnBg);
audioInputBtn.setParentAlignment(GUIAlignment.TOP_RIGHT);
audioInputBtn.setDimension(200, 35);
audioInputBtn.setPosition(-5, 85);
audioInputBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
boolean running = LEDCubeManager.getLEDCube().getSpectrumAnalyzer().isRunningAudioInput();
audioInputBtnBg.setBackgroundColor(running ? new Color(255, 0, 0) : new Color(0, 255, 0));
if (running) LEDCubeManager.getLEDCube().getSpectrumAnalyzer().stopAudioInput();
else LEDCubeManager.getLEDCube().getSpectrumAnalyzer().startAudioInput();
}
});
container.addComponent(audioInputBtn);
mixerGainSlider = new GUISlider(new Color(255, 0, 0), new Color(50, 50, 50));
mixerGainSlider.setParentAlignment(GUIAlignment.TOP_RIGHT);
mixerGainSlider.setDimension(200, 30);
mixerGainSlider.setPosition(-5, 125);
mixerGainSlider.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().getSpectrumAnalyzer().setMixerGain(mixerGainSlider.getValue() * 20);
LEDCubeManager.getConfig().setProperty("sound.inputgain", mixerGainSlider.getValue());
}
});
mixerGainSlider.setValue(LEDCubeManager.getConfig().getFloat("sound.inputgain"));
container.addComponent(mixerGainSlider);
transformWindow = new GUIWindow(new GUIBackground(new Color(10, 10, 10), new Color(255, 0, 0), 2));
transformWindow.setDimension(310, 272);
transformWindow.setPosition(container.getWidth() - transformWindow.getWidth() - 10, container.getHeight() - transformWindow.getHeight() - 360);
transformWindow.setResizable(false);
transformWindow.setCloseAction(GUIWindow.HIDE_ON_CLOSE);
transformWindow.setMinimumSize(new Dimension(50, 150));
transformWindow.setVisible(false);
container.addComponent(transformWindow);
transformBtn = new GUIButton(font, new Color(255, 255, 255), "Transform", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
transformBtn.setParentAlignment(GUIAlignment.BOTTOM_RIGHT);
transformBtn.setDimension(165, 35);
transformBtn.setPosition(-10, -315);
transformBtn.setClickHandler(new GUICallback() {
@Override
public void run() {
transformWindow.setVisible(!transformWindow.isVisible());
if (transformWindow.isVisible()) transformWindow.setToBePutOnTop(true);
}
});
container.addComponent(transformBtn);
mirrorLabel = new GUILabel(font, new Color(255, 255, 255), "Mirror");
mirrorLabel.setDimension(20, 105);
mirrorLabel.setPosition(10, 10);
transformWindow.addComponent(mirrorLabel);
mirrorX = new GUICheckBox(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
mirrorX.setDimension(30, 30);
mirrorX.setPosition(115, 10);
mirrorX.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setReflection(mirrorX.isChecked(), mirrorY.isChecked(), mirrorZ.isChecked());
}
});
transformWindow.addComponent(mirrorX);
mirrorXLabel = new GUILabel(font, new Color(255, 255, 255), "X");
mirrorXLabel.setDimension(20, 30);
mirrorXLabel.setPosition(150, 10);
mirrorX.setLabel(mirrorXLabel);
transformWindow.addComponent(mirrorXLabel);
mirrorY = new GUICheckBox(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
mirrorY.setDimension(30, 30);
mirrorY.setPosition(180, 10);
mirrorY.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setReflection(mirrorX.isChecked(), mirrorY.isChecked(), mirrorZ.isChecked());
}
});
transformWindow.addComponent(mirrorY);
mirrorYLabel = new GUILabel(font, new Color(255, 255, 255), "Y");
mirrorYLabel.setDimension(20, 30);
mirrorYLabel.setPosition(215, 10);
mirrorY.setLabel(mirrorYLabel);
transformWindow.addComponent(mirrorYLabel);
mirrorZ = new GUICheckBox(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
mirrorZ.setDimension(30, 30);
mirrorZ.setPosition(245, 10);
mirrorZ.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setReflection(mirrorX.isChecked(), mirrorY.isChecked(), mirrorZ.isChecked());
}
});
transformWindow.addComponent(mirrorZ);
mirrorZLabel = new GUILabel(font, new Color(255, 255, 255), "Z");
mirrorZLabel.setDimension(20, 30);
mirrorZLabel.setPosition(280, 10);
mirrorZ.setLabel(mirrorZLabel);
transformWindow.addComponent(mirrorZLabel);
rotateLabel = new GUILabel(font, new Color(255, 255, 255), "Rotate (Degrees)");
rotateLabel.setDimension(font.getWidth(rotateLabel.getText()), 30);
rotateLabel.setPosition(10, 50);
transformWindow.addComponent(rotateLabel);
rotateXLabel = new GUILabel(font, new Color(255, 255, 255), "X");
rotateXLabel.setDimension(20, 30);
rotateXLabel.setPosition(10, 93);
transformWindow.addComponent(rotateXLabel);
rotateXSpinner = new GUISpinner(font, new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
rotateXSpinner.setDimension(150, 35);
rotateXSpinner.setPosition(35, 90);
rotateXSpinner.setMinValue(-360);
rotateXSpinner.setMaxValue(360);
rotateXSpinner.setValue(90);
rotateXSpinner.setIncrement(90);
transformWindow.addComponent(rotateXSpinner);
rotateXButton = new GUIButton(font, new Color(255, 255, 255), "Apply", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
rotateXButton.setDimension(100, 35);
rotateXButton.setPosition(195, 90);
rotateXButton.setClickHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().rotateTransform((float)Math.toRadians(rotateXSpinner.getValue()), new Vector3(1, 0, 0));
}
});
transformWindow.addComponent(rotateXButton);
rotateYLabel = new GUILabel(font, new Color(255, 255, 255), "Y");
rotateYLabel.setDimension(20, 30);
rotateYLabel.setPosition(10, 133);
transformWindow.addComponent(rotateYLabel);
rotateYSpinner = new GUISpinner(font, new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
rotateYSpinner.setDimension(150, 35);
rotateYSpinner.setPosition(35, 130);
rotateYSpinner.setMinValue(-360);
rotateYSpinner.setMaxValue(360);
rotateYSpinner.setValue(90);
rotateYSpinner.setIncrement(90);
transformWindow.addComponent(rotateYSpinner);
rotateYButton = new GUIButton(font, new Color(255, 255, 255), "Apply", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
rotateYButton.setDimension(100, 35);
rotateYButton.setPosition(195, 130);
rotateYButton.setClickHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().rotateTransform((float)Math.toRadians(rotateYSpinner.getValue()), new Vector3(0, 1, 0));
}
});
transformWindow.addComponent(rotateYButton);
rotateZLabel = new GUILabel(font, new Color(255, 255, 255), "Z");
rotateZLabel.setDimension(20, 30);
rotateZLabel.setPosition(10, 173);
transformWindow.addComponent(rotateZLabel);
rotateZSpinner = new GUISpinner(font, new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
rotateZSpinner.setDimension(150, 35);
rotateZSpinner.setPosition(35, 170);
rotateZSpinner.setMinValue(-360);
rotateZSpinner.setMaxValue(360);
rotateZSpinner.setValue(90);
rotateZSpinner.setIncrement(90);
transformWindow.addComponent(rotateZSpinner);
rotateZButton = new GUIButton(font, new Color(255, 255, 255), "Apply", new GUIBackground(new Color(255, 0, 0), new Color(50, 50, 50), 2));
rotateZButton.setDimension(100, 35);
rotateZButton.setPosition(195, 170);
rotateZButton.setClickHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().rotateTransform((float)Math.toRadians(rotateZSpinner.getValue()), new Vector3(0, 0, 1));
}
});
transformWindow.addComponent(rotateZButton);
previewTransform = new GUICheckBox(new Color(255, 255, 255), new GUIBackground(new Color(0, 0, 0), new Color(255, 0, 0), 2));
previewTransform.setDimension(30, 30);
previewTransform.setPosition(10, 210);
previewTransform.setChecked(true);
previewTransform.setChangeHandler(new GUICallback() {
@Override
public void run() {
LEDCubeManager.getLEDCube().setPreviewTransform(previewTransform.isChecked());
}
});
transformWindow.addComponent(previewTransform);
previewTransformLabel = new GUILabel(font, new Color(255, 255, 255), "Preview");
previewTransformLabel.setDimension(font.getWidth(previewTransformLabel.getText()), 30);
previewTransformLabel.setPosition(45, 210);
previewTransform.setLabel(previewTransformLabel);
transformWindow.addComponent(previewTransformLabel);
}
@Override
public void update(float delta) {
super.update(delta);
progressSlider.setValueWithoutNotify(LEDCubeManager.getLEDCube().getSpectrumAnalyzer().getPosition());
}
@Override
public void render() {
RenderHelper.drawSquare(LEDCubeManager.getWidth() - 40 - 10, LEDCubeManager.getHeight() - 150 - 10, 40, 150, LEDCubeManager.getLEDCube().getPaintColor());
super.render();
}
public final void populateAnimationList() {
animComboBox.clearItems();
for (String name : LEDCubeManager.getLEDCube().getAnimationNames()) {
animComboBox.addItem(name);
}
animComboBox.setSelectedItem(1);
}
}
|
package com.thaiopensource.relaxng.impl;
import com.thaiopensource.xml.util.Name;
import java.util.Vector;
import java.util.Hashtable;
import org.relaxng.datatype.ValidationContext;
public class PatternMatcher implements Cloneable {
static private class Shared {
private final Pattern start;
private final ValidatorPatternBuilder builder;
private Hashtable recoverPatternTable;
Shared(Pattern start, ValidatorPatternBuilder builder) {
this.start = start;
this.builder = builder;
}
Pattern findElement(Name name) {
if (recoverPatternTable == null)
recoverPatternTable = new Hashtable();
Pattern p = (Pattern)recoverPatternTable.get(name);
if (p == null) {
p = FindElementFunction.findElement(builder, name, start);
recoverPatternTable.put(name, p);
}
return p;
}
PatternMemo fixAfter(PatternMemo p) {
return builder.getPatternMemo(p.getPattern().applyForPattern(new ApplyAfterFunction(builder) {
Pattern apply(Pattern p) {
return builder.makeEmpty();
}
}));
}
}
private PatternMemo memo;
private boolean textMaybeTyped;
private boolean hadError;
private boolean ignoreNextEndTag;
private String errorMessage;
private final Shared shared;
PatternMatcher(Pattern start, ValidatorPatternBuilder builder) {
shared = new Shared(start, builder);
memo = builder.getPatternMemo(start);
}
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new Error("unexpected CloneNotSupportedException");
}
}
public PatternMatcher copy() {
return (PatternMatcher)clone();
}
public boolean matchStartDocument() {
if (memo.isNotAllowed())
return error("schema_allows_nothing");
return true;
}
public boolean matchStartTagOpen(Name name) {
if (setMemo(memo.startTagOpenDeriv(name)))
return true;
PatternMemo next = memo.startTagOpenRecoverDeriv(name);
if (!next.isNotAllowed()) {
memo = next;
return error("required_elements_missing");
}
ValidatorPatternBuilder builder = shared.builder;
next = builder.getPatternMemo(builder.makeAfter(shared.findElement(name), memo.getPattern()));
memo = next;
return error(next.isNotAllowed() ? "unknown_element" : "out_of_context_element", name);
}
public boolean matchAttributeName(Name name) {
if (setMemo(memo.startAttributeDeriv(name)))
return true;
ignoreNextEndTag = true;
return error("impossible_attribute_ignored", name);
}
public boolean matchAttributeValue(String value, ValidationContext vc) {
if (ignoreNextEndTag) {
ignoreNextEndTag = false;
return true;
}
if (setMemo(memo.dataDeriv(value, vc)))
return true;
memo = memo.recoverAfter();
return error("bad_attribute_value_no_name"); // XXX add to catalog
}
public boolean matchStartTagClose() {
boolean ret;
if (setMemo(memo.endAttributes()))
ret = true;
else {
memo = memo.ignoreMissingAttributes();
// XXX should specify which attributes
ret = error("required_attributes_missing");
}
textMaybeTyped = memo.getPattern().getContentType() == Pattern.DATA_CONTENT_TYPE;
return ret;
}
public boolean matchText(String string, ValidationContext vc, boolean nextTagIsEndTag) {
if (textMaybeTyped && nextTagIsEndTag) {
ignoreNextEndTag = true;
return setDataDeriv(string, vc);
}
else {
if (DataDerivFunction.isBlank(string))
return true;
return matchUntypedText();
}
}
public boolean matchUntypedText() {
if (setMemo(memo.mixedTextDeriv()))
return true;
return error("text_not_allowed");
}
public boolean isTextMaybeTyped() {
return textMaybeTyped;
}
private boolean setDataDeriv(String string, ValidationContext vc) {
textMaybeTyped = false;
if (!setMemo(memo.textOnly())) {
memo = memo.recoverAfter();
return error("only_text_not_allowed");
}
if (setMemo(memo.dataDeriv(string, vc))) {
ignoreNextEndTag = true;
return true;
}
PatternMemo next = memo.recoverAfter();
boolean ret = true;
if (!memo.isNotAllowed()) {
if (!next.isNotAllowed()
|| shared.fixAfter(memo).dataDeriv(string, vc).isNotAllowed())
ret = error("string_not_allowed");
}
memo = next;
return ret;
}
public boolean matchEndTag(ValidationContext vc) {
// The tricky thing here is that the derivative that we compute may be notAllowed simply because the parent
// is notAllowed; we don't want to give an error in this case.
if (ignoreNextEndTag)
return true;
if (textMaybeTyped)
return setDataDeriv("", vc);
textMaybeTyped = false;
if (setMemo(memo.endTagDeriv()))
return true;
PatternMemo next = memo.recoverAfter();
if (memo.isNotAllowed()) {
if (!next.isNotAllowed()
|| shared.fixAfter(memo).endTagDeriv().isNotAllowed()) {
memo = next;
return error("unfinished_element");
}
}
memo = next;
return true;
}
public String getErrorMessage() {
return errorMessage;
}
public boolean isValidSoFar() {
return !hadError;
}
// members are of type Name
public Vector possibleStartTags() {
// XXX
return null;
}
public Vector possibleAttributes() {
// XXX
return null;
}
private boolean setMemo(PatternMemo m) {
if (m.isNotAllowed())
return false;
else {
memo = m;
return true;
}
}
private boolean error(String key) {
if (hadError && memo.isNotAllowed())
return true;
hadError = true;
errorMessage = SchemaBuilderImpl.localizer.message(key);
return false;
}
private boolean error(String key, Name arg) {
return error(key, NameFormatter.format(arg));
}
private boolean error(String key, String arg) {
if (hadError && memo.isNotAllowed())
return true;
hadError = true;
errorMessage = SchemaBuilderImpl.localizer.message(key, arg);
return false;
}
}
|
package april_s_fool;
import java.lang.reflect.Field;
/**
* in this class I'm gonna fool around and make some Java-magick ;)
*
* @author GHajba
*/
public class FoolingAround {
public static void main(String[] args) throws Exception
{
final String s1 = new StringBuilder("Welcome").toString();
final String s2 = s1.intern();
System.out.println(s1 != "Welcome");
System.out.println("Welcome".equals(s1));
System.out.println(s2 == "Welcome");
System.out.println("Welcome".equals(s2));
magick();
System.out.println("Welcome");
System.out.println(s1);
System.out.println(s2);
System.out.println("
integerTricks();
System.out.println((Integer)5 * 3);
System.out.println(Integer.valueOf(5));
}
/*
* I know that it is called 'magic' and I'm referencing to occult studies of magic
*/
private static void magick() throws Exception
{
final Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
field.set("Welcome", "Goodbye".toCharArray());
}
private static void integerTricks() throws ClassNotFoundException, Exception {
final Class cls = Class.forName("java.lang.Integer$IntegerCache");
final Field field = cls.getDeclaredField("cache");
field.setAccessible(true);
final Integer[] cache = (Integer[])field.get(null);
cache[133] = 11;
}
}
|
package vnmr.apt;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.Semaphore;
import javax.swing.JOptionPane;
import vnmr.apt.ChannelInfo.TunePosition;
import vnmr.util.Fmt;
import vnmr.probeid.ProbeIdClient;
import static vnmr.apt.TuneUtilities.*;
public class ProbeTune implements Executer, AptDefs {
/*
* Version string of the software. Update this string for every release!
* Must be of the form "x.y...", where x, y, ... are the major,
* minor, and even more minor version numbers.
*/
static private final String VERSION = "1.7";
static private final int STEP_SLACK = 2;
static private final double STEP_RATIO = 5;
static private final int MIN_STEP_REVERSES = 2;
static private final int MAX_STEP_REVERSES = 5;
/** use probe-resident tuning files **/
private static boolean m_useProbeId = false;
/** probe client interface -
* declared static to provide external access without a handle on ProbeTune
*/
private static AptProbeIdClient m_probeId = null;
private static boolean m_useLock = true; // lock access to resources shared by multiple threads
/**
* The maximum number of independent tune motors per channel.
* (One tune and one match.)
*/
static private final int MAX_TUNE_MOTORS = 2; // Motors per channel
private int m_nTuneMotors = MAX_TUNE_MOTORS;
protected List<String> m_commandList = new ArrayList<String>();
private CommandListenersThread m_listeners = null;
private Map<Integer,ChannelInfo> m_chanInfos = null;
private List<ChannelInfo> m_chanList = null;
private MotorControl motorControl = null;
private SweepControl sweepControl = null;
private boolean m_rawDataMode = false;
private boolean m_savedRawDataMode = m_rawDataMode;
private int[] m_nReverses = new int[MAX_TUNE_MOTORS];
private static boolean m_cancel = false;
/** The frequency we currently want to tune to. */
private static double m_targetFreq = Double.NaN;
/**
* The current tune criterion.
*/
private TuneCriterion m_criterion = TuneCriterion.getCriterion("Fine");
private String m_usrProbeName = "";
private String m_probeName = "";
private int m_channelNumber = 0;
private static String m_modeName = null;
private static double m_lowerCutoffFreq = Double.NaN;
private static double m_upperCutoffFreq = Double.NaN;
private static String m_sweepType = "mt";
private static String m_sweepIpAddr = "agilentNA";
private static String m_motorHostname = "V-Protune";
private static String m_motorIpAddr = "172.16.0.245"; // Use if hostname bad
private static String m_commands = null;
private static double[] m_initialSweep = null;
//private static double[] m_calSweep = new double[4];
private static long m_1stSweepTimeout = 30000;
private static boolean m_guiFlag = true;
private static boolean m_autoFlag = false;
private static String m_vnmrSystemDir = "/vnmr";
private static String m_vnmrUserDir
= System.getProperty("user.home") + "/vnmrsys";
private static String m_sysTuneDir = null;
private static boolean m_firstTime= true;
private static boolean m_dispInfo= false;
private static String m_cmdHostAndPort = "";
//private static TuneCriterion[] m_tuneCriteria;
/** What fraction of the way to move to the target in one step. */
static private double m_stepDamping = 0.33;
/** The status message for the latest tuning attempt. */
private TuneResult m_tuneStatus = new TuneResult();
/** List of all the tune results obtained in this run. */
private ArrayList<TuneResult> m_tuneResults = new ArrayList<TuneResult>();
private ReflectionData m_reflectionData = null;
private double m_padAdj = 1.0;
private static String m_tuneUpdate = UPDATING_ON;
private static boolean m_useRefPositions = true;
private static boolean m_favorCurrentChannel = false;
private static int m_maxDegsPerStep = MAX_DEGREES_PER_STEP;
private static boolean m_tuningAttempted = false;
private int m_cmdNum = 0;
/**
* m_debugLevel
* Debug level setting. Current categories are:
* 0 - No message
* 1 - System hardware failure messages (unable to continue)
* 2 - (1) + Tune related failure messages (unable to continue)
* 3 - All error messages
* 4 - All status and information messages
* 5 - Special debug messages
*/
private static int m_debugLevel = 0; //Default no debug messages
/**
* The port number used to ensure that only one ProTune is running on
* this host.
* A ProTune thread listens on this port for a "quitgui" command.
*/
public static int lockPortNumber = 4593;
private static boolean m_probeNamePopup = false;
private static boolean m_isVnmrConnection
= getBooleanProperty("INFO2VJ", true);
/** The date this software version was compiled. */
private static String m_date;
//private static int m_matchCriterionIndex = -1;
private boolean m_sysInitialized = false;
public int m_nExecThreadsRunning = 0;
private static boolean autoStartThread = true;
/** Holds 5 calibration scans in order: open, load, short, probe, sigma. */
private ReflectionData[] m_calData = new ReflectionData[5];
private ExecTuneThread m_execThread = null;
private String m_queuedCommands = "";
private boolean m_isTorqueTool = false;
/** Exit after executing command-line commands. */
private static boolean m_autoExit = true;
public static void main(String[] args) {
String probeName = setup(args);
if (m_probeNamePopup) {
ProbeNamePopup.startProbeTune();
} else {
try {
new ProbeTune(probeName, probeName);
} catch (InterruptedException e) {
return; // User aborted before initialization completed
}
}
}
/**
* Parse arguments and configure static members. It is a public member
* in order to facilitate unit test setup.
* @param args The command line arguments
* @return probe name
*/
public static String setup(String[] args) {
Class<ProbeTune> myclass = ProbeTune.class;
// NB: scons puts the compilation date in the Implementation Version
String date = myclass.getPackage().getImplementationVersion();
String today = new SimpleDateFormat(" yyyy-MM-dd").format(new Date());
m_date = (date != null) ? date : today;
;
//DebugOutput.addCategory("Initialization"); // Default messages
DebugOutput.addCategory("TuningSummary"); // Default messages
DebugOutput.addCategory("TuneAlgorithm"); // Default messages
// NB: apt.debugCategories may be augmented later,
// but enable debug output we know about as soon as possible.
DebugOutput.addCategories(System.getProperty("apt.debugCategories"));
Messages.postDebug("TuningSummary", "Starting ProTune");
// This is for windows and non-windows system with new protune
// script with the "sysdir" and "userdir" properties defined.
String sysdir = System.getProperty("sysdir");
if (sysdir != null) {
m_vnmrSystemDir = sysdir;
}
String userdir = System.getProperty("userdir");
if (userdir != null) {
m_vnmrUserDir = userdir;
}
autoStartThread = true;
if (DebugOutput.isSetFor("Initialization")) {
StringBuffer msg = new StringBuffer("Called with args:");
for (String arg : args) {
msg.append(" \"" + arg + "\"");
}
Messages.postDebug(msg.toString());
}
String probeName = "NoProbeName";
int len = args.length;
for (int i = 0; i < len; i++) {
Messages.postDebug("Initialization", "Got command line flag: "
+ args[i]);
if (args[i].equalsIgnoreCase("-motorIP") && i + 1 < len) {
m_motorIpAddr = m_motorHostname = args[++i];
System.setProperty("apt.motorHostname", m_motorHostname);
} else if (args[i].equalsIgnoreCase("-sweep") && i + 1 < len) {
m_sweepType = args[++i];
System.setProperty("apt.sweepType", m_sweepType);
} else if (args[i].equalsIgnoreCase("-lowerCutoff") && i + 1 < len) {
String lowerCutoff = args[++i];
try {
m_lowerCutoffFreq = Double.parseDouble(lowerCutoff);
System.setProperty("apt.lowerCutoff", lowerCutoff);
} catch (NumberFormatException nfe) {
}
} else if (args[i].equalsIgnoreCase("-upperCutoff") && i + 1 < len) {
String upperCutoff = args[++i];
try {
m_upperCutoffFreq = Double.parseDouble(upperCutoff);
System.setProperty("apt.upperCutoff", upperCutoff);
} catch (NumberFormatException nfe) {
}
} else if (args[i].equalsIgnoreCase("-cmdSocket") && i + 1 < len) {
m_cmdHostAndPort = args[++i];
//m_autoFlag = true; // No interactive messages
} else if (args[i].equalsIgnoreCase("-sweepIP") && i + 1 < len) {
m_sweepIpAddr = args[++i];
System.setProperty("apt.sweepIpAddr", m_sweepIpAddr);
} else if (args[i].equalsIgnoreCase("-vnmrsystem") && i + 1 < len) {
m_vnmrSystemDir = args[++i];
} else if (args[i].equalsIgnoreCase("-vnmruser") && i + 1 < len) {
m_vnmrUserDir = args[++i];
} else if (args[i].equalsIgnoreCase("-systunedir") && i + 1 < len) {
m_sysTuneDir = args[++i];
} else if (args[i].equalsIgnoreCase("-probe") && i + 1 < len) {
probeName = args[++i];
System.setProperty("apt.probeName", probeName);
Messages.postDebug("TuningSummary",
"ProbeTune: probeName=" + probeName);
} else if (args[i].equalsIgnoreCase("-match") && i + 1 < len) {
double match_db = Double.parseDouble(args[++i]);
double match_pow = Math.pow(10, -Math.abs(match_db / 10));
System.setProperty("apt.targetMatch", Fmt.f(6, match_pow));
} else if (args[i].equalsIgnoreCase("-sweepTimeout") && i + 1 < len)
{
String firstSweepTimeout = args[++i];
try {
m_1stSweepTimeout = Long.parseLong(firstSweepTimeout);
System.setProperty("apt.firstSweepTimeout",
firstSweepTimeout);
} catch (NumberFormatException nfe) {
}
} else if (args[i].equalsIgnoreCase("-initialSweep") && i+3 < len) {
m_initialSweep = new double[3];
String start = args[++i];
String stop = args[++i];
String np = args[++i];
try {
m_initialSweep[0] = Double.parseDouble(start);
m_initialSweep[1] = Double.parseDouble(stop);
m_initialSweep[2] = Double.parseDouble(np);
System.setProperty("apt.initialStart", start);
System.setProperty("apt.initialStop", stop);
System.setProperty("apt.initialNp", np);
} catch (NumberFormatException nfe) {
m_initialSweep = null;
}
} else if (args[i].equalsIgnoreCase("-lockPort") && ((i+1) < len)) {
try {
lockPortNumber = Integer.parseInt(args[++i]);
} catch (NumberFormatException nfe) {
}
// System property "apt.lockPort" is set below
} else if (args[i].equalsIgnoreCase("-exec") && i + 1 < len) {
if (m_commands == null) {
m_commands = args[++i];
} else {
m_commands += ";" + args[++i];
}
} else if (args[i].equalsIgnoreCase("-debug") && ((i+1) < len)) {
try {
m_debugLevel = Integer.parseInt(args[++i]);
} catch (NumberFormatException nfe) {
DebugOutput.addCategories(args[i]);
}
} else if (args[i].equalsIgnoreCase("-noGui")) {
disableGui();
} else if (args[i].equalsIgnoreCase("-simpleGui")) {
System.setProperty("apt.simpleGui", "true");
} else if (args[i].equalsIgnoreCase("-torque")) {
System.setProperty("apt.torque", "true");
} else if (args[i].equalsIgnoreCase("-auto")) {
m_autoFlag = true;
} else if (args[i].equalsIgnoreCase("-update") && i + 1 < len) {
m_tuneUpdate = args[++i].trim().toLowerCase();
//System.setProperty("apt.refPositionUpdating", m_tuneUpdate);
} else if (args[i].equalsIgnoreCase("-maxStep") && i + 1 < len) {
try {
m_maxDegsPerStep = Integer.parseInt(args[++i]);
} catch (NumberFormatException nfe) {
}
} else if (args[i].equalsIgnoreCase("-dispInfo") ) {
m_dispInfo= true;
disableGui();
} else if (args[i].equalsIgnoreCase("-probeNamePopup") ) {
m_probeNamePopup= true;
} else if (args[i].equalsIgnoreCase("-probeid")) {
if (i+1 < len && !args[i+1].startsWith("-"))
m_useProbeId = Boolean.valueOf(args[++i]);
else
m_useProbeId = true;
} else if (args[i].equalsIgnoreCase("-dontLock")) {
m_useLock = false;
} else if (args[i].equalsIgnoreCase("+dontLock")) {
m_useLock = true;
} else if (args[i].equalsIgnoreCase("-probeidiolock")) {
// use when ProbeID and ProbeTune are running in same Java VM
ProbeIdClient.io_synch = true;
} else if (args[i].equalsIgnoreCase("-unittest")) {
System.setProperty("INFO2VJ", Boolean.toString(true));
if (args.length == 0) {
org.junit.runner.JUnitCore.main("vnmr.apt.ProbeTuneTest");
System.exit(0);
}
} else if (args[i].equalsIgnoreCase("-mode") && i + 1 < len) {
m_modeName = args[++i];
} else if (args[i].equalsIgnoreCase("-noAutoExit") ) {
m_autoExit = false;
} else {
Messages.postDebugWarning("Bad command line flag: " + args[i]);
}
}
System.setProperty("apt.lockPort", "" + lockPortNumber);
return probeName;
}
public static void disableGui() {
m_guiFlag = false;
m_autoFlag = true; // No Gui implies "auto" since there
// should be no interactive message
}
/**
* Create and initialize the master, ProbeTune, object.
* @param probeName The value of the Vnmr "probe" parameter.
* @param usrProbeName The name of the user directory for the persistence
* files.
* @throws InterruptedException If tuning is aborted before
* initialization completes.
*/
public ProbeTune(String probeName, String usrProbeName)
throws InterruptedException {
ServerSocket locksocket;
Messages.postDebug("Initialization", "ProbeTune<init>");
locksocket = applicationRunning(this.getClass().getName(),
lockPortNumber);
if (locksocket == null) {
Messages.postError("Another instance of ProbeTune is running.");
exit(-4, "failed - Another instance of ProbeTune is running");
} else {
// Listen for the "quitgui" command on the lock socket
new CommandListener(lockPortNumber, locksocket, this).start();
writePid();
}
Messages.postDebug("Initialization", "ProbeTune<lock>");
setProbe(probeName);
m_usrProbeName = usrProbeName;
Messages.postDebug("Initialization", "ProbeTune<probe>");
setRequiredProperties();
readPropertiesFromFile(getVnmrPropertiesFile());
Messages.postDebug("Initialization", "ProbeTune<properties>");
DebugOutput.addCategories(System.getProperty("apt.debugCategories"));
if (!readPropertiesFromFile(getUserConfigFile())) {
readPropertiesFromFile(getSystemConfigFile());
}
Messages.postDebug("Initialization", "ProbeTune<dbg-categories>");
DebugOutput.addCategories(System.getProperty("apt.debugCategories"));
if (!readPropertiesFromFile(getUserProbeConfigFile())) {
readPropertiesFromFile(getSystemProbeConfigFile());
}
DebugOutput.addCategories(System.getProperty("apt.debugCategories"));
Messages.postDebug("Initialization", "ProbeTune<debug>");
// NB: We call these static initializations explicitly to make sure
// they happen after all System Properties are set.
// Initialize debug output first:
setOptions();
ReflectionData.setOptions();
MotorControl.setOptions();
ChannelInfo.setOptions();
if (!checkProbeName(m_probeName, false)) {
String msg = "No system tune directory found for probe \""
+ m_probeName + "\"";
Messages.postError(msg);
// NB: No longer exiting on this error
//errorExit(msg);
}
//m_sweepType = sweepType;
//m_tuneCriteria = TuneCriterion.getStandardCriteria();
setDefaultTarget();
m_listeners = new CommandListenersThread(this);
m_listeners.start();
// Check for channel and motor files
//Messages.postDebug("Checking for configuration files");/*DBG*/
if (!isProbeSupported()) {
Messages.postDebugWarning("No system tune files for probe \""
+ m_probeName + "\"");
exit("failed - no system tune files for probe \""
+ m_probeName + "\"");
}
Messages.postDebug("Initialization", "ProbeTune<config>");
// Start up GUI with communication
m_isTorqueTool = getBooleanProperty("apt.torque", false);
boolean isSimpleGui;
isSimpleGui = getBooleanProperty("apt.simpleGui", false);
if (m_guiFlag) {
try { // Don't fail just because we can't get a GUI!
int port = m_listeners.getPort(20000);
String console = System.getProperty("apt.console", "vnmrs");
if (m_isTorqueTool) {
new TorqueGui(probeName, usrProbeName,
getSysTuneDir(), getUsrTuneDir(),
"localhost", port, console);
Messages.postDebug("Initialization", "Torque GUI");
} else if (isSimpleGui) {
new SimpleGui(probeName, usrProbeName,
getSysTuneDir(), getUsrTuneDir(),
"localhost", port, console);
Messages.postDebug("Initialization", "Simple ProTune GUI");
} else {
new ProbeTuneGui(probeName, usrProbeName, m_modeName,
getSysTuneDir(), getUsrTuneDir(),
"localhost", port, console);
Messages.postDebug("Initialization", "Started ProTune GUI");
}
} catch (Exception e) {
Messages.postDebugWarning("Cannot start ProTune GUI. See showprotunegui parameter");
} catch (java.lang.InternalError e) {
Messages.postDebugWarning("Error starting GUI: "
+ e.getMessage());
}
}
if (m_cmdHostAndPort != null && m_cmdHostAndPort.length() > 0) {
String host = extractHost(m_cmdHostAndPort);
int port = extractPort(m_cmdHostAndPort);
if (port > 0) {
try {
m_listeners.connectTo(host, port);
} catch (Exception e) {}
}
}
sendOptionsToGui();
Messages.postDebug("Initialization", "Sent options to GUI");
/* NOTE: In case of error, can NOT call function "exit()" above here
* because motorControl and m_listener must both exist otherwise
* exit() will give NullPointerException!
*/
motorControl = new MotorControl(this, m_motorHostname);
if (m_isTorqueTool) {
motorControl.setTorqueDataDir(getUsrTuneDir());
} else {
File fdir = new File(getSysTuneBase(), "MotorLogFiles");
motorControl.setMotorDataDir(fdir, getProbeName());
}
Messages.postDebug("Initialization", "motorControl=" + motorControl);
if (isMotorOk()) {
sendToGui("motorOk yes");
} else {
sendToGui("motorOk no");
// if (m_autoFlag) {
// Messages.postError("No motor control: " + m_motorHostname);
// exit(-3, "failed - No motor control: "+ m_motorHostname);
}
Messages.postDebug("Initialization",
"Probe Tune: check if using network analyzer");
String sweepType = System.getProperty("apt.sweepType");
Messages.postDebug("Initialization",
"Probe Tune: apt.sweepType property: \"" + sweepType
+ "\", m_sweepType=\"" + m_sweepType + "\"");
if (sweepType != null) {
m_sweepType = sweepType;
}
if (!m_isTorqueTool) {
if (m_sweepType.equals("mt")) { // Use MTune (actually protune)
Messages.postDebug("Initialization",
"Probe Tune: using Vnmr data");
// Make sure cal directory is ready
MtuneControl.getCalDir(m_probeName);
if (m_initialSweep != null) {
sweepControl = new MtuneControl(this, true,
m_initialSweep[0],
m_initialSweep[1],
(int)m_initialSweep[2]);
} else {
sweepControl = new MtuneControl(this, true);
}
((MtuneControl)sweepControl).setMotorController(motorControl);
} else {
// Use network analyzer
Messages.postDebug("Initialization",
"Probe Tune: using network analyzer");
sweepControl = new NetworkAnalyzer(this, getSweepIpAddr());
}
}
Messages.postDebug("Initialization", "sweepControl=" + sweepControl);
if (isSweepOk()) {
sendToGui("sweepOk yes");
} else if (!m_isTorqueTool){
Messages.postError(" *** NO SWEEP CONTROL *** ");
sendToGui("sweepOk no");
if (m_autoFlag) {
Messages.postError("No sweep control: " + m_sweepType);
exit(-2, "failed - No sweep control: "+m_sweepType);
}
}
Messages.postDebug("Initialization", "ProbeTune<sweeptype>");
setSysInitialized(true);
Messages.postDebug("Initialization", "m_sysInitialized=true");
Messages.postDebug("Initialization", "displayStatus: INITIALIZE");
displayStatus(STATUS_INITIALIZE);
//ChannelInfo chanInfo = getChannelInfo(m_channelNumber);
//String chanName = chanInfo.getPersistenceFileName();
//sendToGui("displayChannel " + chanName);
sendToGui("displayMatchTolerance " + m_criterion.toString());
Messages.postDebug("Initialization", "m_targetMatch="
+ getTargetMatch());
setTuneMode(1000000);
// Set the channel number to the first available
try {
ChannelInfo ci = getChannelInfos().get(0);
m_channelNumber = ci.getChannelNumber();
} catch (Exception e) {
Messages.postDebug("Exception: " + e);
Messages.postStackTrace(e);
exit("No tune channels are defined");
}
if (m_isTorqueTool) {
setChannel(m_channelNumber, 0, false);
sendToGui("sweepOk yes");
displayStatus(STATUS_READY);
} else if (m_commands == null) {
// Default initial command
setChannel(m_channelNumber, 0, true);
ChannelInfo channelInfo = getChannelInfo(m_channelNumber);
Messages.postDebug("Initialization", "channelInfo=" + channelInfo);
measureTune(channelInfo, 00, true);
displayStatus(STATUS_READY);
} else {
displayStatus(STATUS_READY);
if ( m_autoExit ) {
autoStartThread = false;
}
// Execute args from command line
// Commands are separated by semi-colons
StringTokenizer toker = new StringTokenizer(m_commands, ";");
while (toker.hasMoreTokens()) {
String cmd = toker.nextToken();
//displayCommand(cmd);
exec(cmd);
}
if (m_autoExit ) {
Messages.postDebug("Initialization", "ProbeTune<done>");
exec("setTuneMode 0");
autoStartThread = true;
exec("exit");
}
}
// I don't believe this works, in general. -- ChrisP
if(m_dispInfo){
m_dispInfo=false;
String popup;
popup = displayInfo();
popup = popup.replaceAll("<br>", NL);
JOptionPane optPane= new JOptionPane();
JOptionPane.showMessageDialog(optPane, popup, "Protune Info",
JOptionPane.INFORMATION_MESSAGE);
exit(0, "Protune info done");
}
}
public void quit(int ms) throws InterruptedException {
if (motorControl != null) motorControl.quit(ms);
if (sweepControl != null)
if (sweepControl instanceof MtuneControl)
((MtuneControl)sweepControl).stopTuneModeThread(ms);
MtuneControl.close();
m_listeners.close();
}
private void setProbe(String probeName) {
m_probeName = probeName;
if (m_useProbeId) {
try {
m_probeId = new AptProbeIdClient();
} catch (FileNotFoundException e) {
Messages.postError("error setting probe: "+e.getMessage());
e.printStackTrace();
}
}
}
public static String getProbeFile(String file, String subdir, boolean system) {
String tuneDir = subdir + File.separator + file;
if (m_useProbeId) {
File blob = m_probeId.blobLink(file, subdir, system, false);
if (blob != null)
return blob.getPath();
else return null;
} else {
return (system ? getVnmrUserDir() : getVnmrSystemDir())
+ File.separator + tuneDir;
}
}
// private boolean isProbeSupported(String probeName) {
// String dir = getProbeFile(probeName, "tune", false);
// assert(m_useProbeId || dir.equals(getVnmrSystemDir() + "/tune/" + probeName));
// boolean ok = ChannelInfo.isProbeSupported(dir);
// ok &= MotorInfo.isProbeSupported(dir);
// return ok;
private boolean isProbeSupported() {
String dir = getSysTuneDir();
boolean ok = ChannelInfo.isProbeSupported(dir);
ok &= MotorInfo.isProbeSupported(dir);
return ok;
}
private String getSystemConfigFile() {
return getVnmrSystemDir() + File.separator + "tune"
+ File.separator + "protuneConfig";
}
private String getUserConfigFile() {
return getVnmrUserDir() + File.separator + "tune"
+ File.separator + "protuneConfig";
}
private String getSystemProbeConfigFile() {
String file = getProbeFile("protuneConfig",
"tune"+File.separator+m_probeName, true);
assert(m_useProbeId
|| file.equals(getVnmrSystemDir() + File.separator + "tune"
+ File.separator + m_probeName
+ File.separator + "protuneConfig"));
return file;
}
private String getUserProbeConfigFile() {
String file = getProbeFile("protuneConfig",
"tune"+File.separator+m_usrProbeName, false);
assert(m_useProbeId
|| file.equals(getVnmrUserDir() + File.separator + "tune"
+ File.separator + m_usrProbeName
+ File.separator + "protuneConfig"));
return file;
}
private String getVnmrPropertiesFile() {
return getVnmrSystemDir() + File.separator + "tmp" + File.separator
+ "ptuneProperties";
}
/**
* Extract the port number from a string of the form:
* "<code>hostname:1234</code>".
* @param hostAndPort The string to parse.
* @return The port number, or 0 on failure.
*/
private int extractPort(String hostAndPort) {
int port = 0;
String strPort = hostAndPort;
int idx = hostAndPort.indexOf(":");
if (idx > 0) {
strPort = hostAndPort.substring(idx + 1);
}
try {
port = Integer.parseInt(strPort);
} catch (NumberFormatException nfe) {
Messages.postDebugWarning("Bad cmd port number: " + hostAndPort);
}
return port;
}
/**
* Extract the host name from a string of the form:
* "<code>hostname:1234</code>".
* @param hostAndPort The string to parse.
* @return The port number, or "localhost" if there is no host
* part in the input string.
*/
private String extractHost(String hostAndPort) {
int idx = hostAndPort.indexOf(":");
if (idx > 0) {
return hostAndPort.substring(0, idx);
} else {
return "localhost";
}
}
public boolean isMotorOk() {
return motorControl != null && motorControl.isConnected();
}
public boolean isSweepOk() {
return (sweepControl != null && sweepControl.isConnected());
}
private void setDefaultTarget() {
try {
String matchThresh = System.getProperty("apt.targetMatch");
setTargetMatch(Double.valueOf(matchThresh));
} catch(Exception e) {
}
// NB: This will usually be overridden by a channel-specific value
try {
String targetFreq = System.getProperty("apt.targetFreq");
m_targetFreq = Double.valueOf(targetFreq);
} catch(Exception e) {
}
}
/**
* Make sure that all the System Properties we expect are actually there.
*/
private void setRequiredProperties() {
}
private static void setOptions() {
// TODO: Too late to set sysdir and userdir, we already used them
// to read the property files.
setStringFromProperty(m_vnmrSystemDir, "apt.vnmrSystemDir");
setStringFromProperty(m_vnmrUserDir, "apt.vnmrUserDir");
setStringFromProperty(m_tuneUpdate, "apt.refPositionUpdating");
String key = "apt.useRefPositions";
m_useRefPositions = getBooleanProperty(key, true);
key = "apt.favorCurrentChannel";
m_favorCurrentChannel = getBooleanProperty(key, false);
key = "apt.maxStepSize";
m_maxDegsPerStep =getIntProperty(key, m_maxDegsPerStep);
key = "apt.stepDamping";
m_stepDamping = getDoubleProperty(key, m_stepDamping);
}
private static void setStringFromProperty(String var, String property) {
String value = System.getProperty(property);
if (value != null) {
var = value;
}
}
/**
* Read properties from the ptuneProperties file, and set them
* as System properties.
* @param path The path to the properties file.
* @return True if the file was found and was readable.
*/
private static boolean readPropertiesFromFile(String path) {
boolean ok = true;
Messages.postDebug("Properties", "Reading properties from " + path);
BufferedReader in = getReader(path);
if (in == null) {
ok = false;
} else {
try {
String line;
while ((line = in.readLine()) != null) {
// Split off key from the rest of the line
String[] tokens = line.trim().split("[ \t=:]+", 2);
if (tokens.length == 2) {
String key = "apt." + tokens[0];
System.setProperty(key, tokens[1].trim());
Messages.postDebug("Properties",
"Set property " + key
+ " to \"" + tokens[1] + "\"");
}
}
} catch (IOException ioe) {
Messages.postDebug("Properties",
"readPropertiesFromFile: " + ioe);
} finally {
try {
in.close();
} catch (Exception e) {}
}
}
return ok;
}
private void sendOptionsToGui() {
sendToGui("UseRefs " + (m_useRefPositions ? "1" : "0"));
}
private ServerSocket grabServerSocket(String appname, int port)
throws InterruptedException {
boolean app_running = true; //Assume another instance is running
ServerSocket serverSocket = null;
Messages.postDebug("KillApp",
"Check for previous instance of " + appname);
for (int i = 0; app_running && i < 5; i++) {
try {
// Try to create a server socket using the given port number
Messages.postDebug("KillApp",
" See if port " + port + " is busy ...");
serverSocket = new ServerSocket(port);
app_running = false;
Messages.postDebug("KillApp", " ... OK -- not busy");
} catch (IOException ioe) {
// Somehow the port is currently used, this is an indication
// that another instance is running (although this is not
// definitely true!)
Messages.postDebug("KillApp", " ... port is busy");
// Connect to lock socket and send a quit command
String host = "127.0.0.1";
Socket socket = getSocket("Killer", host, port);
PrintWriter cmdSender = null;
if (socket != null) {
try {
cmdSender =
new PrintWriter(socket.getOutputStream(), true);
Messages.postDebug("KillApp",
" ... killing old instance");
cmdSender.println("quitgui");
Thread.sleep(500);
} catch (IOException ioe2) {
Messages.postDebug("KillApp",
" Cannot talk to port " + port);
} finally {
if (cmdSender != null)
cmdSender.close();
}
}
}
}
return serverSocket;
}
protected ServerSocket applicationRunning(String appname, int port)
throws InterruptedException {
ServerSocket serverSocket = grabServerSocket(appname, port);
if (serverSocket == null) {
// It's still running; use a "kill" command
String pid = readPid();
if (isUnix() && pid != null && pid.length() > 0) {
StringTokenizer toker = new StringTokenizer(pid);
if (toker.hasMoreTokens()) {
pid = toker.nextToken();
String[] command = {"sh", "-c", "kill -9 " + pid};
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
} catch (IOException e) {
} finally {
closeProcessStreams(p);
}
}
}
serverSocket = grabServerSocket(appname, port);
}
if (serverSocket == null) {
Messages.postError("Failed to kill previous instance of ProTune");
}
return serverSocket;
}
private static void writePid() {
String pid = getMyPid();
String pidPath = getVnmrSystemDir() + "/tmp/ptunePid";
new File(pidPath).delete();
writeFile(pidPath, pid);
}
private static String getMyPid() {
String pid = ManagementFactory.getRuntimeMXBean().getName();
if (pid != null) {
StringTokenizer toker = new StringTokenizer(pid, "@ \t\n");
if (toker.hasMoreTokens()) {
pid = toker.nextToken();
}
}
return pid;
}
private String readPid() {
String pidPath = getVnmrSystemDir() + "/tmp/ptunePid";
String pid = readFile(pidPath, false);
return pid;
}
private static boolean isUnix() {
String os = System.getProperty("os.name").toLowerCase();
//linux or unix
return (os.indexOf( "nix") >= 0 || os.indexOf( "nux") >= 0);
}
public String getConsoleType() {
return System.getProperty("apt.console", "vnmrs");
}
public static boolean isQuadPhaseProblematic(String console) {
return "vnmrs".equalsIgnoreCase(console);
}
public static boolean isTuneModeSwitchable(String console) {
return ("inova".equalsIgnoreCase(console)
|| "mercury".equalsIgnoreCase(console));
}
public static boolean isTuneBandSwitchable(String console) {
return ("inova".equalsIgnoreCase(console)
|| "mercury".equalsIgnoreCase(console));
}
/**
* Remove duplicate status messages from the given list and return
* remaining messages as an array of Strings. The idea is to keep only
* the last result for each tune frequency.
* @param statusMsgs The full list of tune results.
* @return The culled results as an array of String messages.
*/
public static String[] cullTuneResults(ArrayList<TuneResult> statusMsgs) {
ArrayList<TuneResult> culledList = new ArrayList<TuneResult>();
int n = statusMsgs.size();
// Go through list backwards; add only last msg for each frequency
for (int i = n - 1; i >= 0; --i) {
TuneResult tr = statusMsgs.get(i);
// NB: TuneResult is "equal" iff frequency is the same
if (!culledList.contains(tr)) {
culledList.add(0, tr); // Add to front of list
}
}
int len = culledList.size();
String[] culledArray = new String[len];
for (int i = 0; i < len; i++) {
culledArray[i] = culledList.get(i).toString();
Messages.postDebug("VnmrMessages",
"cullTuneResults: " + culledArray[i]);
}
return culledArray;
}
/**
* Exit with a given single status message.
* The exitCode will be 0 unless the message cannot be
* sent to Vnmr, in which case it will be -1.
* @param msg The message.
*/
public void exit(String msg) {
exit(-1, msg);
}
/**
* Exit with a given exitCode and a given single status message.
* The exitCode will be changed to -1 if the message cannot be
* sent to Vnmr.
* @param exitCode The exit code.
* @param msg The message.
*/
public void exit(int exitCode, TuneResult msg) {
ArrayList<TuneResult> list = new ArrayList<TuneResult>(1);
list.add(msg);
exit(exitCode, list);
}
/**
* Exit with a given exitCode and a given single status message.
* The exitCode will be changed to -1 if the message cannot be
* sent to Vnmr.
* @param exitCode The exit code.
* @param msg The message.
*/
public void exit(int exitCode, String msg) {
String[] list = {msg};
exit(exitCode, list);
}
/**
* Exit with a given exitCode and a given list of status messages.
* Each status message is logged by Vnmr, and a summary status is
* constructed sent as the "done" status of the ProTune run.
* The exitCode will be 0 unless the messages cannot be
* sent to Vnmr, in which case it will be -1.
* @param statusMsgs The messages.
*/
public void exit(ArrayList<TuneResult> statusMsgs) {
exit(0, statusMsgs);
}
public void exit(int exitCode, ArrayList<TuneResult> statusMsgs) {
if (statusMsgs == null) {
statusMsgs = new ArrayList<TuneResult>();
}
String[] msgs = cullTuneResults(statusMsgs);
exit(exitCode, msgs);
}
/**
* Exit with a given exitCode and a given list of status messages.
* Each status message is logged by Vnmr, and a summary status is
* constructed and sent as the "done" status of the ProTune run.
* The exitCode will be changed to -1 if the messages cannot be
* sent to Vnmr.
* @param exitCode The exit code.
* @param statusMsgs The messages.
*/
public void exit(int exitCode, String[] statusMsgs) {
int n = statusMsgs.length;
Messages.postDebug("TuningSummary", "Exiting ProTune with "
+ n + " results");
try {
setTuneMode(0);
// Keep only last result for each frequency
String msg = "";
String summaryStatus = (exitCode == 0) ? "ok" : "failed";
for (String status : statusMsgs) {
if (status.startsWith("failed")) {
summaryStatus = "failed";
msg += VJ_ERR_MSG;
} else if (!"failed".equals(summaryStatus)
&& status.startsWith("Warning"))
{
summaryStatus = "warning";
msg += VJ_WARN_MSG;
} else {
msg += VJ_INFO_MSG;
}
// ProTune reports (prints) each individual status
msg += ("protune('print', '" + status + "')\n");
}
if (statusMsgs.length == 0 && m_tuningAttempted) {
// Nothing tuned
summaryStatus = "failed - tuning did not complete";
}
// Overall ProTune result is the summaryStatus
Thread.sleep(100);
String pfx = summaryStatus.startsWith("ok")
? VJ_INFO_MSG
: (summaryStatus.startsWith("warning") ? VJ_WARN_MSG
: VJ_ERR_MSG);
msg += (pfx + "protune('done', '" + summaryStatus + "')");
Messages.postDebug("TuningSummary",
"Summary done status=" + summaryStatus);
queueToVnmr(msg);
} catch (Exception e) {
errorExit("Problem reporting results: " + e);
}
if (exitCode < 0) {
Messages.postError(statusMsgs[0]);
}
System.exit(exitCode);
}
public void errorExit(String msg) {
msg = VJ_ERR_MSG + "protune('done', 'failed - " + msg + "')";
queueToVnmr(msg);
exit();
}
/**
* Forced exit with no messages.
* The exit code will be -1.
*/
public void exit() {
System.exit(-1);
}
public void displayTuneStatus() {
//Currently GUI is not supporting this command
//sendToGui("displayTuneStatus " + m_tuneStatus.toString("db"));
}
/*
* Abort any pending and current command if possible.
* The routine will be executed in the calling thread. This
* may be a problem in some case. It would be better to modify
* it to run only in main thread in the future.
*/
public void abort(String msg) {
Messages.postWarning(msg);
m_commandList.clear();
setCancel(true);
try {
motorControl.abort();
} catch (Exception e) {
}
return;
}
public void exec(String cmd) {
String lcmd = cmd.toLowerCase();
if (lcmd.startsWith("abort")) {
if (m_execThread != null) {
m_execThread.interrupt();
}
String msg = null;
if (!lcmd.contains("quiet")) {
msg = "ProTune ABORT";
}
abort(msg);
return;
} else if (lcmd.equals("quitgui")) {
/*
* Need to handle "quitgui" here, otherwise it will never
* get executed if the previous command is stuck.
*/
abort("ProbeTune.exec: QUITGUI!");
exit();
return;
}
setCancel(false);
Messages.postDebug("exec", "queueCmd: \"" + cmd + "\"");
m_commandList.add(cmd);
if (autoStartThread)
{
if (m_nExecThreadsRunning < 1) {
m_execThread = new ExecTuneThread();
m_execThread.start();
}
}
}
/**
* Execute a command synchronously (support for unit testing)
* @param cmd The command to execute.
* @throws InterruptedException If command is aborted.
*/
public void execTest(String cmd) throws InterruptedException {
m_commandList.add(cmd);
execute();
}
synchronized public void execute() throws InterruptedException {
if (m_commandList.size() == 0) {
// Nothing to do
return;
}
String cmd = m_commandList.remove(0);
Thread.currentThread().setName(cmd); // Set name for the debugger
m_cmdNum++;
Messages.postDebug("Exec", "Executing cmd
+ m_cmdNum + ": \"" + cmd + "\"");
try {
displayCommand(cmd);
execute(cmd);
} catch (Exception e) {
Messages.postError("Exception executing \"" + cmd + "\": " + e);
Messages.postStackTrace(e);
}
ChannelInfo chanInfo = getChannelInfo(m_channelNumber);
Messages.postDebug("Persistence",
"About to write Persistence. Check chan info");
if (chanInfo != null) {
if (ChannelInfo.isAutoUpdateOk()) {
chanInfo.writePersistence();
}
if (MotorControl.isAutoUpdateOk()) {
motorControl.writePersistence();
}
} else {
Messages.postError("Could not Write Persistence.");
}
Messages.postDebug("Exec", "Cmd done: \"" + cmd + "\"");
}
/**
* Execute a command. This is called in a separate thread that is
* just for this command. Synchronized, so that only one command
* runs at a time. Only the "abort" command bypasses this; abort
* runs in the main thread.
* @throws InterruptedException if this command is aborted.
*/
synchronized public void execute(String cmd) throws InterruptedException {
if (m_cancel) {
Messages.postDebug("Exec",
"Quitting: " + Thread.currentThread().getName());
return; // Canceled while we were queued up
}
StringTokenizer toker = new StringTokenizer(cmd);
//if (toker.hasMoreTokens()) {
// toker.nextToken(); // Discard label for now
String key = "";
if (toker.hasMoreTokens()) {
key = toker.nextToken();
}
if (key.equalsIgnoreCase("getData")) {
if (isSweepOk()) {
sendToGui("sweepOk yes");
// TODO: Wait until sweep is set
int delay = 0;
ChannelInfo chInfo = getChannelInfo(m_channelNumber);
if (toker.hasMoreTokens()) {
String sDelay = toker.nextToken();
try {
delay = Integer.parseInt(sDelay);
} catch (NumberFormatException nfe) {
Messages.postError("Bad delay count in getData cmd: \""
+ sDelay + "\"");
}
}
ReflectionData data = sweepControl.getData(chInfo, delay);
if (data != null) {
m_reflectionData = data;
displayData(data);
);/*DBG*/
/**
* Finds the appropriate channel for the given frequency.
* A centering parameter is calculated that tells how close the
* given frequency is to the center of the channel. A value of 0
* means the frequency is in the center of the channel, and -1 or +1
* mean it is at the lower or upper boundary, respectively.
* If the current channel includes the given frequency
* (abs(centering parameter) <= 1)
* and m_favorCurrentChannel is true,
* the current channel is returned.
* Otherwise, chooses the channel with the smallest centering parameter.
* If the absolute value of the returned centering parameter
* is greater than 1, we cannot tune to the given frequency.
* @param freq Frequency to tune to (Hz).
* @return The channel number to use and it's centering parameter.
*/
private ChannelAlignment findChannel(double freq)
throws InterruptedException {
ChannelInfo ci;
int bestChan = -1;
double bestCentering = 99;
if (m_favorCurrentChannel) {
// See if current channel is OK
ci = getChannelInfo(m_channelNumber);
if (ci != null) {
double center = ci.getCenterTuneFreq();
double span = ci.getSpanTuneFreq();
bestCentering = (freq - center) / (span / 2);
bestChan = m_channelNumber;
}
}
if (Math.abs(bestCentering) > 1) {
// Current channel no good, look for a channel to use
for (ChannelInfo cii : getChannelInfos()) {
if (cii != null) {
double center = cii.getCenterTuneFreq();
double span = cii.getSpanTuneFreq();
double centering = (freq - center) / (span / 2);
if (Math.abs(bestCentering) > Math.abs(centering)) {
bestCentering = centering;
bestChan = cii.getChannelNumber();
}
} else {
break;
}
}
}
return new ChannelAlignment(bestChan, bestCentering);
}
/**
* Move motors to a remembered reference position for the given frequency.
*
* @param freq The desired frequency (Hz).
* @return True if motors are now at an appropriate reference position.
* @throws InterruptedException If command is cancelled.
*/
private boolean goToRef(double freq) throws InterruptedException {
boolean ok = false;
ChannelAlignment bestChannelAlignment = findChannel(freq);
if (Math.abs(bestChannelAlignment.centeringParameter) <= 1) {
int channel = bestChannelAlignment.iChannel;
if (channel >= 0) {
ChannelInfo chanInfo = getChannelInfo(channel);
if (chanInfo != null) {
double freqTol = 2e6;
ok = chanInfo.goToSavedPosition(freq, freqTol);
} else {
Messages.postError("Channel " + channel + " not present");
}
}
}
return ok;
}
/**
* Tune to a given frequency.
* First finds which channel to use and switches to that channel.
* @param target The target to tune to.
* @param useref If true, use any available reference motor positions.
*/
private TuneResult tune(TuneTarget target, boolean useref)
throws InterruptedException {
double match_dB = Math.log10(getTargetMatch()) * 10;
Messages.postDebug("TuningSummary",
"Tuning to " + target.getFreq_str()
+ " with match < " + Fmt.f(1, match_dB) + " dB"
+ ", rfchan=" + target.getRfchan()
+ ", nucleus=" + target.getNucleus());
ChannelAlignment bestChannelAlignment = findChannel(target.getFreq_hz());
long startTime = System.currentTimeMillis();
boolean tuned = false;
if (Math.abs(bestChannelAlignment.centeringParameter) <= 1) {
int ichan = bestChannelAlignment.iChannel;
m_padAdj = 1; // Standard step damping
int metaTries;
for (metaTries = 0; !tuned && metaTries < 4; metaTries++) {
tuned = tune(ichan, target, useref);
useref = false; // Only go to ref position once!
if (isCancel()) {
Messages.postDebug("TuningSummary", "Tuning ABORTED");
String msg = "Tuning was aborted by the user";
m_tuneStatus = new TuneResult("warning", msg);
break;
}
if (!tuned) {
Messages.postDebug("TuneAlgorithm", "Meta-try
+ (metaTries + 1) + " failed");
}
}
double time = (System.currentTimeMillis() - startTime) / 1000.0;
String try_ies = metaTries > 1 ? " tries" : " try";
Messages.postDebug("TuningSummary", "ProbeTune.tune: " + metaTries
+ try_ies + ", Total time " + Fmt.f(1, time)
+ " s" + NL + " ... Result: "
+ m_tuneStatus.toString("db"));
} else {
Messages.postError("Frequency not in range of any channel: "
+ target.getFreq_str());
String msg = target.getFrequencyName()
+ " is not tunable on this probe";
m_tuneStatus = new TuneResult("warning", msg);
tuned = false;
}
displayTuneStatus();
/*System.err.println("ProbeTune.tune: DONE: " + m_tuneStatus);/*DBG*/
return m_tuneStatus;
//return m_tuneResult;
}
private int dampStep(double calcSteps, MotorInfo motorInfo) {
int limit = motorInfo.degToSteps(18);
int minDamped = motorInfo.degToSteps(1.8);
// TODO: Use SDV values of sensitivities to choose how far we step
// towards the target.
double damping = m_stepDamping * m_padAdj;
if (Math.abs(calcSteps) < limit) {
// If we're closer than this limit - more damping
damping = 1 - (1 - damping) * Math.abs(calcSteps) / limit;
}
int nSteps = (int)Math.round(damping * calcSteps);
if (Math.abs(calcSteps) > minDamped && Math.abs(nSteps) < minDamped) {
nSteps = (int)calcSteps; // Round towards 0
}
int absNSteps = Math.abs(nSteps);
int maxMotion = motorInfo.degToSteps(m_maxDegsPerStep);
if (absNSteps > maxMotion) {
nSteps = nSteps > 0 ? maxMotion : -maxMotion;
} else if (absNSteps < limit) {
// If we're below the limit now - still more damping
// TODO: Combine this with above "< limit" adjustment?
double pad = absNSteps / (double)limit;
nSteps = (int)Math.round(pad * nSteps);
}
if (nSteps == 0 && Math.abs(calcSteps) > 0.5) {
nSteps = (int)Math.copySign(1, calcSteps);
}
Messages.postDebug("DampStep","dampStep: calcSteps="
+ Fmt.f(1, calcSteps) + ", nSteps=" + nSteps);
return nSteps;
}
/**
* Tune to a given frequency on a given tune channel.
* @param channel The tune channel number to use.
* @param target The target to tune to.
* @param useref If true, use any available reference motor positions.
* @return True if we are done tuning.
*/
private boolean tune(int channel, TuneTarget target, boolean useref)
throws InterruptedException {
long time0 = System.currentTimeMillis();
boolean done = false;
double freq = target.getFreq_hz();
boolean isNewChannel = channel != m_channelNumber;
setChannel(channel, 0, true); // TODO: Why is rfchan 0, rather than target.getRfchan()?
ChannelInfo chanInfo = getChannelInfo(channel);
m_nTuneMotors = chanInfo.getNumberOfMotors();
if (m_nTuneMotors < 1) {
// This channel not tunable
String msg = target.getFrequencyName() + " is a fixed-tune nucleus";
m_tuneStatus = new TuneResult("ok", msg);
return true; // Return successful status
}
chanInfo.setTuneStepDistance(Double.NaN);
m_tuneStatus = new TuneResult("failed");
Messages.postDebug("AllTuneAlgorithm", "ProbeTune.tune(chan="
+ channel + ", freq="
+ target.getFreq_str() + ")"
+ " np=" + getNp()
+ ", isNewChannel=" + isNewChannel);
Messages.postDebug("AllTuneAlgorithm", "ProbeTune.tune: "
+ "change channel to " + channel);
if (!chanInfo.isChannelReady()) {
Messages.postError("ProbeTune.tune: channel " + channel
+ " not ready.");
String msg = "tune channel #" + channel + " ("
+ target.getFreq_str() + ") is not ready";
m_tuneStatus = new TuneResult("failed", msg);
return (done = false);
}
Messages.postDebug("TuneAlgorithm",
"Switching to channel " + channel
+ " and setting sweep range");
setChannel(channel, target.getRfchan(), true); // Must change sweep
if (freq < chanInfo.getMinTuneFreq()
|| freq > chanInfo.getMaxTuneFreq())
{
Messages.postError("Requested frequency, "
+ target.getFreq_str() + ", out of range: "
+ Fmt.f(3, chanInfo.getMinFreq() / 1e6) + " to "
+ Fmt.f(3, chanInfo.getMaxFreq() / 1e6));
String msg = target.getFreq_str()
+ " is out of the range of tune channel
+ channel;
m_tuneStatus = new TuneResult("failed", msg);
return (done = false);
}
m_targetFreq = freq;
displayTargetFreq(freq, channel);
//chanInfo.initializeChannel(false);
chanInfo.setSwitchToFreq(freq);
//TuneInfo desiredTune = new TuneInfo(freq, target.getMatch_refl());
TuneInfo ti = chanInfo.getFreshTunePosition(0, false);
if (!chanInfo.isSignalDetected()) {
int rfchan = chanInfo.getRfchan();
if (rfchan > 0) {
Messages.postError("Check RF channel " + rfchan
+ " signal path");
} else {
Messages.postError("Check RF signal path");
}
exit("failed - RF signal is too weak on tune chan#" + channel);
return (done = false);
}
if (!getMotorControl().isConnected()
&& !chanInfo.isMatchBetterThan(target))
{
exit("failed - No communication with tune motors");
return (done = false);
}
// if (ti == null) {
// String msg = "cannot get position of tuning resonance in channel
// + channel;
// m_tuneStatus = new TuneResult("failed", msg);
// return (done = false);
measureTune(chanInfo, 00, false);
if (!Double.isNaN(m_lowerCutoffFreq)
|| !Double.isNaN(m_upperCutoffFreq))
{
// NB: This is NOT a normal case
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "A CUTOFF FREQ IS SET...");
if (!chanInfo.isMatchBetterThan(target)) {
boolean atRef = false;
if (useref) {
atRef = chanInfo.goToSavedPosition(freq,
ti,
m_lowerCutoffFreq,
m_upperCutoffFreq,
200e3,
3);
}
ti = chanInfo.getMeasuredTunePosition();
if (atRef && ti != null && chanInfo.isDipDetected()) {
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "Prepare for tuning
+ "Went to reference position");
} else if (ti != null && chanInfo.isDipDetected()) {
// Set sweep to show from current position to dst
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "Prepare for tuning
+ "Set sweep to show "
+ Fmt.f(3, freq / 1e6));
setSweepToShow(ti.getFrequency(), freq);
} else {
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "Prepare for tuning
+ "No dip detected--Set full sweep");
setFullSweep();
}
}
} else if (ti == null
|| !chanInfo.isDipDetected()
|| Math.abs(ti.getFrequency() - freq) > 3e6
|| Math.abs(ti.getReflection()) > 0.15)
{
// We're far from tuned, or we don't see a dip
boolean atRef = false;
if (useref) {
int tol = 5; // degrees
atRef = chanInfo.goToSavedPosition(freq,
ti,
m_lowerCutoffFreq,
m_upperCutoffFreq,
200e3,
tol);
}
ti = chanInfo.getMeasuredTunePosition();
if (atRef && ti != null && chanInfo.isDipDetected()){
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "Prepare for tuning
+ "Went to reference position");
} else if (ti != null && chanInfo.isDipDetected()) {
// Set sweep to show from current position to dst
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "Prepare for tuning
+ "Set sweep to show "
+ Fmt.f(3, freq / 1e6));
setSweepToShow(ti.getFrequency(), freq);
} else {
// We're in an unknown position
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "Prepare for tuning
+ "Freq is unknown--Set full sweep");
chanInfo.setFullSweep();
}
}
measureTune(chanInfo, 00, true);
// Make sure we see the dip before trying to tune iteratively
if (!chanInfo.searchForDip(target)) {
m_tuneStatus = new TuneResult("failed", "cannot find a dip");
return (done = false);
}
ti = chanInfo.getMeasuredTunePosition();
// Set sweep to show from current position to dst
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "Set sweep to show "
+ Fmt.f(3, freq / 1e6));
setSweepToShow(ti.getFrequency(), freq);
//double reflectTol = Math.sqrt(matchTol);
//if (Math.abs(match) > reflectTol) {
// // Step the match motor to confirm the sign
// chanInfo.measureMatchSign(reflectTol);
for (int i = 0; i < m_nTuneMotors; i++) {
m_nReverses[i] = 0;
}
// Go into the iterative tuning loop
chanInfo.clearStuckMotors();
chanInfo.clearEotMotors();
Messages.postDebug("AllTuneAlgorithm", "ProbeTune.tune: "
+ "Enter top level tuning loop");
int totalItrs = 0;
final int MAX_META_TRIES = 2;
int itrs2;
for (itrs2 = 0; itrs2 < MAX_META_TRIES; ) {
itrs2++; // Increment here so count is ok if we break out
// Check if we lost sweep
if (sweepControl instanceof MtuneControl
&& !((MtuneControl)sweepControl).isSweepOk())
{
done = true;
m_tuneStatus = new TuneResult("failed",
"lost sweep communication");
break;
}
// Check if we lost motor
if (!(motorControl.isConnected())) {
done = true;
m_tuneStatus = new TuneResult("failed",
"lost motor communication");
break;
}
if (itrs2 > 1) {
// After a failure, reset channel sensitivities
//chanInfo.initializeChannel(true);
Messages.postDebug("TuneAlgorithm", "ProbeTune.tune: "
+ "RESETTING SENSITIVITIES to "
+ "system values; adding damping.");
chanInfo.resetSensitivity();
m_padAdj = 0.5; // Increased step damping
}
int itrs;
Messages.postDebug("AllTuneAlgorithm",
"ProbeTune.tune: Enter tuneStep() loop");
// Step towards target until we get there or go past it:
for (itrs = 0; tuneStep(chanInfo, target, itrs); itrs++) {}
Messages.postDebug("TuneAlgorithm",
"ProbeTune.tune: tuneStep() did "
+ itrs + " iterations");
if (chanInfo.getStuckMotorNumber() >= 0) {
int n = chanInfo.getMotorNumber(chanInfo.getStuckMotorNumber());
Messages.postError("MOTOR
+ " DOES NOT SEEM TO BE DOING ANYTHING");
// NB: only fatal if we're on the last try
// NB: itrs2 is incremented at top of this loop
if (itrs2 == MAX_META_TRIES) {
done = true;
String msg = "motor #" + n + " having no effect";
m_tuneStatus = new TuneResult("failed", msg);
}
break;
}
// if (chanInfo.getEotMotorNumber() >= 0) {
// int n = chanInfo.getMotorNumber(chanInfo.getEotMotorNumber());
// if (n == chanInfo.getMatchMotor()) {
// ProbeTune.printErrorMessage(2, "MATCH ");
// m_tuneStatus = "failed - match motor ("+n+") at end of travel";
// } else {
// ProbeTune.printErrorMessage(2, "TUNE ");
// m_tuneStatus = "failed - tune motor ("+n+") at end of travel";
// printlnErrorMessage(2, "MOTOR IS AT THE END OF ITS TRAVEL");
// break;
totalItrs += 1 + itrs;
if (chanInfo.isMatchBetterThan(target)) {
done = true;
break;
} else if (chanInfo.getNumberOfMovableMotors() == 0) {
done = true;
// m_tuneStatus = "failed -- All motors at end of travel?";
// m_allMotorsAtLimits = true;
break;
} else if (chanInfo.getNumberOfMovableMotors() == 1) {
// Either we have only one motor to begin with or one
// motor is at the EOT.
// With one motor, can't both tune and match, so we just
// optimize the one motor. (In this case, we just go for
// the best possible match, or any match better than the spec.
// if we happen to see that.)
Messages.postDebug("TuneAlgorithm",
"Single motor check: itrs=" + itrs
+ ", totalItrs=" + totalItrs
+ ", reverses=" + m_nReverses[0]
+ ", tuneDistance="
+ chanInfo.getTuneStepDistance()
);
if (chanInfo.getTuneStepDistance() < 1) {
done = true;
break;
}
}
}
// Get the match result
double matchPwr = chanInfo.getMatchAtRequestedFreq(target);
double matchDb = 10 * Math.log10(matchPwr);
if (done) {
// Set the status message
boolean ok = matchPwr < target.getCriterion().getAccept_pwr();
if (ok) {
// If we're done and the match is OK, status is "ok", even
// if there were other serious errors.
m_tuneStatus = new TuneResult("ok");
+ "call saveCurrentTunePosition");/*DBG*/
Thread.sleep(100); /*TRACK*/
/**
* Do one iteration of stepping towards the desired tune point.
* May (or may not) move all the motors that affect the specified
* channel.
* @return True if tuning is still in progress (more to do).
* Returns false if tuning is done (may have failed).
*/
private boolean tuneStep(ChannelInfo chanInfo, TuneTarget target, int itr)
throws InterruptedException {
double freq = target.getFreq_hz();
boolean motion = false;
if (isCancel()) {
return motion;
}
Messages.postDebug("AllTuneAlgorithm", "ProbeTune.tuneStep() starting");
// Go through all the motors
for (int cmi = 0; cmi < chanInfo.getNumberOfMotors(); cmi++) {
MotorInfo mInfo = chanInfo.getMotorInfo(cmi);
boolean isMatchMotor = chanInfo.isMatchMotor(cmi);
// Measure current position
ReflectionData data = sweepControl.getData(chanInfo, 00, freq);
if (data == null) {
break;// TODO: Need failure message?
}
// Quit right now if we're good enough
if (chanInfo.isMatchBetterThan(target)) {
Messages.postDebug("TuningAlgorithm",
"ProbeTune.tuneStep: done -- match good");
return false;
}
setMeasuredTune(chanInfo, data);
TuneInfo tuneInfo = chanInfo.getMeasuredTunePosition();
double dipRefl = tuneInfo.getReflection();
//Special check to take care of cutoff frequencies. This will
// force the motor to go back to a specific reference location and
// start again if somehow the dip is dropped outside the cutoffs
if ( !Double.isNaN(m_upperCutoffFreq) ) {
// Expanded the tolerence from 25kHz to 125Hz. This
// will cause the motor easier to detect a
// close-to-cutoff situation, thus move out more
// often. Although it might seems to have negative
// effect of resetting the start position more often,
// the second condition of current reflection must
// larger than 3 times the target reflection will
// provide some safety pad to avoid too often move
// back. In addition this expansion may take care of
// not enough resolution problem when the dip gets
// close to the cutoff.
double targetRefl = target.getCriterion().getTarget_refl();
if (((m_upperCutoffFreq - tuneInfo.getFrequency()) < 125e3)
&& (tuneInfo.getReflection() > (targetRefl * 3)) )
{
chanInfo.goToSavedPosition(freq,
tuneInfo,
m_lowerCutoffFreq,
m_upperCutoffFreq,
200e3, 1, false);
Messages.postDebug("TuneAlgorithm",
"ProbeTune.tuneStep: "
+ "moved to reference position");
return true;
}
}
if (!chanInfo.isDipDetected()) {
Messages.postDebug("TuneAlgorithm", "Lost the dip");
if (!chanInfo.retrieveDip()) {
Messages.postDebug("TuneAlgorithm",
"Failed to retrieve dip");
return false; // quit
}
}
// Calculate steps to reach the target
double[] steps = chanInfo.calcStepsToTune(target.getFreq_hz());
if (steps == null) {
Messages.postError("ProbeTune.tuneStep: step calculation failed"
+ " - reseting sensitivities to sys values");
chanInfo.resetSensitivity();
return true; // Keep going
} else {
Messages.postDebug("AllTuneAlgorithm", "cmi=" + cmi
+ ", steps="
+ Fmt.f(2, steps, false, false));
}
// If all (double)steps are zero, either we are already there
// or all the motors are at their limits.
boolean allStepsZero = true;
for (int i = 0; i < steps.length; i++) {
if (steps[i] != 0) {
allStepsZero = false;
break;
}
}
if (allStepsZero) {
m_tuneStatus.setNote("as close as we can get");
return false;
}
// See if we're asking for the impossible (motor past EOT)
chanInfo.setAtLimit(cmi, mInfo.isAtLimit(steps[cmi]));
if (chanInfo.isAtLimit(cmi)) {
Messages.postDebug("TuneAlgorithm",
"Motor " + chanInfo.getMotorNumber(cmi)
+ " is at end of travel");
// NB: We may be able to get there with just the other motor
if (chanInfo.getNumberOfMovableMotors() == 0) {
// It's hopeless -- all motors at limits of travel
Messages.postWarning("All tuning motors at end of travel");
// Don't add this message: already have 1 or 2 EOT messages
//m_tuneStatus += " -- all motors at limits of travel";
return false; // We're done
}
}
// If another motor has to go much farther, skip this one.
//int padMatch = Math.min(5, Math.max(2, itr / 2));
int padMatch = 10;
double targetRefl = getTargetReflection();
double maxStep = getMaxAbs(steps);
//int matchMotor = chanInfo.getMatchMotorChannelIndex();
//double matchStep = matchMotor >= 0 ? steps[matchMotor] : 0;
boolean skipMatch = Math.abs(dipRefl) < targetRefl / padMatch
&& chanInfo.getNumberOfMovableMotors() > 1;
//&& Math.abs(matchStep) < maxStep;
if (skipMatch && !isMatchMotor) {
// Recalculate tune and match steps based on fixed match motor
steps[chanInfo.getMatchMotorChannelIndex()] = 0; // TODO: ???
steps[cmi] = chanInfo.calcSingleMotorStepsToTune(cmi,
target.getFreq_hz());
}
double thisStep = Math.abs(steps[cmi]);
boolean shortDist = (maxStep / thisStep > STEP_RATIO
&& chanInfo.getNumberOfMovableMotors() > 1);
if (Math.round(thisStep) == 0) {
Messages.postDebug("TuneAlgorithm", "ProbeTune.tuneStep: "
+ "Skip motor "
+ chanInfo.getMotorNumber(cmi)
+ ": step is 0");
if (m_nTuneMotors < 2) {
// We must be done.
Messages.postDebug("TuneAlgorithm", "ProbeTune.tuneStep: "
+ "tuneStep rtn false: "
+ "Zero step with single motor");
return false;
}
} else if (shortDist && (isMatchMotor || !skipMatch)) {
Messages.postDebug("TuneAlgorithm", "ProbeTune.tuneStep: "
+ "Skip motor "
+ chanInfo.getMotorNumber(cmi)
+ ": other motor has much farther to go: "
+ Math.round(maxStep) + "/"
+ Math.round(thisStep));
//} else if (unimptStep) {
// Messages.postDebug("TuneAlgorithm", "Skip motor " + cmi
// + ": other step is way big: " + maxStep);
} else if (skipMatch && isMatchMotor) {
Messages.postDebug("TuneAlgorithm", "ProbeTune.tuneStep: "
+ "Skip motor "
+ chanInfo.getMotorNumber(cmi)
+ ": match is OK");
} else if (!chanInfo.isMatchBetterThan(target)) {
// We want to move this motor
// ...unless we have backlash to worry about.
MotorInfo mi = chanInfo.getMotorInfo(cmi);
int nSteps = dampStep(steps[cmi], mi);
Messages.postDebug("AllTuneAlgorithm", "ProbeTune.tuneStep: "
+ "isSameDirection(" + nSteps + ")="
+ mInfo.isSameDirection(nSteps));
if (!mInfo.isSameDirection(nSteps)
&& nSteps != 0
&& (
(m_nReverses[cmi] < MAX_STEP_REVERSES
&& Math.abs(nSteps) > STEP_SLACK)
|| (m_nReverses[cmi] < MIN_STEP_REVERSES // FIXME???
&& Math.abs(nSteps) > STEP_SLACK)
|| (nSteps != 0 && m_nReverses[cmi] == 0)
)
)
{
// We need to back up.
// (Either we're just getting started, or we went too far.)
m_nReverses[cmi]++;
double currentFrequency = tuneInfo.getFrequency();
nSteps = reverseMotor(cmi, chanInfo, nSteps,
currentFrequency, steps[cmi]);
measureTune(chanInfo); // Measure current position
// Recalculate all steps.
steps = chanInfo.calcStepsToTune(target.getFreq_hz());
Messages.postDebug("TuneAlgorithm", "ProbeTune.tuneStep: "
+ "Reversed motor "
+ chanInfo.getMotorNumber(cmi)
+ ": steps="
+ Fmt.f(2, steps, false, false));
if (steps != null) {
nSteps = dampStep(steps[cmi], mi);
}
}
if (mInfo.isSameDirection(nSteps)) {
int maxMotion = mi.degToSteps(m_maxDegsPerStep);
if (Math.abs(nSteps) > maxMotion) {
nSteps = nSteps > 0 ? maxMotion : -maxMotion;
}
// Go towards target
Messages.postDebug("TuneAlgorithm", "ProbeTune.tuneStep: "
+ "Step motor "
+ chanInfo.getMotorNumber(cmi) + " "
+ nSteps + " towards target.");
motion = true;
chanInfo.step(cmi, nSteps);
} else {
// This should never happen
Messages.postDebug("TuneAlgorithm",
"Could not take up backlash in motor "
+ chanInfo.getMotorNumber(cmi));
}
}
}
if (chanInfo.getStuckMotorNumber() >= 0) {
motion = false;
}
Messages.postDebug("AllTuneAlgorithm", "ProbeTune.tuneStep: "
+ "returning from this tuning step with done="
+ !motion);
return motion;
}
/**
* Get ready to reverse a motor by taking up the backlash.
* If the distance is short, back up and approach again from the
* same direction.
* If the distance is far, just take up the backlash in the
* requested (new) direction.
* @param cmi Which motor to turn.
* @param chanInfo Which channel to measure.
* @param reqSteps Where we have requested to go.
* @param currentFrequency The current dip position (Hz).
* @param estSteps How far we think it is to the target.
* @return A new estimate of "reqSteps".
*/
private int reverseMotor(int cmi, ChannelInfo chanInfo, int reqSteps,
double currentFrequency, double estSteps)
throws InterruptedException {
Messages.postDebug("ReverseMotor",
"reverseMotor: reqSteps=" + reqSteps);
int newEstSteps = (int)Math.round(estSteps);
double backlash = chanInfo.getTotalBacklash(cmi);
// NB: graylash is the uncertainty in the backlash
double graylash = chanInfo.getTotalGraylash(cmi);
int reqDir = sign(reqSteps);
int absNSteps = Math.abs(reqSteps);
if (Math.abs(estSteps) > backlash + graylash) {
// Target is far away - just take up the backlash
int n = (int)Math.round(reqDir * backlash);
Messages.postDebug("TuneAlgorithm", "ProbeTune.reverseMotor: "
+ "Go towards target to take up backlash: step "
+ chanInfo.getMotorNumber(cmi) + " " + n);
chanInfo.step(cmi, n);
// NB: just took up the estimated backlash, dip nominally unmoved
} else {
// Choose direction to back off based on which end of the
// channel we are on.
int dir = chanInfo.getSafeTuneDirection(cmi, currentFrequency);
if (dir * reqDir > 0) {
// Back up and try again from previous direction
// TODO: If we are almost tuned: remember both motor positions,
// back up, and bring this motor slowly up to position without
// moving the other motor until we are almost tuned again.
double backoff = backlash + 2 * graylash + Math.abs(estSteps);
int n = (int)Math.round(reqDir * backoff);
Messages.postDebug("TuneAlgorithm", "ProbeTune.reverseMotor: "
+ "Back off past backlash: step "
+ chanInfo.getMotorNumber(cmi) + " " + n);
chanInfo.step(cmi, n, false);
newEstSteps -= Math.round(reqDir * (backoff - backlash));
// Now take up the backlash going the other way
n = (int)Math.round(-reqDir * (backlash + graylash));
Messages.postDebug("TuneAlgorithm", "ProbeTune.reverseMotor: "
+ "...and take up backlash going fwd: step "
+ chanInfo.getMotorNumber(cmi) + " " + n);
chanInfo.step(cmi, n);
newEstSteps -= Math.round(-reqDir * (graylash));
} else {
// Go forward (in previous direction), then take up
// backlash in requested direction
double backoff = backlash + 2 * graylash - absNSteps;
int n = (int)Math.round(-reqDir * backoff);
Messages.postDebug("TuneAlgorithm", "ProbeTune.reverseMotor: "
+ "Go forward past backlash: step "
+ chanInfo.getMotorNumber(cmi) + " " + n);
chanInfo.step(cmi, n, false);
newEstSteps -= n;
// Now take up the backlash going the requested direction
n = (int)Math.round(reqDir * (backlash + graylash));
Messages.postDebug("TuneAlgorithm", "ProbeTune.reverseMotor: "
+ "...and take up backlash going back: step "
+ chanInfo.getMotorNumber(cmi) + " " + n);
chanInfo.step(cmi, n);
newEstSteps -= Math.round(reqDir * (graylash));
}
}
// Now we should going right direction with all backlash taken up
newEstSteps /= 2; // Damping in new default step
Messages.postDebug("ReverseMotor",
"reverseMotor: returning reqSteps=" + newEstSteps);
return newEstSteps;
}
private int sign(double d) {
return d >= 0 ? 1 : -1;
}
/**
* Measure the current tune position on a given channel.
* The result is stored as the Measured Tune Position, as well
* as being returned to the caller.
* @param ci Which channel to measure.
* @return The TuneInfo for the measured tune position.
* @throws InterruptedException if this command is aborted.
*/
private TuneInfo measureTune(ChannelInfo ci) throws InterruptedException {
return measureTune(ci, 00, true);
}
/**
* Measure the current tune position on this channel.
* @param chan Which channel to measure.
* @param when Clock time in ms of oldest acceptable data. Use 0
* to accept any data, or -1 to accept any data newer than the data
* last read.
* @param display If true, the sweep for the measurement is
* sent to the GUI.
* @return The measured tune position.
* @throws InterruptedException if this command is aborted.
*/
public TuneInfo measureTune(ChannelInfo chan, long when, boolean display)
throws InterruptedException {
if (sweepControl == null) {
return null;
}
ReflectionData data = sweepControl.getData(chan, when);
if (data == null) {
Messages.postError("ProbeTune.measureTune: No sweep data");
return null;
}
TuneInfo tuneInfo = new TuneInfo(data);
chan.setMeasuredTunePosition(tuneInfo);
if (display) {
displayData(data);
}
return tuneInfo;
}
/**
* Save the given measured reflection data in the given channel.
* @param chanInfo The channel the data applies to.
* @param data The data.
*/
public void setMeasuredTune(ChannelInfo chanInfo, ReflectionData data) {
TuneInfo tuneInfo = new TuneInfo(data);
chanInfo.setMeasuredTunePosition(tuneInfo);
displayData(data);
}
//public boolean isMatchOk(ChannelInfo chanInfo, TuneInfo dst) {
// return chanInfo.isMatchBetterThan(dst);
//public boolean isMatchBetterThan(double level,
// ReflectionData data, TuneInfo dst) {
// double freq = dst.getFrequency();
// double targetRefl2 = data.getMatchAtFreq(freq);
// return Math.abs(targetRefl2) <= level;
/**
* Get an ordered list of the available ChannelInfos.
* @return The list, ordered by channel number.
*/
public List<ChannelInfo> getChannelInfos() {
if (m_chanList == null) {
if (m_chanInfos == null) {
m_chanInfos = ChannelInfo.getChanInfos(this, m_modeName);
}
// Make sure these are in order
// NB: Optimized for few gaps in the channel numbering
m_chanList = new ArrayList<ChannelInfo>();
int n = m_chanInfos.size();
for (int i = 0, j = 0; j < n; i++) {
ChannelInfo ci = m_chanInfos.get(i);
if (ci != null) {
m_chanList.add(ci);
j++;
}
}
}
return m_chanList;
}
/**
* Get the ChannelInfo instance for the channel with the given index
* number.
* @param iChan The channel index number (starting at 0).
* @return The ChannelInfo object, or null if the channel is unknown.
* @throws InterruptedException if this command is aborted.
*/
public ChannelInfo getChannelInfo(int iChan) throws InterruptedException {
if (m_chanInfos == null) {
m_chanInfos = ChannelInfo.getChanInfos(this);
}
ChannelInfo chanInfo = m_chanInfos.get(iChan);;
if (chanInfo == null) {
String chanName = "chan#" + iChan;
exit("No system channel info found for \""
+ m_probeName + "/" + chanName + "\"");
}
return chanInfo;
}
/**
* Get the ChannelInfo instance for the channel with the given index
* number.
* If the channel does not exist or has not been initialized, null
* is returned.
* @param channel The channel index number (starting at 0).
* @return The ChannelInfo object, or null.
*/
public ChannelInfo getExistingChannelInfo(int channel) {
ChannelInfo chanInfo = null;
try {
chanInfo = m_chanInfos.get(channel);
} catch (Exception e) {}
return chanInfo;
}
public void displayCalibration() {
sendToGui("showCal");
}
/*
public void sendToGui(String s) {
if (guiWriter != null) {
guiWriter.println(s);
} else {
printlnErrorMessage(4, "guiWriter=" + guiWriter);
}
}
*/
public void sendToGui(String s) {
Messages.postDebug("SendToGui", "To GUI> " + s);
m_listeners.write(s);
}
public void displayHzPerStep(double value, String motor) {
sendToGui("setHzPerStep " + value + " " + motor);
}
public void displayMatchPerStep(double value, String motor) {
sendToGui("setMatchPerStep " + value + " " + motor);
}
public void displayBacklash(double value, String motor) {
sendToGui("setBacklash " + value + " " + motor);
}
public void displayTargetFreq(double value, int chan)
throws InterruptedException {
sendToGui("setTargetFreq " + value + " " + chan);
sendToGui("displayMatchTolerance " + m_criterion.toString());
ChannelInfo ci = getChannelInfo(m_channelNumber);
if (ci != null) {
ci.setTargetFreq(value);
}
}
public void displayLastStep(int gmi, int step) {
sendToGui("setLastStep " + gmi + " " + step);
}
public void displayData(ReflectionData data) {
if (data != null) {
m_reflectionData = data;
String prefix = "setData";
if (data.m_calFailed) {
prefix += " calfailed";
}
String strData = data.getStringData(prefix, " ");
sendToGui(strData);
data.calculateDip();
ReflectionData.Dip[] dips = data.getDips();
boolean gotDip = dips != null && dips.length > 0 && dips[0] != null;
if (gotDip) {
for (int i = 0; i < dips.length && dips[i] != null; i++) {
ReflectionData.Dip dip = dips[i];
double[] arc = dip.getCircleArc();
displayFitCircle(arc[0], arc[1], arc[2], arc[3], arc[4]);
double[] reflect = dip.getReflectionAt(m_targetFreq);
if (reflect != null) {
displayReflectionAt(m_targetFreq,
reflect[0], reflect[1]);
}
double dipReflect = dip.getReflection();
double dipFreq = dip.getFrequency();
displayVertex(dipFreq, dipReflect);
Messages.postDebug("DisplayData",
"dip freq=" + Fmt.f(3, dipFreq/1e6)
+ ", sdv="
+ Fmt.f(4, dip.getFrequencySdv()/1e6)
);
}
} else {
displayVertex(Double.NaN, Double.NaN);
double[] reflect = data.getComplexReflectionAtFreq(m_targetFreq);
if (reflect != null) {
displayReflectionAt(m_targetFreq, reflect[0], reflect[1]);
}
}
//displayVertex(data.getDipFreq(), Math.sqrt(data.getDipValue()));
//displayVertex(m_targetFreq, m_targetMatch);
}
Messages.postDebug("DisplayData", "displayData() done");
}
public void displayFitCircle(double x, double y, double r,
double theta0, double deltaTheta) {
sendToGui("displayFitCircle " + x + " " + y + " " + r
+ " " + theta0 + " " + deltaTheta);
}
private void displayReflectionAt(double freq, double real, double imag) {
sendToGui("displayReflectionAt " + freq + " " + real + " " + imag);
}
public void displayVertex(double x, double y) {
sendToGui("setVertex " + x + " " + y);
}
public void displayRefl(double refl) {
sendToGui("setRefl " + refl);
}
public void displayCommand(String cmd) {
sendToGui("displayCommand " + cmd);
}
public void displayStatus(int status) {
sendToGui("setStatus " + status);
}
public void displayIndexingStatus(int motor) {
int status = STATUS_INDEXING0 + motor;
sendToGui("setStatus " + status);
}
public void displayMLStatus(int status) {
sendToGui("setMLStatus " + status);
}
public void displayBandSwitch(int band) {
sendToGui("displayBandSwitch " + band);
}
public void displayPhase(int quadPhase) {
displayPhase(quadPhase, false);
}
public void displayPhase(int quadPhase, boolean isFixedValue) {
String cmd = "displayPhase " + quadPhase;
if (isFixedValue) {
cmd += " fixed";
}
sendToGui(cmd);
}
public void displayProbeDelay(double delay_ns) {
sendToGui("displayProbeDelay " + delay_ns);
}
public void setReceived(String received) { // TODO: purge this method
sendToGui("setReceived " + received);
}
public MotorControl getMotorControl() {
return motorControl;
}
/**
* @return Returns the sweepControl.
*/
public SweepControl getSweepControl() {
return sweepControl;
}
public MotorInfo getMotorInfo(int gmi) throws InterruptedException {
return motorControl.getMotorInfo(gmi);
}
public double getCenter() {
return sweepControl.getCenter();
//return (m_stopFreq + m_startFreq) / 2;
}
public double getSpan() {
return sweepControl.getSpan();
//return m_stopFreq - m_startFreq;
}
public double getTargetFreq() {
return m_targetFreq;
}
/**
* @return Returns the m_1stSweepTimeout.
*/
public static long get1stSweepTimeout() {
return m_1stSweepTimeout;
}
public void setTargetFreq(double freq) throws InterruptedException {
m_targetFreq = freq;
displayTargetFreq(freq, m_channelNumber);
}
/**
* Get the current channel.
* @return The channel.
*/
public ChannelInfo getChannel() {
return m_chanInfos.get(m_channelNumber);
}
//public void step(int gmi, int nSteps) {
// motorControl.step(gmi, nSteps);
// In general, these "setXxxx" methods should update the GUI on
// what's happening.
/**
* Set channel (and probe) name.
* The name must be of the form "PPPPP/chan#N", where "PPPPP" is
* the probe ID string (any length, the characters "/" and "\" not
* allowed), and "N" is an integer giving the channel number.
* This is the name of the file containing the channel config.
* @param name The probe/channel name.
* @param setSweepFlag If true, set sweep to full range of this channel.
* @throws InterruptedException if this command is aborted.
*/
public void setChannel(String name, boolean setSweepFlag)
throws InterruptedException {
int n = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
if (n <= 0) {
Messages.postError("No probe in string: \"" + name + "\"");
} else {
String probeName = name.substring(0, n);
n = 1 + name.lastIndexOf('
if (n <= 0) {
Messages.postError("No channel number in string: \""
+ name + "\"");
} else {
try {
int iChan = Integer.parseInt(name.substring(n));
// Have a legal probe name and channel
setChannel(probeName, iChan, 0, setSweepFlag);
} catch (NumberFormatException nfe) {
Messages.postError("Illegal channel number: \""
+ name.substring(n) + "\"");
}
}
}
}
/**
* Set the channel number, assuming the current probe.
* @param iChan Which channel to set.
* @param rfchan Which RF channel to use, or 0 for automatic.
* @param setSweepFlag If true, set sweep to full range of this channel.
* @return True if channel is set and initialized.
* @throws InterruptedException if this command is aborted.
*/
public boolean setChannel(int iChan, int rfchan, boolean setSweepFlag)
throws InterruptedException {
return setChannel(m_probeName, iChan, rfchan, setSweepFlag);
}
/**
* Set the channel number and probe name.
* @param probeName The probe name (Vnmr "probe" parameeter.
* @param iChan Channel number, starting at 0.
* @param rfchan Which RF channel to use, or 0 for automatic.
* @param setSweepFlag If true, set sweep to full range of this channel.
* @return True if channel is set and initialized.
* @throws InterruptedException if this command is aborted.
*/
public boolean setChannel(String probeName, int iChan, int rfchan,
boolean setSweepFlag)
throws InterruptedException {
if (probeName == null) {
Messages.postError("ProbeTune.setChannel(): Null probe name");
return false;
}
if (!probeName.equals(m_probeName)) {
// Probe changed - dump old channel info.
m_chanInfos = new TreeMap<Integer,ChannelInfo>();
setProbe(probeName);
ChannelInfo.initializeMotorToChannelMap(this);
}
boolean ok = false;
m_channelNumber = iChan;
ChannelInfo ci = getChannelInfo(iChan);
if (ci != null) {
if (ci.getRfchan() == 0) {
ci.setRfchan(rfchan);
}
displayAllChannelInfo();
if (sweepControl instanceof MtuneControl) {
rfchan = ((MtuneControl)sweepControl).initializeRfChan(ci, rfchan);
ok = ((MtuneControl)sweepControl).initializeForChannel(null, rfchan);
}
ci.setChannel(setSweepFlag);
if (sweepControl instanceof MtuneControl) {
ok = ((MtuneControl)sweepControl).initializeForChannel(ci,
rfchan);
}
if (setSweepFlag) {
ci.setFullSweep();
}
setTargetFreq(ci.getTargetFreq());
}
return ok;
}
public String displayInfo() throws InterruptedException {
// HTML abbrevs:
final String BDL = "<tr><td>"; // Begin Data Left
final String EDL = "</td>"; // End Data Left
final String BDR = "<td>"; // Begin Data Right
final String EDR = "</td></tr>"; // End Data Right
final String EBD = EDL + BDR; // End (left) Begin (right) Data
String title = "ProTune_Information";
String msg = "<html><table>";
//String verDate = getSWVersion() + " " + getSWDate();
String verDate = getSWDate();
msg += BDL + "VnmrJ ProTune Version" + EBD + verDate + EDR;
msg += BDL + "Probe Name" + EBD + getProbeName() + EDR;
msg += BDL + "System Tune Directory" + EBD + getSysTuneDir() + EDR;
msg += BDL + "User Tune Directory" + EBD + getUsrTuneDir() + EDR;
if (getSweepControl() instanceof MtuneControl) {
String cpath = MtuneControl.getCalDir(getProbeName());
msg += BDL + "RF Calibration Directory" + EBD + cpath + EDR;
}
if (getMotorName() != null && !getMotorName().equals(getMotorIpAddr())){
msg += BDL + "Module Hostname / IP" + EBD + getMotorName();
msg += " / " + getMotorIpAddr() + EDR;
} else {
msg += BDL + "Module IP Address" + EBD + getMotorIpAddr() + EDR;
}
if (MotorControl.isPZT() || MotorControl.isOptima()) {
String moduleId = MotorControl.getModuleId();
msg += BDL + "Module Serial Number" + EBD + moduleId + EDR;
String ver = motorControl.getFirmwareVersion();
msg += BDL + "Firmware Version" + EBD + ver + EDR;
if (MotorControl.isOptima()) {
// Module Firmware Version
String mver = motorControl.getModuleFWVersion();
msg += BDL + "Module Firmware Version" + EBD + mver + EDR;
int magField = motorControl.readMagneticField();
msg += BDL + "Magnetic Field" + EBD + magField + " gauss" + EDR;
}
// Get odometer readings
for (int gmi = 0; gmi < MotorControl.MAX_MOTORS; gmi++) {
if (motorControl.isValidMotor(gmi)) {
int odo = motorControl.readOdometer(gmi);
msg += BDL + "Motor " + gmi + " Odometer" + EBD + odo + EDR;
}
}
} else {
boolean gotMotor = false;
for (int gmi = 0; gmi < MotorControl.MAX_MOTORS; gmi++) {
if (motorControl.isValidMotor(gmi)) {
gotMotor = true;
String ver = getMotorInfo(gmi).getFirmwareVersion();
msg += BDL + "Motor " + gmi + " Firmware" + EBD + ver + EDR;
}
}
if (!gotMotor) {
msg += BDL + "Firmware" + EBD + "NO COMMUNICATION" + EDR;
}
}
msg += "</table>";
sendToGui("popup info title " + title + " msg " + msg);
return msg;
};
/**
* Send info about this channel to the GUI.
* @throws InterruptedException if this command is aborted.
*/
public void displayAllChannelInfo() throws InterruptedException {
sendToGui("displayChannel " + m_probeName + "/chan#" + m_channelNumber);
displayAllMotorNames();
// Following command indexes if necessary:
motorControl.readAllMotorPositions(); // Updates position in GUI also
ChannelInfo ci = getChannelInfo(m_channelNumber);
ci.displayAllBacklashes();
ci.displaySensitivities();
}
protected void displayAllMotorNames() throws InterruptedException {
ChannelInfo ci = getChannelInfo(m_channelNumber);
int maxMotors = motorControl.getNumberOfMotors();
for (int gmi = 0; gmi < maxMotors; gmi++) {
String name = "";
boolean emphasized = false;
boolean isUsed = motorControl.isValidMotor(gmi);
int cmi = ci.getChannelMotorNumber(gmi);
if (cmi >= 0) {
// This is either Tune or Match.
emphasized = true;
if (cmi == ci.getMatchMotor()) {
name = "Match";
} else {
// Must be the tune motor
name = "Tune";
}
} else {
int j;
if ((j = ci.getMasterOf(gmi)) >= 0) {
name = "Slave of " + j;
} else {
// Maybe it's a switch
j = 0;
for (int i = 0; j >= 0; i++) {
j = ci.getSwitchMotorNumber(i);
if (j == gmi) {
name = "Switch";
}
}
// ... or maybe it's a manual motor
for (int i = 0; true; i++) {
ChannelInfo.ManualMotor manMtr = ci.getManualMotor(i);
if (manMtr == null) {
break;
}
if (manMtr.getGmi() == gmi) {
name = manMtr.getLabel();
}
}
}
}
sendToGui("displayMotorName " + gmi + " " + name);
sendToGui("displayMotorEmphasis " + gmi + " " + emphasized);
sendToGui("displayMotorPresent " + gmi + " " + isUsed);
}
}
public void saveQuadPhase() {
if (sweepControl != null && sweepControl instanceof MtuneControl) {
((MtuneControl)sweepControl).saveQuadPhase();
}
}
public void setQuadPhase(int quadPhase) {
if (sweepControl != null && sweepControl instanceof MtuneControl) {
((MtuneControl)sweepControl).setQuadPhase(quadPhase,
quadPhase >= 0);
}
}
public void resetChannelPhases() throws InterruptedException {
for (ChannelInfo ci : getChannelInfos()) {
ci.setQuadPhase(null);
}
}
public void setProbeDelay(double delay_ns) throws InterruptedException {
if (m_channelNumber >= 0) {
ChannelInfo chanInfo = getChannelInfo(m_channelNumber);
if (chanInfo != null) {
chanInfo.setProbeDelay(delay_ns);
}
}
}
public void setSweep(double center, double span, int rfchan) {
+ ", " + Fmt.f(3, span / 1e6) + ")");/*DBG*/
/**
* @return Returns the m_sysInitialized.
*/
public boolean isSysInitialized() {
return m_sysInitialized;
}
public void setSysInitialized(boolean b) {
m_sysInitialized = b;
sendToGui("setSysInitialized " + (b ? 1 : 0));
}
public int getNp() {
return sweepControl.getNp();
}
public String getProbeName() {
return m_probeName;
}
public String getUsrProbeName() {
return m_usrProbeName;
}
public String getSysTuneBase() {
String tuneDir = getSysTuneDir();
return new File(tuneDir).getParent();
}
public String getSysTuneDir() {
if (m_sysTuneDir == null) {
m_sysTuneDir = m_vnmrSystemDir + "/tune/" + getProbeName();
}
return m_sysTuneDir;
}
public String getUsrTuneDir() {
return getVnmrUserDir() + "/tune/" + getUsrProbeName();
}
public static String getVnmrSystemDir() {
if (m_vnmrSystemDir == null) {
m_vnmrSystemDir = "/vnmr";
}
return m_vnmrSystemDir;
}
public static String getVnmrUserDir() {
return m_vnmrUserDir;
}
/**
* @return Returns the m_debugLevel.
*/
public int getDebugLevel() {
return m_debugLevel;
}
public static String getSWVersion() {
return VERSION;
}
public static String getSWDate() {
return m_date;
}
public static boolean isSwVersionAtLeast(String reqVersion) {
StringTokenizer tok1 = new StringTokenizer(VERSION, ".");
StringTokenizer tok2 = new StringTokenizer(reqVersion, ".");
boolean rtn = true;
while (tok2.hasMoreTokens()) {
if (!tok1.hasMoreTokens()) {
rtn = false;
break;
} else {
int v1 = Integer.parseInt(tok1.nextToken());
int v2 = Integer.parseInt(tok2.nextToken());
if (v1 < v2) {
rtn = false; // Current version too small
break;
} else if (v1 > v2) {
break; // Current version bigger than required
}
}
}
return rtn;
}
/**
* Set the network host name for the motor module.
* @param name The host name.
*/
public static void setMotorName(String name) {
m_motorHostname = name;
}
/**
* Get the network host name for the motor module.
* @return The host name.
*/
public static String getMotorName() {
return m_motorHostname;
}
/**
* Set the IP address of the motor module.
* @param address The IP address as a "dot string".
*/
public static void setMotorAddress(String address) {
m_motorIpAddr = address;
}
/**
* @return Returns the IP address of the motor module as a "dot string".
*/
public static String getMotorIpAddr() {
return m_motorIpAddr;
}
/**
* @return Returns the m_sweepIpAddr.
*/
public static String getSweepIpAddr() {
m_sweepIpAddr = getProperty("apt.sweepIpAddr", m_sweepIpAddr);
return m_sweepIpAddr;
}
public void setTuneMode(int mode) throws InterruptedException {
if (motorControl != null) motorControl.sendToMotor("tune " + mode);
sendToGui("displayTuneMode " + mode);
}
public void setRawDataMode(boolean b) {
m_rawDataMode = b;
displayRawDataMode(b);
}
public void saveRawDataMode() {
m_savedRawDataMode = m_rawDataMode;
}
public void restoreRawDataMode() {
m_rawDataMode = m_savedRawDataMode;
displayRawDataMode(m_rawDataMode);
}
public boolean isRawDataMode() {
return m_rawDataMode;
}
public void displayMotorBacklash(int gmi) throws InterruptedException {
int backlash = 0;
ChannelInfo ci = getExistingChannelInfo(m_channelNumber);
if (ci != null) {
int cmi = ci.getChannelMotorNumber(gmi);
if (cmi >= 0) {
backlash = ci.getTotalBacklash(cmi);
}
}
if (backlash == 0) {
backlash = (int)Math.round(getMotorInfo(gmi).getBacklash());
}
sendToGui("displayMotorBacklash " + gmi + " " + backlash);
}
private void displayRawDataMode(boolean b) {
int mode = b ? 1 : 0;
sendToGui("displayRawDataMode " + mode);
}
/**
* Put commands in a file to be executed by Vnmr when it gets
* around to looking at the file - maybe at blocksize.
* @param command The command to send.
* @return True if successful.
*/
public boolean queueToVnmr(String command) {
final String COMMANDPATH = getVnmrSystemDir()+"/tmp/ptuneCmds";
Messages.postDebug("VnmrMessages|QueueToVnmr",
"ProbeTune.queueToVnmr: \"" + command + "\"");
// See if there is stuff already queued up
File cmdfile = new File(COMMANDPATH);
if (cmdfile.delete()) {
// There was stuff there, append these commands to previous ones.
if (m_queuedCommands.length() > 0 && !m_queuedCommands.endsWith(NL)) {
m_queuedCommands += NL;
}
m_queuedCommands += command;
} else {
m_queuedCommands = command;
}
// First, write to a temp file
String tmpout = COMMANDPATH + "tmp";
File tmpfile = new File(tmpout);
PrintWriter out = null;
try {
// NB: Only send ASCII characters
FileOutputStream fout = new FileOutputStream(tmpfile);
OutputStreamWriter osw = new OutputStreamWriter(fout, "US-ASCII");
out = new PrintWriter(new BufferedWriter(osw));
out.println(m_queuedCommands);
out.close();
// Now, move the temp file to the right place.
if (!tmpfile.renameTo(cmdfile)) {
cmdfile.delete();
if (!tmpfile.renameTo(cmdfile)) {
Messages.postError("Unable to rename "+tmpfile.getName());
}
}
} catch (IOException ioe) {
Messages.postError("Can't write Vnmr cmds in " + tmpfile.getName()
+ ": " + ioe);
} catch (NullPointerException npe){
Messages.postError("Can't write Vnmr cmds in " + tmpfile.getName()
+ ": " + npe);
} finally {
try { out.close(); } catch (Exception e){};
}
return true;
}
/**
* Send a command to be executed by Vnmr.
* @param command Command to send.
* @return True if command was sent.
*/
static synchronized public boolean sendToVnmr(String command) {
Messages.postDebug("SendToVnmr", "cmd=\"" + command + "\"");
if (!m_isVnmrConnection) {
return false;
}
String reason = "";
String infoPath = getVnmrUserDir() + "/persistence/.talk2j";
if (m_isVnmrConnection && !new File(infoPath).canRead()) {
m_isVnmrConnection = false;
reason = "File \"" + infoPath + "\" is not readable";
}
String execPath = getVnmrSystemDir() + "/bin/send2Vnmr";
if (m_isVnmrConnection && !new File(execPath).canExecute()) {
m_isVnmrConnection = false;
reason = "File \"" + execPath + "\" is not executable";
}
if (m_isVnmrConnection) {
try {
// Only send ASCII characters
command = new String(command.getBytes("US-ASCII"));
} catch (UnsupportedEncodingException e1) {
// Will never happen
}
Messages.postDebug("SendToVnmr", "talk file = \""
+ infoPath + "\", cmd=\"" + command + "\"");
String[] cmdArray = new String[3];
cmdArray[0] = execPath;
cmdArray[1] = infoPath;
cmdArray[2] = command;
Process process = null;
try {
process = Runtime.getRuntime().exec(cmdArray);
int status = 1;
for (int i = 0; i < 100; i++) {
try {
status = process.exitValue();
Messages.postDebug("sendToVnmr",
"send2Vnmr status=" + status
+ ", tries =" + i);
break;
} catch (IllegalThreadStateException itse) {
// process is still running
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// If interrupted, can try again later
process.destroy();
status = 0;
break;
}
}
}
if (status != 0) {
process.destroy();
if (m_isVnmrConnection) {
m_isVnmrConnection = false;
Messages.postDebugWarning("send2Vnmr timed out");
}
}
} catch (IOException e) {
m_isVnmrConnection = false;
reason = "send2Vnmr shell command failed: " + e;
} finally {
closeProcessStreams(process);
}
}
if (!m_isVnmrConnection) {
Messages.postError("Cannot send message to Vnmr: " + reason);
}
return m_isVnmrConnection;
}
/**
* Set the tolerance on the match.
* @param thresh The threshold in units of the
* square of the reflection coefficient.
*/
public void setTargetMatch(double thresh) {
double target_db = 10 * Math.log10(thresh);
m_criterion = new TuneCriterion(target_db);
}
/**
* Get the tolerance on the match.
* @return The threshold in units of the
* square of the reflection coefficient.
*/
public double getTargetMatch() {
return m_criterion.getTarget_pwr();
}
/**
* Get the tolerance on the match.
* @return The threshold in units of dB.
*/
public double getTargetMatch_db() {
return m_criterion.getTarget_db();
}
/**
* Get the tolerance on the reflection amplitude.
* The absolute value of the reflection coefficient.
* @return The absolute value of the biggest tolerated reflection.
*/
public double getTargetReflection() {
return m_criterion.getTarget_refl();
}
public static AptProbeIdClient getProbe() {
return m_probeId;
}
public static boolean useProbeId() {
return m_useProbeId;
}
/**
* See if the system has tune information for the given probe.
* @param name The probe name, normally the Vnmr "probe" parameter.
* @param sysFlag If true, look only in system directory.
* @return True if "/vnmr/tune/[probename]" exists.
*/
public boolean checkProbeName(String name, boolean sysFlag) {
return getProbeFile(name, sysFlag) != null;
}
// public File getProbeObject(String name, String obj, boolean sysFlag) {
// return new File(obj, getProbeFile(name, sysFlag).getPath());
// public static File getProbeUserFile(String name) {
// if (m_useProbeId) {
// return m_probeId.blobLink(name, "tune", false, true);
// return new File(getVnmrUserDir() + "/tune/" + name);
public File getProbeFile(String name, boolean sysFlag) {
// get a link to the probe if Probe ID is enabled
File file = null;
if (m_useProbeId) {
file = m_probeId.blobLink(name, "tune", sysFlag, false);
} else {
// otherwise try user directory first
file = new File(getUsrTuneDir());
if (sysFlag || !file.exists()) {
// No user file (or ignoring it); try system directory
file = new File(getSysTuneDir());
if (!file.exists()) {
return null; // No file; give up
}
}
}
return file;
}
// public BufferedReader getPersistenceReader(String name, boolean sysFlag) {
// // Look for a persistence file
// // Try user directory first
// File file = getProbeFile(name, sysFlag);
// if (file == null) return null;
// BufferedReader in = null;
// try {
// in = new BufferedReader(new FileReader(file));
// } catch (FileNotFoundException fnfe) {
// Messages.postDebug("Persistence",
// "ProbeTune.getPersistenceReader: "
// + "Reading \"" + file.getPath() + "\"");
// return in;
// public PrintWriter getPersistenceWriter(String name) {
// PrintWriter out = null;
// if (m_useProbeId) {
// // this is in the user directory, which may be different than
// // the original source of the data in the system directory and
// // may, in fact, not exist on the probe yet.
// out = m_probeId.getPrintWriter(name, "tune", false, false);
// } else {
// // Can only write to user directory
// String path = getVnmrUserDir() + "/tune/" + name;
// File file = new File(path);
// // Make sure we have a directory to write into
// File dir = file.getParentFile();
// if (!dir.isDirectory()) {
// if (!dir.mkdirs()) {
// return null; // Can't get that directory
// try {
// out = new PrintWriter(new BufferedWriter(new FileWriter(path)));
// Messages.postDebug("Persistence",
// "ProbeTune.getPersistenceWriter: "
// + "writing \"" + path + "\"");
// } catch (IOException ioe) {
// Messages.postError("Cannot write persistence file: \""
// + path + "\": " + ioe);
// return out;
public void writePortNumber(int portNum) {
String path = getVnmrSystemDir() + "/acqqueue/ptunePort";
File file = new File(path);
file.delete();
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
out.println(InetAddress.getLocalHost().getHostName()
+ " " + portNum);
} catch (IOException ioe) {
} finally {
try { out.close(); } catch (Exception e) {}
}
}
class ExecTuneThread extends Thread {
ExecTuneThread() {
}
public void run() {
m_nExecThreadsRunning++;
//String cmd = "";
try {
while (m_commandList.size() > 0) {
displayStatus(STATUS_RUNNING);
try {
//cmd = m_commandList.get(0);
} catch (IndexOutOfBoundsException ioobe) {
Messages.postDebug("Exec",
"Exception getting next command: "
+ ioobe);
}
//setName("exec " + cmd); // Set thread name for the debugger
try {
//Messages.postDebug("Exec", "Call execute for: " + cmd);
execute();
} catch (InterruptedException ie) {
Messages.postWarning("Command aborted");
setCancel(false);
}
if (isCancel()) {
Messages.postWarning("Command was cancelled");
setCancel(false);
}
displayStatus(STATUS_READY);
}
} finally {
displayStatus(STATUS_READY);
m_nExecThreadsRunning
if (m_nExecThreadsRunning < 0) {
Messages.postError("Error: m_nExecThreadsRunning="
+ m_nExecThreadsRunning);
m_nExecThreadsRunning = 0;
}
}
}
}
/**
* Maintain a list of listeners, all waiting for commands from
* different sockets. One listener is created when the run()
* method is called. When a connection is made on the socket,
* CommandListener calls listenerConnected() and another socket is
* created; thus, there is always a socket available for a new
* connection. The host name and port number of the unconnected
* socket are kept in a well known file: /vnmr/acqqueue/ptunePort.
*/
class CommandListenersThread extends Thread implements ListenerManager {
private Semaphore m_lock = new Semaphore(1);
private Executer mm_master;
private ArrayList<CommandListener> mm_listeners
= new ArrayList<CommandListener>();
CommandListenersThread(Executer master) {
mm_master = master;
}
private void lock() {
if (m_useLock) try {
m_lock.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void release() {
if (m_useLock) m_lock.release();
}
/**
* Send a message to all connected listeners.
* @param msg The message to send.
*/
public void write(String msg) {
lock();
int nWritten = 0;
int n = mm_listeners.size();
for (int i = 0; i < n; i++) {
CommandListener listener = mm_listeners.get(i);
if (listener.isConnected()) {
PrintWriter writer = listener.getWriter();
writer.println(msg);
nWritten++;
}
}
release();
if (nWritten == 0) {
if(m_firstTime){
Messages.postDebug("CommandListeners",
"No listeners connected");
m_firstTime= false;
}
}
}
/** used for cleanup in unit test framework */
public synchronized void close() {
ArrayList<CommandListener> listeners = new ArrayList<CommandListener>();
lock();
listeners.addAll(mm_listeners);
release();
for (CommandListener listener : listeners) {
listener.close();
}
}
public void listenerDisconnected(CommandListener listener) {
Messages.postDebug("CommandListeners",
"listenerDisconnected: " + listener);
lock();
mm_listeners.remove(listener);
release();
}
public void listenerConnected(CommandListener listener) {
Messages.postDebug("CommandListeners",
"listenerConnected: " + listener);
makeListener();
}
/**
* Return the number of an unconnected port.
* @param timeout How long to keep trying (ms).
* @return The port number, or 0 on failure.
* @throws InterruptedException If user aborts.
*/
public int getPort(int timeout) throws InterruptedException {
boolean gotit = false;
long t0 = System.currentTimeMillis();
long wait = 0;
while (!gotit && wait < timeout) {
int n = mm_listeners.size();
for (int i = 0; i < n; i++) {
CommandListener listener = mm_listeners.get(i);
if (!listener.isConnected()) {
return listener.getPort();
}
}
Thread.sleep(100);
wait = System.currentTimeMillis() - t0;
}
Messages.postError("getPort: All ports in use!");
return 0;
}
private void makeListener() {
CommandListener listener = new CommandListener(mm_master, this);
int port = listener.getPort();
writePortNumber(port); // Write port number to file
listener.start();
lock();
mm_listeners.add(listener);
release();
}
/**
* Create a listener attached to a client socket at the
* given host and port.
* @param host The host name or IP.
* @param port The port number.
* @throws IOException If there is an I/O error in connecting.
* @throws UnknownHostException If the host cannot be found.
*/
public void connectTo(String host, int port)
throws UnknownHostException, IOException {
CommandListener listener = new CommandListener(mm_master,
host, port, this);
listener.start();
lock();
mm_listeners.add(listener);
release();
}
public void run() {
makeListener();
}
}
/**
* Container class to hold a channel number and its centering parameter.
*/
public class ChannelAlignment {
public double centeringParameter;
public int iChannel;
public ChannelAlignment(int channelNumber, double centering){
centeringParameter = centering;
iChannel = channelNumber;
}
}
}
|
package me.nallar.tickthreading.patcher;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javassist.CannotCompileException;
import javassist.ClassMap;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.BadBytecode;
import javassist.expr.Cast;
import javassist.expr.ConstructorCall;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.Handler;
import javassist.expr.Instanceof;
import javassist.expr.MethodCall;
import javassist.expr.NewArray;
import javassist.expr.NewExpr;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.mappings.MethodDescription;
@SuppressWarnings ("MethodMayBeStatic")
public class Patches {
private final ClassRegistry classRegistry;
public Patches(ClassRegistry classRegistry) {
this.classRegistry = classRegistry;
}
@Patch (
requiredAttributes = "class"
)
public CtClass replace(CtClass clazz, Map<String, String> attributes) throws NotFoundException, CannotCompileException {
Log.info("Replacing " + clazz.getName() + " with " + attributes.get("class"));
String oldName = clazz.getName();
clazz.setName(oldName + "_old");
CtClass newClass = classRegistry.getClass(attributes.get("class"));
newClass.getClassFile2().setSuperclass(null);
newClass.setName(oldName);
return newClass;
}
@Patch
public void replaceMethod(CtMethod method, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode {
String fromClass = attributes.get("fromClass");
String code = attributes.get("code");
if (fromClass != null) {
String fromMethod = attributes.get("fromMethod");
CtMethod replacingMethod = fromMethod == null ?
classRegistry.getClass(fromClass).getDeclaredMethod(method.getName(), method.getParameterTypes())
: MethodDescription.fromString(fromClass, fromMethod).inClass(classRegistry.getClass(fromClass));
Log.info("Replacing " + new MethodDescription(method).getMCPName() + " with " + new MethodDescription(replacingMethod).getMCPName());
ClassMap classMap = new ClassMap();
classMap.put(fromClass, method.getDeclaringClass().getName());
method.setBody(replacingMethod, classMap);
method.getMethodInfo().rebuildStackMap(classRegistry.classes);
method.getMethodInfo().rebuildStackMapForME(classRegistry.classes);
} else if (code != null) {
Log.info("Replacing " + new MethodDescription(method).getMCPName() + " with " + code);
method.setBody(code);
} else {
Log.severe("Missing required attributes for replaceMethod");
}
}
@Patch (
name = "public"
)
public void makePublic(CtMethod ctMethod) {
ctMethod.setModifiers(Modifier.setPublic(ctMethod.getModifiers()));
}
@Patch (
requiredAttributes = "field,class"
)
public void newInitializer(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException {
String field = attributes.get("field");
String clazz = attributes.get("class");
String initialise = "{ " + field + " = new " + clazz + "(); }";
// Return value ignored - just used to cause a NotFoundException if the field doesn't exist.
ctClass.getDeclaredField(field);
for (CtConstructor ctConstructor : ctClass.getConstructors()) {
ctConstructor.insertAfter(initialise);
}
classRegistry.add(ctClass, clazz);
}
@Patch (
requiredAttributes = "field,class"
)
public void newField(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException {
String field = attributes.get("field");
String clazz = attributes.get("class");
String initialise = attributes.get("code");
if (initialise == null) {
initialise = "new " + clazz + "();";
}
CtClass newType = classRegistry.getClass(clazz);
CtField ctField = new CtField(newType, field, ctClass);
if (attributes.get("static") != null) {
ctField.setModifiers(ctField.getModifiers() | Modifier.STATIC | Modifier.PUBLIC);
}
CtField.Initializer initializer = CtField.Initializer.byExpr(initialise);
ctClass.addField(ctField, initializer);
classRegistry.add(ctClass, clazz);
}
@Patch (
requiredAttributes = "code"
)
public void insertBefore(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException {
String field = attributes.get("field");
String code = attributes.get("code");
if (field != null) {
code = code.replace("$field", field);
}
ctBehavior.insertBefore(code);
}
@Patch (
requiredAttributes = "code"
)
public void insertAfter(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException {
String field = attributes.get("field");
String code = attributes.get("code");
if (field != null) {
code = code.replace("$field", field);
}
ctBehavior.insertAfter(code);
}
@Patch (
requiredAttributes = "field"
)
public void lock(CtMethod ctMethod, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException {
String field = attributes.get("field");
CtClass ctClass = ctMethod.getDeclaringClass();
CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null);
ctMethod.setName(ctMethod.getName() + "_nolock");
replacement.setBody("{ this." + field + ".lock(); try { return $proceed($$); } finally { this." + field + ".unlock(); } }", "this", ctMethod.getName());
ctClass.addMethod(replacement);
}
@Patch
public void synchronize(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException {
String field = attributes.get("field");
if (field == null) {
int currentModifiers = ctMethod.getModifiers();
if (Modifier.isSynchronized(currentModifiers)) {
Log.warning("Method: " + ctMethod.getLongName() + " is already synchronized");
} else {
ctMethod.setModifiers(currentModifiers | Modifier.SYNCHRONIZED);
}
} else {
CtClass ctClass = ctMethod.getDeclaringClass();
CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null);
ctMethod.setName(ctMethod.getName() + "_nosynchronize");
replacement.setBody("synchronized(this." + field + ") { return $proceed($$); }", "this", ctMethod.getName());
ctClass.addMethod(replacement);
}
}
@Patch
public void ignoreExceptions(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException, NotFoundException {
String returnCode = attributes.get("code");
if (returnCode == null) {
returnCode = "return;";
}
ctMethod.addCatch("{ " + returnCode + '}', classRegistry.getClass("java.lang.Exception"));
}
@Patch
public void replaceInstantiations(CtBehavior object, Map<String, String> attributes) {
// TODO: Implement this, change some newInitializer patches to use this
}
public void replaceInstantiationsImplementation(CtBehavior ctBehavior, final Map<String, List<String>> replacementClasses) throws CannotCompileException {
// TODO: Learn to use ASM, javassist isn't nice for some things. :(
final Map<Integer, String> newExprType = new HashMap<Integer, String>();
ctBehavior.instrument(new ExprEditor() {
NewExpr lastNewExpr;
int newPos = 0;
@Override
public void edit(NewExpr e) {
lastNewExpr = null;
newPos++;
if (replacementClasses.containsKey(e.getClassName())) {
lastNewExpr = e;
}
}
@Override
public void edit(FieldAccess e) {
NewExpr myLastNewExpr = lastNewExpr;
lastNewExpr = null;
if (myLastNewExpr != null) {
Log.fine('(' + myLastNewExpr.getSignature() + ") " + myLastNewExpr.getClassName() + " at " + myLastNewExpr.getFileName() + ':' + myLastNewExpr.getLineNumber() + ':' + newPos);
newExprType.put(newPos, classSignatureToName(e.getSignature()));
}
}
@Override
public void edit(MethodCall e) {
lastNewExpr = null;
}
@Override
public void edit(NewArray e) {
lastNewExpr = null;
}
@Override
public void edit(Cast e) {
lastNewExpr = null;
}
@Override
public void edit(Instanceof e) {
lastNewExpr = null;
}
@Override
public void edit(Handler e) {
lastNewExpr = null;
}
@Override
public void edit(ConstructorCall e) {
lastNewExpr = null;
}
});
ctBehavior.instrument(new ExprEditor() {
int newPos = 0;
@Override
public void edit(NewExpr e) throws CannotCompileException {
newPos++;
try {
Log.fine(e.getFileName() + ':' + e.getLineNumber() + ", pos: " + newPos);
if (newExprType.containsKey(newPos)) {
String replacementType = null, assignedType = newExprType.get(newPos);
Log.fine(assignedType + " at " + e.getFileName() + ':' + e.getLineNumber());
Class<?> assignTo = Class.forName(assignedType);
for (String replacementClass : replacementClasses.get(e.getClassName())) {
if (assignTo.isAssignableFrom(Class.forName(replacementClass))) {
replacementType = replacementClass;
break;
}
}
if (replacementType == null) {
return;
}
String block = "{$_=new " + replacementType + "($$);}";
Log.fine("Replaced with " + block + ", " + replacementType.length() + ':' + assignedType.length());
e.replace(block);
}
} catch (ClassNotFoundException el) {
Log.severe("Could not replace instantiation, class not found.", el);
}
}
});
}
private static String classSignatureToName(String signature) {
//noinspection HardcodedFileSeparator
return signature.substring(1, signature.length() - 1).replace("/", ".");
}
}
|
import java.net.SocketPermission;
import java.util.Scanner;
public class PawnRace {
public static void main(String[] args) {
boolean isHumanPlayer1 = args[0].equals("H");
boolean isHumanPlayer2 = args[1].equals("H");
char whiteGap = args[2].charAt(0);
char blackGap = args[3].charAt(0);
Board board = new Board(whiteGap, blackGap);
Game game = new Game(board);
Player p1 = new Player(board, game, Color.WHITE, isHumanPlayer1);
Player p2 = new Player(board, game, Color.BLACK, isHumanPlayer2);
int playerTurn = 1;
Scanner input = new Scanner(System.in);
String moveSAN;
Move move;
board.display();
while(!game.isFinished()) {
if(playerTurn == 1) {
if(isHumanPlayer1) {
do {
System.out.println("Play your move! ");
moveSAN = input.next();
}while(!NotationUtil.validStringMove(moveSAN.toLowerCase(), Color.WHITE, board));
moveSAN = NotationUtil.toStandardNotation(moveSAN, Color.WHITE, board);
move = game.parseMove(moveSAN);
game.applyMove(move);
} else {
p1.makeMove();
}
playerTurn = 2;
} else {
if(isHumanPlayer2) {
do {
System.out.println("Play your move! ");
moveSAN = input.next();
} while(!NotationUtil.validStringMove(moveSAN.toLowerCase(), Color.BLACK, board));
moveSAN = NotationUtil.toStandardNotation(moveSAN, Color.BLACK, board);
move = game.parseMove(moveSAN);
game.applyMove(move);
} else {
p2.makeMove();
}
playerTurn = 1;
}
board.display();
}
Color winner = game.getGameResult();
System.out.println(GameUtil.gameResults(winner));
}
}
|
package org.perl6.rakudo;
import org.perl6.nqp.tools.EvalServer;
public class RakudoEvalServer extends EvalServer {
private String appname = null;
public String run(String code) throws Exception {
return super.run(appname, code);
}
public String run(String[] argv) throws Exception {
return super.run(appname, argv);
}
$P6_INSTALL_PREFIX/languages/perl6/runtime/*
*/
public RakudoEvalServer() {
String[] cps = System.getProperty("java.class.path").split("[;:]");
for(String cfile : cps) {
if(cfile.endsWith("perl6.jar")) {
appname = cfile;
break;
}
}
if(appname == null) {
throw new RuntimeException("CLASSPATH not set properly, couldn't find perl6.jar");
}
System.setProperty("perl6.prefix", appname.substring(0, appname.indexOf("/languages")));
System.setProperty("perl6.execname", "RakudoEvalServer");
}
}
|
package com.jme3.app;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial.CullHint;
import com.jme3.scene.shape.Quad;
/**
* Displays stats in SimpleApplication's GUI node or
* using the node and font parameters provided.
*
* @author Paul Speed
*/
public class StatsAppState extends AbstractAppState {
private Application app;
protected StatsView statsView;
protected boolean showSettings = true;
private boolean showFps = true;
private boolean showStats = true;
private boolean darkenBehind = true;
protected Node guiNode;
protected float secondCounter = 0.0f;
protected int frameCounter = 0;
protected BitmapText fpsText;
protected BitmapFont guiFont;
protected Geometry darkenFps;
protected Geometry darkenStats;
public StatsAppState() {
}
public StatsAppState( Node guiNode, BitmapFont guiFont ) {
this.guiNode = guiNode;
this.guiFont = guiFont;
}
/**
* Called by SimpleApplication to provide an early font
* so that the fpsText can be created before init. This
* is because several applications expect to directly access
* fpsText... unfortunately.
*/
void setFont( BitmapFont guiFont ) {
this.guiFont = guiFont;
this.fpsText = new BitmapText(guiFont, false);
}
public BitmapText getFpsText() {
return fpsText;
}
public StatsView getStatsView() {
return statsView;
}
public float getSecondCounter() {
return secondCounter;
}
public void toggleStats() {
setDisplayFps( !showFps );
setDisplayStatView( !showStats );
}
public void setDisplayFps(boolean show) {
showFps = show;
if (fpsText != null) {
fpsText.setCullHint(show ? CullHint.Never : CullHint.Always);
if (darkenFps != null) {
darkenFps.setCullHint(showFps && darkenBehind ? CullHint.Never : CullHint.Always);
}
}
}
public void setDisplayStatView(boolean show) {
showStats = show;
if (statsView != null ) {
statsView.setEnabled(show);
statsView.setCullHint(show ? CullHint.Never : CullHint.Always);
if (darkenStats != null) {
darkenStats.setCullHint(showStats && darkenBehind ? CullHint.Never : CullHint.Always);
}
}
}
public void setDarkenBehind(boolean darkenBehind) {
this.darkenBehind = darkenBehind;
setEnabled(isEnabled());
}
public boolean isDarkenBehind() {
return darkenBehind;
}
@Override
public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app);
this.app = app;
if (app instanceof SimpleApplication) {
SimpleApplication simpleApp = (SimpleApplication)app;
if (guiNode == null) {
guiNode = simpleApp.guiNode;
}
if (guiFont == null ) {
guiFont = simpleApp.guiFont;
}
}
if (guiNode == null) {
throw new RuntimeException( "No guiNode specific and cannot be automatically determined." );
}
if (guiFont == null) {
guiFont = app.getAssetManager().loadFont("Interface/Fonts/Default.fnt");
}
loadFpsText();
loadStatsView();
loadDarken();
}
/**
* Attaches FPS statistics to guiNode and displays it on the screen.
*
*/
public void loadFpsText() {
if (fpsText == null) {
fpsText = new BitmapText(guiFont, false);
}
fpsText.setLocalTranslation(0, fpsText.getLineHeight(), 0);
fpsText.setText("Frames per second");
fpsText.setCullHint(showFps ? CullHint.Never : CullHint.Always);
guiNode.attachChild(fpsText);
}
/**
* Attaches Statistics View to guiNode and displays it on the screen
* above FPS statistics line.
*
*/
public void loadStatsView() {
statsView = new StatsView("Statistics View",
app.getAssetManager(),
app.getRenderer().getStatistics());
// move it up so it appears above fps text
statsView.setLocalTranslation(0, fpsText.getLineHeight(), 0);
statsView.setEnabled(showStats);
statsView.setCullHint(showStats ? CullHint.Never : CullHint.Always);
guiNode.attachChild(statsView);
}
public void loadDarken() {
Material mat = new Material(app.assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", new ColorRGBA(0,0,0,0.5f));
mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
darkenFps = new Geometry("StatsDarken", new Quad(200, fpsText.getLineHeight()));
darkenFps.setMaterial(mat);
darkenFps.setLocalTranslation(0, 0, -1);
darkenFps.setCullHint(showFps && darkenBehind ? CullHint.Never : CullHint.Always);
guiNode.attachChild(darkenFps);
darkenStats = new Geometry("StatsDarken", new Quad(200, statsView.getHeight()));
darkenStats.setMaterial(mat);
darkenStats.setLocalTranslation(0, fpsText.getHeight(), -1);
darkenStats.setCullHint(showStats && darkenBehind ? CullHint.Never : CullHint.Always);
guiNode.attachChild(darkenStats);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (enabled) {
fpsText.setCullHint(showFps ? CullHint.Never : CullHint.Always);
darkenFps.setCullHint(showFps && darkenBehind ? CullHint.Never : CullHint.Always);
statsView.setEnabled(showStats);
statsView.setCullHint(showStats ? CullHint.Never : CullHint.Always);
darkenStats.setCullHint(showStats && darkenBehind ? CullHint.Never : CullHint.Always);
} else {
fpsText.setCullHint(CullHint.Always);
darkenFps.setCullHint(CullHint.Always);
statsView.setEnabled(false);
statsView.setCullHint(CullHint.Always);
darkenStats.setCullHint(CullHint.Always);
}
}
@Override
public void update(float tpf) {
if (showFps) {
secondCounter += app.getTimer().getTimePerFrame();
frameCounter ++;
if (secondCounter >= 1.0f) {
int fps = (int) (frameCounter / secondCounter);
fpsText.setText("Frames per second: " + fps);
secondCounter = 0.0f;
frameCounter = 0;
}
}
}
@Override
public void cleanup() {
super.cleanup();
guiNode.detachChild(statsView);
guiNode.detachChild(fpsText);
guiNode.detachChild(darkenFps);
guiNode.detachChild(darkenStats);
}
}
|
package dr.app.tracer.analysis;
import dr.inference.trace.MarginalLikelihoodAnalysis;
import jam.framework.AuxilaryFrame;
import jam.framework.DocumentFrame;
import javax.swing.*;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class BayesFactorsFrame extends AuxilaryFrame {
private List<MarginalLikelihoodAnalysis> marginalLikelihoods = new ArrayList<MarginalLikelihoodAnalysis>();
private JPanel contentPanel;
private JComboBox transformCombo;
private BayesFactorsModel bayesFactorsModel;
private JTable bayesFactorsTable;
enum Transform {
LN_BF("ln Bayes Factors"),
LOG10_BF("log10 Bayes Factors"),
BF("Bayes Factors");
Transform(String name) {
this.name = name;
}
public String toString() {
return name;
}
private String name;
}
public BayesFactorsFrame(DocumentFrame frame, String title, String info, boolean hasErrors, boolean isAICM) {
super(frame);
setTitle(title);
bayesFactorsModel = new BayesFactorsModel(hasErrors, isAICM);
bayesFactorsTable = new JTable(bayesFactorsModel);
JScrollPane scrollPane1 = new JScrollPane(bayesFactorsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
contentPanel = new JPanel(new BorderLayout(0, 0));
contentPanel.setOpaque(false);
contentPanel.setBorder(new BorderUIResource.EmptyBorderUIResource(
new java.awt.Insets(0, 0, 6, 0)));
JToolBar toolBar = new JToolBar();
toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
toolBar.setFloatable(false);
transformCombo = new JComboBox(Transform.values());
transformCombo.setFont(UIManager.getFont("SmallSystemFont"));
JLabel label = new JLabel("Show:");
label.setFont(UIManager.getFont("SmallSystemFont"));
label.setLabelFor(transformCombo);
toolBar.add(label);
toolBar.add(transformCombo);
toolBar.add(new JToolBar.Separator(new Dimension(8, 8)));
contentPanel.add(toolBar, BorderLayout.NORTH);
transformCombo.addItemListener(
new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent ev) {
bayesFactorsModel.fireTableDataChanged();
}
}
);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
label = new JLabel(info);
label.setFont(UIManager.getFont("SmallSystemFont"));
panel1.add(label, BorderLayout.NORTH);
panel1.add(scrollPane1, BorderLayout.CENTER);
contentPanel.add(panel1, BorderLayout.CENTER);
label = new JLabel("<html>Marginal likelihood estimated using the method Newton & Raftery <br>" +
"(Newton M, Raftery A: Approximate Bayesian inference with the weighted likelihood bootstrap.<br>" +
"Journal of the Royal Statistical Society, Series B 1994, 56:3-48)<br>" +
"with the modifications proprosed by Suchard et al (2001, <i>MBE</i> <b>18</b>: 1001-1013)</html>");
label.setFont(UIManager.getFont("SmallSystemFont"));
if (isAICM) {
label = new JLabel("<html>Model comparison through AICM, lower values indicate better model fit. <br> " +
"Please cite: Baele, Lemey, Bedford, Rambaut, Suchard and Alekseyenko. Improving the accuracy of demographic" +
" and molecular clock model comparison while accommodating phylogenetic uncertainty. In prep.</html>");
label.setFont(UIManager.getFont("SmallSystemFont"));
}
contentPanel.add(label, BorderLayout.SOUTH);
setContentsPanel(contentPanel);
getSaveAction().setEnabled(false);
getSaveAsAction().setEnabled(false);
getCutAction().setEnabled(false);
getCopyAction().setEnabled(true);
getPasteAction().setEnabled(false);
getDeleteAction().setEnabled(false);
getSelectAllAction().setEnabled(false);
getFindAction().setEnabled(false);
getZoomWindowAction().setEnabled(false);
}
public void addMarginalLikelihood(MarginalLikelihoodAnalysis marginalLikelihood) {
this.marginalLikelihoods.add(marginalLikelihood);
bayesFactorsModel.fireTableStructureChanged();
bayesFactorsTable.repaint();
}
public void initializeComponents() {
setSize(new Dimension(640, 480));
}
public boolean useExportAction() {
return true;
}
public JComponent getExportableComponent() {
return contentPanel;
}
public void doCopy() {
java.awt.datatransfer.Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
java.awt.datatransfer.StringSelection selection =
new java.awt.datatransfer.StringSelection(bayesFactorsModel.toString());
clipboard.setContents(selection, selection);
}
class BayesFactorsModel extends AbstractTableModel {
String[] columnNames = {"Trace", "ln P(data | model)", "S.E."};
boolean isAICM = false;
private DecimalFormat formatter2 = new DecimalFormat("
private int columnCount;
public BayesFactorsModel(boolean hasErrors, boolean isAICM) {
this.columnCount = (hasErrors ? 3 : 2);
this.isAICM = isAICM;
if (isAICM) {
columnNames[1] = "AICM";
}
}
public int getColumnCount() {
return columnCount + marginalLikelihoods.size();
}
public int getRowCount() {
return marginalLikelihoods.size();
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return marginalLikelihoods.get(row).getTraceName();
}
if (col == 1) {
return formatter2.format(marginalLikelihoods.get(row).getLogMarginalLikelihood());
} else if (columnCount > 2 && col == 2) {
return " +/- " + formatter2.format(marginalLikelihoods.get(row).getBootstrappedSE());
} else {
if (col - columnCount != row) {
double lnML1 = marginalLikelihoods.get(row).getLogMarginalLikelihood();
double lnML2 = marginalLikelihoods.get(col - columnCount).getLogMarginalLikelihood();
double lnRatio = lnML1 - lnML2;
if (isAICM) {
lnRatio = lnML2 - lnML1;
}
double value;
switch ((Transform) transformCombo.getSelectedItem()) {
case BF:
value = Math.exp(lnRatio);
break;
case LN_BF:
value = lnRatio;
break;
case LOG10_BF:
value = lnRatio / Math.log(10.0);
break;
default:
throw new IllegalArgumentException("Unknown transform type");
}
return formatter2.format(value);
} else {
return "-";
}
}
}
public String getColumnName(int column) {
if (column < columnCount) {
return columnNames[column];
}
return marginalLikelihoods.get(column - columnCount).getTraceName();
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
}
|
package edu.mit.streamjit.impl.compiler;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Table;
import edu.mit.streamjit.api.Filter;
import edu.mit.streamjit.api.Identity;
import edu.mit.streamjit.api.Joiner;
import edu.mit.streamjit.api.OneToOneElement;
import edu.mit.streamjit.api.Rate;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitjoin;
import edu.mit.streamjit.api.Splitter;
import edu.mit.streamjit.api.StatefulFilter;
import edu.mit.streamjit.api.Worker;
import edu.mit.streamjit.impl.blob.Blob;
import edu.mit.streamjit.impl.common.Configuration;
import edu.mit.streamjit.impl.common.ConnectWorkersVisitor;
import edu.mit.streamjit.impl.common.IOInfo;
import edu.mit.streamjit.impl.common.MessageConstraint;
import edu.mit.streamjit.impl.common.Workers;
import edu.mit.streamjit.impl.compiler.insts.ArrayLoadInst;
import edu.mit.streamjit.impl.compiler.insts.ArrayStoreInst;
import edu.mit.streamjit.impl.compiler.insts.BinaryInst;
import edu.mit.streamjit.impl.compiler.insts.CallInst;
import edu.mit.streamjit.impl.compiler.insts.CastInst;
import edu.mit.streamjit.impl.compiler.insts.Instruction;
import edu.mit.streamjit.impl.compiler.insts.JumpInst;
import edu.mit.streamjit.impl.compiler.insts.LoadInst;
import edu.mit.streamjit.impl.compiler.insts.NewArrayInst;
import edu.mit.streamjit.impl.compiler.insts.ReturnInst;
import edu.mit.streamjit.impl.compiler.insts.StoreInst;
import edu.mit.streamjit.impl.compiler.types.MethodType;
import edu.mit.streamjit.impl.compiler.types.RegularType;
import edu.mit.streamjit.impl.interp.Channel;
import edu.mit.streamjit.impl.interp.ChannelFactory;
import edu.mit.streamjit.impl.interp.EmptyChannel;
import edu.mit.streamjit.util.Pair;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 4/24/2013
*/
public final class Compiler {
/**
* A counter used to generate package names unique to a given machine.
*/
private static final AtomicInteger PACKAGE_NUMBER = new AtomicInteger();
private final Set<Worker<?, ?>> workers;
private final Configuration config;
private final int maxNumCores;
private final ImmutableSet<IOInfo> ioinfo;
private final Worker<?, ?> firstWorker, lastWorker;
/**
* Maps a worker to the StreamNode that contains it. Updated by
* StreamNode's constructors. (It would be static in
* StreamNode if statics of inner classes were supported and worked as
* though there was one instance per parent instance.)
*/
private final Map<Worker<?, ?>, StreamNode> streamNodes = new IdentityHashMap<>();
private ImmutableMap<StreamNode, Integer> schedule;
private ImmutableMap<Worker<?, ?>, Integer> initSchedule;
private final String packagePrefix;
private final Module module = new Module();
private final Klass blobKlass;
/**
* The steady-state execution multiplier (the number of executions to run
* per synchronization).
*/
private final int multiplier;
/**
* The work method type, which is void(Object[][], int[], int[], Object[][],
* int[], int[]). (There is no receiver argument.)
*/
private final MethodType workMethodType;
private ImmutableTable<Worker<?, ?>, Worker<?, ?>, BufferData> buffers;
public Compiler(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores) {
this.workers = workers;
this.config = config;
this.maxNumCores = maxNumCores;
this.ioinfo = IOInfo.create(workers);
//We can only have one first and last worker, though they can have
//multiple inputs/outputs.
Worker<?, ?> firstWorker = null, lastWorker = null;
for (IOInfo io : ioinfo)
if (io.isInput())
if (firstWorker == null)
firstWorker = io.downstream();
else
checkArgument(firstWorker == io.downstream(), "two input workers");
else
if (lastWorker == null)
lastWorker = io.upstream();
else
checkArgument(lastWorker == io.upstream(), "two output workers");
assert firstWorker != null : "Can't happen! No first worker?";
assert lastWorker != null : "Can't happen! No last worker?";
this.firstWorker = firstWorker;
this.lastWorker = lastWorker;
//We require that all rates of workers in our set are fixed, except for
//the output rates of the last worker.
for (Worker<?, ?> w : workers) {
for (Rate r : w.getPeekRates())
checkArgument(r.isFixed());
for (Rate r : w.getPopRates())
checkArgument(r.isFixed());
if (w != lastWorker)
for (Rate r : w.getPushRates())
checkArgument(r.isFixed());
}
//We don't support messaging.
List<MessageConstraint> constraints = MessageConstraint.findConstraints(firstWorker);
for (MessageConstraint c : constraints) {
checkArgument(!workers.contains(c.getSender()));
checkArgument(!workers.contains(c.getRecipient()));
}
this.packagePrefix = "compiler"+PACKAGE_NUMBER.getAndIncrement()+".";
this.blobKlass = new Klass(packagePrefix + "Blob",
module.getKlass(Object.class),
Collections.singletonList(module.getKlass(Blob.class)),
module);
this.multiplier = config.getParameter("multiplier", Configuration.IntParameter.class).getValue();
this.workMethodType = module.types().getMethodType(void.class, Object[][].class, int[].class, int[].class, Object[][].class, int[].class, int[].class);
}
public Blob compile() {
for (Worker<?, ?> w : workers)
new StreamNode(w); //adds itself to streamNodes map
fuse();
//Compute per-node steady state execution counts.
for (StreamNode n : ImmutableSet.copyOf(streamNodes.values()))
n.internalSchedule();
externalSchedule();
allocateCores();
declareBuffers();
computeInitSchedule();
//We generate a work method for each worker (which may result in
//duplicates, but is required in general to handle worker fields), then
//generate core code that stitches them together and does any
//required data movement.
for (Worker<?, ?> w : streamNodes.keySet())
makeWorkMethod(w);
//TODO: generate core code
addBlobPlumbing();
blobKlass.dump(new PrintWriter(System.out, true));
return instantiateBlob();
}
/**
* Fuses StreamNodes as directed by the configuration.
*/
private void fuse() {
//TODO: some kind of worklist algorithm that fuses until no more fusion
//possible, to handle state, peeking, or attempts to fuse with more than
//one predecessor.
}
/**
* Allocates StreamNodes to cores as directed by the configuration, possibly
* fissing them (if assigning one node to multiple cores).
* TODO: do we want to permit unequal fiss allocations (e.g., 6 SSEs here,
* 3 SSEs there)?
*/
private void allocateCores() {
//TODO
//Note that any node containing a splitter or joiner can only go on one
//core (as it has to synchronize for its inputs and outputs).
//For now, just put everything on core 0.
for (StreamNode n : ImmutableSet.copyOf(streamNodes.values()))
n.cores.add(0);
}
/**
* Computes buffer capacity and initial sizes, declaring (but not
* arranging for initialization of) the blob class fields pointing to the
* buffers.
*/
private void declareBuffers() {
ImmutableTable.Builder<Worker<?, ?>, Worker<?, ?>, BufferData> builder = ImmutableTable.<Worker<?, ?>, Worker<?, ?>, BufferData>builder();
for (Pair<Worker<?, ?>, Worker<?, ?>> p : allWorkerPairsInBlob())
//Only declare buffers for worker pairs not in the same node. If
//a node needs internal buffering, it handles that itself. (This
//implies that peeking filters cannot be fused upwards, but that's
//a bad idea anyway.)
if (!streamNodes.get(p.first).equals(streamNodes.get(p.second)))
builder.put(p.first, p.second, new BufferData(p.first, p.second));
buffers = builder.build();
}
/**
* Computes the initialization schedule using the scheduler.
*/
private void computeInitSchedule() {
ImmutableList.Builder<Scheduler.Channel<Worker<?, ?>>> builder = ImmutableList.<Scheduler.Channel<Worker<?, ?>>>builder();
for (Pair<Worker<?, ?>, Worker<?, ?>> p : allWorkerPairsInBlob()) {
int i = Workers.getSuccessors(p.first).indexOf(p.second);
int j = Workers.getPredecessors(p.second).indexOf(p.first);
int pushRate = p.first.getPushRates().get(i).max();
int popRate = p.second.getPopRates().get(j).max();
builder.add(new Scheduler.Channel<>(p.first, p.second, pushRate, popRate, buffers.get(p.first, p.second).initialSize));
}
initSchedule = Scheduler.schedule(builder.build());
}
@SuppressWarnings({"unchecked", "rawtypes"})
private ImmutableList<Pair<Worker<?, ?>, Worker<?, ?>>> allWorkerPairsInBlob() {
ImmutableList.Builder<Pair<Worker<?, ?>, Worker<?, ?>>> builder = ImmutableList.<Pair<Worker<?, ?>, Worker<?, ?>>>builder();
for (Worker<?, ?> u : workers)
for (Worker<?, ?> d : Workers.getSuccessors(u))
if (workers.contains(d))
builder.add(new Pair(u, d));
return builder.build();
}
/**
* Make the work method for the given worker. We actually make two methods
* here: first we make a copy with a dummy receiver argument, just to have a
* copy to work with. After remapping every use of that receiver (remapping
* field accesses to the worker's static fields, remapping JIT-hooks to
* their implementations, and remapping utility methods in the worker class
* recursively), we then create the actual work method without the receiver
* argument.
* @param worker
*/
private void makeWorkMethod(Worker<?, ?> worker) {
StreamNode node = streamNodes.get(worker);
int id = Workers.getIdentifier(worker);
int numInputs = getNumInputs(worker);
int numOutputs = getNumOutputs(worker);
Klass workerKlass = module.getKlass(worker.getClass());
Method oldWork = workerKlass.getMethod("work", module.types().getMethodType(void.class, worker.getClass()));
oldWork.resolve();
//Add a dummy receiver argument so we can clone the user's work method.
MethodType rworkMethodType = workMethodType.prependArgument(module.types().getRegularType(workerKlass));
Method newWork = new Method("rwork"+id, rworkMethodType, EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass);
newWork.arguments().get(0).setName("dummyReceiver");
newWork.arguments().get(1).setName("ichannels");
newWork.arguments().get(2).setName("ioffsets");
newWork.arguments().get(3).setName("iincrements");
newWork.arguments().get(4).setName("ochannels");
newWork.arguments().get(5).setName("ooffsets");
newWork.arguments().get(6).setName("oincrements");
Map<Value, Value> vmap = new IdentityHashMap<>();
vmap.put(oldWork.arguments().get(0), newWork.arguments().get(0));
Cloning.cloneMethod(oldWork, newWork, vmap);
BasicBlock entryBlock = new BasicBlock(module, "entry");
newWork.basicBlocks().add(0, entryBlock);
//We make copies of the offset arrays. (int[].clone() returns Object,
//so we have to cast.)
Method clone = Iterables.getOnlyElement(module.getKlass(Object.class).getMethods("clone"));
CallInst ioffsetCloneCall = new CallInst(clone, newWork.arguments().get(2));
entryBlock.instructions().add(ioffsetCloneCall);
CastInst ioffsetCast = new CastInst(module.types().getArrayType(int[].class), ioffsetCloneCall);
entryBlock.instructions().add(ioffsetCast);
LocalVariable ioffsetCopy = new LocalVariable((RegularType)ioffsetCast.getType(), "ioffsetCopy", newWork);
StoreInst popCountInit = new StoreInst(ioffsetCopy, ioffsetCast);
popCountInit.setName("ioffsetInit");
entryBlock.instructions().add(popCountInit);
CallInst ooffsetCloneCall = new CallInst(clone, newWork.arguments().get(5));
entryBlock.instructions().add(ooffsetCloneCall);
CastInst ooffsetCast = new CastInst(module.types().getArrayType(int[].class), ooffsetCloneCall);
entryBlock.instructions().add(ooffsetCast);
LocalVariable ooffsetCopy = new LocalVariable((RegularType)ooffsetCast.getType(), "ooffsetCopy", newWork);
StoreInst pushCountInit = new StoreInst(ooffsetCopy, ooffsetCast);
pushCountInit.setName("ooffsetInit");
entryBlock.instructions().add(pushCountInit);
entryBlock.instructions().add(new JumpInst(newWork.basicBlocks().get(1)));
//Remap stuff in rwork.
for (BasicBlock b : newWork.basicBlocks())
for (Instruction i : ImmutableList.copyOf(b.instructions()))
if (Iterables.contains(i.operands(), newWork.arguments().get(0)))
remapEliminiatingReceiver(i, worker);
//At this point, we've replaced all uses of the dummy receiver argument.
assert newWork.arguments().get(0).uses().isEmpty();
Method trueWork = new Method("work"+id, workMethodType, EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass);
vmap.clear();
vmap.put(newWork.arguments().get(0), null);
for (int i = 1; i < newWork.arguments().size(); ++i)
vmap.put(newWork.arguments().get(i), trueWork.arguments().get(i-1));
Cloning.cloneMethod(newWork, trueWork, vmap);
node.workMethod = trueWork;
newWork.eraseFromParent();
}
private void remapEliminiatingReceiver(Instruction inst, Worker<?, ?> worker) {
BasicBlock block = inst.getParent();
Method rwork = inst.getParent().getParent();
if (inst instanceof CallInst) {
CallInst ci = (CallInst)inst;
Method method = ci.getMethod();
Klass filterKlass = module.getKlass(Filter.class);
Klass splitterKlass = module.getKlass(Splitter.class);
Klass joinerKlass = module.getKlass(Joiner.class);
Method pop1Filter = filterKlass.getMethod("pop", module.types().getMethodType(Object.class, Filter.class));
assert pop1Filter != null;
Method pop1Splitter = splitterKlass.getMethod("pop", module.types().getMethodType(Object.class, Splitter.class));
assert pop1Splitter != null;
Method push1Filter = filterKlass.getMethod("push", module.types().getMethodType(void.class, Filter.class, Object.class));
assert push1Filter != null;
Method push1Joiner = joinerKlass.getMethod("push", module.types().getMethodType(void.class, Joiner.class, Object.class));
assert push1Joiner != null;
Method pop2 = joinerKlass.getMethod("pop", module.types().getMethodType(Object.class, Joiner.class, int.class));
assert pop2 != null;
Method push2 = splitterKlass.getMethod("push", module.types().getMethodType(void.class, Splitter.class, int.class, Object.class));
assert push2 != null;
Method inputs = joinerKlass.getMethod("inputs", module.types().getMethodType(int.class, Joiner.class));
assert inputs != null;
Method outputs = splitterKlass.getMethod("outputs", module.types().getMethodType(int.class, Splitter.class));
assert outputs != null;
Method channelPush = module.getKlass(Channel.class).getMethod("push", module.types().getMethodType(void.class, Channel.class, Object.class));
assert channelPush != null;
if (method.equals(pop1Filter) || method.equals(pop1Splitter) || method.equals(pop2)) {
Value channelNumber = method.equals(pop2) ? ci.getArgument(1) : module.constants().getSmallestIntConstant(0);
Argument ichannels = rwork.getArgument("ichannels");
ArrayLoadInst channel = new ArrayLoadInst(ichannels, channelNumber);
LoadInst ioffsets = new LoadInst(rwork.getLocalVariable("ioffsetCopy"));
ArrayLoadInst offset = new ArrayLoadInst(ioffsets, channelNumber);
ArrayLoadInst item = new ArrayLoadInst(channel, offset);
item.setName("poppedItem");
Argument iincrements = rwork.getArgument("iincrements");
ArrayLoadInst increment = new ArrayLoadInst(iincrements, channelNumber);
BinaryInst newOffset = new BinaryInst(offset, BinaryInst.Operation.ADD, increment);
ArrayStoreInst storeNewOffset = new ArrayStoreInst(ioffsets, channelNumber, newOffset);
inst.replaceInstWithInsts(item, channel, ioffsets, offset, item, increment, newOffset, storeNewOffset);
} else if ((method.equals(push1Filter) || method.equals(push1Joiner)) || method.equals(push2)) {
Value channelNumber = method.equals(push2) ? ci.getArgument(1) : module.constants().getSmallestIntConstant(0);
Value item = method.equals(push2) ? ci.getArgument(2) : ci.getArgument(1);
Argument ochannels = rwork.getArgument("ochannels");
ArrayLoadInst channel = new ArrayLoadInst(ochannels, channelNumber);
LoadInst ooffsets = new LoadInst(rwork.getLocalVariable("ooffsetCopy"));
ArrayLoadInst offset = new ArrayLoadInst(ooffsets, channelNumber);
ArrayStoreInst store = new ArrayStoreInst(channel, offset, item);
Argument oincrements = rwork.getArgument("oincrements");
ArrayLoadInst increment = new ArrayLoadInst(oincrements, channelNumber);
BinaryInst newOffset = new BinaryInst(offset, BinaryInst.Operation.ADD, increment);
ArrayStoreInst storeNewOffset = new ArrayStoreInst(ooffsets, channelNumber, newOffset);
inst.replaceInstWithInsts(store, channel, ooffsets, offset, store, increment, newOffset, storeNewOffset);
} else if (method.equals(outputs)) {
inst.replaceInstWithValue(module.constants().getSmallestIntConstant(getNumOutputs(worker)));
} else if (method.equals(inputs)) {
inst.replaceInstWithValue(module.constants().getSmallestIntConstant(getNumInputs(worker)));
} else
throw new AssertionError(inst);
} else if (inst instanceof LoadInst) {
LoadInst li = (LoadInst)inst;
assert li.getLocation() instanceof Field;
LoadInst replacement = new LoadInst(streamNodes.get(worker).fields.get(worker, (Field)li.getLocation()));
li.replaceInstWithInst(replacement);
} else
throw new AssertionError("Couldn't eliminate reciever: "+inst);
}
private int getNumInputs(Worker<?, ?> w) {
return Workers.getInputChannels(w).size();
}
private int getNumOutputs(Worker<?, ?> w) {
return Workers.getOutputChannels(w).size();
}
/**
* Adds required plumbing code to the blob class, such as the ctor and the
* implementations of the Blob methods.
*/
private void addBlobPlumbing() {
//ctor
Method init = new Method("<init>",
module.types().getMethodType(module.types().getType(blobKlass)),
EnumSet.noneOf(Modifier.class),
blobKlass);
BasicBlock b = new BasicBlock(module);
init.basicBlocks().add(b);
Method objCtor = module.getKlass(Object.class).getMethods("<init>").iterator().next();
b.instructions().add(new CallInst(objCtor));
b.instructions().add(new ReturnInst(module.types().getVoidType()));
//TODO: other Blob interface methods
}
private Blob instantiateBlob() {
ModuleClassLoader mcl = new ModuleClassLoader(module);
try {
Class<?> blobClass = mcl.loadClass(blobKlass.getName());
Constructor<?> ctor = blobClass.getDeclaredConstructor();
ctor.setAccessible(true);
return (Blob)ctor.newInstance();
} catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException ex) {
throw new AssertionError(ex);
}
}
/**
* WorkerData contains worker-specific information.
*/
private static final class WorkerData {
private final Worker<?, ?> worker;
/**
* The method corresponding to this worker's work method. May be null
* if the method hasn't been created yet.
*/
private Method workMethod;
/**
* Maps fields in the worker class to fields in the blob class for this
* particular worker.
*/
private final Map<Field, Field> fields = new IdentityHashMap<>();
/**
* Maps final fields in the worker class to their actual values, for
* inlining or blob initialization purposes.
*/
private final Map<Field, Object> fieldValues = new IdentityHashMap<>();
private Field popCount, pushCount;
private WorkerData(Worker<?, ?> worker) {
this.worker = worker;
}
}
private void externalSchedule() {
ImmutableSet<StreamNode> nodes = ImmutableSet.copyOf(streamNodes.values());
ImmutableList.Builder<Scheduler.Channel<StreamNode>> channels = ImmutableList.<Scheduler.Channel<StreamNode>>builder();
for (StreamNode a : nodes)
for (StreamNode b : nodes)
channels.addAll(a.findChannels(b));
schedule = Scheduler.schedule(channels.build());
System.out.println(schedule);
}
private final class StreamNode {
private final int id;
private final ImmutableSet<Worker<?, ?>> workers;
private final ImmutableSet<IOInfo> ioinfo;
/**
* The number of individual worker executions per steady-state execution
* of the StreamNode.
*/
private ImmutableMap<Worker<?, ?>, Integer> execsPerNodeExec;
/**
* This node's work method. May be null if the method hasn't been
* created yet. TODO: if we put multiplicities inside work methods,
* we'll need one per core. Alternately we could put them outside and
* inline/specialize as a postprocessing step.
*/
private Method workMethod;
/**
* Maps each worker's fields to the corresponding fields in the blob
* class.
*/
private final Table<Worker<?, ?>, Field, Field> fields = HashBasedTable.create();
/**
* Maps each worker's fields to the actual values of those fields.
*/
private final Table<Worker<?, ?>, Field, Object> fieldValues = HashBasedTable.create();
private final List<Integer> cores = new ArrayList<>();
private StreamNode(Worker<?, ?> worker) {
this.id = Workers.getIdentifier(worker);
this.workers = (ImmutableSet<Worker<?, ?>>)ImmutableSet.of(worker);
this.ioinfo = IOInfo.create(workers);
buildWorkerData(worker);
assert !streamNodes.containsKey(worker);
streamNodes.put(worker, this);
}
/**
* Fuses two StreamNodes. They should not yet have been scheduled or
* had work functions constructed.
*/
private StreamNode(StreamNode a, StreamNode b) {
this.id = Math.min(a.id, b.id);
this.workers = ImmutableSet.<Worker<?, ?>>builder().addAll(a.workers).addAll(b.workers).build();
this.ioinfo = IOInfo.create(workers);
this.fields.putAll(a.fields);
this.fields.putAll(b.fields);
this.fieldValues.putAll(a.fieldValues);
this.fieldValues.putAll(b.fieldValues);
for (Worker<?, ?> w : a.workers)
streamNodes.put(w, this);
for (Worker<?, ?> w : b.workers)
streamNodes.put(w, this);
}
/**
* Compute the steady-state multiplicities of each worker in this node
* for each execution of the node.
*/
public void internalSchedule() {
if (workers.size() == 1) {
this.execsPerNodeExec = ImmutableMap.<Worker<?, ?>, Integer>builder().put(workers.iterator().next(), 1).build();
return;
}
//Find all the channels within this StreamNode.
List<Scheduler.Channel<Worker<?, ?>>> channels = new ArrayList<>();
for (Worker<?, ?> w : workers) {
@SuppressWarnings("unchecked")
List<Worker<?, ?>> succs = (List<Worker<?, ?>>)Workers.getSuccessors(w);
for (int i = 0; i < succs.size(); ++i) {
Worker<?, ?> s = succs.get(i);
if (workers.contains(s)) {
int j = Workers.getPredecessors(s).indexOf(w);
assert j != -1;
channels.add(new Scheduler.Channel<>(w, s, w.getPushRates().get(i).max(), s.getPopRates().get(j).max()));
}
}
}
this.execsPerNodeExec = Scheduler.schedule(channels);
}
/**
* Returns a list of scheduler channels from this node to the given
* node, with rates corrected for the internal schedule for each node.
*/
public List<Scheduler.Channel<StreamNode>> findChannels(StreamNode other) {
ImmutableList.Builder<Scheduler.Channel<StreamNode>> retval = ImmutableList.<Scheduler.Channel<StreamNode>>builder();
for (IOInfo info : ioinfo) {
if (info.isOutput() && other.workers.contains(info.downstream())) {
int i = Workers.getSuccessors(info.upstream()).indexOf(info.downstream());
assert i != -1;
int j = Workers.getPredecessors(info.downstream()).indexOf(info.upstream());
assert j != -1;
retval.add(new Scheduler.Channel<>(this, other,
info.upstream().getPushRates().get(i).max() * execsPerNodeExec.get(info.upstream()),
info.downstream().getPopRates().get(j).max() * other.execsPerNodeExec.get(info.downstream())));
}
}
return retval.build();
}
private void buildWorkerData(Worker<?, ?> worker) {
Klass workerKlass = module.getKlass(worker.getClass());
//Build the new fields.
for (Field f : workerKlass.fields()) {
java.lang.reflect.Field rf = f.getBackingField();
Set<Modifier> modifiers = EnumSet.of(Modifier.PRIVATE, Modifier.STATIC);
//We can make the new field final if the original field is final or
//if the worker isn't stateful.
if (f.modifiers().contains(Modifier.FINAL) || !(worker instanceof StatefulFilter))
modifiers.add(Modifier.FINAL);
Field nf = new Field(f.getType().getFieldType(),
"w" + id + "$" + f.getName(),
modifiers,
blobKlass);
fields.put(worker, f, nf);
try {
rf.setAccessible(true);
Object value = rf.get(worker);
fieldValues.put(worker, f, value);
} catch (IllegalAccessException ex) {
//Either setAccessible will succeed or we'll throw a
//SecurityException, so we'll never get here.
throw new AssertionError("Can't happen!", ex);
}
}
}
}
private final class BufferData {
/**
* The field (for intracore buffers) or two fields (for intercore
* buffers) pointing to the buffers. If there are two fields, the first
* is the reader's buffer (which gets filled with initial buffering) and
* the second is the writer's buffer (which is empty).
*/
public final ImmutableList<Field> fields;
/**
* The buffer capacity.
*/
public final int capacity;
/**
* The buffer initial size. This is generally less than the capacity
* for intracore buffers introduced by peeking. Intercore buffers
* always get filled to capacity.
*/
public final int initialSize;
private BufferData(Worker<?, ?> upstream, Worker<?, ?> downstream) {
RegularType objArrayTy = blobKlass.getParent().types().getRegularType(Object[].class);
String fieldName = "buf"+Workers.getIdentifier(upstream)+"_"+Workers.getIdentifier(downstream);
final StreamNode downstreamNode = streamNodes.get(downstream);
//Do we need to synchronize to pass data between these two nodes?
boolean intracore = streamNodes.get(upstream).cores.equals(downstreamNode.cores);
if (intracore)
fields = ImmutableList.of(new Field(objArrayTy, fieldName, EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass));
else
fields = ImmutableList.of(new Field(objArrayTy, fieldName+"a", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass),
new Field(objArrayTy, fieldName+"b", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC), blobKlass));
int chanIdx = Workers.getPredecessors(downstream).indexOf(upstream);
assert chanIdx != -1;
int pop = downstream.getPopRates().get(chanIdx).max(), peek = downstream.getPeekRates().get(chanIdx).max();
int excessPeeks = Math.max(peek - pop, 0);
this.capacity = downstreamNode.execsPerNodeExec.get(downstream) * schedule.get(downstreamNode) * multiplier * pop + excessPeeks;
this.initialSize = intracore ? excessPeeks : capacity;
}
}
public static void main(String[] args) {
OneToOneElement<Integer, Integer> graph = new Splitjoin<>(new RoundrobinSplitter<Integer>(), new RoundrobinJoiner<Integer>(), new Identity<Integer>(), new Identity<Integer>());
ConnectWorkersVisitor cwv = new ConnectWorkersVisitor(new ChannelFactory() {
@Override
public <E> Channel<E> makeChannel(Worker<?, E> upstream, Worker<E, ?> downstream) {
return new EmptyChannel<>();
}
});
graph.visit(cwv);
Set<Worker<?, ?>> workers = Workers.getAllWorkersInGraph(cwv.getSource());
Configuration config = new CompilerBlobFactory().getDefaultConfiguration(workers);
int maxNumCores = 1;
Compiler compiler = new Compiler(workers, config, maxNumCores);
Blob blob = compiler.compile();
blob.getCoreCount();
}
}
|
package eu.seebetter.ini.chips.davis;
import ch.unizh.ini.jaer.chip.retina.DVSTweaks;
import ch.unizh.ini.jaer.config.MuxControlPanel;
import ch.unizh.ini.jaer.config.OutputMap;
import ch.unizh.ini.jaer.config.boards.LatticeLogicConfig;
import ch.unizh.ini.jaer.config.cpld.CPLDByte;
import ch.unizh.ini.jaer.config.cpld.CPLDConfigValue;
import ch.unizh.ini.jaer.config.cpld.CPLDInt;
import ch.unizh.ini.jaer.config.fx2.PortBit;
import ch.unizh.ini.jaer.config.fx2.TriStateablePortBit;
import ch.unizh.ini.jaer.config.onchip.ChipConfigChain;
import ch.unizh.ini.jaer.config.onchip.OnchipConfigBit;
import ch.unizh.ini.jaer.config.onchip.OutputMux;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.border.TitledBorder;
import net.sf.jaer.biasgen.AddressedIPot;
import net.sf.jaer.biasgen.AddressedIPotArray;
import net.sf.jaer.biasgen.Biasgen.HasPreference;
import net.sf.jaer.biasgen.IPot;
import net.sf.jaer.biasgen.Masterbias;
import net.sf.jaer.biasgen.Pot;
import net.sf.jaer.biasgen.PotTweakerUtilities;
import net.sf.jaer.biasgen.VDAC.VPot;
import net.sf.jaer.biasgen.coarsefine.AddressedIPotCF;
import net.sf.jaer.biasgen.coarsefine.ShiftedSourceBiasCF;
import net.sf.jaer.biasgen.coarsefine.ShiftedSourceControlsCF;
import net.sf.jaer.chip.Chip;
import net.sf.jaer.hardwareinterface.HardwareInterfaceException;
import net.sf.jaer.hardwareinterface.usb.cypressfx3libusb.CypressFX3;
import net.sf.jaer.util.HasPropertyTooltips;
import net.sf.jaer.util.ParameterControlPanel;
import net.sf.jaer.util.PropertyTooltipSupport;
/**
* Base class for configuration of Davis cameras
*
* @author tobi
*/
class DavisConfig extends LatticeLogicConfig implements DavisDisplayConfigInterface, DavisTweaks, HasPreference {
protected ShiftedSourceBiasCF ssn, ssp;
protected JPanel configPanel;
protected JTabbedPane configTabbedPane;
// portA
protected PortBit runCpld = new PortBit(chip, "a3", "runCpld",
"(A3) Set high to run CPLD which enables event capture, low to hold logic in reset", true);
protected PortBit runAdc = new PortBit(chip, "c0", "runAdc",
"(C0) High to run ADC. Bound together with adcEnabled.", true);
// portE
/**
* Bias generator power down bit
*/
protected PortBit powerDown = new PortBit(chip, "e2", "powerDown",
"(E2) High to disable master bias and tie biases to default rails", false);
protected PortBit nChipReset = new PortBit(chip, "e3", "nChipReset",
"(E3) Low to reset AER circuits and hold pixels in reset, High to run", true); // shouldn't need to manipulate
// CPLD shift register contents specified here by CPLDInt and CPLDBit
protected CPLDInt exposureControlRegister = new CPLDInt(
chip,
23,
0,
(1<<20)-1,
"exposure",
"global shutter exposure time between reset and readout phases; interpretation depends on whether rolling or global shutter readout is used.",
0);
protected CPLDInt colSettle = new CPLDInt(
chip,
39,
24,
(1<<7)-1,
"colSettle",
"time in 30MHz clock cycles to settle after column select before readout; allows all pixels in column to drive in parallel the row readout lines (like resSettle)",
0);
protected CPLDInt rowSettle = new CPLDInt(
chip,
55,
40,
(1<<6)-1,
"rowSettle",
"time in 30MHz clock cycles for pixel source follower to settle after each pixel's row select before ADC conversion; this is the fastest process of readout. In new logic value must be <64.",
0);
protected CPLDInt resSettle = new CPLDInt(
chip,
71,
56,
(1<<7)-1,
"resSettle",
"time in 30MHz clock cycles to settle after column reset before readout; allows all pixels in column to drive in parallel the row readout lines (like colSettle)",
0);
protected CPLDInt frameDelay = new CPLDInt(chip, 87, 72,(1<<16)-1,"frameDelay",
"time between two frames; scaling of this parameter depends on readout logic used", 0);
/*
* IMU registers, defined in logic IMUStateMachine
* constant IMUInitAddr0 : std_logic_vector(7 downto 0) := "01101011"; -- ADDR: (0x6b) IMU power management register
* and clock selection
* constant IMUInitAddr1 : std_logic_vector(7 downto 0) := "00011010"; -- ADDR: (0x1A) DLPF (digital low pass
* filter)
* constant IMUInitAddr2 : std_logic_vector(7 downto 0) := "00011001"; -- ADDR: (0x19) Sample rate divider
* constant IMUInitAddr3 : std_logic_vector(7 downto 0) := "00011011"; -- ADDR: (0x1B) Gyro Configuration: Full
* Scale Range / Sensitivity
* constant IMUInitAddr4 : std_logic_vector(7 downto 0) := "00011100"; -- ADDR: (0x1C) Accel Configuration: Full
* Scale Range / Sensitivity
*/
protected CPLDByte miscControlBits = new CPLDByte(chip, 95, 88, 255,"miscControlBits",
"Bit0: IMU run (0=stop, 1=run). Bit1: Rolling shutter (0=global shutter, 1=rolling shutter). Bits2-7: unused ",
(byte) 1);
// See Invensense MPU-6100 IMU datasheet RM-MPU-6100A.pdf
protected CPLDByte imu0PowerMgmtClkRegConfig = new CPLDByte(chip, 103, 96, 255, "imu0_PWR_MGMT_1",
"1=Disable sleep, select x axis gyro as clock source", (byte) 1); // PWR_MGMT_1
protected CPLDByte imu1DLPFConfig = new CPLDByte(chip, 111, 104, 255, "imu1_CONFIG",
"1=digital low pass filter DLPF: FS=1kHz, Gyro 188Hz, 1.9ms delay ", (byte) 1); // CONFIG
protected CPLDByte imu2SamplerateDividerConfig = new CPLDByte(chip, 119, 112, 255, "imu2_SMPLRT_DIV",
"0=sample rate divider: 1 Khz sample rate when DLPF is enabled", (byte) 0); // SMPLRT_DIV
protected CPLDByte imu3GyroConfig = new CPLDByte(chip, 127, 120, 255, "imu3_GYRO_CONFIG",
"8=500 deg/s, 65.5 LSB per deg/s ", (byte) 8); // GYRO_CONFIG:
protected CPLDByte imu4AccelConfig = new CPLDByte(chip, 135, 128, 255, "imu4_ACCEL_CONFIG",
"ACCEL_CONFIG: Bits 4:3 code AFS_SEL. 8=4g, 8192 LSB per g", (byte) 8); // ACCEL_CONFIG:
protected CPLDInt nullSettle = new CPLDInt(chip, 151, 136, (1<<5)-1, "nullSettle",
"time to remain in NULL state between columns", 0);
// these pots for DVSTweaks
protected AddressedIPotCF diffOn, diffOff, refr, pr, sf, diff;
// subclasses for controlling aspects of camera
protected DavisConfig.VideoControl videoControl;
protected DavisConfig.ApsReadoutControl apsReadoutControl;
protected DavisConfig.ImuControl imuControl;
protected int aeReaderFifoSize;
protected int aeReaderNumBuffers;
protected int autoShotThreshold; // threshold for triggering a new frame snapshot automatically
// DVSTweasks from DVS128
protected float bandwidth = 1;
protected boolean debugControls = false;
protected float maxFiringRate = 1;
protected float onOffBalance = 1;
protected float threshold = 1;
protected boolean translateRowOnlyEvents;
JPanel userFriendlyControls;
public DavisConfig(Chip chip) {
super(chip);
setName("DavisConfig");
// port bits
addConfigValue(nChipReset);
addConfigValue(powerDown);
addConfigValue(runAdc);
addConfigValue(runCpld);
// cpld shift register stuff
addConfigValue(exposureControlRegister);
addConfigValue(resSettle);
addConfigValue(rowSettle);
addConfigValue(colSettle);
addConfigValue(frameDelay);
addConfigValue(nullSettle);
addConfigValue(miscControlBits);
// imu config values
addConfigValue(imu0PowerMgmtClkRegConfig);
addConfigValue(imu1DLPFConfig);
addConfigValue(imu2SamplerateDividerConfig);
addConfigValue(imu3GyroConfig);
addConfigValue(imu4AccelConfig);
// masterbias
getMasterbias().setKPrimeNFet(55e-3f); // estimated from tox=42A, mu_n=670 cm^2/Vs // TODO fix for UMC18 process
getMasterbias().setMultiplier(4); // =45 correct for dvs320
getMasterbias().setWOverL(4.8f / 2.4f); // masterbias has nfet with w/l=2 at output
getMasterbias().addObserver(this); // changes to masterbias come back to update() here
// shifted sources (not used on SeeBetter10/11)
ssn = new ShiftedSourceBiasCF(this);
ssn.setSex(Pot.Sex.N);
ssn.setName("SSN");
ssn.setTooltipString("n-type shifted source that generates a regulated voltage near ground");
ssn.addObserver(this);
ssn.setAddress(21);
ssp = new ShiftedSourceBiasCF(this);
ssp.setSex(Pot.Sex.P);
ssp.setName("SSP");
ssp.setTooltipString("p-type shifted source that generates a regulated voltage near Vdd");
ssp.addObserver(this);
ssp.setAddress(20);
ssBiases[1] = ssn;
ssBiases[0] = ssp;
setPotArray(new AddressedIPotArray(this));
try {
// private AddressedIPotCF diffOn, diffOff, refr, pr, sf, diff;
diff = addAIPot("DiffBn,n,normal,differencing amp");
diffOn = addAIPot("OnBn,n,normal,DVS brighter threshold");
diffOff = addAIPot("OffBn,n,normal,DVS darker threshold");
addAIPot("ApsCasEpc,p,cascode,cascode between APS und DVS");
addAIPot("DiffCasBnc,n,cascode,differentiator cascode bias");
addAIPot("ApsROSFBn,n,normal,APS readout source follower bias");
addAIPot("LocalBufBn,n,normal,Local buffer bias"); // TODO what's this?
addAIPot("PixInvBn,n,normal,Pixel request inversion static inverter bias");
pr = addAIPot("PrBp,p,normal,Photoreceptor bias current");
sf = addAIPot("PrSFBp,p,normal,Photoreceptor follower bias current (when used in pixel type)");
refr = addAIPot("RefrBp,p,normal,DVS refractory period current");
addAIPot("AEPdBn,n,normal,Request encoder pulldown static current");
addAIPot("LcolTimeoutBn,n,normal,No column request timeout");
addAIPot("AEPuXBp,p,normal,AER column pullup");
addAIPot("AEPuYBp,p,normal,AER row pullup");
addAIPot("IFThrBn,n,normal,Integrate and fire intensity neuron threshold");
addAIPot("IFRefrBn,n,normal,Integrate and fire intensity neuron refractory period bias current");
addAIPot("PadFollBn,n,normal,Follower-pad buffer bias current");
addAIPot("apsOverflowLevel,n,normal,special overflow level bias ");
addAIPot("biasBuffer,n,normal,special buffer bias ");
} catch (Exception e) {
throw new Error(e.toString());
}
// graphicOptions
videoControl = new VideoControl();
videoControl.addObserver(this);
// on-chip configuration chain
chipConfigChain = new DavisChipConfigChain(chip);
chipConfigChain.addObserver(this);
// control of log readout
apsReadoutControl = new ApsReadoutControl();
// imuControl
imuControl = new ImuControl();
setBatchEditOccurring(true);
loadPreferences();
setBatchEditOccurring(false);
try {
sendConfiguration(this);
} catch (HardwareInterfaceException ex) {
Logger.getLogger(DAVIS240BaseCamera.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* Overrides the default to built the custom control panel for configuring
* the output multiplexers and many other chip, board and display controls.
*
* @return a new panel for controlling this chip and board configuration
*/
@Override
public JPanel buildControlPanel() {
// if(displayControlPanel!=null) return displayControlPanel;
configPanel = new JPanel();
configPanel.setLayout(new BorderLayout());
debugControls = chip.getPrefs().getBoolean("debugControls", false);
// add a reset button on top of everything
final Action resetChipAction = new AbstractAction("Reset chip") {
{
putValue(Action.SHORT_DESCRIPTION, "Resets the pixels and the AER logic momentarily");
}
@Override
public void actionPerformed(ActionEvent evt) {
resetChip();
}
};
// add action to display user friendly controls toggled either next to expert controls or in another tab
final Action toggleDebugControlsAction = new AbstractAction("Toggle debug controls") {
{
putValue(Action.SHORT_DESCRIPTION, "Toggles display of user friendly controls next to other tabbed panes for debugging");
}
@Override
public void actionPerformed(ActionEvent evt) {
toggleDebugControls();
}
};
JPanel specialButtons = new JPanel();
specialButtons.setLayout(new BoxLayout(specialButtons, BoxLayout.X_AXIS));
specialButtons.add(new JButton(resetChipAction));
specialButtons.add(new JButton(toggleDebugControlsAction));
configTabbedPane = new JTabbedPane();
setBatchEditOccurring(true); // stop updates on building panel
configPanel.add(specialButtons, BorderLayout.NORTH);
userFriendlyControls = new DavisUserControlPanel(chip);
if (debugControls) {
configPanel.add(userFriendlyControls, BorderLayout.EAST);
} else {
// user friendly control panel
configTabbedPane.add("<html><strong><font color=\"red\">User-Friendly Controls", userFriendlyControls);
}
// graphics
JPanel videoControlPanel = new JPanel();
videoControlPanel.add(new JLabel("<html>Controls display of APS video frame data"));
videoControlPanel.setLayout(new BoxLayout(videoControlPanel, BoxLayout.Y_AXIS));
configTabbedPane.add("Video Control", videoControlPanel);
videoControlPanel.add(new ParameterControlPanel(getVideoControl()));
// biasgen
JPanel combinedBiasShiftedSourcePanel = new JPanel();
videoControlPanel.add(new JLabel("<html>Low-level control of on-chip bias currents and voltages. <p>These are only for experts!"));
combinedBiasShiftedSourcePanel.setLayout(new BoxLayout(combinedBiasShiftedSourcePanel, BoxLayout.Y_AXIS));
combinedBiasShiftedSourcePanel.add(super.buildControlPanel());
combinedBiasShiftedSourcePanel.add(new ShiftedSourceControlsCF(ssn));
combinedBiasShiftedSourcePanel.add(new ShiftedSourceControlsCF(ssp));
configTabbedPane.addTab("Bias Current Control", combinedBiasShiftedSourcePanel);
// muxes
configTabbedPane.addTab("Debug Output MUX control", getChipConfigChain().buildMuxControlPanel());
// aps readout
JPanel apsReadoutPanel = new JPanel();
apsReadoutPanel.add(new JLabel("<html>Low-level control of APS frame readout. <p>Hover over value fields to see explanations. <b>Incorrect settings will result in unusable output."));
apsReadoutPanel.setLayout(new BoxLayout(apsReadoutPanel, BoxLayout.Y_AXIS));
configTabbedPane.add("APS Readout Control", apsReadoutPanel);
apsReadoutPanel.add(new ParameterControlPanel(getApsReadoutControl()));
// IMU control
JPanel imuControlPanel = new JPanel();
imuControlPanel.add(new JLabel("<html>Low-level control of integrated inertial measurement unit."));
imuControlPanel.setLayout(new BoxLayout(imuControlPanel, BoxLayout.Y_AXIS));
configTabbedPane.add("IMU Control", imuControlPanel);
imuControlPanel.add(new ImuControlPanel(this));
// autoexposure
if (chip instanceof DavisBaseCamera) {
JPanel autoExposurePanel = new JPanel();
autoExposurePanel.add(new JLabel("<html>Automatic exposure control.<p>The settings here determine when and by how much the exposure value should be changed. <p> The strategy followed attempts to avoid a sitation <b> where too many pixels are under- or over-exposed. Hover over entry fields to see explanations."));
autoExposurePanel.setLayout(new BoxLayout(autoExposurePanel, BoxLayout.Y_AXIS));
configTabbedPane.add("APS Autoexposure Control", autoExposurePanel);
autoExposurePanel.add(new ParameterControlPanel(((DavisBaseCamera) chip).getAutoExposureController()));
}
// chip config
JPanel chipConfigPanel = getChipConfigChain().getChipConfigPanel();
configTabbedPane.addTab("Chip configuration", chipConfigPanel);
configPanel.add(configTabbedPane, BorderLayout.CENTER);
// only select panel after all added
try {
configTabbedPane.setSelectedIndex(chip.getPrefs().getInt("DavisBaseCamera.bgTabbedPaneSelectedIndex", 0));
} catch (IndexOutOfBoundsException e) {
configTabbedPane.setSelectedIndex(0);
}
// add listener to store last selected tab
configTabbedPane.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
tabbedPaneMouseClicked(evt);
}
});
setBatchEditOccurring(false);
return configPanel;
}
/**
* @return the aeReaderFifoSize
*/
public int getAeReaderFifoSize() {
return aeReaderFifoSize;
}
/**
* @return the aeReaderNumBuffers
*/
public int getAeReaderNumBuffers() {
return aeReaderNumBuffers;
}
public int getAutoShotEventThreshold() {
return autoShotThreshold;
}
public float getBandwidthTweak() {
return bandwidth;
}
public float getBrightness() {
if (getVideoControl() == null) {
return 0;
}
return getVideoControl().getBrightness();
}
public float getContrast() {
if (getVideoControl() == null) {
return 1;
}
return getVideoControl().getContrast();
}
public int getExposureDelayMs() {
int ed = getExposureControlRegister().get() / 1000;
return ed;
}
public int getFrameDelayMs() {
int fd = frameDelay.get() / 1000;
return fd;
}
public float getGamma() {
if (getVideoControl() == null) {
return 1;
}
return getVideoControl().getGamma();
}
public float getMaxFiringRateTweak() {
return maxFiringRate;
}
public float getOnOffBalanceTweak() {
return onOffBalance;
}
public float getThresholdTweak() {
return threshold;
}
public boolean isCaptureEventsEnabled() {
if (nChipReset == null) {
return false; // only to handle initial call before we are fully constructed, when propertyChangeListeners
// are called
}
return nChipReset.isSet();
}
public boolean isCaptureFramesEnabled() {
if (getApsReadoutControl() == null) {
return false;
}
return getApsReadoutControl().isAdcEnabled();
}
public boolean isDisplayEvents() {
if (getVideoControl() == null) {
return false;
}
return getVideoControl().isDisplayEvents();
}
public boolean isDisplayFrames() {
if (getVideoControl() == null) {
return false;
}
return getVideoControl().isDisplayFrames();
}
public boolean isDisplayImu() {
return getImuControl().isDisplayImu();
}
public boolean isImuEnabled() {
return getImuControl().isImuEnabled();
}
public boolean isTranslateRowOnlyEvents() {
return translateRowOnlyEvents;
}
public boolean isUseAutoContrast() {
if (getVideoControl() == null) {
return false;
}
return getVideoControl().isUseAutoContrast();
}
@Override
public void loadPreference() {
super.loadPreference(); // To change body of generated methods, choose Tools | Templates.
setAeReaderFifoSize(getChip().getPrefs().getInt("aeReaderFifoSize", 1 << 15));
setAeReaderNumBuffers(getChip().getPrefs().getInt("aeReaderNumBuffers", 4));
setTranslateRowOnlyEvents(getChip().getPrefs().getBoolean("translateRowOnlyEvents", false));
setCaptureEvents(isCaptureEventsEnabled()); // just to call propertyChangeListener that sets GUI buttons
setDisplayEvents(isDisplayEvents()); // just to call propertyChangeListener that sets GUI buttons
setCaptureFramesEnabled(isCaptureFramesEnabled());
setDisplayFrames(isDisplayFrames()); // calls GUI update listeners
}
/**
* Momentarily puts the pixels and on-chip AER logic in reset and then
* releases the reset.
*
*/
protected void resetChip() {
log.info("resetting AER communication");
nChipReset.set(false);
nChipReset.set(true);
}
/**
* @param aeReaderFifoSize the aeReaderFifoSize to set
*/
public void setAeReaderFifoSize(int aeReaderFifoSize) {
if (aeReaderFifoSize < (1 << 8)) {
aeReaderFifoSize = 1 << 8;
} else if (((aeReaderFifoSize) & (aeReaderFifoSize - 1)) != 0) {
int newval = Integer.highestOneBit(aeReaderFifoSize - 1);
log.warning("tried to set a non-power-of-two value " + aeReaderFifoSize + "; rounding down to nearest power of two which is " + newval);
aeReaderFifoSize = newval;
}
this.aeReaderFifoSize = aeReaderFifoSize;
}
/**
* @param aeReaderNumBuffers the aeReaderNumBuffers to set
*/
public void setAeReaderNumBuffers(int aeReaderNumBuffers) {
this.aeReaderNumBuffers = aeReaderNumBuffers;
}
public void setAutoShotEventThreshold(int threshold) {
this.autoShotThreshold = threshold;
}
/**
* Tweaks bandwidth around nominal value.
*
* @param val -1 to 1 range
*/
public void setBandwidthTweak(float val) {
if (val > 1) {
val = 1;
} else if (val < -1) {
val = -1;
}
float old = bandwidth;
if (old == val) {
return;
}
// log.info("tweak bandwidth by " + val);
bandwidth = val;
final float MAX = 30;
pr.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX));
sf.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX));
chip.getSupport().firePropertyChange(DVSTweaks.BANDWIDTH, old, val);
}
public void setBrightness(float brightness) {
if (getVideoControl() == null) {
return;
}
getVideoControl().setBrightness(brightness);
}
public void setCaptureEvents(boolean selected) {
if (nChipReset == null) {
return;
}
boolean old = nChipReset.isSet();
nChipReset.set(selected);
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_CAPTURE_EVENTS_ENABLED, null, selected); // TODO have to
// set null for
// old value
// because
// nChipReset is
// a bit but it
// is not linked
// to listeners
// like button,
// so when
// preferences
// are loaded
// and new value
// is set, then
// it may be
// that the
// button is not
// updated
}
public void setCaptureFramesEnabled(boolean yes) {
if (getApsReadoutControl() == null) {
return;
}
getApsReadoutControl().setAdcEnabled(yes);
}
public void setContrast(float contrast) {
if (getVideoControl() == null) {
return;
}
getVideoControl().setContrast(contrast);
}
public void setDisplayEvents(boolean displayEvents) {
if (getVideoControl() == null) {
return;
}
getVideoControl().setDisplayEvents(displayEvents);
}
public void setDisplayFrames(boolean displayFrames) {
if (getVideoControl() == null) {
return;
}
getVideoControl().setDisplayFrames(displayFrames);
}
public void setDisplayImu(boolean yes) {
getImuControl().setDisplayImu(yes);
}
public void setExposureDelayMs(int ms) {
int exp = ms * 1000;
getExposureControlRegister().set(exp);
}
public void setFrameDelayMs(int ms) {
int fd = ms * 1000;
frameDelay.set(fd);
}
public void setGamma(float gamma) {
if (getVideoControl() == null) {
return;
}
getVideoControl().setGamma(gamma);
}
public void setImuEnabled(boolean yes) {
getImuControl().setImuEnabled(yes);
}
/**
* Tweaks max firing rate (refractory period), larger is shorter refractory
* period.
*
* @param val -1 to 1 range
*/
public void setMaxFiringRateTweak(float val) {
if (val > 1) {
val = 1;
} else if (val < -1) {
val = -1;
}
float old = maxFiringRate;
if (old == val) {
return;
}
maxFiringRate = val;
final float MAX = 100;
refr.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX));
chip.getSupport().firePropertyChange(DVSTweaks.MAX_FIRING_RATE, old, val);
}
/**
* Tweaks balance of on/off events. Increase for more ON events.
*
* @param val -1 to 1 range.
*/
public void setOnOffBalanceTweak(float val) {
if (val > 1) {
val = 1;
} else if (val < -1) {
val = -1;
}
float old = onOffBalance;
if (old == val) {
return;
}
onOffBalance = val;
final float MAX = 10;
diff.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX));
chip.getSupport().firePropertyChange(DVSTweaks.ON_OFF_BALANCE, old, val);
}
/**
* Tweaks threshold, larger is higher threshold.
*
* @param val -1 to 1 range
*/
public void setThresholdTweak(float val) {
if (val > 1) {
val = 1;
} else if (val < -1) {
val = -1;
}
float old = threshold;
if (old == val) {
return;
}
final float MAX = 10;
threshold = val;
diffOn.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX));
diffOff.changeByRatioFromPreferred(1 / PotTweakerUtilities.getRatioTweak(val, MAX));
chip.getSupport().firePropertyChange(DVSTweaks.THRESHOLD, old, val);
}
/**
* If set, then row-only events are transmitted to raw packets from USB
* interface
*
* @param translateRowOnlyEvents true to translate these parasitic events.
*/
public void setTranslateRowOnlyEvents(boolean translateRowOnlyEvents) {
boolean old = this.translateRowOnlyEvents;
this.translateRowOnlyEvents = translateRowOnlyEvents;
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_TRANSLATE_ROW_ONLY_EVENTS, old, this.translateRowOnlyEvents);
if ((getHardwareInterface() != null) && (getHardwareInterface() instanceof CypressFX3)) {
// Translate Row-only Events is now in the logic.
try {
((CypressFX3) getHardwareInterface()).spiConfigSend(CypressFX3.FPGA_DVS, (short) 6, (translateRowOnlyEvents) ? (0) : (1));
} catch (HardwareInterfaceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setUseAutoContrast(boolean useAutoContrast) {
if (getVideoControl() == null) {
return;
}
getVideoControl().setUseAutoContrast(useAutoContrast);
}
@Override
public void storePreference() {
super.storePreference(); // To change body of generated methods, choose Tools | Templates.
getChip().getPrefs().putInt("aeReaderFifoSize", aeReaderFifoSize);
getChip().getPrefs().putInt("aeReaderNumBuffers", aeReaderNumBuffers);
getChip().getPrefs().putBoolean("translateRowOnlyEvents", translateRowOnlyEvents);
}
protected void tabbedPaneMouseClicked(MouseEvent evt) {
chip.getPrefs().putInt("DavisBaseCamera.bgTabbedPaneSelectedIndex", configTabbedPane.getSelectedIndex());
}
protected void toggleDebugControls() {
if (debugControls) {
configPanel.remove(userFriendlyControls);
} else {
configTabbedPane.remove(userFriendlyControls);
}
debugControls = !debugControls;
chip.getPrefs().putBoolean("debugControls", debugControls);
if (debugControls) {
configPanel.add(userFriendlyControls, BorderLayout.EAST);
} else {
// user friendly control panel
configTabbedPane.add("User-Friendly Controls", userFriendlyControls);
configTabbedPane.setSelectedComponent(userFriendlyControls);
}
}
/**
* The central point for communication with HW from biasgen. All objects in
* SeeBetterConfig are Observables and addConfigValue SeeBetterConfig.this
* as Observer. They then call notifyObservers when their state changes.
* Objects such as ADC store preferences for ADC, and update should update
* the hardware registers accordingly.
*
* @param observable IPot, Scanner, etc
* @param object notifyChange - not used at present
*/
@Override
public synchronized void update(Observable observable, Object object) {
// thread safe to ensure gui cannot
// retrigger this while it is sending
// something
// sends a vendor request depending on type of update
// vendor request is always VR_CONFIG
// value is the type of update
// index is sometimes used for 16 bitmask updates
// bytes are the rest of data
if (isBatchEditOccurring()) {
return;
}
// log.info("update with " + observable);
try {
if ((observable instanceof IPot) || (observable instanceof VPot)) {
// must send all of the onchip shift
// register values to replace shift
// register contents
sendOnChipConfig();
} else if ((observable instanceof OutputMux) || (observable instanceof OnchipConfigBit)) {
sendOnChipConfigChain();
} else if (observable instanceof ShiftedSourceBiasCF) {
sendOnChipConfig();
} else if (observable instanceof ChipConfigChain) {
sendOnChipConfigChain();
} else if (observable instanceof Masterbias) {
powerDown.set(getMasterbias().isPowerDownEnabled());
} else if (observable instanceof TriStateablePortBit) {
// tristateable should come first before configbit
// since it is subclass
TriStateablePortBit b = (TriStateablePortBit) observable;
byte[] bytes = {(byte) ((b.isSet() ? (byte) 1 : (byte) 0) | (b.isHiZ() ? (byte) 2 : (byte) 0))};
sendFx2ConfigCommand(CMD_SETBIT, b.getPortbit(), bytes); // sends value=CMD_SETBIT, index=portbit with
// (port(b=0,d=1,e=2)<<8)|bitmask(e.g.
// 00001000) in MSB/LSB, byte[0]= OR of
// value (1,0), hiZ=2/0, bit is set if
// tristate, unset if driving port
} else if (observable instanceof PortBit) {
PortBit b = (PortBit) observable;
byte[] bytes = {b.isSet() ? (byte) 1 : (byte) 0};
sendFx2ConfigCommand(CMD_SETBIT, b.getPortbit(), bytes); // sends value=CMD_SETBIT, index=portbit with
// (port(b=0,d=1,e=2)<<8)|bitmask(e.g.
// 00001000) in MSB/LSB, byte[0]=value (1,0)
} else if (observable instanceof CPLDConfigValue) {
sendCPLDConfig();
} else if (observable instanceof AddressedIPot) {
sendAIPot((AddressedIPot) observable);
} else {
super.update(observable, object); // super (SeeBetterConfig) handles others, e.g. masterbias
}
} catch (HardwareInterfaceException e) {
log.warning("On update() caught " + e.toString());
}
}
/**
* Controls the APS intensity readout by wrapping the relevant bits
*/
public class ApsReadoutControl extends Observable implements Observer, HasPropertyTooltips {
PropertyTooltipSupport tooltipSupport = new PropertyTooltipSupport();
public ApsReadoutControl() {
super();
rowSettle.addObserver(this);
colSettle.addObserver(this);
getExposureControlRegister().addObserver(this);
resSettle.addObserver(this);
frameDelay.addObserver(this);
runAdc.addObserver(this);
// TODO awkward renaming of properties here due to wrongly named delegator methods
tooltipSupport.setPropertyTooltip("adcEnabled", runAdc.getDescription());
tooltipSupport.setPropertyTooltip("rowSettleCC", rowSettle.getDescription());
tooltipSupport.setPropertyTooltip("colSettleCC", colSettle.getDescription());
tooltipSupport.setPropertyTooltip("exposureDelayUS", getExposureControlRegister().getDescription());
tooltipSupport.setPropertyTooltip("resSettleCC", resSettle.getDescription());
tooltipSupport.setPropertyTooltip("frameDelayUS", frameDelay.getDescription());
nullSettle.addObserver(this);
tooltipSupport.setPropertyTooltip("nullSettleCC", nullSettle.getDescription());
tooltipSupport.setPropertyTooltip("globalShutterMode", "Has no effect on Davis240a camera. On Davis240b/c cameras, enables global shutter readout. If disabled, enables rolling shutter readout.");
}
public boolean isAdcEnabled() {
return runAdc.isSet();
}
public void setAdcEnabled(boolean yes) {
boolean oldval = runAdc.isSet();
runAdc.set(yes);
// TODO we must always call listeners because by loading prefs, we maybe have changed runAdc but not been
// informed of those changes, because
// we are not registered directly as listeners on the bit itself....
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_CAPTURE_FRAMES_ENABLED, null, runAdc.isSet());
// if (oldval != yes) {
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
public boolean isGlobalShutterMode() {
return (miscControlBits.get() & 2) == 0; // bit clear is global shutter, bit set is rolling shutter
}
public void setGlobalShutterMode(boolean yes) {
int oldval = miscControlBits.get();
boolean oldbool = isGlobalShutterMode();
int newval = (oldval & (~2)) | (yes ? 0 : 2); // set bit1=1 to select rolling shutter mode, 0 for global
// shutter mode
miscControlBits.set(newval);
// Update chip config chain.
((DavisConfig.DavisChipConfigChain) getChipConfigChain()).globalShutter.set(yes);
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_GLOBAL_SHUTTER_MODE_ENABLED, oldbool, yes);
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
public void setColSettleCC(int cc) {
colSettle.set(cc);
}
public void setRowSettleCC(int cc) {
rowSettle.set(cc);
}
public void setResSettleCC(int cc) {
resSettle.set(cc);
}
public void setFrameDelayUS(int cc) {
frameDelay.set(cc);
}
public void setExposureDelayUS(int cc) {
getExposureControlRegister().set(cc);
}
public void setNullSettleCC(int cc) {
nullSettle.set(cc);
}
public int getColSettleCC() {
return colSettle.get();
}
public int getRowSettleCC() {
return rowSettle.get();
}
public int getResSettleCC() {
return resSettle.get();
}
public int getFrameDelayUS() {
return frameDelay.get();
}
public int getExposureDelayUS() {
return getExposureControlRegister().get();
}
public int getNullSettleCC() {
return nullSettle.get();
}
@Override
public void update(Observable o, Object arg) {
if (o == runAdc) {
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_CAPTURE_FRAMES_ENABLED, null, runAdc.isSet());
}
}
@Override
public String getPropertyTooltip(String propertyName) {
return tooltipSupport.getPropertyTooltip(propertyName);
}
}
/**
* IMU control of Invensense IMU-6100A, encapsulated here.
*/
public class ImuControl extends Observable implements HasPropertyTooltips, HasPreference, PreferenceChangeListener {
PropertyTooltipSupport tooltipSupport = new PropertyTooltipSupport();
private ImuGyroScale imuGyroScale;
private ImuAccelScale imuAccelScale;
private boolean displayImuEnabled;
public ImuControl() {
super();
// imu0PowerMgmtClkRegConfig.addObserver(this);
// imu1DLPFConfig.addObserver(this);
// imu2SamplerateDividerConfig.addObserver(this);
// imu3GyroConfig.addObserver(this);
// imu4AccelConfig.addObserver(this);
// TODO awkward renaming of properties here due to wrongly named delegator methods
hasPreferenceList.add(this);
loadPreference();
tooltipSupport.setPropertyTooltip("imu0", imu0PowerMgmtClkRegConfig.getDescription());
tooltipSupport.setPropertyTooltip("imu1", imu1DLPFConfig.getDescription());
tooltipSupport.setPropertyTooltip("imu2", imu2SamplerateDividerConfig.getDescription());
tooltipSupport.setPropertyTooltip("imu3", imu3GyroConfig.getDescription());
tooltipSupport.setPropertyTooltip("imu4", imu4AccelConfig.getDescription());
IMUSample.setFullScaleGyroDegPerSec(imuGyroScale.fullScaleDegPerSec);
IMUSample.setGyroSensitivityScaleFactorDegPerSecPerLsb(1 / imuGyroScale.scaleFactorLsbPerDegPerSec);
IMUSample.setFullScaleAccelG(imuAccelScale.fullScaleG);
IMUSample.setAccelSensitivityScaleFactorGPerLsb(1 / imuAccelScale.scaleFactorLsbPerG);
chip.getPrefs().addPreferenceChangeListener(this);
}
public boolean isImuEnabled() {
return (miscControlBits.get() & 1) == 1;
}
public void setImuEnabled(boolean yes) {
boolean old = (miscControlBits.get() & 1) == 1;
int oldval = miscControlBits.get();
int newval = (oldval & (~1)) | (yes ? 1 : 0);
miscControlBits.set(newval);
getSupport().firePropertyChange(PROPERTY_IMU_ENABLED, old, yes);
}
/**
* Register 26: CONFIG, digital low pass filter setting DLPF_CFG
*/
public void setDLPF(int dlpf) {
if ((dlpf < 0) || (dlpf > 6)) {
throw new IllegalArgumentException("dlpf=" + dlpf + " is outside allowed range 0-6");
}
int old = imu1DLPFConfig.get() & 7;
int oldval = imu1DLPFConfig.get();
int newval = (oldval & (~7)) | (dlpf);
imu1DLPFConfig.set(newval);
activateNewRegisterValues();
getSupport().firePropertyChange(PROPERTY_IMU_DLPF_CHANGED, old, dlpf);
}
public int getDLPF() {
return imu1DLPFConfig.get() & 7;
}
/**
* Register 27: Sample rate divider
*/
public void setSampleRateDivider(int srd) {
if ((srd < 0) || (srd > 255)) {
throw new IllegalArgumentException("sampleRateDivider=" + srd + " is outside allowed range 0-255");
}
int old = imu2SamplerateDividerConfig.get();
imu2SamplerateDividerConfig.set(srd & 255);
activateNewRegisterValues();
getSupport().firePropertyChange(PROPERTY_IMU_SAMPLE_RATE_CHANGED, old, srd);
}
public int getSampleRateDivider() {
return imu2SamplerateDividerConfig.get();
}
public ImuGyroScale getGyroScale() {
return imuGyroScale;
}
public void setGyroScale(ImuGyroScale scale) {
ImuGyroScale old = this.imuGyroScale;
this.imuGyroScale = scale;
setFS_SEL(imuGyroScale.fs_sel);
IMUSample.setFullScaleGyroDegPerSec(imuGyroScale.fullScaleDegPerSec);
IMUSample.setGyroSensitivityScaleFactorDegPerSecPerLsb(1 / imuGyroScale.scaleFactorLsbPerDegPerSec);
getSupport().firePropertyChange(PROPERTY_IMU_GYRO_SCALE_CHANGED, old, this.imuGyroScale);
}
/**
* @return the imuAccelScale
*/
public ImuAccelScale getAccelScale() {
return imuAccelScale;
}
/**
* @param imuAccelScale the imuAccelScale to set
*/
public void setAccelScale(ImuAccelScale scale) {
ImuAccelScale old = this.imuAccelScale;
this.imuAccelScale = scale;
setAFS_SEL(imuAccelScale.afs_sel);
IMUSample.setFullScaleAccelG(imuAccelScale.fullScaleG);
IMUSample.setAccelSensitivityScaleFactorGPerLsb(1 / imuAccelScale.scaleFactorLsbPerG);
getSupport().firePropertyChange(PROPERTY_IMU_ACCEL_SCALE_CHANGED, old, this.imuAccelScale);
}
// accel scale bits
private void setAFS_SEL(int val) {
// AFS_SEL bits are bits 4:3 in accel register
if ((val < 0) || (val > 3)) {
throw new IllegalArgumentException("value " + val + " is outside range 0-3");
}
int oldval = imu4AccelConfig.get();
int newval = (oldval & (~(3 << 3))) | (val << 3);
setImu4(newval);
}
// gyro scale bits
private void setFS_SEL(int val) {
// AFS_SEL bits are bits 4:3 in accel register
if ((val < 0) || (val > 3)) {
throw new IllegalArgumentException("value " + val + " is outside range 0-3");
}
int oldval = imu3GyroConfig.get();
int newval = (oldval & (~(3 << 3))) | (val << 3);
setImu3(newval);
}
public boolean isDisplayImu() {
return displayImuEnabled;
}
public void setDisplayImu(boolean yes) {
boolean old = this.displayImuEnabled;
this.displayImuEnabled = yes;
getSupport().firePropertyChange(PROPERTY_IMU_DISPLAY_ENABLED, old, displayImuEnabled);
}
private void setImu0(int value) throws IllegalArgumentException {
imu0PowerMgmtClkRegConfig.set(value);
activateNewRegisterValues();
}
private int getImu0() {
return imu0PowerMgmtClkRegConfig.get();
}
private void setImu1(int value) throws IllegalArgumentException {
imu1DLPFConfig.set(value);
activateNewRegisterValues();
}
private int getImu1() {
return imu1DLPFConfig.get();
}
private void setImu2(int value) throws IllegalArgumentException {
imu2SamplerateDividerConfig.set(value);
activateNewRegisterValues();
}
private int getImu2() {
return imu2SamplerateDividerConfig.get();
}
private void setImu3(int value) throws IllegalArgumentException {
imu3GyroConfig.set(value);
activateNewRegisterValues();
}
private int getImu3() {
return imu3GyroConfig.get();
}
private void setImu4(int value) throws IllegalArgumentException {
imu4AccelConfig.set(value);
activateNewRegisterValues();
}
private int getImu4() {
return imu4AccelConfig.get();
}
private void activateNewRegisterValues() {
if (isImuEnabled()) {
setImuEnabled(false);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
setImuEnabled(true);
}
}
@Override
public String getPropertyTooltip(String propertyName) {
return tooltipSupport.getPropertyTooltip(propertyName);
}
@Override
public final void loadPreference() {
try {
setGyroScale(ImuGyroScale.valueOf(chip.getPrefs().get("ImuGyroScale", ImuGyroScale.GyroFullScaleDegPerSec1000.toString())));
setAccelScale(ImuAccelScale.valueOf(chip.getPrefs().get("ImuAccelScale", ImuAccelScale.ImuAccelScaleG8.toString())));
setDisplayImu(chip.getPrefs().getBoolean("IMU.displayEnabled", true));
} catch (Exception e) {
log.warning(e.toString());
}
}
@Override
public void storePreference() {
chip.getPrefs().put("ImuGyroScale", imuGyroScale.toString());
chip.getPrefs().put("ImuAccelScale", imuAccelScale.toString());
chip.getPrefs().putBoolean("IMU.displayEnabled", this.displayImuEnabled);
}
@Override
public void preferenceChange(PreferenceChangeEvent e) {
if (e.getKey().toLowerCase().contains("imu")) {
log.info(this + " preferenceChange(): event=" + e + " key=" + e.getKey() + " newValue=" + e.getNewValue());
}
if (e.getNewValue() == null) {
return;
}
try {
// log.info(e.toString());
switch (e.getKey()) {
case "ImuAccelScale":
setAccelScale(ImuAccelScale.valueOf(e.getNewValue()));
break;
case "ImuGyroScale":
setGyroScale(ImuGyroScale.valueOf(e.getNewValue()));
break;
case "IMU.displayEnabled":
setDisplayImu(Boolean.valueOf(e.getNewValue()));
}
} catch (IllegalArgumentException iae) {
log.warning(iae.toString() + ": Preference value=" + e.getNewValue() + " for the preferenc with key=" + e.getKey() + " is not a proper enum for an IMU setting");
}
}
}
public class VideoControl extends Observable implements Observer, HasPreference, HasPropertyTooltips {
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public boolean displayEvents = chip.getPrefs().getBoolean("VideoControl.displayEvents", true);
public boolean displayFrames = chip.getPrefs().getBoolean("VideoControl.displayFrames", true);
public boolean useAutoContrast = chip.getPrefs().getBoolean("VideoControl.useAutoContrast", false);
public float contrast = chip.getPrefs().getFloat("VideoControl.contrast", 1.0F);
public float brightness = chip.getPrefs().getFloat("VideoControl.brightness", 0.0F);
private float gamma = chip.getPrefs().getFloat("VideoControl.gamma", 1); // gamma control for improving display
// on crappy beamer output
private PropertyTooltipSupport tooltipSupport = new PropertyTooltipSupport();
public VideoControl() {
super();
hasPreferenceList.add(this);
tooltipSupport.setPropertyTooltip("displayEvents", "display DVS events");
tooltipSupport.setPropertyTooltip("displayFrames", "display APS frames");
tooltipSupport.setPropertyTooltip("useAutoContrast", "automatically set the display contrast for APS frames");
tooltipSupport.setPropertyTooltip("brightness", "sets the brightness for APS frames, which is the lowest level of display intensity. Default is 0.");
tooltipSupport.setPropertyTooltip("contrast", "sets the contrast for APS frames, which multiplies sample values by this quantity. Default is 1.");
tooltipSupport.setPropertyTooltip("gamma", "sets the display gamma for APS frames, which applies a power law to optimize display for e.g. monitors. Default is 1.");
}
/**
* @return the displayFrames
*/
public boolean isDisplayFrames() {
return displayFrames;
}
/**
* @param displayFrames the displayFrames to set
*/
public void setDisplayFrames(boolean displayFrames) {
boolean old = this.displayFrames;
this.displayFrames = displayFrames;
chip.getPrefs().putBoolean("VideoControl.displayFrames", displayFrames);
if (chip.getAeViewer() != null) {
chip.getAeViewer().interruptViewloop();
}
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_DISPLAY_FRAMES_ENABLED, old, displayFrames);
if (old != displayFrames) {
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
}
/**
* @return the displayEvents
*/
public boolean isDisplayEvents() {
return displayEvents;
}
/**
* @param displayEvents the displayEvents to set
*/
public void setDisplayEvents(boolean displayEvents) {
boolean old = this.displayEvents;
this.displayEvents = displayEvents;
chip.getPrefs().putBoolean("VideoControl.displayEvents", displayEvents);
if (chip.getAeViewer() != null) {
chip.getAeViewer().interruptViewloop();
}
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_DISPLAY_EVENTS_ENABLED, old, displayEvents);
if (old != displayEvents) {
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
}
public boolean isUseAutoContrast() {
return useAutoContrast;
}
public void setUseAutoContrast(boolean useAutoContrast) {
boolean old = this.useAutoContrast;
this.useAutoContrast = useAutoContrast;
chip.getPrefs().putBoolean("VideoControl.useAutoContrast", useAutoContrast);
if (chip.getAeViewer() != null) {
chip.getAeViewer().interruptViewloop();
}
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_AUTO_CONTRAST_ENABLED, old, this.useAutoContrast);
if (old != useAutoContrast) {
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
}
/**
* @return the contrast
*/
public float getContrast() {
return contrast;
}
/**
* @param contrast the contrast to set
*/
public void setContrast(float contrast) {
float old = this.contrast;
this.contrast = contrast;
chip.getPrefs().putFloat("VideoControl.contrast", contrast);
if (chip.getAeViewer() != null) {
chip.getAeViewer().interruptViewloop();
}
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_CONTRAST, old, contrast);
if (old != contrast) {
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
}
/**
* @return the brightness
*/
public float getBrightness() {
return brightness;
}
/**
* @param brightness the brightness to set
*/
public void setBrightness(float brightness) {
float old = this.brightness;
this.brightness = brightness;
chip.getPrefs().putFloat("VideoControl.brightness", brightness);
if (chip.getAeViewer() != null) {
chip.getAeViewer().interruptViewloop();
}
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_BRIGHTNESS, old, this.brightness);
if (old != brightness) {
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
}
/**
* @return the gamma
*/
public float getGamma() {
return gamma;
}
/**
* @param gamma the gamma to set
*/
public void setGamma(float gamma) {
float old = this.gamma;
this.gamma = gamma;
chip.getPrefs().putFloat("VideoControl.gamma", gamma);
if (chip.getAeViewer() != null) {
chip.getAeViewer().interruptViewloop();
}
notifyObservers();
getSupport().firePropertyChange(DavisDisplayConfigInterface.PROPERTY_GAMMA, old, this.gamma);
if (old != gamma) {
setChanged();
notifyObservers(); // inform ParameterControlPanel
}
}
@Override
public void update(Observable o, Object arg) {
setChanged();
notifyObservers(arg);
// if (o == ) {
// propertyChangeSupport.firePropertyChange(EVENT_GRAPHICS_DISPLAY_INTENSITY, null, runAdc.isSet());
// } // TODO
}
/**
* @return the propertyChangeSupport
*/
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
@Override
public void loadPreference() {
setDisplayFrames(chip.getPrefs().getBoolean("VideoControl.displayFrames", true)); // use setter to make sure
// GUIs are updated by
// property changes
setDisplayEvents(chip.getPrefs().getBoolean("VideoControl.displayEvents", true));
setUseAutoContrast(chip.getPrefs().getBoolean("VideoControl.useAutoContrast", false));
setContrast(chip.getPrefs().getFloat("VideoControl.contrast", 1.0F));
setBrightness(chip.getPrefs().getFloat("VideoControl.brightness", 0.0F));
setGamma(chip.getPrefs().getFloat("VideoControl.gamma", 1.0F));
}
@Override
public void storePreference() {
chip.getPrefs().putBoolean("VideoControl.displayEvents", displayEvents);
chip.getPrefs().putBoolean("VideoControl.displayFrames", displayFrames);
chip.getPrefs().putBoolean("VideoControl.useAutoContrast", useAutoContrast);
chip.getPrefs().putFloat("VideoControl.contrast", contrast);
chip.getPrefs().putFloat("VideoControl.brightness", brightness);
chip.getPrefs().putFloat("VideoControl.gamma", gamma);
}
@Override
public String getPropertyTooltip(String propertyName) {
return tooltipSupport.getPropertyTooltip(propertyName);
}
}
public String[] choices() {
String[] s = new String[ImuAccelScale.values().length];
for (int i = 0; i < ImuAccelScale.values().length; i++) {
s[i] = ImuAccelScale.values()[i].fullScaleString;
}
return s;
}
/**
* @return the videoControl
*/
public DavisConfig.VideoControl getVideoControl() {
return videoControl;
}
/**
* @return the apsReadoutControl
*/
public DavisConfig.ApsReadoutControl getApsReadoutControl() {
return apsReadoutControl;
}
/**
* @return the imuControl
*/
public DavisConfig.ImuControl getImuControl() {
return imuControl;
}
/**
* @return the exposureControlRegister
*/
public CPLDInt getExposureControlRegister() {
return exposureControlRegister;
}
/**
* Formats bits represented in a string as '0' or '1' as a byte array to be
* sent over the interface to the firmware, for loading in big endian bit
* order, in order of the bytes sent starting with byte 0.
* <p>
* Because the firmware writes integral bytes it is important that the bytes
* sent to the device are padded with leading bits (at msbs of first byte)
* that are finally shifted out of the on-chip shift register.
*
* Therefore <code>bitString2Bytes</code> should only be called ONCE, after
* the complete bit string has been assembled, unless it is known the other
* bits are an integral number of bytes.
*
* @param bitString in msb to lsb order from left end, where msb will be in
* msb of first output byte
* @return array of bytes to send
*/
public class DavisChipConfigChain extends ChipConfigChain {
// Config Bits
OnchipConfigBit resetCalib = new OnchipConfigBit(chip, "resetCalib", 0,
"turns the bias generator integrate and fire calibration neuron off", true),
typeNCalib = new OnchipConfigBit(
chip,
"typeNCalib",
1,
"make the bias generator intgrate and fire calibration neuron configured to measure N type biases; otherwise measures P-type currents",
false),
resetTestpixel = new OnchipConfigBit(chip, "resetTestpixel", 2, "keeps the test pixel in reset", true),
hotPixelSuppression = new OnchipConfigBit(
chip,
"hotPixelSuppression",
3,
"<html>DAViS240a: turns on the hot pixel suppression. <p>DAViS240b: enables test pixel stripes on right side of array <p>DAViS240c: no effect",
false),
nArow = new OnchipConfigBit(chip, "nArow", 4, "use nArow in the AER state machine", false),
useAout = new OnchipConfigBit(chip, "useAout", 5, "turn the pads for the analog MUX outputs on", true),
globalShutter = new OnchipConfigBit(
chip,
"globalShutter",
6,
"Use the global shutter or not, only has effect on DAVIS240b/c cameras. No effect in DAVIS240a cameras. On-chip control bit that is looded into on-chip shift register.",
false);
// Muxes
OutputMux[] amuxes = {new AnalogOutputMux(1), new AnalogOutputMux(2), new AnalogOutputMux(3)};
OutputMux[] dmuxes = {new DigitalOutputMux(1), new DigitalOutputMux(2), new DigitalOutputMux(3),
new DigitalOutputMux(4)};
OutputMux[] bmuxes = {new DigitalOutputMux(0)};
ArrayList<OutputMux> muxes = new ArrayList();
MuxControlPanel controlPanel = null;
public DavisChipConfigChain(Chip chip) {
super(chip);
this.sbChip = chip;
TOTAL_CONFIG_BITS = 24;
hasPreferenceList.add(this);
configBits = new OnchipConfigBit[7];
configBits[0] = resetCalib;
configBits[1] = typeNCalib;
configBits[2] = resetTestpixel;
configBits[3] = hotPixelSuppression;
configBits[4] = nArow;
configBits[5] = useAout;
configBits[6] = globalShutter;
for (OnchipConfigBit b : configBits) {
b.addObserver(this);
}
muxes.addAll(Arrays.asList(bmuxes));
muxes.addAll(Arrays.asList(dmuxes)); // 4 digital muxes, first in list since at end of chain - bits must be
// sent first, before any biasgen bits
muxes.addAll(Arrays.asList(amuxes)); // finally send the 3 voltage muxes
for (OutputMux m : muxes) {
m.addObserver(this);
m.setChip(chip);
}
bmuxes[0].setName("BiasOutMux");
bmuxes[0].put(0, "IFThrBn");
bmuxes[0].put(1, "AEPuYBp");
bmuxes[0].put(2, "AEPuXBp");
bmuxes[0].put(3, "LColTimeout");
bmuxes[0].put(4, "AEPdBn");
bmuxes[0].put(5, "RefrBp");
bmuxes[0].put(6, "PrSFBp");
bmuxes[0].put(7, "PrBp");
bmuxes[0].put(8, "PixInvBn");
bmuxes[0].put(9, "LocalBufBn");
bmuxes[0].put(10, "ApsROSFBn");
bmuxes[0].put(11, "DiffCasBnc");
bmuxes[0].put(12, "ApsCasBpc");
bmuxes[0].put(13, "OffBn");
bmuxes[0].put(14, "OnBn");
bmuxes[0].put(15, "DiffBn");
dmuxes[0].setName("DigMux3");
dmuxes[1].setName("DigMux2");
dmuxes[2].setName("DigMux1");
dmuxes[3].setName("DigMux0");
for (int i = 0; i < 4; i++) {
dmuxes[i].put(0, "AY179right");
dmuxes[i].put(1, "Acol");
dmuxes[i].put(2, "ColArbTopA");
dmuxes[i].put(3, "ColArbTopR");
dmuxes[i].put(4, "FF1");
dmuxes[i].put(5, "FF2");
dmuxes[i].put(6, "Rcarb");
dmuxes[i].put(7, "Rcol");
dmuxes[i].put(8, "Rrow");
dmuxes[i].put(9, "RxarbE");
dmuxes[i].put(10, "nAX0");
dmuxes[i].put(11, "nArowBottom");
dmuxes[i].put(12, "nArowTop");
dmuxes[i].put(13, "nRxOn");
}
dmuxes[3].put(14, "AY179");
dmuxes[3].put(15, "RY179");
dmuxes[2].put(14, "AY179");
dmuxes[2].put(15, "RY179");
dmuxes[1].put(14, "biasCalibSpike");
dmuxes[1].put(15, "nRY179right");
dmuxes[0].put(14, "nResetRxCol");
dmuxes[0].put(15, "nRYtestpixel");
amuxes[0].setName("AnaMux2");
amuxes[1].setName("AnaMux1");
amuxes[2].setName("AnaMux0");
for (int i = 0; i < 3; i++) {
amuxes[i].put(0, "on");
amuxes[i].put(1, "off");
amuxes[i].put(2, "vdiff");
amuxes[i].put(3, "nResetPixel");
amuxes[i].put(4, "pr");
amuxes[i].put(5, "pd");
}
amuxes[0].put(6, "calibNeuron");
amuxes[0].put(7, "nTimeout_AI");
amuxes[1].put(6, "apsgate");
amuxes[1].put(7, "apsout");
amuxes[2].put(6, "apsgate");
amuxes[2].put(7, "apsout");
}
class VoltageOutputMap extends OutputMap {
final void put(int k, int v) {
put(k, v, "Voltage " + k);
}
VoltageOutputMap() {
put(0, 1);
put(1, 3);
put(2, 5);
put(3, 7);
put(4, 9);
put(5, 11);
put(6, 13);
put(7, 15);
}
}
class DigitalOutputMap extends OutputMap {
DigitalOutputMap() {
for (int i = 0; i < 16; i++) {
put(i, i, "DigOut " + i);
}
}
}
class AnalogOutputMux extends OutputMux {
AnalogOutputMux(int n) {
super(sbChip, 4, 8, (new VoltageOutputMap()));
setName("Voltages" + n);
}
}
class DigitalOutputMux extends OutputMux {
DigitalOutputMux(int n) {
super(sbChip, 4, 16, (new DigitalOutputMap()));
setName("LogicSignals" + n);
}
}
@Override
public String getBitString() {
// System.out.print("dig muxes ");
String dMuxBits = getMuxBitString(dmuxes);
// System.out.print("config bits ");
String configBits = getConfigBitString();
// System.out.print("analog muxes ");
String aMuxBits = getMuxBitString(amuxes);
// System.out.print("bias muxes ");
String bMuxBits = getMuxBitString(bmuxes);
String chipConfigChain = (dMuxBits + configBits + aMuxBits + bMuxBits);
// System.out.println("On chip config chain: "+chipConfigChain);
return chipConfigChain; // returns bytes padded at end
}
String getMuxBitString(OutputMux[] muxs) {
StringBuilder s = new StringBuilder();
for (OutputMux m : muxs) {
s.append(m.getBitString());
}
// System.out.println(s);
return s.toString();
}
String getConfigBitString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < (TOTAL_CONFIG_BITS - getConfigBits().length); i++) {
s.append("0");
}
for (int i = getConfigBits().length - 1; i >= 0; i
s.append(getConfigBits()[i].isSet() ? "1" : "0");
}
// System.out.println(s);
return s.toString();
}
@Override
public MuxControlPanel buildMuxControlPanel() {
return new MuxControlPanel(muxes);
}
@Override
public JPanel getChipConfigPanel() {
JPanel chipConfigPanel = new JPanel();
chipConfigPanel.setLayout(new BoxLayout(chipConfigPanel, BoxLayout.Y_AXIS));
// On-Chip config bits
JPanel extraPanel = new JPanel();
extraPanel.setLayout(new BoxLayout(extraPanel, BoxLayout.Y_AXIS));
for (OnchipConfigBit b : getConfigBits()) {
extraPanel.add(new JRadioButton(b.getAction()));
}
extraPanel.setBorder(new TitledBorder("Extra on-chip bits"));
chipConfigPanel.add(extraPanel);
// FX2 port bits
JPanel portBitsPanel = new JPanel();
portBitsPanel.setLayout(new BoxLayout(portBitsPanel, BoxLayout.Y_AXIS));
for (PortBit p : portBits) {
portBitsPanel.add(new JRadioButton(p.getAction()));
}
portBitsPanel.setBorder(new TitledBorder("Cypress FX2 port bits"));
chipConfigPanel.add(portBitsPanel);
// event translation control
JPanel eventTranslationControlPanel = new JPanel();
eventTranslationControlPanel.setBorder(new TitledBorder("DVS event translation control"));
eventTranslationControlPanel.setLayout(new BoxLayout(eventTranslationControlPanel, BoxLayout.Y_AXIS));
// add a reset button on top of everything
final Action translateRowOnlyEventsAction = new AbstractAction("Translate row-only events") {
{
putValue(Action.SHORT_DESCRIPTION,
"<html>Controls whether row-only events (row request but no column request) "
+ "<br>are captured from USB data stream in ApsDvsHardwareInterface. "
+ "<p>These events are rendered as OFF events at x=239");
putValue(Action.SELECTED_KEY, translateRowOnlyEvents);
}
@Override
public void actionPerformed(ActionEvent evt) {
setTranslateRowOnlyEvents(!isTranslateRowOnlyEvents());
}
};
final JRadioButton translateRowOnlyEventsButton = new JRadioButton(translateRowOnlyEventsAction);
eventTranslationControlPanel.add(translateRowOnlyEventsButton);
getSupport().addPropertyChangeListener(DavisDisplayConfigInterface.PROPERTY_TRANSLATE_ROW_ONLY_EVENTS,
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
translateRowOnlyEventsButton.setSelected((boolean) evt.getNewValue());
}
});
chipConfigPanel.add(eventTranslationControlPanel);
return chipConfigPanel;
}
}
}
|
package etomica.potential;
import etomica.api.IAtomList;
import etomica.api.IAtomType;
import etomica.api.IVector;
import etomica.space.ISpace;
import etomica.space.Tensor;
/**
* Wraps a soft-spherical potential to apply a truncation to it. Energy and
* its derivatives are set to zero at a specified cutoff. (No accounting is
* made of the infinite force existing at the cutoff point). Lrc potential
* is based on integration of energy from cutoff to infinity, assuming no
* pair correlations beyond the cutoff.
*/
public class P2SoftSphericalTruncated extends Potential2SoftSpherical
implements PotentialTruncated {
public P2SoftSphericalTruncated(ISpace _space, Potential2SoftSpherical potential, double truncationRadius) {
super(_space);
this.potential = potential;
setTruncationRadius(truncationRadius);
}
/**
* Returns the wrapped potential.
*/
public Potential2SoftSpherical getWrappedPotential() {
return potential;
}
/**
* Returns the energy of the wrapped potential if the separation
* is less than the cutoff value
* @param r2 the squared distance between the atoms
*/
public double u(double r2) {
return (r2 < r2Cutoff) ? potential.u(r2) : 0.0;
}
/**
* Returns the derivative (r du/dr) of the wrapped potential if the separation
* is less than the cutoff value
* @param r2 the squared distance between the atoms
*/
public double du(double r2) {
return (r2 < r2Cutoff) ? potential.du(r2) : 0.0;
}
/**
* Returns the 2nd derivative (r^2 d^2u/dr^2) of the wrapped potential if the separation
* is less than the cutoff value
* @param r2 the squared distance between the atoms
*/
public double d2u(double r2) {
return (r2 < r2Cutoff) ? potential.d2u(r2) : 0.0;
}
/**
* Returns the value of uInt for the wrapped potential.
*/
public double uInt(double rC) {
return potential.uInt(rC);
}
/**
* Mutator method for the radial cutoff distance.
*/
public void setTruncationRadius(double rCut) {
rCutoff = rCut;
r2Cutoff = rCut*rCut;
}
/**
* Accessor method for the radial cutoff distance.
*/
public double getTruncationRadius() {return rCutoff;}
/**
* Returns the truncation radius.
*/
public double getRange() {
return rCutoff;
}
/**
* Returns the dimension (length) of the radial cutoff distance.
*/
public etomica.units.Dimension getTruncationRadiusDimension() {return etomica.units.Length.DIMENSION;}
/**
* Returns the zero-body potential that evaluates the contribution to the
* energy and its derivatives from pairs that are separated by a distance
* exceeding the truncation radius.
*/
public Potential0Lrc makeLrcPotential(IAtomType[] types) {
if (!makeLrc) return null;
return new P0Lrc(space, potential, this, types);
}
public void setMakeLrc(boolean newMakeLrc) {
makeLrc = newMakeLrc;
}
public boolean getMakeLrc() {
return makeLrc;
}
/**
* Inner class that implements the long-range correction for this truncation scheme.
*/
public static class P0Lrc extends Potential0Lrc implements Potential2Soft {
private final double A;
private final int D;
private Potential2Soft potential;
public P0Lrc(ISpace space, Potential2Soft truncatedPotential,
Potential2Soft potential, IAtomType[] types) {
super(space, types, truncatedPotential);
this.potential = potential;
A = space.sphereArea(1.0); //multiplier for differential surface element
D = space.D(); //spatial dimension
}
public double energy(IAtomList atoms) {
return uCorrection(nPairs()/box.getBoundary().volume());
}
public double virial(IAtomList atoms) {
return duCorrection(nPairs()/box.getBoundary().volume());
}
public double hyperVirial(IAtomList pair) {
return d2uCorrection(nPairs()/box.getBoundary().volume()) + duCorrection(nPairs()/box.getBoundary().volume());
}
public IVector[] gradient(IAtomList atoms) {
return null;
}
public IVector[] gradient(IAtomList atoms, Tensor pressureTensor) {
double virial = virial(atoms) / pressureTensor.D();
for (int i=0; i<pressureTensor.D(); i++) {
pressureTensor.setComponent(i,i,pressureTensor.component(i,i)-virial);
}
// we'd like to throw an exception and return the tensor, but we can't. return null
// instead. it should work about as well as throwing an exception.
return null;
}
/**
* Uses result from integration-by-parts to evaluate integral of
* r2 d2u/dr2 using integral of u.
* @param pairDensity average pairs-per-volume affected by the potential.
*/
public double d2uCorrection(double pairDensity) {
double rCutoff = potential.getRange();
double integral = ((Potential2Soft)truncatedPotential).integral(rCutoff);
//need potential to be spherical to apply here
integral = -A*space.powerD(rCutoff)*((Potential2Soft)truncatedPotential).u(rCutoff*rCutoff) - D*integral;
integral = -A*space.powerD(rCutoff)*((Potential2SoftSpherical)truncatedPotential).du(rCutoff*rCutoff) - (D+1)*integral;
return pairDensity*integral;
}
/**
* Long-range correction to the energy.
* @param pairDensity average pairs-per-volume affected by the potential.
*/
public double uCorrection(double pairDensity) {
double rCutoff = potential.getRange();
double integral = ((Potential2Soft)truncatedPotential).integral(rCutoff);
return pairDensity*integral;
}
/**
* Uses result from integration-by-parts to evaluate integral of
* r du/dr using integral of u.
* @param pairDensity average pairs-per-volume affected by the potential.
*/
public double duCorrection(double pairDensity) {
double rCutoff = potential.getRange();
double integral = ((Potential2Soft)truncatedPotential).integral(rCutoff);
//need potential to be spherical to apply here
integral = -A*space.powerD(rCutoff)*((Potential2Soft)truncatedPotential).u(rCutoff*rCutoff) - D*integral;
return pairDensity*integral;
}
public double u(double r2) {
throw new RuntimeException("nope");
}
public double integral(double rC) {
throw new RuntimeException("nope");
}
public double du(double r2) {
throw new RuntimeException("nope");
}
}//end of P0lrc
protected double rCutoff, r2Cutoff;
protected boolean makeLrc = true;
protected final Potential2SoftSpherical potential;
}
|
package de.mrapp.android.preference;
import java.util.Collection;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import de.mrapp.android.preference.adapter.PreferenceHeaderAdapter;
import de.mrapp.android.preference.fragment.FragmentListener;
import de.mrapp.android.preference.fragment.PreferenceHeaderFragment;
import de.mrapp.android.preference.parser.PreferenceHeaderParser;
/**
* An activity, which provides a navigation for multiple groups of preferences,
* in which each group is represented by an instance of the class
* {@link PreferenceHeader}. On devices with small screens, e.g. on smartphones,
* the navigation is designed to use the whole available space and selecting an
* item causes the corresponding preferences to be shown full screen as well. On
* devices with large screens, e.g. on tablets, the navigation and the
* preferences of the currently selected item are shown split screen.
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public abstract class PreferenceActivity extends Activity implements
FragmentListener, OnItemClickListener {
/**
* The name of the extra, which is used to save the class name of the
* fragment, which is currently shown, within a bundle.
*/
private static final String CURRENT_FRAGMENT_EXTRA = PreferenceActivity.class
.getSimpleName() + "::CurrentFragment";
/**
* The name of the extra, which is used to save the index of the currently
* selected preference header, within a bundle.
*/
private static final String SELECTED_PREFERENCE_HEADER_EXTRA = PreferenceActivity.class
.getSimpleName() + "::SelectedPreferenceHeader";
/**
* The fragment, which contains the preference headers and provides the
* navigation to each header's fragment.
*/
private PreferenceHeaderFragment preferenceHeaderFragment;
/**
* The parent view of the fragment, which provides the navigation to each
* preference header's fragment.
*/
private ViewGroup preferenceHeaderParentView;
/**
* The parent view of the fragment, which is used to show the preferences of
* the currently selected preference header on devices with a large screen.
*/
private ViewGroup preferenceScreenParentView;
/**
* The view, which is used to draw a shadow besides the navigation on
* devices with a large screen.
*/
private View shadowView;
/**
* The full qualified class name of the fragment, which is currently shown
* or null, if no preference header is currently selected.
*/
private String currentFragment;
/**
* True, if the back button of the action bar should be shown, false
* otherwise.
*/
private boolean displayHomeAsUp;
/**
* Shows the fragment, which corresponds to a specific preference header.
*
* @param preferenceHeader
* The preference header, the fragment, which should be shown,
* corresponds to, as an instance of the class
* {@link PreferenceHeader}. The preference header may not be
* null
*/
private void showPreferenceScreen(final PreferenceHeader preferenceHeader) {
currentFragment = preferenceHeader.getFragment();
showPreferenceScreen(currentFragment);
}
/**
* Shows the fragment, which corresponds to a specific class name.
*
* @param fragmentName
* The full qualified class name of the fragment, which should be
* shown, as a {@link String}
*/
private void showPreferenceScreen(final String fragmentName) {
Fragment fragment = Fragment.instantiate(this, fragmentName);
if (isSplitScreen()) {
replaceFragment(fragment, R.id.preference_screen_parent, 0);
} else {
replaceFragment(fragment, R.id.preference_header_parent,
FragmentTransaction.TRANSIT_FRAGMENT_FADE);
showActionBarBackButton();
}
}
/**
* Shows the fragment, which provides the navigation to each preference
* header's fragment.
*/
private void showPreferenceHeaders() {
int transition = 0;
if (currentFragment != null) {
transition = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE;
currentFragment = null;
}
replaceFragment(preferenceHeaderFragment,
R.id.preference_header_parent, transition);
}
/**
* Replaces the fragment, which is currently contained by a specific parent
* view, by an other fragment.
*
* @param fragment
* The fragment, which should replace the current fragment, as an
* instance of the class {@link Fragment}. The fragment may not
* be null
* @param parentViewId
* The id of the parent view, which contains the fragment, that
* should be replaced, as an {@link Integer} value
* @param transition
* The transition, which should be shown when replacing the
* fragment, as an {@link Integer} value or 0, if no transition
* should be shown
*/
private void replaceFragment(final Fragment fragment,
final int parentViewId, final int transition) {
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.setTransition(transition);
transaction.replace(parentViewId, fragment);
transaction.commit();
}
/**
* Shows the back button in the activity's action bar.
*/
private void showActionBarBackButton() {
if (getActionBar() != null) {
displayHomeAsUp = isDisplayHomeAsUpEnabled();
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
/**
* Hides the back button in the activity's action bar, if it was not
* previously shown.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void hideActionBarBackButton() {
if (getActionBar() != null && !displayHomeAsUp) {
getActionBar().setDisplayHomeAsUpEnabled(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
getActionBar().setHomeButtonEnabled(false);
}
}
}
/**
* Returns, whether the back button of the action bar is currently shown, or
* not.
*
* @return True, if the back button of the action bar is currently shown,
* false otherwise
*/
private boolean isDisplayHomeAsUpEnabled() {
if (getActionBar() != null) {
return (getActionBar().getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) == ActionBar.DISPLAY_HOME_AS_UP;
}
return false;
}
/**
* Returns the parent view of the fragment, which provides the navigation to
* each preference header's fragment. On devices with a small screen this
* parent view is also used to show a preference header's fragment, when a
* header is currently selected.
*
* @return The parent view of the fragment, which provides the navigation to
* each preference header's fragment, as an instance of the class
* {@link ViewGroup}. The parent view may not be null
*/
public final ViewGroup getPreferenceHeaderParentView() {
return preferenceHeaderParentView;
}
/**
* Returns the parent view of the fragment, which is used to show the
* preferences of the currently selected preference header on devices with a
* large screen.
*
* @return The parent view of the fragment, which is used to show the
* preferences of the currently selected preference header, as an
* instance of the class {@link ViewGroup} or null, if the device
* has a small screen
*/
public final ViewGroup getPreferenceScreenParentView() {
return preferenceScreenParentView;
}
/**
* Returns the view, which is used to draw a shadow besides the navigation
* on devices with a large screen.
*
* @return The view, which is used to draw a shadow besides the navigation,
* as an instance of the class {@link View} or null, if the device
* has a small screen
*/
public final View getShadowView() {
return shadowView;
}
/**
* Returns the list view, which is used to show the preference headers.
*
* @return The list view, which is used to show the preference header, as an
* instance of the class {@link ListView}. The list view may not be
* null
*/
public final ListView getListView() {
return preferenceHeaderFragment.getListView();
}
/**
* Returns the adapter, which provides the preference headers for
* visualization using the list view.
*
* @return The adapter, which provides the preference headers for
* visualization using the list view, as an instance of the class
* {@link PreferenceHeaderAdapter}. The adapter may not be null
*/
public final PreferenceHeaderAdapter getListAdapter() {
return preferenceHeaderFragment.getListAdapter();
}
/**
* Adds all preference headers, which are specified by a specific XML
* resource.
*
* @param resourceId
* The resource id of the XML file, which specifies the
* preference headers, as an {@link Integer} value. The resource
* id must correspond to a valid XML resource
*/
public final void addPreferenceHeadersFromResource(final int resourceId) {
getListAdapter().addAllItems(
PreferenceHeaderParser.fromResource(this, resourceId));
}
/**
* Adds a new preference header.
*
* @param preferenceHeader
* The preference header, which should be added, as an instance
* of the class {@link PreferenceHeader}. The preference header
* may not be null
* @return
*/
public final void addPreferenceHeader(
final PreferenceHeader preferenceHeader) {
getListAdapter().addItem(preferenceHeader);
}
/**
* Adds all preference headers, which are contained by a specific
* collection.
*
* @param preferenceHeaders
* The collection, which contains the preference headers, which
* should be added, as an instance of the type {@link Collection}
* or an empty collection, if no preference headers should be
* added
*/
public final void addAllPreferenceHeaders(
final Collection<PreferenceHeader> preferenceHeaders) {
getListAdapter().addAllItems(preferenceHeaders);
}
/**
* Removes a specific preference header.
*
* @param preferenceHeader
* The preference header, which should be removed, as an instance
* of the class {@link PreferenceHeader}. The preference header
* may not be null
* @return True, if the preference header has been removed, false otherwise
*/
public final boolean removePreferenceHeader(
final PreferenceHeader preferenceHeader) {
return getListAdapter().removeItem(preferenceHeader);
}
/**
* Removes all preference headers.
*/
public final void clearPreferenceHeaders() {
getListAdapter().clear();
}
/**
* Returns, whether the preference headers and the corresponding fragments
* are shown split screen, or not.
*
* @return True, if the preference headers and the corresponding fragments
* are shown split screen, false otherwise
*/
public final boolean isSplitScreen() {
return getPreferenceScreenParentView() != null;
}
/**
* Sets the color of the shadow, which is drawn besides the navigation on
* devices with a large screen.
*
* @param shadowColor
* The color, which should be set, as an {@link Integer} value
*/
@SuppressWarnings("deprecation")
public final void setShadowColor(final int shadowColor) {
if (getShadowView() != null) {
GradientDrawable gradient = new GradientDrawable(
Orientation.LEFT_RIGHT, new int[] { shadowColor,
Color.TRANSPARENT });
getShadowView().setBackgroundDrawable(gradient);
}
}
@Override
public final void onFragmentCreated(final Fragment fragment) {
onCreatePreferenceHeaders();
getListView().setOnItemClickListener(this);
if (isSplitScreen()) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
if (!getListAdapter().isEmpty()) {
getListView().setItemChecked(0, true);
showPreferenceScreen(getListAdapter().getItem(0));
}
}
}
@Override
public final void onItemClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
showPreferenceScreen(getListAdapter().getItem(position));
}
@Override
public final boolean onKeyDown(final int keyCode, final KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && !isSplitScreen()
&& currentFragment != null) {
showPreferenceHeaders();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public final boolean onOptionsItemSelected(final MenuItem item) {
if (item.getItemId() == android.R.id.home && !isSplitScreen()
&& currentFragment != null) {
showPreferenceHeaders();
hideActionBarBackButton();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preference_activity);
preferenceHeaderParentView = (ViewGroup) findViewById(R.id.preference_header_parent);
preferenceScreenParentView = (ViewGroup) findViewById(R.id.preference_screen_parent);
shadowView = findViewById(R.id.shadow_view);
setShadowColor(getResources().getColor(R.color.shadow));
preferenceHeaderFragment = new PreferenceHeaderFragment();
preferenceHeaderFragment.addFragmentListener(this);
showPreferenceHeaders();
}
@Override
protected final void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(CURRENT_FRAGMENT_EXTRA, currentFragment);
outState.putInt(SELECTED_PREFERENCE_HEADER_EXTRA, getListView()
.getCheckedItemPosition());
}
@Override
protected final void onRestoreInstanceState(final Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentFragment = savedInstanceState.getString(CURRENT_FRAGMENT_EXTRA);
int selectedPreferenceHeader = savedInstanceState
.getInt(SELECTED_PREFERENCE_HEADER_EXTRA);
if (currentFragment != null) {
showPreferenceScreen(currentFragment);
}
if (selectedPreferenceHeader != ListView.INVALID_POSITION) {
getListView().setItemChecked(selectedPreferenceHeader, true);
}
}
/**
* The method, which is invoked, when the preference headers should be
* created. This method has to be overridden by implementing subclasses to
* add the preference headers.
*/
protected abstract void onCreatePreferenceHeaders();
}
|
package edu.cmu.minorthird.text.learn;
import edu.cmu.minorthird.text.*;
import edu.cmu.minorthird.classify.*;
import edu.cmu.minorthird.classify.sequential.*;
import edu.cmu.minorthird.util.*;
import edu.cmu.minorthird.util.gui.*;
import com.lgc.wsh.util.*;
import com.lgc.wsh.inv.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
/** Allows one to adjust the parameters of a learned extractor.
*/
public class ExtractorTweaker
{
private CMMTweaker cmmTweaker = new CMMTweaker();
static private Logger log = Logger.getLogger(ExtractorTweaker.class);
/** Return the value of bias term before the last tweak.
*/
public double getOldBias() { return cmmTweaker.oldBias(); }
/** Return the value of bias term after the last tweak.
*/
public double getNewBias() { return cmmTweaker.newBias(); }
/** Return a modified copy of the annotator. Only works for annotators
* learned by the voted perceptron and/or CRF learners.
*/
public ExtractorAnnotator tweak(ExtractorAnnotator annotator,double bias)
{
if (annotator instanceof SequenceAnnotatorLearner.SequenceAnnotator) {
SequenceAnnotatorLearner.SequenceAnnotator sa = (SequenceAnnotatorLearner.SequenceAnnotator)annotator;
SequenceClassifier sc = (SequenceClassifier) sa.getSequenceClassifier();
if ((sc instanceof CMM)) {
CMM cmm = (CMM)sc;
return new
SequenceAnnotatorLearner.SequenceAnnotator(
cmmTweaker.tweak(cmm,bias),
sa.getSpanFeatureExtractor(),
sa.getReduction(),
sa.getSpanType()
);
} else {
throw new IllegalArgumentException("can't tweak annotator based on sequence classifier of type "+
sc.getClass());
}
} else {
throw new IllegalArgumentException("can't tweak annotator of type "+
annotator.getClass());
}
}
// command-line processing
private File fromFile=null;
private File toFile=null;
private TextLabels textLabels=null;
private String spanType=null;
private double newBias=0, lo=-999, hi=999;
private double beta=1.0;
private boolean biasSpecified=false, loSpecified=false, hiSpecified=false;
public class MyCLP extends BasicCommandLineProcessor
{
public void loadFrom(String s) { fromFile=new File(s); }
public void saveAs(String s) { toFile=new File(s); }
public void labels(String s) { textLabels=FancyLoader.loadTextLabels(s); }
public void spanType(String s) { spanType=s; }
public void newBias(String s) { newBias=StringUtil.atof(s); biasSpecified=true; }
public void lowBias(String s) { lo=StringUtil.atof(s); loSpecified=true; }
public void hiBias(String s) { hi=StringUtil.atof(s); hiSpecified=true; }
public void beta(String s) { beta=StringUtil.atof(s); }
}
public CommandLineProcessor getCLP() { return new MyCLP(); }
private void doMain() throws IOException
{
if (fromFile==null) throw new IllegalStateException("need to specify -loadFrom");
ExtractorAnnotator annotator = (ExtractorAnnotator)IOUtil.loadSerialized(fromFile);
ExtractorAnnotator tweaked = null;
if (biasSpecified) {
// just tweak the bias as given
tweaked = tweak(annotator,newBias);
} else if (!biasSpecified && textLabels!=null && spanType!=null) {
// try and optimize f1 on the provided set of text labels
// figure out initial bounds
if (!loSpecified || !hiSpecified) {
tweak(annotator,0);
double v = getOldBias();
if (v<0) v = -v;
if (!loSpecified) lo = -10*v;
if (!hiSpecified) hi = 10*v;
System.out.println("oldBias term was "+v+" testing between "+lo+" and "+hi);
}
System.out.println("try to maximize token F[beta] for beta="+beta+" (b>1 rewards recall, b<1 precision)");
AnnTester annTester = new AnnTester(annotator,beta);
ScalarSolver solver = new ScalarSolver(annTester);
double optBias = solver.solve(lo, hi, 0.01, 0.01, 40, null);
tweaked = tweak(annotator,optBias);
}
if (toFile!=null) IOUtil.saveSerialized((Serializable)tweaked, toFile);
}
private class AnnTester implements ScalarSolver.Function
{
private ExtractorAnnotator ann;
private double beta=1.0;
public AnnTester(ExtractorAnnotator annotator,double beta)
{
this.ann=annotator; this.beta=beta;
}
public double function(double d)
{
ExtractorAnnotator tweakedAnn = tweak(ann,d);
TextLabels annLabels = tweakedAnn.annotatedCopy(textLabels);
SpanDifference sd =
new SpanDifference(
annLabels.instanceIterator(ann.getSpanType()),
annLabels.instanceIterator(spanType),
annLabels.closureIterator(spanType));
double f = 0;
double p = sd.tokenPrecision();
double r = sd.tokenRecall();
if (p!=0 || p!=0) {
f = (beta*beta+1.0)*p*r/(beta*beta*p+r);
}
System.out.println("after testing bias "+d+" yields f["+beta+"]="+f+" for p/r of "+p+"/"+r);
return -f; //scalar solver tries to minimize this
}
}
public static void main(String[] args)
{
try {
ExtractorTweaker xt = new ExtractorTweaker();
xt.getCLP().processArguments(args);
xt.doMain();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
package edu.iu.grid.oim.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import com.divrep.DivRep;
import com.divrep.DivRepEvent;
import com.divrep.DivRepEventListener;
import com.divrep.common.DivRepButton;
import com.divrep.common.DivRepTextArea;
import com.divrep.common.DivRepTextBox;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.lib.AuthorizationException;
import edu.iu.grid.oim.lib.StaticConfig;
import edu.iu.grid.oim.model.CertificateRequestStatus;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.db.CertificateRequestModelBase;
import edu.iu.grid.oim.model.db.CertificateRequestHostModel;
import edu.iu.grid.oim.model.db.ContactModel;
import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.exceptions.CertificateRequestException;
import edu.iu.grid.oim.view.BootBreadCrumbView;
import edu.iu.grid.oim.view.BootMenuView;
import edu.iu.grid.oim.view.BootPage;
import edu.iu.grid.oim.view.CertificateMenuView;
import edu.iu.grid.oim.view.GenericView;
import edu.iu.grid.oim.view.HostCertificateTable;
import edu.iu.grid.oim.view.HtmlView;
import edu.iu.grid.oim.view.IView;
public class CertificateHostServlet extends ServletBase {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(CertificateHostServlet.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
UserContext context = new UserContext(request);
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
BootMenuView menuview = new BootMenuView(context, "certificate");
IView content = null;
String dirty_id = request.getParameter("id");
String status = request.getParameter("status");
if(status != null && dirty_id != null) {
//display status
int id = Integer.parseInt(dirty_id);
CertificateRequestHostRecord rec;
try {
rec = model.get(id);
IView view = statusView(rec);
view.render(response.getWriter());
} catch (SQLException e) {
log.info("Failed to load specified certificate", e);
return;
}
} else {
if(dirty_id != null) {
try {
int id = Integer.parseInt(dirty_id);
CertificateRequestHostRecord rec = model.get(id);
if(rec == null) {
log.info("No request found with a specified request ID.");
return;
}
if(!model.canView(rec)) {
throw new AuthorizationException("You don't have access to view this certificate");
}
ArrayList<CertificateRequestModelBase<CertificateRequestHostRecord>.LogDetail> logs = model.getLogs(CertificateRequestHostModel.class, id);
String submenu = "certificatehost";
if(request.getParameter("search") != null) {
submenu = "certificatesearchhost";
}
content = createDetailView(context, rec, logs, submenu);
} catch (SQLException e) {
throw new ServletException("Failed to load specified certificate", e);
}
} else {
content = createListView(context);
}
BootPage page = new BootPage(context, menuview, content, null);
page.render(response.getWriter());
}
}
protected IView statusView(final CertificateRequestHostRecord rec) {
return new IView() {
@Override
public void render(PrintWriter out) {
if(rec.status.equals(CertificateRequestStatus.ISSUING)) {
//count number of certificate issued
int issued = 0;
String[] pkcs7s = rec.getPKCS7s();
for(String pkcs7 : pkcs7s) {
if(pkcs7 != null) issued++;
}
int percent = issued*100/pkcs7s.length;
out.write("Certificates issued so far: "+issued+" of "+pkcs7s.length);
out.write("<div class=\"progress active\">");
out.write("<div class=\"bar\" style=\"width: "+percent+"%;\"></div>");
out.write("</div>");
} else {
//not issuing anymore - redirect
out.write("<script>document.location='certificatehost?id="+rec.id+"';</script>");
}
}
};
}
protected IView createDetailView(
final UserContext context,
final CertificateRequestHostRecord rec,
final ArrayList<CertificateRequestModelBase<CertificateRequestHostRecord>.LogDetail> logs,
final String submenu) throws ServletException
{
final Authorization auth = context.getAuthorization();
final SimpleDateFormat dformat = new SimpleDateFormat();
dformat.setTimeZone(auth.getTimeZone());
return new IView(){
@Override
public void render(PrintWriter out) {
out.write("<div id=\"content\">");
out.write("<div class=\"row-fluid\">");
out.write("<div class=\"span3\">");
CertificateMenuView menu = new CertificateMenuView(context, submenu);
menu.render(out);
out.write("</div>"); //span3
out.write("<div class=\"span9\">");
BootBreadCrumbView bread_crumb = new BootBreadCrumbView();
bread_crumb.addCrumb("Host Certificate Requests", "certificatehost");
bread_crumb.addCrumb(Integer.toString(rec.id), null);
bread_crumb.render(out);
renderDetail(out);
renderLog(out);
out.write("</div>"); //span9
out.write("</div>"); //row-fluid
out.write("</div>"); //content
}
public void renderDetail(PrintWriter out) {
out.write("<table class=\"table nohover\">");
out.write("<tbody>");
out.write("<tr>");
out.write("<th>Status</th>");
out.write("<td>"+StringEscapeUtils.escapeHtml(rec.status));
if(rec.status.equals(CertificateRequestStatus.ISSUING)) {
out.write("<div id=\"status_progress\">Loading...</div>");
out.write("<script>");
out.write("function loadstatus() { ");
out.write("$('#status_progress').load('certificatehost?id="+rec.id+"&status');");
out.write("setTimeout('loadstatus()', 2000);");
out.write("}");
out.write("loadstatus();");
out.write("</script>");
}
out.write("</td>");
out.write("</tr>");
out.write("<tr>");
out.write("<th>Requester</th>");
try {
ContactModel cmodel = new ContactModel(context);
if(rec.requester_contact_id != null) {
ContactRecord requester = cmodel.get(rec.requester_contact_id);
out.write("<td>");
if(auth.isUser()) {
out.write("<b>"+StringEscapeUtils.escapeHtml(requester.name)+"</b>");
out.write(" <code><a href=\"mailto:"+requester.primary_email+"\">"+requester.primary_email+"</a></code>");
out.write(" Phone: "+requester.primary_phone);
} else {
out.write(StringEscapeUtils.escapeHtml(requester.name)+"</td>");
}
out.write("</td>");
} else {
out.write("<td><span class=\"label label-warning\">Unconfirmed</span> "+rec.requester_name+"</td>");
}
} catch (SQLException e1) {
out.write("<td>(sql error)</td>");
}
out.write("</tr>");
out.write("<tr>");
out.write("<th>Requested Time</th>");
out.write("<td>"+dformat.format(rec.request_time)+"</td>");
out.write("</tr>");
out.write("<tr>");
out.write("<th>Grid Admins</th>");
out.write("<td>");
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
try {
ArrayList<ContactRecord> gas = model.findGridAdmin(rec);
out.write("<ul>");
for(ContactRecord ga : gas) {
out.write("<li>");
out.write("<b>"+StringEscapeUtils.escapeHtml(ga.name)+"</b>");
if(auth.isUser()) {
out.write(" <code><a href=\"mailto:"+ga.primary_email+"\">"+ga.primary_email+"</a></code>");
out.write(" Phone: "+ga.primary_phone);
}
out.write("</li>");
}
out.write("</ul>");
} catch (CertificateRequestException e) {
out.write("<span class=\"label label-important\">No GridAdmin</span>");
}
out.write("</td></tr>");
out.write("<tr>");
out.write("<th>GOC Ticket</th>");
out.write("<td><a target=\"_blank\" href=\""+StaticConfig.conf.getProperty("url.gocticket")+"/"+rec.goc_ticket_id+"\">"+rec.goc_ticket_id+"</a></td>");
out.write("</tr>");
out.write("<tr>");
out.write("<th>FQDNs</th>");
out.write("<td>");
String[] cns = rec.getCNs();
String[] serial_ids = null;
if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
serial_ids = rec.getSerialIDs();
}
out.write("<table class=\"table table-bordered table-striped\">");
out.write("<thead><tr><th>CN</th><th colspan=\"1\">Certificates</th><th>Serial Number</th></tr></thead>");
int i = 0;
out.write("<tbody>");
for(String cn : cns) {
out.write("<tr>");
out.write("<th>"+StringEscapeUtils.escapeHtml(cn)+"</th>");
if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
//out.write("<td><a href=\"certificatedownload?id="+rec.id+"&type=host&download=pkcs7&idx="+i+"\">Download PKCS7</a></td>");
out.write("<td><a href=\"certificatedownload?id="+rec.id+"&type=host&download=pem&idx="+i+"\">Download PEM</a></td>");
out.write("<td>"+serial_ids[i]+"</td>");
} else {
out.write("<td colspan=\"3\"><span class=\"muted\">Not yet issued</span></td>");
}
out.write("</tr>");
++i;
}
out.write("</tbody></table>");
out.write("</td>");
out.write("</tr>");
out.write("<tr>");
out.write("<th>Next Action</th>");
out.write("<td>");
GenericView action_control = nextActionControl(context, rec);
action_control.render(out);
out.write("</td>");
out.write("</tr>");
out.write("</tbody>");
out.write("</table>");
}
public void renderLog(PrintWriter out) {
//logs
out.write("<h2>Log</h2>");
out.write("<table class=\"table nohover\">");
out.write("<thead><tr><th>By</th><th>IP</th><th>Status</th><th>Note</th><th>Timestamp</th></tr></thead>");
out.write("<tbody>");
boolean latest = true;
for(CertificateRequestModelBase<CertificateRequestHostRecord>.LogDetail log : logs) {
if(latest) {
out.write("<tr class=\"latest\">");
latest = false;
} else {
out.write("<tr>");
}
if(log.contact != null) {
out.write("<td>"+StringEscapeUtils.escapeHtml(log.contact.name)+"</td>");
} else {
out.write("<td>(Guest)</td>");
}
out.write("<td>"+log.ip+"</td>");
out.write("<td>"+log.status+"</td>");
out.write("<td>"+StringEscapeUtils.escapeHtml(log.comment)+"</td>");
out.write("<td>"+dformat.format(log.time)+"</td>");
out.write("</tr>");
}
out.write("</tbody>");
out.write("</table>");
}
};
}
protected GenericView nextActionControl(final UserContext context, final CertificateRequestHostRecord rec) {
GenericView v = new GenericView();
if(rec.status.equals(CertificateRequestStatus.REQUESTED) ||
rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED)) {
v.add(new HtmlView("<p class=\"alert alert-info\">GridAdmin to approve request</p>"));
} else if(rec.status.equals(CertificateRequestStatus.APPROVED)) {
v.add(new HtmlView("<p class=\"alert alert-info\">Requester to issue certificate & download</p>"));
} else if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
v.add(new HtmlView("<p class=\"alert alert-info\">Requester to download certificate</p>"));
} else if(rec.status.equals(CertificateRequestStatus.REJECTED) ||
rec.status.equals(CertificateRequestStatus.REVOKED) ||
rec.status.equals(CertificateRequestStatus.EXPIRED)
) {
v.add(new HtmlView("<p class=\"alert alert-info\">No further action.</p>"));
} else if(rec.status.equals(CertificateRequestStatus.FAILED)) {
v.add(new HtmlView("<p class=\"alert alert-info\">GOC engineer to troubleshoot & resubmit</p>"));
} else if(rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
v.add(new HtmlView("<p class=\"alert alert-info\">GridAdmin to revoke certificates</p>"));
} else if(rec.status.equals(CertificateRequestStatus.ISSUING)) {
v.add(new HtmlView("<p class=\"alert alert-info\">Please wait for a minute for signer to sign.</p>"));
}
final String url = "certificatehost?id="+rec.id;
final DivRepTextArea note = new DivRepTextArea(context.getPageRoot());
note.setLabel("Action Note");
note.setRequired(true);
note.setHidden(true);
v.add(note);
//controls
final CertificateRequestHostModel model = new CertificateRequestHostModel(context);
if(model.canApprove(rec)) {
final DivRepButton button = new DivRepButton(context.getPageRoot(), "<button class=\"btn btn-primary\"><i class=\"icon-ok icon-white\"></i> Approve</button>");
button.setStyle(DivRepButton.Style.HTML);
button.addClass("inline");
button.addEventListener(new DivRepEventListener() {
public void handleEvent(DivRepEvent e) {
if(note.validate()) {
context.setComment(note.getValue());
try {
model.approve(rec);
button.redirect(url);
} catch (CertificateRequestException e1) {
log.error("Failed to approve host certificate", e1);
button.alert(e1.toString());
}
}
}
});
note.setHidden(false);
v.add(button);
}
if(model.canRequestRenew(rec)) {
final DivRepButton button = new DivRepButton(context.getPageRoot(), "<button class=\"btn btn-primary\"><i class=\"icon-refresh icon-white\"></i> Request Renew</button>");
button.setStyle(DivRepButton.Style.HTML);
button.addClass("inline");
button.addEventListener(new DivRepEventListener() {
public void handleEvent(DivRepEvent e) {
if(note.validate()) {
context.setComment(note.getValue());
try {
model.requestRenew(rec);
button.redirect(url);
} catch (CertificateRequestException e1) {
button.alert("Failed to request renewal");
}
}
}
});
v.add(button);
note.setHidden(false);
}
if(model.canRequestRevoke(rec)) {
final DivRepButton button = new DivRepButton(context.getPageRoot(), "<button class=\"btn btn-primary\"><i class=\"icon-exclamation-sign icon-white\"></i> Request Revocation</button>");
button.setStyle(DivRepButton.Style.HTML);
button.addClass("inline");
button.addEventListener(new DivRepEventListener() {
public void handleEvent(DivRepEvent e) {
if(note.validate()) {
context.setComment(note.getValue());
try {
model.requestRevoke(rec);
button.redirect(url);
} catch (CertificateRequestException e1) {
button.alert("Failed to request revoke request");
}
}
}
});
v.add(button);
note.setHidden(false);
}
if(model.canIssue(rec)) {
//Authorization auth = context.getAuthorization();
final DivRepButton button = new DivRepButton(context.getPageRoot(), "<button class=\"btn btn-primary\"><i class=\"icon-download-alt icon-white\"></i> Issue Certificates</button>");
button.setStyle(DivRepButton.Style.HTML);
button.addClass("inline");
button.addEventListener(new DivRepEventListener() {
public void handleEvent(DivRepEvent e) {
try {
model.startissue(rec);
button.redirect(url);
} catch(CertificateRequestException ex) {
log.warn("CertificateRequestException while issuging certificate:", ex);
button.alert(ex.getMessage());
}
}
});
v.add(button);
}
if(model.canCancel(rec)) {
final DivRepButton button = new DivRepButton(context.getPageRoot(), "<button class=\"btn\">Cancel Request</button>");
button.setStyle(DivRepButton.Style.HTML);
button.addClass("inline");
button.addEventListener(new DivRepEventListener() {
public void handleEvent(DivRepEvent e) {
context.setComment(note.getValue());
try {
model.cancel(rec);
button.redirect(url);
} catch (CertificateRequestException e1) {
button.alert("Failed to cancel request");
}
}
});
v.add(button);
}
if(model.canReject(rec)) {
final DivRepButton button = new DivRepButton(context.getPageRoot(), "<button class=\"btn btn-danger\"><i class=\"icon-remove icon-white\"></i> Reject Request</button>");
button.setStyle(DivRepButton.Style.HTML);
button.addClass("inline");
button.addEventListener(new DivRepEventListener() {
public void handleEvent(DivRepEvent e) {
if(note.validate()) {
context.setComment(note.getValue());
try {
model.reject(rec);
button.redirect(url);
} catch (CertificateRequestException e1) {
button.alert("Failed to reject request");
}
}
}
});
v.add(button);
note.setHidden(false);
}
if(model.canRevoke(rec)) {
final DivRepButton button = new DivRepButton(context.getPageRoot(), "<button class=\"btn btn-danger\"><i class=\"icon-exclamation-sign icon-white\"></i> Revoke</button>");
button.setStyle(DivRepButton.Style.HTML);
button.addClass("inline");
button.addEventListener(new DivRepEventListener() {
public void handleEvent(DivRepEvent e) {
if(note.validate()) {
context.setComment(note.getValue());
try {
model.revoke(rec);
button.redirect(url);
} catch (CertificateRequestException e1) {
button.alert("Failed to cancel request");
}
}
}
});
v.add(button);
note.setHidden(false);
}
return v;
}
protected IView createListView(final UserContext context) throws ServletException
{
final Authorization auth = context.getAuthorization();
final SimpleDateFormat dformat = new SimpleDateFormat();
dformat.setTimeZone(auth.getTimeZone());
/*
class IDForm extends DivRep {
final DivRepTextBox id;
final DivRepButton open;
public IDForm(DivRep parent) {
super(parent);
id = new DivRepTextBox(this);
//id.setLabel("Open by Request ID");
id.setWidth(150);
open = new DivRepButton(this, "Open");
open.addEventListener(new DivRepEventListener() {
@Override
public void handleEvent(DivRepEvent e) {
if(id.getValue() == null || id.getValue().trim().isEmpty()) {
alert("Please enter request ID to open");
} else {
redirect("certificatehost?id="+id.getValue());
}
}
});
open.addClass("btn");
}
@Override
public void render(PrintWriter out) {
out.write("<div id=\""+getNodeID()+"\" class=\"pull-right\">");
//out.write("<p>Please enter host certificate request ID to view details</p>");
out.write("<table><tr>");
out.write("<td>Open By Request ID </td>");
out.write("<td>");
id.render(out);
out.write("</td>");
out.write("<td style=\"vertical-align: top;\">");
open.render(out);
out.write("</td>");
out.write("</tr></table>");
out.write("</div>");
}
@Override
protected void onEvent(DivRepEvent e) {
// TODO Auto-generated method stub
}
};
*/
return new IView(){
@Override
public void render(PrintWriter out) {
out.write("<div id=\"content\">");
out.write("<div class=\"row-fluid\">");
out.write("<div class=\"span3\">");
CertificateMenuView menu = new CertificateMenuView(context, "certificatehost");
menu.render(out);
out.write("</div>"); //span3
out.write("<div class=\"span9\">");
/*
IDForm form = new IDForm(context.getPageRoot());
form.render(out);
*/
if(auth.isUser()) {
renderMyList(out);
}
out.write("</div>"); //span9
out.write("</div>"); //row-fluid
}
public void renderMyList(PrintWriter out) {
CertificateRequestHostModel model = new CertificateRequestHostModel(context);
try {
ArrayList<CertificateRequestHostRecord> recs = model.getIApprove(auth.getContact().id);
if(recs.size() != 0) {
out.write("<h2>Host Certificate Requests that I Approve</h2>");
HostCertificateTable table = new HostCertificateTable(context, recs, false);
table.render(out);
}
} catch (SQLException e1) {
out.write("<div class=\"alert\">Failed to load host certificate requests that I am gridadmin of</div>");
log.error(e1);
}
try {
ArrayList<CertificateRequestHostRecord> recs = model.getISubmitted(auth.getContact().id);
if(recs.size() == 0) {
out.write("<p class=\"muted\">You have not requested any host certificate.</p>");
} else {
out.write("<h2>Host Certificate Requests that I Requested</h2>");
HostCertificateTable table = new HostCertificateTable(context, recs, false);
table.render(out);
}
} catch (SQLException e1) {
out.write("<div class=\"alert\">Failed to load my user certificate requests</div>");
log.error(e1);
}
out.write("</div>");//content
}
};
}
}
|
/**
* ViewSimScreen
*
* Class representing the screen that displays the grid as
* the simulation runs.
*
* @author Willy McHie and Ian Walling
* Wheaton College, CSCI 335, Spring 2013
*/
package edu.wheaton.simulator.gui.screen;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import edu.wheaton.simulator.gui.BoxLayoutAxis;
import edu.wheaton.simulator.gui.GeneralButtonListener;
import edu.wheaton.simulator.gui.Gui;
import edu.wheaton.simulator.gui.MaxSize;
import edu.wheaton.simulator.gui.PrefSize;
import edu.wheaton.simulator.gui.ScreenManager;
import edu.wheaton.simulator.gui.SimulatorFacade;
public class ViewSimScreen extends Screen {
private static final long serialVersionUID = -6872689283286800861L;
private GridBagConstraints c;
private boolean canSpawn;
private final EntityScreen entitiesScreen;
private final Screen layerScreen;
private final Screen globalFieldScreen;
private final Screen optionsScreen;
public ViewSimScreen(final SimulatorFacade gm) {
super(gm);
setSpawn(false);
this.setLayout(new GridBagLayout());
((GridBagLayout)this.getLayout()).columnWeights = new double[]{0, 1};
final JTabbedPane tabs = new JTabbedPane();
tabs.setMaximumSize(new Dimension(550, 550));
entitiesScreen = new EntityScreen(gm);
layerScreen = new LayerScreen(gm);
globalFieldScreen = new FieldScreen(gm);
optionsScreen = new SetupScreen(gm);
tabs.addTab("Agent", entitiesScreen);
tabs.addTab("Layers", layerScreen);
tabs.addTab("Global Fields", globalFieldScreen);
tabs.addTab("Options", optionsScreen);
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
if (tabs.getSelectedComponent().toString() == "Agent")
canSpawn = true;
else {
canSpawn = false;
}
entitiesScreen.load();
layerScreen.load();
globalFieldScreen.load();
optionsScreen.load();
}
});
gm.getGridPanel().addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent me) {
if (getGuiManager().canSpawn()) {
int standardSize = Math.min(gm.getGridPanel().getWidth()
/ gm.getGridWidth(), gm.getGridPanel()
.getHeight() / gm.getGridHeight());
int x = me.getX() / standardSize;
int y = me.getY() / standardSize;
if (canSpawn) {
if (gm.getAgent(x, y) == null) {
gm.addAgent(entitiesScreen.getList()
.getSelectedValue().toString(), x, y);
} else {
gm.removeAgent(x, y);
}
}
gm.getGridPanel().repaint();
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 2;
c.weightx = 0;
c.insets = new Insets(5, 5, 5, 5);
this.add(tabs, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.gridy = 0;
c.ipadx = 600;
c.ipady = 600;
c.gridwidth = 2;
c.weighty = 1;
c.weightx = 1;
c.insets = new Insets(5, 5, 5, 5);
this.add(gm.getGridPanel(), c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 2;
this.add(makeButtonPanel(), c);
this.setVisible(true);
}
private JPanel makeButtonPanel() {
// TODO most of these will become tabs, adding temporarily for
// navigation purposes
ScreenManager sm = getScreenManager();
JPanel buttonPanel = Gui.makePanel((LayoutManager) null, new MaxSize(
500, 50), PrefSize.NULL, makeStartButton(), Gui.makeButton(
"Pause", null, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getGuiManager().pause();
canSpawn = true;
}
}), Gui.makeButton("Statistics", null,
new GeneralButtonListener("Statistics", sm)));
return buttonPanel;
}
public void setSpawn(boolean canSpawn) {
this.canSpawn = canSpawn;
}
private JButton makeStartButton() {
JButton b = Gui.makeButton("Start/Resume", null, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SimulatorFacade gm = getGuiManager();
canSpawn = false;
gm.getGridPanel().repaint();
gm.start();
}
});
return b;
}
@Override
public void load() {
entitiesScreen.load();
layerScreen.load();
globalFieldScreen.load();
optionsScreen.load();
validate();
getGuiManager().getGridPanel().repaint();
}
}
|
package org.voltdb.compiler;
import org.hsqldb_voltpatches.HSQLInterface;
import org.hsqldb_voltpatches.HSQLInterface.HSQLParseException;
import org.voltcore.logging.VoltLogger;
import org.voltdb.ParameterSet;
import org.voltdb.VoltDB;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Database;
import org.voltdb.planner.CompiledPlan;
import org.voltdb.planner.CorePlan;
import org.voltdb.planner.PartitioningForStatement;
import org.voltdb.planner.QueryPlanner;
import org.voltdb.planner.TrivialCostModel;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.utils.Encoder;
/**
* Planner tool accepts an already compiled VoltDB catalog and then
* interactively accept SQL and outputs plans on standard out.
*/
public class PlannerTool {
private static final VoltLogger hostLog = new VoltLogger("HOST");
final Database m_database;
final Cluster m_cluster;
final HSQLInterface m_hsql;
final int m_catalogVersion;
final AdHocCompilerCache m_cache;
public static final int AD_HOC_JOINED_TABLE_LIMIT = 5;
public PlannerTool(final Cluster cluster, final Database database, int catalogVersion) {
assert(cluster != null);
assert(database != null);
m_database = database;
m_cluster = cluster;
m_catalogVersion = catalogVersion;
m_cache = AdHocCompilerCache.getCacheForCatalogVersion(catalogVersion);
// LOAD HSQL
m_hsql = HSQLInterface.loadHsqldb();
String hexDDL = m_database.getSchema();
String ddl = Encoder.hexDecodeToString(hexDDL);
String[] commands = ddl.split("\n");
for (String command : commands) {
String decoded_cmd = Encoder.hexDecodeToString(command);
decoded_cmd = decoded_cmd.trim();
if (decoded_cmd.length() == 0)
continue;
try {
m_hsql.runDDLCommand(decoded_cmd);
}
catch (HSQLParseException e) {
// need a good error message here
throw new RuntimeException("Error creating hsql: " + e.getMessage() + " in DDL statement: " + decoded_cmd);
}
}
hostLog.info("hsql loaded");
}
public AdHocPlannedStatement planSql(String sqlIn, Object partitionParam, boolean inferSP, boolean allowParameterization) {
if ((sqlIn == null) || (sqlIn.length() == 0)) {
throw new RuntimeException("Can't plan empty or null SQL.");
}
// remove any spaces or newlines
String sql = sqlIn.trim();
hostLog.debug("received sql stmt: " + sql);
// no caching for forced single or forced multi SQL
boolean cacheable = (partitionParam == null) && (inferSP);
// check the literal cache for a match
if (cacheable) {
AdHocPlannedStatement cachedPlan = m_cache.getWithSQL(sqlIn);
if (cachedPlan != null) {
return cachedPlan;
}
}
//Reset plan node id counter
AbstractPlanNode.resetPlanNodeIds();
// PLAN THE STMT
TrivialCostModel costModel = new TrivialCostModel();
PartitioningForStatement partitioning = new PartitioningForStatement(partitionParam, inferSP, inferSP);
QueryPlanner planner = new QueryPlanner(
sql, "PlannerTool", "PlannerToolProc", m_cluster, m_database,
partitioning, m_hsql, new DatabaseEstimates(), true,
AD_HOC_JOINED_TABLE_LIMIT, costModel, null, null);
CompiledPlan plan = null;
String parsedToken = null;
try {
planner.parse();
parsedToken = planner.parameterize();
if (parsedToken != null) {
// if cacheable, check the cache for a matching pre-parameterized plan
// if plan found, build the full plan using the parameter data in the
// QueryPlanner.
if (cacheable) {
CorePlan core = m_cache.getWithParsedToken(parsedToken);
if (core != null) {
ParameterSet params = new ParameterSet();
planner.buildParameterSetFromExtractedLiteralsAndReturnPartitionIndex(
core.parameterTypes, params);
Object partitionKey = null;
if (core.partitioningParamIndex >= 0) {
partitionKey = params.toArray()[core.partitioningParamIndex];
}
AdHocPlannedStatement ahps = new AdHocPlannedStatement(sql.getBytes(VoltDB.UTF8ENCODING),
core,
params,
partitionKey);
m_cache.put(sql, parsedToken, ahps);
return ahps;
}
}
// if not cacheable or no cach hit, do the expensive full planning
plan = planner.plan();
assert(plan != null);
}
} catch (Exception e) {
throw new RuntimeException("Error compiling query: " + e.getMessage(), e);
}
if (!allowParameterization &&
(plan.extractedParamValues.size() == 0) &&
(plan.parameters.length > 0))
{
throw new RuntimeException("ERROR: PARAMETERIZATION IN AD HOC QUERY");
}
if (plan.isContentDeterministic() == false) {
String potentialErrMsg =
"Statement has a non-deterministic result - statement: \"" +
sql + "\" , reason: " + plan.nondeterminismDetail();
// throw new RuntimeException(potentialErrMsg);
hostLog.warn(potentialErrMsg);
}
// OUTPUT THE RESULT
AdHocPlannedStatement ahps = new AdHocPlannedStatement(plan, m_catalogVersion);
if (cacheable && planner.compiledAsParameterizedPlan()) {
assert(parsedToken != null);
assert(((ahps.partitionParam == null) && (ahps.core.partitioningParamIndex == -1)) ||
((ahps.partitionParam != null) && (ahps.core.partitioningParamIndex >= 0)));
m_cache.put(sqlIn, parsedToken, ahps);
}
return ahps;
}
}
|
package autobahn.encoder;
import java.io.IOException;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyObject;
import org.jruby.RubyHash;
import org.jruby.RubyString;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import static org.jruby.runtime.Visibility.*;
import org.msgpack.jruby.RubyObjectPacker;
import org.msgpack.jruby.RubyObjectUnpacker;
import org.msgpack.MessagePack;
import org.msgpack.packer.BufferPacker;
import org.msgpack.packer.Packer;
import com.ning.compress.lzf.LZFEncoder;
import com.ning.compress.lzf.LZFDecoder;
@JRubyClass(name="Autobahn::MsgPackLzfEncoder")
public class MsgPackLzfEncoder extends RubyObject {
private final MessagePack msgPack;
private final RubyObjectUnpacker unpacker;
private final RubyHash properties;
public MsgPackLzfEncoder(Ruby runtime, RubyClass type) {
super(runtime, type);
this.msgPack = new MessagePack();
this.unpacker = new RubyObjectUnpacker(msgPack);
this.properties = RubyHash.newHash(runtime);
this.properties.put(runtime.newSymbol("content_type"), runtime.newString("application/msgpack"));
this.properties.put(runtime.newSymbol("content_encoding"), runtime.newString("lzf"));
}
@JRubyMethod(name = "initialize", visibility = PRIVATE)
public IRubyObject initialize(ThreadContext ctx) {
return this;
}
public byte[] encodeRaw(IRubyObject obj) throws IOException {
// TODO: move into msgpack-jruby, make a method that returns byte[]
BufferPacker bufferedPacker = msgPack.createBufferPacker();
Packer packer = new RubyObjectPacker(msgPack, bufferedPacker).write(obj);
byte[] packed = bufferedPacker.toByteArray();
byte[] compressed = LZFEncoder.encode(packed);
return compressed;
}
@JRubyMethod(required = 1)
public IRubyObject encode(ThreadContext ctx, IRubyObject obj) throws IOException {
return RubyString.newString(ctx.getRuntime(), encodeRaw(obj));
}
@JRubyMethod(required = 1)
public IRubyObject decode(ThreadContext ctx, IRubyObject str) throws IOException {
// TODO: move into msgpack-jruby, make a method that takes byte[]
byte[] compressed = str.asString().getBytes();
byte[] packed = LZFDecoder.decode(compressed);
return unpacker.unpack(ctx.getRuntime(), packed);
}
@JRubyMethod(name = "properties")
public IRubyObject getProperties(ThreadContext ctx) {
return properties;
}
public static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass type) {
return new MsgPackLzfEncoder(runtime, type);
}
};
}
|
package jolie.net;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.Interpreter;
import jolie.lang.Constants;
import jolie.lang.NativeType;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.Method;
import jolie.net.http.MultiPartFormDataParser;
import jolie.net.http.json.JsonUtils;
import jolie.net.ports.Interface;
import jolie.net.protocols.CommProtocol;
import jolie.runtime.ByteArray;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.OperationTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.runtime.typing.TypeCastingException;
import jolie.util.LocationParser;
import jolie.xml.XmlUtils;
import joliex.gwt.client.JolieService;
import joliex.gwt.server.JolieGWTConverter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* HTTP protocol implementation
* @author Fabrizio Montesi
* 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status codes
*/
public class HttpProtocol extends CommProtocol
{
private static final int DEFAULT_STATUS_CODE = 200;
private static final int DEFAULT_REDIRECTION_STATUS_CODE = 303;
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; // default content type per RFC 2616#7.2.1
private static final Map< Integer, String > statusCodeDescriptions = new HashMap< Integer, String >();
private static final Set< Integer > locationRequiredStatusCodes = new HashSet< Integer >();
static {
locationRequiredStatusCodes.add( 301 );
locationRequiredStatusCodes.add( 302 );
locationRequiredStatusCodes.add( 303 );
locationRequiredStatusCodes.add( 307 );
locationRequiredStatusCodes.add( 308 );
}
static {
// Initialise the HTTP Status code map.
statusCodeDescriptions.put( 100,"Continue" );
statusCodeDescriptions.put( 101,"Switching Protocols" );
statusCodeDescriptions.put( 102,"Processing" );
statusCodeDescriptions.put( 200,"OK" );
statusCodeDescriptions.put( 201,"Created" );
statusCodeDescriptions.put( 202,"Accepted" );
statusCodeDescriptions.put( 203,"Non-Authoritative Information" );
statusCodeDescriptions.put( 204,"No Content" );
statusCodeDescriptions.put( 205,"Reset Content" );
statusCodeDescriptions.put( 206,"Partial Content" );
statusCodeDescriptions.put( 207,"Multi-Status" );
statusCodeDescriptions.put( 208,"Already Reported" );
statusCodeDescriptions.put( 226,"IM Used" );
statusCodeDescriptions.put( 300,"Multiple Choices" );
statusCodeDescriptions.put( 301,"Moved Permanently" );
statusCodeDescriptions.put( 302,"Found" );
statusCodeDescriptions.put( 303,"See Other" );
statusCodeDescriptions.put( 304,"Not Modified" );
statusCodeDescriptions.put( 305,"Use Proxy" );
statusCodeDescriptions.put( 306,"Reserved" );
statusCodeDescriptions.put( 307,"Temporary Redirect" );
statusCodeDescriptions.put( 308,"Permanent Redirect" );
statusCodeDescriptions.put( 400,"Bad Request" );
statusCodeDescriptions.put( 401,"Unauthorized" );
statusCodeDescriptions.put( 402,"Payment Required" );
statusCodeDescriptions.put( 403,"Forbidden" );
statusCodeDescriptions.put( 404,"Not Found" );
statusCodeDescriptions.put( 405,"Method Not Allowed" );
statusCodeDescriptions.put( 406,"Not Acceptable" );
statusCodeDescriptions.put( 407,"Proxy Authentication Required" );
statusCodeDescriptions.put( 408,"Request Timeout" );
statusCodeDescriptions.put( 409,"Conflict" );
statusCodeDescriptions.put( 410,"Gone" );
statusCodeDescriptions.put( 411,"Length Required" );
statusCodeDescriptions.put( 412,"Precondition Failed" );
statusCodeDescriptions.put( 413,"Request Entity Too Large" );
statusCodeDescriptions.put( 414,"Request-URI Too Long" );
statusCodeDescriptions.put( 415,"Unsupported Media Type" );
statusCodeDescriptions.put( 416,"Requested Range Not Satisfiable" );
statusCodeDescriptions.put( 417,"Expectation Failed" );
statusCodeDescriptions.put( 422,"Unprocessable Entity" );
statusCodeDescriptions.put( 423,"Locked" );
statusCodeDescriptions.put( 424,"Failed Dependency" );
statusCodeDescriptions.put( 426,"Upgrade Required" );
statusCodeDescriptions.put( 427,"Unassigned" );
statusCodeDescriptions.put( 428,"Precondition Required" );
statusCodeDescriptions.put( 429,"Too Many Requests" );
statusCodeDescriptions.put( 430,"Unassigned" );
statusCodeDescriptions.put( 431,"Request Header Fields Too Large" );
statusCodeDescriptions.put( 500,"Internal Server Error" );
statusCodeDescriptions.put( 501,"Not Implemented" );
statusCodeDescriptions.put( 502,"Bad Gateway" );
statusCodeDescriptions.put( 503,"Service Unavailable" );
statusCodeDescriptions.put( 504,"Gateway Timeout" );
statusCodeDescriptions.put( 505,"HTTP Version Not Supported" );
statusCodeDescriptions.put( 507,"Insufficient Storage" );
statusCodeDescriptions.put( 508,"Loop Detected" );
statusCodeDescriptions.put( 509,"Unassigned" );
statusCodeDescriptions.put( 510,"Not Extended" );
statusCodeDescriptions.put( 511,"Network Authentication Required" );
}
private static class Parameters {
private static final String KEEP_ALIVE = "keepAlive";
private static final String DEBUG = "debug";
private static final String COOKIES = "cookies";
private static final String METHOD = "method";
private static final String ALIAS = "alias";
private static final String MULTIPART_HEADERS = "multipartHeaders";
private static final String CONCURRENT = "concurrent";
private static final String USER_AGENT = "userAgent";
private static final String HOST = "host";
private static final String HEADERS = "headers";
private static final String ADD_HEADERS = "addHeader";
private static final String STATUS_CODE = "statusCode";
private static final String REDIRECT = "redirect";
private static final String DEFAULT_OPERATION = "default";
private static final String COMPRESSION = "compression";
private static final String COMPRESSION_TYPES = "compressionTypes";
private static final String REQUEST_COMPRESSION = "requestCompression";
private static final String FORMAT = "format";
private static final String CHARSET = "charset";
private static final String CONTENT_TYPE = "contentType";
private static final String CONTENT_TRANSFER_ENCODING = "contentTransferEncoding";
private static final String CONTENT_DISPOSITION = "contentDisposition";
private static class MultiPartHeaders {
private static final String FILENAME = "filename";
}
}
private static class Headers {
private static final String JOLIE_MESSAGE_ID = "X-Jolie-MessageID";
}
private String inputId = null;
private final Transformer transformer;
private final DocumentBuilderFactory docBuilderFactory;
private final DocumentBuilder docBuilder;
private final URI uri;
private final boolean inInputPort;
private MultiPartFormDataParser multiPartFormDataParser = null;
public String name()
{
return "http";
}
public boolean isThreadSafe()
{
return checkBooleanParameter( Parameters.CONCURRENT );
}
public HttpProtocol(
VariablePath configurationPath,
URI uri,
boolean inInputPort,
TransformerFactory transformerFactory,
DocumentBuilderFactory docBuilderFactory,
DocumentBuilder docBuilder
)
throws TransformerConfigurationException
{
super( configurationPath );
this.uri = uri;
this.inInputPort = inInputPort;
this.transformer = transformerFactory.newTransformer();
this.docBuilderFactory = docBuilderFactory;
this.docBuilder = docBuilder;
transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
}
private void valueToDocument(
Value value,
Node node,
Document doc
)
{
node.appendChild( doc.createTextNode( value.strValue() ) );
Element currentElement;
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
for( Value val : entry.getValue() ) {
currentElement = doc.createElement( entry.getKey() );
node.appendChild( currentElement );
Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val );
if ( attrs != null ) {
for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) {
currentElement.setAttribute(
attrEntry.getKey(),
attrEntry.getValue().first().strValue()
);
}
}
valueToDocument( val, currentElement, doc );
}
}
}
}
public String getMultipartHeaderForPart( String operationName, String partName )
{
if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) {
Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS );
if ( v.hasChildren( partName ) ) {
v = v.getFirstChild( partName );
if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) {
v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME );
return v.strValue();
}
}
}
return null;
}
private final static String BOUNDARY = "----Jol13H77p77Bound4r155";
private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
String domain;
StringBuilder cookieSB = new StringBuilder();
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "";
if ( domain.isEmpty() || hostname.endsWith( domain ) ) {
cookieSB
.append( entry.getKey() )
.append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( ";" );
}
}
}
if ( cookieSB.length() > 0 ) {
headerBuilder
.append( "Cookie: " )
.append( cookieSB )
.append( HttpUtils.CRLF );
}
}
}
private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
headerBuilder
.append( "Set-Cookie: " )
.append( entry.getKey() ).append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( "; expires=" )
.append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" )
.append( "; domain=" )
.append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" )
.append( "; path=" )
.append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" );
if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) {
headerBuilder.append( "; secure" );
}
headerBuilder.append( HttpUtils.CRLF );
}
}
}
}
private String encoding = null;
private String requestFormat = null;
private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
if ( value.children().isEmpty() == false ) {
headerBuilder.append( '?' );
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
for( Value v : entry.getValue() ) {
headerBuilder
.append( entry.getKey() )
.append( '=' )
.append( URLEncoder.encode( v.strValue(), charset ) )
.append( '&' );
}
}
}
}
private void send_appendJsonQueryString( CommMessage message, String charset, StringBuilder headerBuilder )
throws IOException
{
if ( message.value().hasChildren() == false ) {
headerBuilder.append( "?=" );
JsonUtils.valueToJsonString( message.value(), getSendType( message ), headerBuilder );
}
}
private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
int offset = 0;
ArrayList<String> aliasKeys = new ArrayList<String>();
String currStrValue;
String currKey;
StringBuilder result = new StringBuilder( alias );
Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias );
while( m.find() ) {
if ( m.group( 1 ) == null ) { // We have to use URLEncoder
currKey = alias.substring( m.start() + 2, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = URLEncoder.encode( value.strValue(), charset );
} else {
currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset );
aliasKeys.add( currKey );
}
} else { // We have to insert the string raw
currKey = alias.substring( m.start() + 3, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = value.strValue();
} else {
currStrValue = value.getFirstChild( currKey ).strValue();
aliasKeys.add( currKey );
}
}
result.replace(
m.start() + offset, m.end() + offset,
currStrValue
);
offset += currStrValue.length() - 3 - currKey.length();
}
// removing used keys
for( int k = 0; k < aliasKeys.size(); k++ ) {
value.children().remove( aliasKeys.get( k ) );
}
headerBuilder.append( result );
}
private String send_getFormat()
{
String format = "xml";
if ( inInputPort && requestFormat != null ) {
format = requestFormat;
requestFormat = null;
} else if ( hasParameter( Parameters.FORMAT ) ) {
format = getStringParameter( Parameters.FORMAT );
}
return format;
}
private static class EncodedContent {
private ByteArray content = null;
private String contentType = DEFAULT_CONTENT_TYPE;
private String contentDisposition = "";
}
private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format )
throws IOException
{
EncodedContent ret = new EncodedContent();
if ( inInputPort == false && method == Method.GET ) {
// We are building a GET request
return ret;
}
if ( "xml".equals( format ) ) {
ret.contentType = "text/xml";
Document doc = docBuilder.newDocument();
Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") );
doc.appendChild( root );
if ( message.isFault() ) {
Element faultElement = doc.createElement( message.fault().faultName() );
root.appendChild( faultElement );
valueToDocument( message.fault().value(), faultElement, doc );
} else {
valueToDocument( message.value(), root, doc );
}
Source src = new DOMSource( doc );
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
Result dest = new StreamResult( tmpStream );
try {
transformer.transform( src, dest );
} catch( TransformerException e ) {
throw new IOException( e );
}
ret.content = new ByteArray( tmpStream.toString().getBytes( charset ) );
} else if ( "binary".equals( format ) ) {
if ( message.value().isByteArray() ) {
ret.content = (ByteArray) message.value().valueObject();
ret.contentType = "application/octet-stream";
}
} else if ( "html".equals( format ) ) {
ret.contentType = "text/html";
if ( message.isFault() ) {
StringBuilder builder = new StringBuilder();
builder.append( "<html><head><title>" );
builder.append( message.fault().faultName() );
builder.append( "</title></head><body>" );
builder.append( message.fault().value().strValue() );
builder.append( "</body></html>" );
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
}
} else if ( "multipart/form-data".equals( format ) ) {
ret.contentType = "multipart/form-data; boundary=" + BOUNDARY;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
StringBuilder builder = new StringBuilder();
for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
builder.append( "--" ).append( BOUNDARY ).append( HttpUtils.CRLF );
builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' );
boolean isBinary = false;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.MULTIPART_HEADERS ) ) {
Value specOpParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.MULTIPART_HEADERS );
if ( specOpParam.hasChildren( "partName" ) ) {
ValueVector partNames = specOpParam.getChildren( "partName" );
for( int p = 0; p < partNames.size(); p++ ) {
if ( partNames.get( p ).hasChildren( "part" ) ) {
if ( partNames.get( p ).getFirstChild( "part" ).strValue().equals( entry.getKey() ) ) {
isBinary = true;
if ( partNames.get( p ).hasChildren( "filename" ) ) {
builder.append( "; filename=\"" ).append( partNames.get( p ).getFirstChild( "filename" ).strValue() ).append( "\"" );
}
if ( partNames.get( p ).hasChildren( "contentType" ) ) {
builder.append( HttpUtils.CRLF ).append( "Content-Type:" ).append( partNames.get( p ).getFirstChild( "contentType" ).strValue() );
}
}
}
}
}
}
builder.append( HttpUtils.CRLF ).append( HttpUtils.CRLF );
if ( isBinary ) {
bStream.write( builder.toString().getBytes( charset ) );
bStream.write( entry.getValue().first().byteArrayValue().getBytes() );
builder.delete( 0, builder.length() - 1 );
builder.append( HttpUtils.CRLF );
} else {
builder.append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF );
}
}
}
builder.append( "--" + BOUNDARY + "--" );
bStream.write( builder.toString().getBytes( charset ));
ret.content = new ByteArray( bStream.toByteArray() );
} else if ( "x-www-form-urlencoded".equals( format ) ) {
ret.contentType = "application/x-www-form-urlencoded";
Iterator< Entry< String, ValueVector > > it =
message.value().children().entrySet().iterator();
StringBuilder builder = new StringBuilder();
if ( message.isFault() ) {
builder.append( "faultName=" );
builder.append( URLEncoder.encode( message.fault().faultName(), HttpUtils.URL_DECODER_ENC ) );
builder.append( "&data=" );
builder.append( URLEncoder.encode( message.fault().value().strValue(), HttpUtils.URL_DECODER_ENC ) );
} else {
Entry< String, ValueVector > entry;
while( it.hasNext() ) {
entry = it.next();
builder.append( entry.getKey() )
.append( "=" )
.append( URLEncoder.encode( entry.getValue().first().strValue(), HttpUtils.URL_DECODER_ENC ) );
if ( it.hasNext() ) {
builder.append( '&' );
}
}
}
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "text/x-gwt-rpc".equals( format ) ) {
ret.contentType = "text/x-gwt-rpc";
try {
if ( message.isFault() ) {
ret.content = new ByteArray(
RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset )
);
} else {
joliex.gwt.client.Value v = new joliex.gwt.client.Value();
JolieGWTConverter.jolieToGwtValue( message.value(), v );
ret.content = new ByteArray(
RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset )
);
}
} catch( SerializationException e ) {
throw new IOException( e );
}
} else if ( "json".equals( format ) || "application/json".equals( format ) ) {
ret.contentType = "application/json";
StringBuilder jsonStringBuilder = new StringBuilder();
if ( message.isFault() ) {
Value error = message.value().getFirstChild( "error" );
error.getFirstChild( "code" ).setValue( -32000 );
error.getFirstChild( "message" ).setValue( message.fault().faultName() );
error.getChildren( "data" ).set( 0, message.fault().value() );
}
JsonUtils.valueToJsonString( message.value(), getSendType( message ), jsonStringBuilder );
ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) );
} else if ( "raw".equals( format ) ) {
if ( message.isFault() ) {
ret.content = new ByteArray( message.fault().value().strValue().getBytes( charset ) );
} else {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
}
}
return ret;
}
private boolean isLocationNeeded( int statusCode )
{
return locationRequiredStatusCodes.contains( statusCode );
}
private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder )
{
int statusCode = DEFAULT_STATUS_CODE;
String statusDescription = null;
if( hasParameter( Parameters.STATUS_CODE ) ) {
statusCode = getIntParameter( Parameters.STATUS_CODE );
if ( !statusCodeDescriptions.containsKey( statusCode ) ) {
Interpreter.getInstance().logWarning( "HTTP protocol for operation " +
message.operationName() +
" is sending a message with status code " +
statusCode +
", which is not in the HTTP specifications."
);
statusDescription = "Internal Server Error";
} else if ( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) {
// if statusCode is a redirection code, location parameter is needed
Interpreter.getInstance().logWarning( "HTTP protocol for operation " +
message.operationName() +
" is sending a message with status code " +
statusCode +
", which expects a redirect parameter but the latter is not set."
);
}
} else if ( hasParameter( Parameters.REDIRECT ) ) {
statusCode = DEFAULT_REDIRECTION_STATUS_CODE;
}
if ( statusDescription == null ) {
statusDescription = statusCodeDescriptions.get( statusCode );
}
headerBuilder.append( "HTTP/1.1 " + statusCode + " " + statusDescription + HttpUtils.CRLF );
// if redirect has been set, the redirect location parameter is set
if ( hasParameter( Parameters.REDIRECT ) ) {
headerBuilder.append( "Location: " + getStringParameter( Parameters.REDIRECT ) + HttpUtils.CRLF );
}
send_appendSetCookieHeader( message, headerBuilder );
headerBuilder.append( "Server: Jolie" ).append( HttpUtils.CRLF );
StringBuilder cacheControlHeader = new StringBuilder();
if ( hasParameter( "cacheControl" ) ) {
Value cacheControl = getParameterFirstValue( "cacheControl" );
if ( cacheControl.hasChildren( "maxAge" ) ) {
cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() );
}
}
if ( cacheControlHeader.length() > 0 ) {
headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( HttpUtils.CRLF );
}
}
private void send_appendRequestMethod( Method method, StringBuilder headerBuilder )
{
headerBuilder.append( method.id() );
}
private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) {
headerBuilder.append( '/' );
}
headerBuilder.append( uri.getPath() );
if ( hasOperationSpecificParameter( message.operationName(), Parameters.ALIAS ) ) {
String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS );
send_appendParsedAlias( alias, message.value(), charset, headerBuilder );
} else {
headerBuilder.append( message.operationName() );
}
if ( method == Method.GET ) {
boolean jsonFormat = false;
if ( getParameterFirstValue( Parameters.METHOD ).hasChildren( "queryFormat" ) ) {
if ( getParameterFirstValue( Parameters.METHOD ).getFirstChild( "queryFormat" ).strValue().equals( "json" ) ) {
jsonFormat = true;
send_appendJsonQueryString( message, charset, headerBuilder );
}
}
if ( !jsonFormat ) {
send_appendQuerystring( message.value(), charset, headerBuilder );
}
}
}
private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder )
{
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) {
Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() );
//String realm = v.getFirstChild( "realm" ).strValue();
String userpass =
v.getFirstChild( "userid" ).strValue() + ":" +
v.getFirstChild( "password" ).strValue();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
userpass = encoder.encode( userpass.getBytes() );
headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( HttpUtils.CRLF );
}
}
private void send_appendHeader( CommMessage message, StringBuilder headerBuilder )
{
Value v = getParameterFirstValue( Parameters.ADD_HEADERS );
if ( v != null ) {
if ( v.hasChildren("header") ) {
for( Value head : v.getChildren("header") ) {
String header =
head.strValue() + ": " +
head.getFirstChild( "value" ).strValue();
headerBuilder.append( header ).append( HttpUtils.CRLF );
}
}
}
}
private Method send_getRequestMethod( CommMessage message )
throws IOException
{
Method method =
hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ?
Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() )
: hasParameter( Parameters.METHOD ) ?
Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() )
:
Method.POST;
return method;
}
private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
send_appendRequestMethod( method, headerBuilder );
headerBuilder.append( ' ' );
send_appendRequestPath( message, method, headerBuilder, charset );
headerBuilder.append( " HTTP/1.1" + HttpUtils.CRLF );
headerBuilder.append( "Host: " + uri.getHost() + HttpUtils.CRLF );
send_appendCookies( message, uri.getHost(), headerBuilder );
send_appendAuthorizationHeader( message, headerBuilder );
if ( checkBooleanParameter( Parameters.COMPRESSION, true ) ) {
String requestCompression = getStringParameter( Parameters.REQUEST_COMPRESSION );
if ( requestCompression.equals( "gzip" ) || requestCompression.equals( "deflate" ) ) {
encoding = requestCompression;
headerBuilder.append( "Accept-Encoding: " + encoding + HttpUtils.CRLF );
} else {
headerBuilder.append( "Accept-Encoding: gzip, deflate" + HttpUtils.CRLF );
}
}
send_appendHeader( message, headerBuilder );
}
private void send_appendGenericHeaders(
CommMessage message,
EncodedContent encodedContent,
String charset,
StringBuilder headerBuilder
)
throws IOException
{
if ( checkBooleanParameter( Parameters.KEEP_ALIVE, true ) == false || channel().toBeClosed() ) {
channel().setToBeClosed( true );
headerBuilder.append( "Connection: close" + HttpUtils.CRLF );
}
if ( checkBooleanParameter( Parameters.CONCURRENT, true ) ) {
headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( HttpUtils.CRLF );
}
if ( encodedContent.content != null ) {
String contentType = getStringParameter( Parameters.CONTENT_TYPE );
if ( contentType.length() > 0 ) {
encodedContent.contentType = contentType;
}
encodedContent.contentType = encodedContent.contentType.toLowerCase();
headerBuilder.append( "Content-Type: " + encodedContent.contentType );
if ( charset != null ) {
headerBuilder.append( "; charset=" + charset.toLowerCase() );
}
headerBuilder.append( HttpUtils.CRLF );
String transferEncoding = getStringParameter( Parameters.CONTENT_TRANSFER_ENCODING );
if ( transferEncoding.length() > 0 ) {
headerBuilder.append( "Content-Transfer-Encoding: " + transferEncoding + HttpUtils.CRLF );
}
String contentDisposition = getStringParameter( Parameters.CONTENT_DISPOSITION );
if ( contentDisposition.length() > 0 ) {
encodedContent.contentDisposition = contentDisposition;
headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + HttpUtils.CRLF );
}
boolean compression = encoding != null && checkBooleanParameter( Parameters.COMPRESSION, true );
String compressionTypes = getStringParameter(
Parameters.COMPRESSION_TYPES,
"text/html text/css text/plain text/xml text/x-js application/json application/javascript"
).toLowerCase();
if ( compression && !compressionTypes.equals( "*" ) && !compressionTypes.contains( encodedContent.contentType ) ) {
compression = false;
}
if ( compression ) {
encodedContent.content = HttpUtils.encode( encoding, encodedContent.content, headerBuilder );
}
headerBuilder.append( "Content-Length: " + (encodedContent.content.size()) + HttpUtils.CRLF ); //headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + HttpUtils.CRLF );
} else {
headerBuilder.append( "Content-Length: 0" + HttpUtils.CRLF );
}
}
private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent, String charset )
throws IOException
{
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Sending:\n" );
debugSB.append( header );
if (
getParameterVector( Parameters.DEBUG ).first().getFirstChild( "showContent" ).intValue() > 0
&& encodedContent.content != null
) {
debugSB.append( encodedContent.content.toString( charset ) );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
}
private void send_internal( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
Method method = send_getRequestMethod( message );
String charset = HttpUtils.getCharset( getStringParameter( Parameters.CHARSET ), null );
String format = send_getFormat();
EncodedContent encodedContent = send_encodeContent( message, method, charset, format );
StringBuilder headerBuilder = new StringBuilder();
if ( inInputPort ) {
// We're responding to a request
send_appendResponseHeaders( message, headerBuilder );
} else {
// We're sending a notification or a solicit
send_appendRequestHeaders( message, method, headerBuilder, charset );
}
send_appendGenericHeaders( message, encodedContent, charset, headerBuilder );
headerBuilder.append( HttpUtils.CRLF );
send_logDebugInfo( headerBuilder, encodedContent, charset );
inputId = message.operationName();
ostream.write( headerBuilder.toString().getBytes( charset ) );
if ( encodedContent.content != null ) {
ostream.write( encodedContent.content.getBytes() );
}
}
public void send( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
try {
send_internal( ostream, message, istream );
} catch ( IOException e ) {
if ( inInputPort ) {
HttpUtils.errorGenerator( ostream, e );
}
throw e;
}
}
private void parseXML( HttpMessage message, Value value, String charset )
throws IOException
{
try {
if ( message.size() > 0 ) {
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
src.setEncoding( charset );
Document doc = builder.parse( src );
XmlUtils.documentToValue( doc, value );
}
} catch( ParserConfigurationException pce ) {
throw new IOException( pce );
} catch( SAXException saxe ) {
throw new IOException( saxe );
}
}
private static void parseJson( HttpMessage message, Value value, boolean strictEncoding, String charset )
throws IOException
{
JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ), charset ), value, strictEncoding );
}
private static void parseForm( HttpMessage message, Value value, String charset )
throws IOException
{
String line = new String( message.content(), charset );
String[] pair;
for( String item : line.split( "&" ) ) {
pair = item.split( "=", 2 );
if ( pair.length != 2 ) {
throw new IOException( "Item " + item + " not in x-www-form-urlencoded" );
}
value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], HttpUtils.URL_DECODER_ENC ) );
}
}
private void parseMultiPartFormData( HttpMessage message, Value value, String charset )
throws IOException
{
multiPartFormDataParser = new MultiPartFormDataParser( message, value, charset );
multiPartFormDataParser.parse();
}
private static String parseGWTRPC( HttpMessage message, Value value, String charset )
throws IOException
{
RPCRequest request = RPC.decodeRequest( new String( message.content(), charset ) );
String operationName = (String)request.getParameters()[0];
joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1];
JolieGWTConverter.gwtToJolieValue( requestValue, value );
return operationName;
}
private void recv_checkForSetCookie( HttpMessage message, Value value )
throws IOException
{
if ( hasParameter( Parameters.COOKIES ) ) {
String type;
Value cookies = getParameterFirstValue( Parameters.COOKIES );
Value cookieConfig;
Value v;
for( HttpMessage.Cookie cookie : message.setCookies() ) {
if ( cookies.hasChildren( cookie.name() ) ) {
cookieConfig = cookies.getFirstChild( cookie.name() );
if ( cookieConfig.isString() ) {
v = value.getFirstChild( cookieConfig.strValue() );
type =
cookieConfig.hasChildren( "type" ) ?
cookieConfig.getFirstChild( "type" ).strValue()
:
"string";
recv_assignCookieValue( cookie.value(), v, type );
}
}
/*currValue = Value.create();
currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() );
currValue.getNewChild( "path" ).setValue( cookie.path() );
currValue.getNewChild( "name" ).setValue( cookie.name() );
currValue.getNewChild( "value" ).setValue( cookie.value() );
currValue.getNewChild( "domain" ).setValue( cookie.domain() );
currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) );
cookieVec.add( currValue );*/
}
}
}
private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword )
throws IOException
{
NativeType type = NativeType.fromString( typeKeyword );
if ( NativeType.INT == type ) {
try {
value.setValue( new Integer( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.LONG == type ) {
try {
value.setValue( new Long( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.STRING == type ) {
value.setValue( cookieValue );
} else if ( NativeType.DOUBLE == type ) {
try {
value.setValue( new Double( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.BOOL == type ) {
value.setValue( Boolean.valueOf( cookieValue ) );
} else {
value.setValue( cookieValue );
}
}
private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
Value cookies = null;
if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) {
cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookies = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookies != null ) {
Value v;
String type;
for( Entry< String, String > entry : message.cookies().entrySet() ) {
if ( cookies.hasChildren( entry.getKey() ) ) {
Value cookieConfig = cookies.getFirstChild( entry.getKey() );
if ( cookieConfig.isString() ) {
v = decodedMessage.value.getFirstChild( cookieConfig.strValue() );
if ( cookieConfig.hasChildren( "type" ) ) {
type = cookieConfig.getFirstChild( "type" ).strValue();
} else {
type = "string";
}
recv_assignCookieValue( entry.getValue(), v, type );
}
}
}
}
}
private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
Value headers = null;
if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) {
headers = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS );
} else if ( hasParameter( Parameters.HEADERS ) ) {
headers = getParameterFirstValue( Parameters.HEADERS );
}
if ( headers != null ) {
for( String headerName : headers.children().keySet() ) {
String headerAlias = headers.getFirstChild( headerName ).strValue();
headerName = headerName.replace( "_", "-" );
decodedMessage.value.getFirstChild( headerAlias ).setValue( message.getPropertyOrEmptyString( headerName ) );
}
}
}
private static void recv_parseQueryString( HttpMessage message, Value value )
{
Map< String, Integer > indexes = new HashMap< String, Integer >();
String queryString = message.requestPath() == null ? "" : message.requestPath();
String[] kv = queryString.split( "\\?" );
Integer index;
if ( kv.length > 1 ) {
queryString = kv[1];
String[] params = queryString.split( "&" );
for( String param : params ) {
kv = param.split( "=", 2 );
if ( kv.length > 1 ) {
index = indexes.get( kv[0] );
if ( index == null ) {
index = 0;
indexes.put( kv[0], index );
}
value.getChildren( kv[0] ).get( index ).setValue( kv[1] );
indexes.put( kv[0], index + 1 );
}
}
}
}
/*
* Prints debug information about a received message
*/
private void recv_logDebugInfo( HttpMessage message, String charset )
throws IOException
{
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Receiving:\n" );
debugSB.append( "HTTP Code: " + message.statusCode() + "\n" );
debugSB.append( "Resource: " + message.requestPath() + "\n" );
debugSB.append( "--> Header properties\n" );
for( Entry< String, String > entry : message.properties() ) {
debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' );
}
for( HttpMessage.Cookie cookie : message.setCookies() ) {
debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' );
}
for( Entry< String, String > entry : message.cookies().entrySet() ) {
debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' );
}
if (
getParameterFirstValue( Parameters.DEBUG ).getFirstChild( "showContent" ).intValue() > 0
&& message.content() != null
) {
debugSB.append( "--> Message content\n" );
debugSB.append( new String( message.content(), charset ) );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
private void recv_parseRequestFormat( HttpMessage message, String type )
throws IOException
{
requestFormat = null;
if ( "text/x-gwt-rpc".equals( type ) ) {
requestFormat = "text/x-gwt-rpc";
} else if ( "application/json".equals( type ) ) {
requestFormat = "application/json";
}
}
private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String type, String charset )
throws IOException
{
String format = "xml";
if ( hasParameter( Parameters.FORMAT ) ) {
format = getStringParameter( Parameters.FORMAT );
}
if ( "text/html".equals( type ) ) {
decodedMessage.value.setValue( new String( message.content(), charset ) );
} else if ( "application/x-www-form-urlencoded".equals( type ) ) {
parseForm( message, decodedMessage.value, charset );
} else if ( "text/xml".equals( type ) ) {
parseXML( message, decodedMessage.value, charset );
} else if ( "text/x-gwt-rpc".equals( type ) ) {
decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value, charset );
} else if ( "multipart/form-data".equals( type ) ) {
parseMultiPartFormData( message, decodedMessage.value, charset );
} else if (
"application/octet-stream".equals( type ) || type.startsWith( "image/" )
|| "application/zip".equals( type )
) {
decodedMessage.value.setValue( new ByteArray( message.content() ) );
} else if ( "application/json".equals( type ) || "json".equals( format ) ) {
boolean strictEncoding = checkStringParameter( "json_encoding", "strict" );
parseJson( message, decodedMessage.value, strictEncoding, charset );
} else if ( "xml".equals( format ) || "rest".equals( format ) ) {
parseXML( message, decodedMessage.value, charset );
} else {
decodedMessage.value.setValue( new String( message.content(), charset ) );
}
}
private String getDefaultOperation( HttpMessage.Type t )
{
if ( hasParameter( Parameters.DEFAULT_OPERATION ) ) {
Value dParam = getParameterFirstValue( Parameters.DEFAULT_OPERATION );
String method = HttpUtils.httpMessageTypeToString( t );
if ( method == null || dParam.hasChildren( method ) == false ) {
return dParam.strValue();
} else {
return dParam.getFirstChild( method ).strValue();
}
}
return null;
}
private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage )
{
if ( decodedMessage.operationName == null ) {
String requestPath = message.requestPath().split( "\\?" )[0];
decodedMessage.operationName = requestPath;
Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName );
if ( m.find() ) {
int resourceStart = m.end();
if ( m.find() ) {
decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() );
decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() );
}
}
}
if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) {
String defaultOpId = getDefaultOperation( message.type() );
if ( defaultOpId != null ) {
Value body = decodedMessage.value;
decodedMessage.value = Value.create();
decodedMessage.value.getChildren( "data" ).add( body );
decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName );
if ( message.userAgent() != null ) {
decodedMessage.value.getFirstChild( Parameters.USER_AGENT ).setValue( message.userAgent() );
}
Value cookies = decodedMessage.value.getFirstChild( "cookies" );
for( Entry< String, String > cookie : message.cookies().entrySet() ) {
cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() );
}
decodedMessage.operationName = defaultOpId;
}
}
}
private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage )
{
if ( multiPartFormDataParser != null ) {
String target;
for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) {
if ( entry.getValue().filename() != null ) {
target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() );
if ( target != null ) {
decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() );
}
}
}
multiPartFormDataParser = null;
}
}
private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
recv_checkForCookies( message, decodedMessage );
recv_checkForGenericHeader( message, decodedMessage );
recv_checkForMultiPartHeaders( decodedMessage );
if (
message.userAgent() != null &&
hasParameter( Parameters.USER_AGENT )
) {
getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() );
}
if ( getParameterVector( Parameters.HOST ) != null ) {
getParameterFirstValue( Parameters.HOST ).setValue( message.getPropertyOrEmptyString( Parameters.HOST ) );
}
}
private static class DecodedMessage {
private String operationName = null;
private Value value = Value.create();
private String resourcePath = "/";
private long id = CommMessage.GENERIC_ID;
}
private void recv_checkForStatusCode( HttpMessage message )
{
if ( hasParameter( Parameters.STATUS_CODE ) ) {
getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() );
}
}
private CommMessage recv_internal( InputStream istream, OutputStream ostream )
throws IOException
{
HttpMessage message = new HttpParser( istream ).parse();
String charset = HttpUtils.getCharset( getStringParameter( Parameters.CHARSET ), message );
CommMessage retVal = null;
DecodedMessage decodedMessage = new DecodedMessage();
HttpUtils.recv_checkForChannelClosing( message, channel() );
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
recv_logDebugInfo( message, charset );
}
recv_checkForStatusCode( message );
encoding = message.getProperty( "accept-encoding" );
String contentType = DEFAULT_CONTENT_TYPE;
if ( message.getProperty( "content-type" ) != null ) {
contentType = message.getProperty( "content-type" ).split( ";" )[0].toLowerCase();
}
recv_parseRequestFormat( message, contentType );
if ( message.size() > 0 ) {
recv_parseMessage( message, decodedMessage, contentType, charset );
}
if ( checkBooleanParameter( Parameters.CONCURRENT ) ) {
String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID );
if ( messageId != null ) {
try {
decodedMessage.id = Long.parseLong( messageId );
} catch( NumberFormatException e ) {}
}
}
if ( message.isResponse() ) {
recv_checkForSetCookie( message, decodedMessage.value );
retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null );
} else if ( message.isError() == false ) {
if ( message.isGet() ) {
recv_parseQueryString( message, decodedMessage.value );
}
recv_checkReceivingOperation( message, decodedMessage );
recv_checkForMessageProperties( message, decodedMessage );
retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null );
}
if ( retVal != null && "/".equals( retVal.resourcePath() ) && channel().parentPort() != null
&& (channel().parentPort().getInterface().containsOperation( retVal.operationName() )
|| channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null) ) {
try {
// The message is for this service
boolean hasInput = false;
OneWayTypeDescription oneWayTypeDescription = null;
if ( channel().parentInputPort() != null ) {
if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) {
oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asOneWayTypeDescription();
hasInput = true;
}
}
if ( !hasInput ) {
Interface iface = channel().parentPort().getInterface();
oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() );
}
if ( oneWayTypeDescription != null ) {
// We are receiving a One-Way message
oneWayTypeDescription.requestType().cast( retVal.value() );
} else {
hasInput = false;
RequestResponseTypeDescription rrTypeDescription = null;
if ( channel().parentInputPort() != null ) {
if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) {
rrTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asRequestResponseTypeDescription();
hasInput = true;
}
}
if ( !hasInput ) {
Interface iface = channel().parentPort().getInterface();
rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() );
}
if ( retVal.isFault() ) {
Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() );
if ( faultType != null ) {
faultType.cast( retVal.value() );
}
} else {
if ( message.isResponse() ) {
rrTypeDescription.responseType().cast( retVal.value() );
} else {
rrTypeDescription.requestType().cast( retVal.value() );
}
}
}
} catch( TypeCastingException e ) {
// TODO: do something here?
}
}
return retVal;
}
public CommMessage recv( InputStream istream, OutputStream ostream )
throws IOException
{
try {
return recv_internal( istream, ostream );
} catch ( IOException e ) {
if ( inInputPort && channel().isOpen() ) {
HttpUtils.errorGenerator( ostream, e );
}
throw e;
}
}
private Type getSendType( CommMessage message )
throws IOException
{
Type ret = null;
if ( channel().parentPort() == null ) {
throw new IOException( "Could not retrieve communication port for HTTP protocol" );
}
OperationTypeDescription opDesc = channel().parentPort().getOperationTypeDescription( message.operationName(), Constants.ROOT_RESOURCE_PATH );
if ( opDesc == null ) {
return null;
}
if ( opDesc.asOneWayTypeDescription() != null ) {
if ( message.isFault() ) {
ret = Type.UNDEFINED;
} else {
OneWayTypeDescription ow = opDesc.asOneWayTypeDescription();
ret = ow.requestType();
}
} else if ( opDesc.asRequestResponseTypeDescription() != null ) {
RequestResponseTypeDescription rr = opDesc.asRequestResponseTypeDescription();
if ( message.isFault() ) {
ret = rr.getFaultType( message.fault().faultName() );
if ( ret == null ) {
ret = Type.UNDEFINED;
}
} else {
ret = ( inInputPort ) ? rr.responseType() : rr.requestType();
}
}
return ret;
}
}
|
package org.fakekoji;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class Utils {
private static final ClassLoader classLoader = Utils.class.getClassLoader();
public static String readResource(Path path) throws IOException {
return readFile(classLoader.getResource(path.toString()));
}
public static String readFile(File file) throws IOException {
final StringBuilder content = new StringBuilder();
final FileReader fileReader = new FileReader(file);
final BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line);
}
bufferedReader.close();
fileReader.close();
return content.toString();
}
public static String readFile(URL url) throws IOException {
return readFile(new File(url.getFile()));
}
public static void writeToFile(Path path, String content) throws IOException {
writeToFile(path.toFile(), content);
}
public static void writeToFile(File file, String content) throws IOException {
final PrintWriter writer = new PrintWriter(file.getAbsolutePath());
writer.write(content);
writer.flush();
writer.close();
}
public static void moveFile(File source, File target) throws IOException {
Files.move(source.toPath(), target.toPath(), REPLACE_EXISTING);
}
}
|
package io.cloudchaser.murmur.types;
import static io.cloudchaser.murmur.types.MurmurType.STRING;
/**
*
* @author Mihail K
* @since 0.1
*/
public class MurmurString extends MurmurObject {
private final String value;
public MurmurString(String value) {
super(STRING);
this.value = value;
}
@Override
public Object toJavaObject() {
return value;
}
@Override
public boolean isCompatible(Class<?> type) {
return type.isAssignableFrom(String.class) ||
type.isAssignableFrom(CharSequence.class);
}
@Override
public Object getAsJavaType(Class<?> type) {
// Java string type.
if(type.isAssignableFrom(String.class) ||
type.isAssignableFrom(CharSequence.class)) {
return value;
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurInteger asInteger() {
return MurmurInteger.ZERO;
}
@Override
public MurmurDecimal asDecimal() {
return MurmurDecimal.ZERO;
}
@Override
public MurmurString asString() {
return this;
}
@Override
public MurmurObject opPositive() {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opNegative() {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opIncrement() {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opDecrement() {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opPlus(MurmurObject other) {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opMinus(MurmurObject other) {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opMultiply(MurmurObject other) {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opDivide(MurmurObject other) {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opModulo(MurmurObject other) {
// Strings don't support integer arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opShiftLeft(MurmurObject other) {
// Strings don't support bitshift.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opShiftRight(MurmurObject other) {
// Strings don't support bitshift.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLessThan(MurmurObject other) {
// Strings don't support inequality.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opGreaterThan(MurmurObject other) {
// Strings don't support inequality.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLessOrEqual(MurmurObject other) {
// Strings don't support inequality.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opGreaterOrEqual(MurmurObject other) {
// Strings don't support inequality.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opEquals(MurmurObject other) {
// Check for supported operation.
if(other.getType() == STRING) {
return MurmurBoolean.create(
value.equals(((MurmurString)other).value));
}
// Not equal.
return MurmurBoolean.FALSE;
}
@Override
public MurmurObject opNotEquals(MurmurObject other) {
// Check for supported operation.
if(other.getType() == STRING) {
return MurmurBoolean.create(!
value.equals(((MurmurString)other).value));
}
// Not equal.
return MurmurBoolean.TRUE;
}
@Override
public MurmurObject opBitNot() {
// Strings don't support bit arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opBitAnd(MurmurObject other) {
// Strings don't support bit arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opBitXor(MurmurObject other) {
// Strings don't support bit arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opBitOr(MurmurObject other) {
// Strings don't support bit arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLogicalNot() {
// Strings don't support boolean arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLogicalAnd(MurmurObject other) {
// Strings don't support boolean arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLogicalOr(MurmurObject other) {
// Strings don't support boolean arithmetic.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opIndex(MurmurObject other) {
// Strings don't support array indexing.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opConcat(MurmurObject other) {
// Convert to string and do concat.
MurmurString string = other.asString();
return new MurmurString(value + string.value);
}
@Override
public String toString() {
return "MurmurString{value=" + value + '}';
}
}
|
/**
* WAVLTree
*
* An implementation of a WAVL Tree with
* distinct integer keys and info
*
*/
public class WAVLTree {
private WAVLNode root;
/**
* Constructor; creates a tree with empty Node
*/
public WAVLTree(int key , String info) {
this.root = new WAVLNode(key , info);
}
/**
* public boolean empty()
*
* returns true if and only if the tree is empty
*
*/
public boolean empty() {
return false; // to be replaced by student code
}
/**
* public String search(WAVLTree T , int k)
*
* recursive search
*/
public String search(WAVLNode node , int k)
{
if(node.key == k)
{
return node.info;
}
else if(node.key < k) && (node.right != null)
{
return search(node.right, k);
}
else if(node.left != null)
{
return search(node.left , k);
}
return null;
}
/**
* public String search(int k)
*
* returns the info of an item with key k if it exists in the tree
* otherwise, returns null
*/
public String search(int k) {
if (this.root != null)
{
if(this.root.key == k)
{
return this.root.info;
}
else if((this.root.key < k) && (this.root.right != null))
{
return search(this.root.right , k);
}
else if((this.root.key > k) && (this.root.left != null))
{
return search(this.root.left , k);
}
}
return null; // to be replaced by student code
}
/**
* public int insert(int k, String i)
*
* inserts an item with key k and info i to the WAVL tree.
* the tree must remain valid (keep its invariants).
* returns the number of rebalancing operations, or 0 if no rebalancing operations were necessary.
* returns -1 if an item with key k already exists in the tree.
*/
public int insert(int k, String i) {
return 42; // to be replaced by student code
}
/**
* public int delete(int k)
*
* deletes an item with key k from the binary tree, if it is there;
* the tree must remain valid (keep its invariants).
* returns the number of rebalancing operations, or 0 if no rebalancing operations were needed.
* returns -1 if an item with key k was not found in the tree.
*/
public int delete(int k)
{
return 42; // to be replaced by student code
}
/**
* public String min()
*
* Returns the ifo of the item with the smallest key in the tree,
* or null if the tree is empty
*/
public String min()
{
return "42"; // to be replaced by student code
}
/**
* public String max()
*
* Returns the info of the item with the largest key in the tree,
* or null if the tree is empty
*/
public String max() {
return "42"; // to be replaced by student code
}
/**
* public int[] keysToArray()
*
* Returns a sorted array which contains all keys in the tree,
* or an empty array if the tree is empty.
*/
public int[] keysToArray()
{
int[] arr = new int[42]; // to be replaced by student code
return arr; // to be replaced by student code
}
/**
* public String[] infoToArray()
*
* Returns an array which contains all info in the tree,
* sorted by their respective keys,
* or an empty array if the tree is empty.
*/
public String[] infoToArray() {
String[] arr = new String[42]; // to be replaced by student code
return arr; // to be replaced by student code
}
/**
* public int size()
*
* Returns the number of nodes in the tree.
*
* precondition: none
* postcondition: none
*/
public int size() {
return 42; // to be replaced by student code
}
/**
* public class WAVLNode
*
* If you wish to implement classes other than WAVLTree
* (for example WAVLNode), do it in this file, not in
* another file.
* This is an example which can be deleted if no such classes are necessary.
*/
public class WAVLNode {
/**
* Node data
*/
private String info;
/**
* Key
*/
private int key;
/**
* Left child
*/
private WAVLNode left;
/**
* Right child
*/
private WAVLNode right;
/**
* Height of node
*/
private int height;
public WAVLNode(int key,String info){
this.key = key;
this.info = info;
this.left = null;
this.right = null;
this.height = 0;
}
}
}
|
package org.jaxen.util;
import java.io.IOException;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.jaxen.JaxenConstants;
public class IdentityHashMap extends AbstractMap implements Map, Cloneable,
java.io.Serializable {
/**
* The hash table data.
*/
private transient Entry table[];
/**
* The total number of mappings in the hash table.
*/
private transient int count;
/**
* The table is rehashed when its size exceeds this threshold. (The
* value of this field is (int)(capacity * loadFactor).)
*
* @serial
*/
private int threshold;
/**
* The load factor for the hashtable.
*
* @serial
*/
private float loadFactor;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
private transient int modCount = 0;
public IdentityHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Initial Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load factor: "+
loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry[initialCapacity];
threshold = (int)(initialCapacity * loadFactor);
}
public IdentityHashMap(int initialCapacity) {
this(initialCapacity, 0.75f);
}
/**
* Constructs a new, empty map with a default capacity and load
* factor, which is <code>0.75</code>.
*/
public IdentityHashMap() {
this(11, 0.75f);
}
/**
* Constructs a new map with the same mappings as the given map. The
* map is created with a capacity of twice the number of mappings in
* the given map or 11 (whichever is greater), and a default load factor,
* which is <code>0.75</code>.
*
* @param t the map whose mappings are to be placed in this map
*/
public IdentityHashMap(Map t) {
this(Math.max(2*t.size(), 11), 0.75f);
putAll(t);
}
/**
* Returns the number of key-value mappings in this map
*
* @return the number of key-value mappings in this map
*/
public int size() {
return count;
}
/**
* Returns <code>true</code> if this map contains no key-value mappings
*
* @return <code>true</code> if this map contains no key-value mappings
*/
public boolean isEmpty() {
return count == 0;
}
/**
* Returns <code>true</code> if this map maps one or more keys to the
* specified value.
*
* @param value value whose presence in this map is to be tested.
* @return <code>true</code> if this map maps one or more keys to the
* specified value
*/
public boolean containsValue(Object value) {
Entry tab[] = table;
if (value==null) {
for (int i = tab.length ; i > 0 ; i
for (Entry e = tab[i] ; e != null ; e = e.next)
if (e.value==null)
return true;
} else {
for (int i = tab.length ; i > 0 ; i
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;
}
return false;
}
/**
* Returns <code>true</code> if this map contains a mapping for the specified
* key.
*
* @return <code>true</code> if this map contains a mapping for the specified
* key
* @param key key whose presence in this Map is to be tested
*/
public boolean containsKey(Object key) {
Entry tab[] = table;
if (key != null) {
//int hash = key.hashCode();
int hash = System.identityHashCode( key );
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
// if (e.hash==hash && key.equals(e.key))
if (e.hash==hash && ( key == e.key ) )
return true;
} else {
for (Entry e = tab[0]; e != null; e = e.next)
if (e.key==null) return true;
}
return false;
}
/**
* Returns the value to which this map maps the specified key. Returns
* <code>null</code> if the map contains no mapping for this key. A return
* value of <code>null</code> does not <i>necessarily</i> indicate that the
* map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to <code>null</code>. The <code>containsKey</code>
* operation may be used to distinguish these two cases.
*
* @return the value to which this map maps the specified key
* @param key key whose associated value is to be returned
*/
public Object get(Object key) {
Entry tab[] = table;
if (key != null) {
// int hash = key.hashCode();
int hash = System.identityHashCode( key );
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
// if ((e.hash == hash) && key.equals(e.key))
if ((e.hash == hash) && ( key == e.key ) )
return e.value;
} else {
for (Entry e = tab[0]; e != null; e = e.next)
if (e.key==null)
return e.value;
}
return null;
}
/**
* Rehashes the contents of this map into a new <code>IdentityHashMap</code> instance
* with a larger capacity. This method is called automatically when the
* number of keys in this map exceeds its capacity and load factor.
*/
private void rehash() {
int oldCapacity = table.length;
Entry oldMap[] = table;
int newCapacity = oldCapacity * 2 + 1;
Entry newMap[] = new Entry[newCapacity];
modCount++;
threshold = (int)(newCapacity * loadFactor);
table = newMap;
for (int i = oldCapacity ; i
for (Entry old = oldMap[i] ; old != null ; ) {
Entry e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for this key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return previous value associated with specified key, or <code>null</code>
* if there was no mapping for key. A <code>null</code> return can
* also indicate that the IdentityHashMap previously associated
* <code>null</code> with the specified key.
*/
public Object put(Object key, Object value) {
// XXX this method is a HotSpot in Jaxen
// Makes sure the key is not already in the IdentityHashMap.
// I think this copy, which has no semantic effect, is being
// done to speed things up by using a local variable instead of a field
// access. I'm not sure this is significant. - ERH
Entry tab[] = table;
int hash = 0;
int index = 0;
if (key != null) {
hash = System.identityHashCode( key );
index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && ( key == e.key ) ) {
Object old = e.value;
e.value = value;
return old;
}
}
} else {
for (Entry e = tab[0] ; e != null ; e = e.next) {
if (e.key == null) {
Object old = e.value;
e.value = value;
return old;
}
}
}
modCount++;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry e = new Entry(hash, key, value, tab[index]);
tab[index] = e;
count++;
return null;
}
/**
* Removes the mapping for this key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return previous value associated with specified key, or <code>null</code>
* if there was no mapping for key. A <code>null</code> return can
* also indicate that the map previously associated <code>null</code>
* with the specified key.
*/
public Object remove(Object key) {
Entry tab[] = table;
if (key != null) {
// int hash = key.hashCode();
int hash = System.identityHashCode( key );
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
// if ((e.hash == hash) && key.equals(e.key)) {
if ((e.hash == hash) && ( key == e.key ) ) {
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
count
Object oldValue = e.value;
e.value = null;
return oldValue;
}
}
} else {
for (Entry e = tab[0], prev = null; e != null;
prev = e, e = e.next) {
if (e.key == null) {
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[0] = e.next;
count
Object oldValue = e.value;
e.value = null;
return oldValue;
}
}
}
return null;
}
/**
* Copies all of the mappings from the specified map to this one.
*
* These mappings replace any mappings that this map had for any of the
* keys currently in the specified Map.
*
* @param t mappings to be stored in this map
*/
public void putAll(Map t) {
Iterator i = t.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
put(e.getKey(), e.getValue());
}
}
/**
* Removes all mappings from this map.
*/
public void clear() {
Entry tab[] = table;
modCount++;
for (int index = tab.length; --index >= 0; )
tab[index] = null;
count = 0;
}
/**
* Returns a shallow copy of this <code>IdentityHashMap</code> instance: the keys and
* values themselves are not cloned.
*
* @return a shallow copy of this map
*/
public Object clone() {
try {
IdentityHashMap t = (IdentityHashMap)super.clone();
t.table = new Entry[table.length];
for (int i = table.length ; i
t.table[i] = (table[i] != null)
? (Entry)table[i].clone() : null;
}
t.keySet = null;
t.entrySet = null;
t.values = null;
t.modCount = 0;
return t;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
// Views
private transient Set keySet = null;
private transient Set entrySet = null;
private transient Collection values = null;
/**
* Returns a set view of the keys contained in this map. The set is
* backed by the map, so changes to the map are reflected in the set, and
* vice-versa. The set supports element removal, which removes the
* corresponding mapping from this map, via the <code>Iterator.remove</code>,
* <code>Set.remove</code>, <code>removeAll</code>, <code>retainAll</code>, and
* <code>clear</code> operations. It does not support the <code>add</code> or
* <code>addAll</code> operations.
*
* @return a set view of the keys contained in this map
*/
public Set keySet() {
if (keySet == null) {
keySet = new AbstractSet() {
public Iterator iterator() {
return getHashIterator(KEYS);
}
public int size() {
return count;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
int oldSize = count;
IdentityHashMap.this.remove(o);
return count != oldSize;
}
public void clear() {
IdentityHashMap.this.clear();
}
};
}
return keySet;
}
/**
* Returns a collection view of the values contained in this map. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element
* removal, which removes the corresponding mapping from this map, via the
* <code>Iterator.remove</code>, <code>Collection.remove</code>,
* <code>removeAll</code>, <code>retainAll</code>, and <code>clear</code> operations.
* It does not support the <code>add</code> or <code>addAll</code> operations.
*
* @return a collection view of the values contained in this map
*/
public Collection values() {
if (values==null) {
values = new AbstractCollection() {
public Iterator iterator() {
return getHashIterator(VALUES);
}
public int size() {
return count;
}
public boolean contains(Object o) {
return containsValue(o);
}
public void clear() {
IdentityHashMap.this.clear();
}
};
}
return values;
}
/**
* Returns a collection view of the mappings contained in this map. Each
* element in the returned collection is a <code>Map.Entry</code>. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element
* removal, which removes the corresponding mapping from the map, via the
* <code>Iterator.remove</code>, <code>Collection.remove</code>,
* <code>removeAll</code>, <code>retainAll</code>, and <code>clear</code> operations.
* It does not support the <code>add</code> or <code>addAll</code> operations.
*
* @return a collection view of the mappings contained in this map
* @see java.util.Map.Entry
*/
public Set entrySet() {
if (entrySet==null) {
entrySet = new AbstractSet() {
public Iterator iterator() {
return getHashIterator(ENTRIES);
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry tab[] = table;
// int hash = (key==null ? 0 : key.hashCode());
int hash = (key==null ? 0 : System.identityHashCode( key ) );
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
if (e.hash==hash && e.equals(entry))
return true;
return false;
}
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry tab[] = table;
// int hash = (key==null ? 0 : key.hashCode());
int hash = (key==null ? 0 : System.identityHashCode( key ) );
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e.hash==hash && e.equals(entry)) {
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
count
e.value = null;
return true;
}
}
return false;
}
public int size() {
return count;
}
public void clear() {
IdentityHashMap.this.clear();
}
};
}
return entrySet;
}
private Iterator getHashIterator(int type) {
if (count == 0) {
return JaxenConstants.EMPTY_ITERATOR;
} else {
return new HashIterator(type);
}
}
/**
* IdentityHashMap collision list entry.
*/
private static class Entry implements Map.Entry {
int hash;
Object key;
Object value;
Entry next;
Entry(int hash, Object key, Object value, Entry next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
protected Object clone() {
return new Entry(hash, key, value,
(next==null ? null : (Entry)next.clone()));
}
// Map.Entry Ops
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
public Object setValue(Object value) {
Object oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ (value==null ? 0 : value.hashCode());
}
public String toString() {
return key+"="+value;
}
}
// Types of Iterators
private static final int KEYS = 0;
private static final int VALUES = 1;
private static final int ENTRIES = 2;
private class HashIterator implements Iterator {
Entry[] table = IdentityHashMap.this.table;
int index = table.length;
Entry entry = null;
Entry lastReturned = null;
int type;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
private int expectedModCount = modCount;
HashIterator(int type) {
this.type = type;
}
public boolean hasNext() {
Entry e = entry;
int i = index;
Entry t[] = table;
/* Use locals for faster loop iteration */
while (e == null && i > 0)
e = t[--i];
entry = e;
index = i;
return e != null;
}
public Object next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry et = entry;
int i = index;
Entry t[] = table;
/* Use locals for faster loop iteration */
while (et == null && i > 0)
et = t[--i];
entry = et;
index = i;
if (et != null) {
Entry e = lastReturned = entry;
entry = e.next;
return type == KEYS ? e.key : (type == VALUES ? e.value : e);
}
throw new NoSuchElementException();
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry[] tab = IdentityHashMap.this.table;
int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e == lastReturned) {
modCount++;
expectedModCount++;
if (prev == null)
tab[index] = e.next;
else
prev.next = e.next;
count
lastReturned = null;
return;
}
}
throw new ConcurrentModificationException();
}
}
/**
* Save the state of the <code>IdentityHashMap</code> instance to a stream (i.e.,
* serialize it).
*
* @serialData the <em>capacity</em> of the IdentityHashMap (the length of the
* bucket array) is emitted (int), followed by the
* <em>size</em> of the IdentityHashMap (the number of key-value
* mappings), followed by the key (Object) and value (Object)
* for each key-value mapping represented by the IdentityHashMap.
* The key-value mappings are emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the threshold, load factor, and any hidden stuff
s.defaultWriteObject();
// Write out number of buckets
s.writeInt(table.length);
// Write out size (number of Mappings)
s.writeInt(count);
// Write out keys and values (alternating)
for (int index = table.length-1; index >= 0; index
Entry entry = table[index];
while (entry != null) {
s.writeObject(entry.key);
s.writeObject(entry.value);
entry = entry.next;
}
}
}
private static final long serialVersionUID = 362498820763181265L;
/**
* Reconstitute the <code>IdentityHashMap</code> instance from a stream (i.e.,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the threshold, loadfactor, and any hidden stuff
s.defaultReadObject();
// Read in number of buckets and allocate the bucket array;
int numBuckets = s.readInt();
table = new Entry[numBuckets];
// Read in size (number of Mappings)
int size = s.readInt();
// Read the keys and values, and put the mappings in the IdentityHashMap
for (int i=0; i<size; i++) {
Object key = s.readObject();
Object value = s.readObject();
put(key, value);
}
}
int capacity() {
return table.length;
}
float loadFactor() {
return loadFactor;
}
}
|
//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
//You should have received a copy of the GNU Lesser General Public
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package opennlp.tools.namefind;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import opennlp.maxent.EventStream;
import opennlp.maxent.GIS;
import opennlp.maxent.GISModel;
import opennlp.maxent.MaxentModel;
import opennlp.maxent.PlainTextByLineDataStream;
import opennlp.maxent.TwoPassDataIndexer;
import opennlp.maxent.io.SuffixSensitiveGISModelWriter;
import opennlp.tools.util.BeamSearch;
import opennlp.tools.util.Sequence;
/**
* Class for creating a maximum-entropy-based name finder.
*/
public class NameFinderME implements NameFinder {
protected MaxentModel _npModel;
protected NameContextGenerator _contextGen;
private Sequence bestSequence;
private BeamSearch beam;
public static final String START = "start";
public static final String CONTINUE = "cont";
public static final String OTHER = "other";
/**
* Creates a new name finder with the specified model.
* @param mod The model to be used to find names.
*/
public NameFinderME(MaxentModel mod) {
this(mod, new DefaultNameContextGenerator(), 10);
}
/**
* Creates a new name finder with the specified model and context generator.
* @param mod The model to be used to find names.
* @param cg The context generator to be used with this name finder.
*/
public NameFinderME(MaxentModel mod, NameContextGenerator cg) {
this(mod, cg, 10);
}
/**
* Creates a new name finder with the specified model and context generator.
* @param mod The model to be used to find names.
* @param cg The context generator to be used with this name finder.
* @param beamSize The size of the beam to be used in decoding this model.
*/
public NameFinderME(MaxentModel mod, NameContextGenerator cg, int beamSize) {
_npModel = mod;
_contextGen = cg;
beam = new NameBeamSearch(beamSize, cg, mod);
}
/* inherieted javadoc */
public List find(List toks, Map prevTags) {
bestSequence = beam.bestSequence(toks, new Object[] { prevTags });
return bestSequence.getOutcomes();
}
/* inherieted javadoc */
public String[] find(Object[] toks, Map prevTags) {
bestSequence = beam.bestSequence(toks, new Object[] { prevTags });
List c = bestSequence.getOutcomes();
return (String[]) c.toArray(new String[c.size()]);
}
/**
* This method determines wheter the outcome is valid for the preceeding sequence.
* This can be used to implement constraints on what sequences are valid.
* @param outcome The outcome.
* @param sequence The precceding sequence of outcomes assignments.
* @return true is the outcome is valid for the sequence, false otherwise.
*/
protected boolean validOutcome(String outcome, Sequence sequence) {
if (outcome.equals(CONTINUE)) {
List tags = sequence.getOutcomes();
int li = tags.size() - 1;
if (li == -1) {
return false;
}
else if (((String) tags.get(li)).equals(OTHER)) {
return false;
}
}
return true;
}
/**
* Implementation of the abstract beam search to allow the name finder to use the common beam search code.
*
*/
private class NameBeamSearch extends BeamSearch {
/**
* Creams a beam seach of the specified size sing the specified model with the specified context generator.
* @param size The size of the beam.
* @param cg The context generator used with the specified model.
* @param model The model used to determine names.
*/
public NameBeamSearch(int size, NameContextGenerator cg, MaxentModel model) {
super(size, cg, model);
}
protected boolean validSequence(int i, List sequence, Sequence s, String outcome) {
return validOutcome(outcome, s);
}
}
/**
* Populates the specified array with the probabilities of the last decoded sequence. The
* sequence was determined based on the previous call to <code>chunk</code>. The
* specified array should be at least as large as the numbe of tokens in the previous call to <code>chunk</code>.
* @param probs An array used to hold the probabilities of the last decoded sequence.
*/
public void probs(double[] probs) {
bestSequence.getProbs(probs);
}
/**
* Returns an array with the probabilities of the last decoded sequence. The
* sequence was determined based on the previous call to <code>chunk</code>.
* @return An array with the same number of probabilities as tokens were sent to <code>chunk</code>
* when it was last called.
*/
public double[] probs() {
return bestSequence.getProbs();
}
private static GISModel train(EventStream es, int iterations, int cut) throws IOException {
return GIS.trainModel(iterations, new TwoPassDataIndexer(es, cut));
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("usage: NameFinderME training_file model");
System.exit(1);
}
try {
File inFile = new File(args[0]);
File outFile = new File(args[1]);
GISModel mod;
EventStream es = new NameFinderEventStream(new PlainTextByLineDataStream(new FileReader(inFile)));
if (args.length > 3)
mod = train(es, Integer.parseInt(args[2]), Integer.parseInt(args[3]));
else
mod = train(es, 100, 5);
System.out.println("Saving the model as: " + args[1]);
new SuffixSensitiveGISModelWriter(mod, outFile).persist();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package gov.nih.nci.nautilus.query;
import gov.nih.nci.nautilus.criteria.GeneIDCriteria;
import gov.nih.nci.nautilus.criteria.RegionCriteria;
import gov.nih.nci.nautilus.criteria.FoldChangeCriteria;
import gov.nih.nci.nautilus.queryprocessing.QueryHandler;
import gov.nih.nci.nautilus.queryprocessing.GeneExprQueryHandler;
import java.util.*;
import gov.nih.nci.nautilus.de.*;
public class GeneExpressionQuery extends Query {
private GeneIDCriteria geneIDCrit;
private RegionCriteria regionCrit;
private FoldChangeCriteria foldChgCrit;
private QueryHandler HANDLER;
public QueryHandler getQueryHandler() throws Exception {
return (HANDLER == null) ? new GeneExprQueryHandler() : HANDLER;
}
public QueryType getQueryType() throws Exception {
return QueryType.GENE_EXPR_QUERY_TYPE;
}
public GeneExpressionQuery() {
super();
}
public GeneIDCriteria getGeneIDCrit() {
return geneIDCrit;
}
public String toString(){
ResourceBundle labels = null;
String OutStr = "Gene Expression Data\n\n";
OutStr += "Query: " + this.getQueryName()+"\n\n";
try {
labels = ResourceBundle.getBundle("gov.nih.nci.nautilus.struts.ApplicationResources", Locale.US);
FoldChangeCriteria thisFoldChangeCrit = this.getFoldChgCrit();
if (!thisFoldChangeCrit.isEmpty() && labels != null) {
String thisCriteria = thisFoldChangeCrit.getClass().getName();
OutStr += labels.getString(thisCriteria.substring(thisCriteria.lastIndexOf(".")+1))+ "\n";
Collection foldChangeObjects = thisFoldChangeCrit.getFoldChangeObjects();
for (Iterator iter = foldChangeObjects.iterator(); iter.hasNext();) {
DomainElement de = (DomainElement) iter.next();
String thisDomainElement = de.getClass().getName();
OutStr += labels.getString(thisDomainElement.substring(thisDomainElement.lastIndexOf(".")+1)) +": "+de.getValue()+"\n";
}
}
else System.out.println("Fold Change Criteria is empty or Application Resources file is missing");
GeneIDCriteria thisGeneIDCrit = this.getGeneIDCrit();
if (!thisGeneIDCrit.isEmpty() && labels != null) {
String thisCriteria = thisGeneIDCrit.getClass().getName();
OutStr += labels.getString(thisCriteria.substring(thisCriteria.lastIndexOf(".")+1))+ "\n";
Collection geneIDObjects = thisGeneIDCrit.getGeneIdentifiers();
for (Iterator iter = geneIDObjects.iterator(); iter.hasNext();) {
DomainElement de = (DomainElement) iter.next();
String thisDomainElement = de.getClass().getName();
OutStr += labels.getString(thisDomainElement.substring(thisDomainElement.lastIndexOf(".")+1)) +": "+de.getValue()+"\n";
}
}
else System.out.println("Gene ID Criteria is empty or Application Resources file is missing");
RegionCriteria thisRegionCrit = this.getRegionCrit();
if (!thisRegionCrit.isEmpty() && labels != null) {
String thisCriteria = thisRegionCrit.getClass().getName();
OutStr += labels.getString(thisCriteria.substring(thisCriteria.lastIndexOf(".")+1))+ "\n";
DomainElement cytoBandDE = thisRegionCrit.getCytoband();
DomainElement chromosomeDE = thisRegionCrit.getChromNumber();
DomainElement chrStartDE = thisRegionCrit.getStart();
DomainElement chrEndDE = thisRegionCrit.getEnd();
if (cytoBandDE != null) {
String cytoBandStr = cytoBandDE.getClass().getName();
OutStr += labels.getString(cytoBandStr.substring(cytoBandStr.lastIndexOf(".")+1)) +": "+cytoBandDE.getValue()+"\n";
}else {
String chromosomeDEStr = chromosomeDE.getClass().getName();
OutStr += labels.getString(chromosomeDEStr.substring(chromosomeDEStr.lastIndexOf(".")+1)) +": "+chromosomeDE.getValue()+"\n";
if (chrStartDE != null && chrEndDE != null) {
String chrStartDEStr = chrStartDE.getClass().getName();
String chrEndDEStr = chrEndDE.getClass().getName();
OutStr += "\n"+labels.getString(chrStartDEStr.substring(chrStartDEStr.lastIndexOf(".")+1, chrStartDEStr.lastIndexOf("$")))+"(kb)\n";
OutStr += labels.getString(chrStartDEStr.substring(chrStartDEStr.lastIndexOf(".")+1)) +": "+chrStartDE.getValue()+"\n";
OutStr += labels.getString(chrEndDEStr.substring(chrEndDEStr.lastIndexOf(".")+1)) +": "+chrEndDE.getValue()+"\n";
}
}
}
else System.out.println("Region Criteria is empty or Application Resources file is missing");
}
catch (Exception ie) {
ie.printStackTrace();
System.out.println("Error in ResourceBundle - " + ie.getMessage());
}
return OutStr;
}
public void setGeneIDCrit(GeneIDCriteria geneIDCrit) {
this.geneIDCrit = geneIDCrit;
}
public RegionCriteria getRegionCrit() {
return regionCrit;
}
public void setRegionCrit(RegionCriteria regionCrit) {
this.regionCrit = regionCrit;
}
public FoldChangeCriteria getFoldChgCrit() {
return foldChgCrit;
}
public void setFoldChgCrit(FoldChangeCriteria foldChgCrit) {
this.foldChgCrit = foldChgCrit;
}
class Handler {
}
}
|
package info.tregmine.listeners;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.Queue;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.SkullType;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import info.tregmine.Tregmine;
import info.tregmine.api.PlayerReport;
import info.tregmine.api.TregminePlayer;
import info.tregmine.api.Rank;
import info.tregmine.api.PlayerBannedException;
import info.tregmine.api.lore.Created;
import info.tregmine.api.util.ScoreboardClearTask;
import info.tregmine.database.DAOException;
import info.tregmine.database.IContext;
import info.tregmine.database.IInventoryDAO;
import info.tregmine.database.IMotdDAO;
import info.tregmine.database.ILogDAO;
import info.tregmine.database.IPlayerDAO;
import info.tregmine.database.IPlayerReportDAO;
import info.tregmine.database.IWalletDAO;
import info.tregmine.database.IMentorLogDAO;
import info.tregmine.commands.MentorCommand;
import static info.tregmine.database.IInventoryDAO.InventoryType;
public class TregminePlayerListener implements Listener
{
private static class RankComparator implements Comparator<TregminePlayer>
{
private int order;
public RankComparator()
{
this.order = 1;
}
public RankComparator(boolean reverseOrder)
{
this.order = reverseOrder ? -1 : 1;
}
@Override
public int compare(TregminePlayer a, TregminePlayer b)
{
return order * (a.getGuardianRank() - b.getGuardianRank());
}
}
private final static String[] quitMessages =
new String[] {
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " deserted from the battlefield with a hearty good bye!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " stole the cookies and ran!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja platypus!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " parachuted of the plane and into the unknown!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja creeper!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " jumped off the plane with a cobble stone parachute!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " built Rome in one day and now deserves a break!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will come back soon because Tregmine is awesome!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " leaves the light and enter darkness.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnects from a better life.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " already miss the best friends in the world!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will build something epic next time.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " is not banned... yet!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " has left our world!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " went to browse Tregmine's forums instead!",
ChatColor.DARK_GRAY + "Quit - %s" + "'s" + ChatColor.DARK_GRAY + " CPU was killed by the Rendermen!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " logged out by accident!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the IRL warp!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the game due to IRL chunk error issues!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the Matrix. Say hi to Morpheus!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnected? What is this!? Impossibru!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found a lose cable and ate it.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the true END of minecraft.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found love elswhere.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " rage quit the server.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was not accidently banned by " + ChatColor.DARK_RED + "BlackX",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " got " + ChatColor.WHITE + "TROLLED by " + ChatColor.DARK_RED + "TheScavenger101",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " lost an epic rap battle with " + ChatColor.DARK_RED + "einand",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was bored to death by " + ChatColor.DARK_RED + "knipil",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " went squid fishing with " + ChatColor.DARK_RED + "GeorgeBombadil",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " shouldn't have joined a spelling bee with " + ChatColor.DARK_RED + "mejjad",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was paralyzed by a gaze from " + ChatColor.DARK_RED + "mksen",
};
private Tregmine plugin;
private Map<Item, TregminePlayer> droppedItems;
public TregminePlayerListener(Tregmine instance)
{
this.plugin = instance;
droppedItems = new HashMap<Item, TregminePlayer>();
}
@EventHandler
public void onPlayerClick(PlayerInteractEvent event)
{
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
Player player = event.getPlayer();
BlockState block = event.getClickedBlock().getState();
if (block instanceof Skull) {
Skull skull = (Skull) block;
if (!skull.getSkullType().equals(SkullType.PLAYER)) {
return;
}
String owner = skull.getOwner();
TregminePlayer skullowner = plugin.getPlayerOffline(owner);
if (skullowner != null){
ChatColor C = skullowner.getNameColor();
player.sendMessage(ChatColor.AQUA + "This is " + C + owner + "'s " + ChatColor.AQUA + "head!");
}else{
player.sendMessage(ChatColor.AQUA + "This is " + ChatColor.WHITE + owner + ChatColor.AQUA + "'s head!");
}
}
}
@EventHandler
public void onPlayerItemHeld(InventoryCloseEvent event)
{
Player player = (Player) event.getPlayer();
if (player.getGameMode() == GameMode.CREATIVE) {
for (ItemStack item : player.getInventory().getContents()) {
if (item != null) {
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(Created.CREATIVE.toColorString());
TregminePlayer p = this.plugin.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getChatName());
lore.add(ChatColor.WHITE + "Value: " + ChatColor.MAGIC
+ "0000" + ChatColor.RESET + ChatColor.WHITE
+ " Treg");
meta.setLore(lore);
item.setItemMeta(meta);
}
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event)
{
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
Location loc = block.getLocation();
if (player.getItemInHand().getType() == Material.BOOK) {
player.sendMessage(ChatColor.DARK_AQUA + "Type: "
+ ChatColor.AQUA + block.getType().toString() + " ("
+ ChatColor.BLUE + block.getType().getId()
+ ChatColor.DARK_AQUA + ")");
player.sendMessage(ChatColor.DARK_AQUA + "Data: "
+ ChatColor.AQUA + (int) block.getData());
player.sendMessage(ChatColor.RED + "X" + ChatColor.WHITE + ", "
+ ChatColor.GREEN + "Y" + ChatColor.WHITE + ", "
+ ChatColor.BLUE + "Z" + ChatColor.WHITE + ": "
+ ChatColor.RED + loc.getBlockX() + ChatColor.WHITE
+ ", " + ChatColor.GREEN + loc.getBlockY()
+ ChatColor.WHITE + ", " + ChatColor.BLUE
+ loc.getBlockZ());
try {
player.sendMessage(ChatColor.DARK_AQUA + "Biome: "
+ ChatColor.AQUA + block.getBiome().toString());
} catch (Exception e) {
player.sendMessage(ChatColor.DARK_AQUA + "Biome: "
+ ChatColor.AQUA + "NULL");
}
Tregmine.LOGGER.info("POS: " + loc.getBlockX() + ", "
+ loc.getBlockY() + ", " + loc.getBlockZ());
}
}
}
@EventHandler
public void onPreCommand(PlayerCommandPreprocessEvent event)
{
// Tregmine.LOGGER.info("COMMAND: " + event.getPlayer().getName() + "::"
// + event.getMessage());
}
@EventHandler
public void onPlayerLogin(PlayerLoginEvent event)
{
TregminePlayer player;
try {
player = plugin.addPlayer(event.getPlayer(), event.getAddress());
if (player == null) {
event.disallow(Result.KICK_OTHER, "Something went wrong");
return;
}
}
catch (PlayerBannedException e) {
event.disallow(Result.KICK_BANNED, e.getMessage());
return;
}
if (player.getRank() == Rank.UNVERIFIED) {
player.setChatState(TregminePlayer.ChatState.SETUP);
}
if (player.getLocation().getWorld().getName().matches("world_the_end")) {
player.teleport(this.plugin.getServer().getWorld("world")
.getSpawnLocation());
}
if (player.getKeyword() != null) {
String keyword =
player.getKeyword()
+ ".mc.tregmine.info:25565".toLowerCase();
Tregmine.LOGGER.warning("host: " + event.getHostname());
Tregmine.LOGGER.warning("keyword:" + keyword);
if (keyword.equals(event.getHostname().toLowerCase())
|| keyword.matches("mc.tregmine.info")) {
Tregmine.LOGGER.warning(player.getName()
+ " keyword :: success");
}
else {
Tregmine.LOGGER.warning(player.getName() + " keyword :: faild");
event.disallow(Result.KICK_BANNED, "Wrong keyword!");
}
}
else {
Tregmine.LOGGER.warning(player.getName() + " keyword :: notset");
}
if (player.getRank() == Rank.GUARDIAN) {
player.setGuardianState(TregminePlayer.GuardianState.QUEUED);
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
event.setJoinMessage(null);
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (player == null) {
event.getPlayer().kickPlayer("error loading profile!");
return;
}
Rank rank = player.getRank();
// Handle invisibility, if set
List<TregminePlayer> players = plugin.getOnlinePlayers();
if (player.hasFlag(TregminePlayer.Flags.INVISIBLE)) {
player.sendMessage(ChatColor.YELLOW + "You are now invisible!");
// Hide the new player from all existing players
for (TregminePlayer current : players) {
if (!current.getRank().canVanish()) {
current.hidePlayer(player);
} else {
current.showPlayer(player);
}
}
}
else {
for (TregminePlayer current : players) {
current.showPlayer(player);
}
}
// Hide currently invisible players from the player that just signed on
for (TregminePlayer current : players) {
if (current.hasFlag(TregminePlayer.Flags.INVISIBLE)) {
player.hidePlayer(current);
} else {
player.showPlayer(current);
}
if (player.getRank().canVanish()) {
player.showPlayer(current);
}
}
// Set applicable game mode
if (rank == Rank.BUILDER) {
player.setGameMode(GameMode.CREATIVE);
}
else if (!rank.canUseCreative()) {
player.setGameMode(GameMode.SURVIVAL);
}
// Try to find a mentor for new players
if (rank == Rank.UNVERIFIED) {
return;
}
// Check if the player is allowed to fly
if (player.hasFlag(TregminePlayer.Flags.HARDWARNED)) {
player.sendMessage("You are hardwarned and are not allowed to fly.");
player.setAllowFlight(false);
} else if (rank.canFly()) {
player.sendMessage("You are allowed to fly");
player.setAllowFlight(true);
} else {
player.sendMessage("no-z-cheat");
player.sendMessage("You are NOT allowed to fly");
player.setAllowFlight(false);
}
try (IContext ctx = plugin.createContext()) {
if (player.getPlayTime() > 10 * 3600 && rank == Rank.SETTLER) {
player.setRank(Rank.RESIDENT);
rank = Rank.RESIDENT;
IPlayerDAO playerDAO = ctx.getPlayerDAO();
playerDAO.updatePlayer(player);
playerDAO.updatePlayerInfo(player);
player.sendMessage(ChatColor.DARK_GREEN + "Congratulations! " +
"You are now a resident on Tregmine!");
}
// Load inventory from DB - disabled until we know it's reliable
/*PlayerInventory inv = (PlayerInventory) player.getInventory();
DBInventoryDAO invDAO = new DBInventoryDAO(conn);
int invId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER);
if (invId != -1) {
Tregmine.LOGGER.info("Loaded inventory from DB");
inv.setContents(invDAO.getStacks(invId, inv.getSize()));
}
int armorId = invDAO.getInventoryId(player.getId(),
InventoryType.PLAYER_ARMOR);
if (armorId != -1) {
Tregmine.LOGGER.info("Loaded armor from DB");
inv.setArmorContents(invDAO.getStacks(armorId, 4));
}*/
// Load motd
IMotdDAO motdDAO = ctx.getMotdDAO();
String message = motdDAO.getMotd();
if (message != null) {
String[] lines = message.split("\n");
for (String line : lines) {
player.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + line);
}
}
} catch (DAOException e) {
throw new RuntimeException(e);
}
// Show a score board
if (player.isOnline()) {
ScoreboardManager manager = Bukkit.getScoreboardManager();
Scoreboard board = manager.getNewScoreboard();
Objective objective = board.registerNewObjective("1", "2");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
objective.setDisplayName("" + ChatColor.DARK_RED + ""
+ ChatColor.BOLD + "Welcome to Tregmine!");
try (IContext ctx = plugin.createContext()) {
IWalletDAO walletDAO = ctx.getWalletDAO();
// Get a fake offline player
String desc = ChatColor.BLACK + "Your Balance:";
Score score = objective.getScore(Bukkit.getOfflinePlayer(desc));
score.setScore((int)walletDAO.balance(player));
} catch (DAOException e) {
throw new RuntimeException(e);
}
player.setScoreboard(board);
ScoreboardClearTask.start(plugin, player);
}
// Recalculate guardians
activateGuardians();
if (rank == Rank.TOURIST) {
// Try to find a mentor for tourists that rejoin
MentorCommand.findMentor(plugin, player);
}
else if (player.canMentor()) {
Queue<TregminePlayer> students = plugin.getStudentQueue();
if (students.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Mentors are needed! " +
"Type /mentor to offer your services!");
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event)
{
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (player == null) {
Tregmine.LOGGER.info(event.getPlayer().getName() + " was not found " +
"in players map when quitting.");
return;
}
event.setQuitMessage(null);
if (!player.isOp()) {
String message = null;
if (player.getQuitMessage() != null) {
message = player.getChatName() + " quit: " + ChatColor.YELLOW + player.getQuitMessage();
} else {
Random rand = new Random();
int msgIndex = rand.nextInt(quitMessages.length);
message = String.format(quitMessages[msgIndex], player.getChatName());
}
plugin.getServer().broadcastMessage(message);
}
// Look if there are any students being mentored by the exiting player
if (player.getStudent() != null) {
TregminePlayer student = player.getStudent();
try (IContext ctx = plugin.createContext()) {
IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO();
int mentorLogId = mentorLogDAO.getMentorLogId(student, player);
mentorLogDAO.updateMentorLogEvent(mentorLogId,
IMentorLogDAO.MentoringEvent.CANCELLED);
} catch (DAOException e) {
throw new RuntimeException(e);
}
student.setMentor(null);
player.setStudent(null);
student.sendMessage(ChatColor.RED + "Your mentor left. We'll try " +
"to find a new one for you as quickly as possible.");
MentorCommand.findMentor(plugin, student);
}
else if (player.getMentor() != null) {
TregminePlayer mentor = player.getMentor();
try (IContext ctx = plugin.createContext()) {
IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO();
int mentorLogId = mentorLogDAO.getMentorLogId(player, mentor);
mentorLogDAO.updateMentorLogEvent(mentorLogId,
IMentorLogDAO.MentoringEvent.CANCELLED);
} catch (DAOException e) {
throw new RuntimeException(e);
}
mentor.setStudent(null);
player.setMentor(null);
mentor.sendMessage(ChatColor.RED + "Your student left. :(");
}
plugin.removePlayer(player);
Tregmine.LOGGER.info("Unloaded settings for " + player.getName() + ".");
activateGuardians();
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event)
{
TregminePlayer player = this.plugin.getPlayer(event.getPlayer());
if (player == null) {
event.getPlayer().kickPlayer("error loading profile!");
}
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
TregminePlayer player = this.plugin.getPlayer(event.getPlayer());
if (player.getGameMode() == GameMode.CREATIVE) {
event.setCancelled(true);
return;
}
if (!player.getRank().arePickupsLogged()) {
return;
}
if (!player.getRank().canPickup()) {
event.setCancelled(true);
return;
}
try (IContext ctx = plugin.createContext()) {
Item item = event.getItem();
TregminePlayer droppedBy = droppedItems.get(item);
if (droppedBy != null && droppedBy.getId() != player.getId()) {
ItemStack stack = item.getItemStack();
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertGiveLog(droppedBy, player, stack);
player.sendMessage(ChatColor.YELLOW + "You got " +
stack.getAmount() + " " + stack.getType() + " from " +
droppedBy.getName() + ".");
if (droppedBy.isOnline()) {
droppedBy.sendMessage(ChatColor.YELLOW + "You gave " +
stack.getAmount() + " " + stack.getType() + " to " +
player.getName() + ".");
}
}
droppedItems.remove(item);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
TregminePlayer player = this.plugin.getPlayer(event.getPlayer());
if (player.getGameMode() == GameMode.CREATIVE) {
event.setCancelled(true);
return;
}
if (!player.getRank().arePickupsLogged()) {
return;
}
if (!player.getRank().canPickup()) {
event.setCancelled(true);
return;
}
Item item = event.getItemDrop();
droppedItems.put(item, player);
}
@EventHandler
public void onPlayerKick(PlayerKickEvent event)
{
event.setLeaveMessage(null);
}
private void activateGuardians()
{
// Identify all guardians and categorize them based on their current
// state
Player[] players = plugin.getServer().getOnlinePlayers();
Set<TregminePlayer> guardians = new HashSet<TregminePlayer>();
List<TregminePlayer> activeGuardians = new ArrayList<TregminePlayer>();
List<TregminePlayer> inactiveGuardians =
new ArrayList<TregminePlayer>();
List<TregminePlayer> queuedGuardians = new ArrayList<TregminePlayer>();
for (Player srvPlayer : players) {
TregminePlayer guardian = plugin.getPlayer(srvPlayer.getName());
if (guardian == null || guardian.getRank() != Rank.GUARDIAN) {
continue;
}
TregminePlayer.GuardianState state = guardian.getGuardianState();
if (state == null) {
state = TregminePlayer.GuardianState.QUEUED;
}
switch (state) {
case ACTIVE:
activeGuardians.add(guardian);
break;
case INACTIVE:
inactiveGuardians.add(guardian);
break;
case QUEUED:
queuedGuardians.add(guardian);
break;
}
guardian.setGuardianState(TregminePlayer.GuardianState.QUEUED);
guardians.add(guardian);
}
Collections.sort(activeGuardians, new RankComparator());
Collections.sort(inactiveGuardians, new RankComparator(true));
Collections.sort(queuedGuardians, new RankComparator());
int idealCount = (int) Math.ceil(Math.sqrt(players.length) / 2);
// There are not enough guardians active, we need to activate a few more
if (activeGuardians.size() <= idealCount) {
// Make a pool of every "willing" guardian currently online
List<TregminePlayer> activationList =
new ArrayList<TregminePlayer>();
activationList.addAll(activeGuardians);
activationList.addAll(queuedGuardians);
// If the pool isn't large enough to satisfy demand, we add the
// guardians
// that have made themselves inactive as well.
if (activationList.size() < idealCount) {
int diff = idealCount - activationList.size();
// If there aren't enough of these to satisfy demand, we add all
// of them
if (diff >= inactiveGuardians.size()) {
activationList.addAll(inactiveGuardians);
}
// Otherwise we just add the lowest ranked of the inactive
else {
activationList.addAll(inactiveGuardians.subList(0, diff));
}
}
// If there are more than necessarry guardians online, only activate
// the most highly ranked.
Set<TregminePlayer> activationSet;
if (activationList.size() > idealCount) {
Collections.sort(activationList, new RankComparator());
activationSet =
new HashSet<TregminePlayer>(activationList.subList(0,
idealCount));
}
else {
activationSet = new HashSet<TregminePlayer>(activationList);
}
// Perform activation
StringBuffer globalMessage = new StringBuffer();
String delim = "";
for (TregminePlayer guardian : activationSet) {
guardian.setGuardianState(TregminePlayer.GuardianState.ACTIVE);
globalMessage.append(delim);
globalMessage.append(guardian.getName());
delim = ", ";
}
Set<TregminePlayer> oldActiveGuardians =
new HashSet<TregminePlayer>(activeGuardians);
if (!activationSet.containsAll(oldActiveGuardians)
|| activationSet.size() != oldActiveGuardians.size()) {
plugin.getServer()
.broadcastMessage(
ChatColor.BLUE
+ "Active guardians are: "
+ globalMessage
+ ". Please contact any of them if you need help.");
// Notify previously active guardian of their state change
for (TregminePlayer guardian : activeGuardians) {
if (!activationSet.contains(guardian)) {
guardian.sendMessage(ChatColor.BLUE
+ "You are no longer on active duty, and should not respond to help requests, unless asked by an admin or active guardian.");
}
}
// Notify previously inactive guardians of their state change
for (TregminePlayer guardian : inactiveGuardians) {
if (activationSet.contains(guardian)) {
guardian.sendMessage(ChatColor.BLUE
+ "You have been restored to active duty and should respond to help requests.");
}
}
// Notify previously queued guardians of their state change
for (TregminePlayer guardian : queuedGuardians) {
if (activationSet.contains(guardian)) {
guardian.sendMessage(ChatColor.BLUE
+ "You are now on active duty and should respond to help requests.");
}
}
}
}
}
}
|
package com.dyz.persist.util;
public class Naizi {
// private int[] paiList = new int[]{1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,2};
// public static void main(String[] args){
// Naizi test = new Naizi();
// System.out.println(Naizi.testHuiPai(test.paiList));
public static boolean testHuiPai(int [][] paiList ){
int[] pai =GlobalUtil.CloneIntList(paiList[0]);
for(int i=0;i<paiList[0].length;i++){
if(paiList[1][i] == 1 && pai[i] >= 3) {
pai[i] -= 3;
}else if(paiList[1][i] == 2 && pai[i] == 4){
pai[i] -= 4;
}
}
return getNeedHunNum(pai);
}
/**
*
* type
* @return
*/
private static boolean getNeedHunNum(int[] paiList){
int zhong = paiList[31];
int[] wan_arr = new int[9];
int[] tiao_arr = new int[9];
int[] tong_arr = new int[9];
int needNum = 0;
int index = 0;
for(int i=0;i<27;i++){
if(i<9){
wan_arr[index] = paiList[i];
index++;
}
if(i>=9 && i<18){
if(i == 9){
index = 0;
}
tiao_arr[index] = paiList[i];
index++;
}
if(i>=18){
if(i == 18){
index = 0;
}
tong_arr[index] = paiList[i];
index++;
}
}
needNum = getNumWithJiang(wan_arr.clone()) + getNumber(tiao_arr.clone()) + getNumber(tong_arr.clone());
if(needNum <= zhong){
return true;
}
else {
needNum = getNumber(wan_arr.clone()) + getNumWithJiang(tiao_arr.clone()) + getNumber(tong_arr.clone());
if(needNum <= zhong){
return true;
}
else{
needNum = getNumber(wan_arr.clone()) + getNumber(tiao_arr.clone()) + getNumWithJiang(tong_arr.clone());
if(needNum <= zhong){
return true;
}
else{
return false;
}
}
}
}
private static int getNumWithJiang(int[] temp_arr){
boolean isjiang = false;
int result = 0;
boolean isOne = true;
for(int i=0;i<9;i++){
if(temp_arr[i]>1){
isOne = false;
}
}
for(int i=0;i<9;i++){
if(temp_arr[i]>0){
if(temp_arr[i] >= 3){
if(i<7) {
if (temp_arr[i + 1] == 1 && temp_arr[i + 2] == 1) {
temp_arr[i]
temp_arr[i + 1]
temp_arr[i + 2]
i
} else {
temp_arr[i] -= 3;
i
}
}else{
temp_arr[i] -= 3;
i
}
}else {
if (i < 7) {
if (temp_arr[i] >= 2 && isjiang == false && temp_arr[i + 1] == 0) {
temp_arr[i] -= 2;
isjiang = true;
i
} else {
if (temp_arr[i + 1] > 0 && temp_arr[i + 2] > 0) {
if(temp_arr[i] >=2 && isjiang == false){
temp_arr[i] -= 2;
isjiang = true;
i
}else {
temp_arr[i]
temp_arr[i + 1]
temp_arr[i + 2]
i
}
} else if (temp_arr[i + 1] > 0 && temp_arr[i + 2] == 0) {
if(isjiang == false && temp_arr[i] >= 2){
isjiang = true;
temp_arr[i] -= 2;
i
}else{
temp_arr[i]
temp_arr[i + 1]
result++;
i
}
} else if (temp_arr[i + 1] == 0 && temp_arr[i + 2] > 0) {
if (isOne) {
if (isjiang == false) {
if (temp_arr[i] == 1) {
temp_arr[i] = 0;
isjiang = true;
result++;
i
}
}
} else {
temp_arr[i]
temp_arr[i + 2]
result++;
i
}
} else if (temp_arr[i + 1] == 0 && temp_arr[i + 2] == 0) {
if (isjiang == true) {
temp_arr[i + 1]++;
result++;
i
} else {
if (temp_arr[i] == 1) {
temp_arr[i] = 0;
isjiang = true;
result++;
i
} else {
if (temp_arr[i] >= 2) {
isjiang = true;
temp_arr[i] -= 2;
i
}
}
}
}
}
} else {
if (i == 7) {
if (isjiang == false) {
if (temp_arr[i] == 1) {
temp_arr[i] = 0;
result++;
isjiang = true;
} else if (temp_arr[i] >= 2) {
temp_arr[i] -= 2;
isjiang = true;
i
}
} else {
if (temp_arr[i] > 0 && temp_arr[i + 1] > 0) {
temp_arr[i]
temp_arr[i + 1]
result++;
i
} else if (temp_arr[i] > 0 && temp_arr[i + 1] == 0) {
result = result + 3 - temp_arr[i];
temp_arr[i] = 0;
}
}
} else {
if (isjiang == false) {
if (temp_arr[i] == 1) {
temp_arr[i] = 0;
result++;
isjiang = true;
} else if (temp_arr[i] >= 2) {
temp_arr[i] -= 2;
isjiang = true;
i
}
} else {
result = result + 3 - temp_arr[i];
temp_arr[i] = 0;
}
}
}
}
}
}
if(isjiang == false){
result += 2;
}
System.out.print("getNumWithJiang ===> "+result+" ==>> ");
for(int a = 0;a<temp_arr.length;a++){
System.out.print(temp_arr[a]+",");
}
System.out.println();
return result;
}
private static int getNumber(int[] temp_arr){
int result = 0;
for(int i=0;i<9;i++) {
if(temp_arr[i] > 0) {
if(temp_arr[i] >= 3){
temp_arr[i] -= 3;
i
}else {
if (i < 7) {
if (temp_arr[i + 1] > 0 && temp_arr[i + 2] > 0) {
temp_arr[i]
temp_arr[i + 1]
temp_arr[i + 2]
i
} else if (temp_arr[i + 1] > 0 && temp_arr[i + 2] == 0) {
temp_arr[i]
temp_arr[i + 1]
result++;
i
} else if (temp_arr[i + 1] == 0 && temp_arr[i + 2] > 0) {
temp_arr[i]
temp_arr[i + 2]
result++;
i
} else if (temp_arr[i + 1] == 0 && temp_arr[i + 2] == 0) {
if (temp_arr[i] == 2) {
temp_arr[i] = 0;
result++;
} else {
temp_arr[i] = 0;
result += 2;
}
}
} else {
if (i == 7) {
if (temp_arr[i] > 0 && temp_arr[i + 1] > 0) {
temp_arr[i]
temp_arr[i + 1]
result++;
i
} else if (temp_arr[i] > 0 && temp_arr[i + 1] == 0) {
result = result + 3 - temp_arr[i];
temp_arr[i] = 0;
}
} else {
result = result + 3 - temp_arr[i];
temp_arr[i] = 0;
}
}
}
}
}
System.out.print("getNumber ===> "+result+" ==>> ");
for(int a = 0;a<temp_arr.length;a++){
System.out.print(temp_arr[a]+",");
}
System.out.println();
return result;
}
public static void main(String[] args){
int [] test = new int[]{0,2,0,1,0,0,0,0,0, 1,1,1,0,0,0,0,0,0, 0,0,1,1,1,0,0,0,0, 0,0,0,0,2,0,0};
getNeedHunNum(test);
}
}
|
package org.apache.velocity.context;
import java.util.Hashtable;
import java.io.Serializable;
/**
* Interface describing the application data context. This set of
* routines is used by the application to set and remove 'named' data
* object to pass them to the template engine to use when rendering
* a template.
*
* This is the same set of methods supported by the original Context
* class
*
* @see org.apache.velocity.context.AbstractContext
* @see org.apache.velocity.VelocityContext
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: Context.java,v 1.4 2001/10/23 20:48:04 dlr Exp $
*/
public interface Context
{
/**
* Adds a name/value pair to the context.
*
* @param key The name to key the provided value with.
* @param value The corresponding value.
*/
Object put(String key, Object value);
/**
* Gets the value corresponding to the provided key from the context.
*
* @param key The name of the desired value.
* @return The value corresponding to the provided key.
*/
Object get(String key);
/**
* Indicates whether the specified key is in the context.
*
* @param key The key to look for.
* @return Whether the key is in the context.
*/
boolean containsKey(Object key);
/**
* Get all the keys for the values in the context
*/
Object[] getKeys();
/**
* Removes the value associated with the specified key from the context.
*
* @param key The name of the value to remove.
* @return The value that the key was mapped to, or <code>null</code>
* if unmapped.
*/
Object remove(Object key);
}
|
package info.tregmine.listeners;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scoreboard.*;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import info.tregmine.Tregmine;
import info.tregmine.api.*;
import info.tregmine.api.lore.Created;
import info.tregmine.api.util.ScoreboardClearTask;
import info.tregmine.commands.MentorCommand;
import info.tregmine.database.*;
import info.tregmine.events.PlayerMoveBlockEvent;
import info.tregmine.quadtree.Point;
import info.tregmine.zones.*;
public class TregminePlayerListener implements Listener
{
private static class RankComparator implements Comparator<TregminePlayer>
{
private int order;
public RankComparator()
{
this.order = 1;
}
public RankComparator(boolean reverseOrder)
{
this.order = reverseOrder ? -1 : 1;
}
@Override
public int compare(TregminePlayer a, TregminePlayer b)
{
return order * (a.getGuardianRank() - b.getGuardianRank());
}
}
private final static String[] quitMessages =
new String[] {
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " deserted from the battlefield with a hearty good bye!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " stole the cookies and ran!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja platypus!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " parachuted of the plane and into the unknown!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja creeper!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " jumped off the plane with a cobble stone parachute!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " built Rome in one day and now deserves a break!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will come back soon because Tregmine is awesome!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " leaves the light and enter darkness.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnects from a better life.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " already miss the best friends in the world!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will build something epic next time.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " is not banned... yet!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " has left our world!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " went to browse Tregmine's forums instead!",
ChatColor.DARK_GRAY + "Quit - %s" + "'s" + ChatColor.DARK_GRAY + " CPU was killed by the Rendermen!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " logged out by accident!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the IRL warp!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the game due to IRL chunk error issues!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the Matrix. Say hi to Morpheus!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnected? What is this!? Impossibru!",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found a lose cable and ate it.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the true END of minecraft.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found love elswhere.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " rage quit the server.",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was not accidently banned by " + ChatColor.DARK_RED + "BlackX",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " got " + ChatColor.WHITE + "TROLLED by " + ChatColor.DARK_RED + "TheScavenger101",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " lost an epic rap battle with " + ChatColor.DARK_RED + "einand",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was bored to death by " + ChatColor.DARK_RED + "knipil",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " went squid fishing with " + ChatColor.DARK_RED + "GeorgeBombadil",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " shouldn't have joined a spelling bee with " + ChatColor.DARK_RED + "mejjad",
ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was paralyzed by a gaze from " + ChatColor.DARK_RED + "mksen",
};
private Tregmine plugin;
private Map<Item, TregminePlayer> droppedItems;
public TregminePlayerListener(Tregmine instance)
{
this.plugin = instance;
droppedItems = new HashMap<Item, TregminePlayer>();
}
@EventHandler
public void onPlayerClick(PlayerInteractEvent event)
{
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
Player player = event.getPlayer();
BlockState block = event.getClickedBlock().getState();
if (block instanceof Skull) {
Skull skull = (Skull) block;
if (!skull.getSkullType().equals(SkullType.PLAYER)) {
return;
}
String owner = skull.getOwner();
TregminePlayer skullowner = plugin.getPlayerOffline(owner);
if (skullowner != null){
ChatColor C = skullowner.getNameColor();
player.sendMessage(ChatColor.AQUA + "This is " + C + owner + "'s " + ChatColor.AQUA + "head!");
}else{
player.sendMessage(ChatColor.AQUA + "This is " + ChatColor.WHITE + owner + ChatColor.AQUA + "'s head!");
}
}
}
@EventHandler
public void onPlayerItemHeld(InventoryCloseEvent event)
{
Player player = (Player) event.getPlayer();
if (player.getGameMode() == GameMode.CREATIVE) {
for (ItemStack item : player.getInventory().getContents()) {
if (item != null) {
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(Created.CREATIVE.toColorString());
TregminePlayer p = this.plugin.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getChatName());
lore.add(ChatColor.WHITE + "Value: " + ChatColor.MAGIC
+ "0000" + ChatColor.RESET + ChatColor.WHITE
+ " Treg");
meta.setLore(lore);
item.setItemMeta(meta);
}
}
}
TregminePlayer p = plugin.getPlayer(player);
p.saveInventory(p.getCurrentInventory());
}
@EventHandler
public void onPlayerRespawnSave(PlayerRespawnEvent event)
{
TregminePlayer p = plugin.getPlayer(event.getPlayer());
p.saveInventory(p.getCurrentInventory());
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event)
{
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
Location loc = block.getLocation();
if (player.getItemInHand().getType() == Material.BOOK) {
player.sendMessage(ChatColor.DARK_AQUA + "Type: "
+ ChatColor.AQUA + block.getType().toString() + " ("
+ ChatColor.BLUE + block.getType().getId()
+ ChatColor.DARK_AQUA + ")");
player.sendMessage(ChatColor.DARK_AQUA + "Data: "
+ ChatColor.AQUA + (int) block.getData());
player.sendMessage(ChatColor.RED + "X" + ChatColor.WHITE + ", "
+ ChatColor.GREEN + "Y" + ChatColor.WHITE + ", "
+ ChatColor.BLUE + "Z" + ChatColor.WHITE + ": "
+ ChatColor.RED + loc.getBlockX() + ChatColor.WHITE
+ ", " + ChatColor.GREEN + loc.getBlockY()
+ ChatColor.WHITE + ", " + ChatColor.BLUE
+ loc.getBlockZ());
try {
player.sendMessage(ChatColor.DARK_AQUA + "Biome: "
+ ChatColor.AQUA + block.getBiome().toString());
} catch (Exception e) {
player.sendMessage(ChatColor.DARK_AQUA + "Biome: "
+ ChatColor.AQUA + "NULL");
}
Tregmine.LOGGER.info("POS: " + loc.getBlockX() + ", "
+ loc.getBlockY() + ", " + loc.getBlockZ());
}
}
}
@EventHandler
public void onPreCommand(PlayerCommandPreprocessEvent event)
{
// Tregmine.LOGGER.info("COMMAND: " + event.getPlayer().getName() + "::"
// + event.getMessage());
}
@EventHandler
public void onPlayerLogin(PlayerLoginEvent event)
{
TregminePlayer player;
try {
player = plugin.addPlayer(event.getPlayer(), event.getAddress());
if (player == null) {
event.disallow(Result.KICK_OTHER, "Something went wrong");
return;
}
}
catch (PlayerBannedException e) {
event.disallow(Result.KICK_BANNED, e.getMessage());
return;
}
if (player.getRank() == Rank.UNVERIFIED) {
player.setChatState(TregminePlayer.ChatState.SETUP);
}
if (player.getLocation().getWorld().getName().matches("world_the_end")) {
player.teleport(this.plugin.getServer().getWorld("world")
.getSpawnLocation());
}
if (player.getKeyword() != null) {
String keyword =
player.getKeyword()
+ ".mc.tregmine.info:25565".toLowerCase();
Tregmine.LOGGER.warning("host: " + event.getHostname());
Tregmine.LOGGER.warning("keyword:" + keyword);
if (keyword.equals(event.getHostname().toLowerCase())
|| keyword.matches("mc.tregmine.info")) {
Tregmine.LOGGER.warning(player.getName()
+ " keyword :: success");
}
else {
Tregmine.LOGGER.warning(player.getName() + " keyword :: faild");
event.disallow(Result.KICK_BANNED, "Wrong keyword!");
}
}
else {
Tregmine.LOGGER.warning(player.getName() + " keyword :: notset");
}
if (player.getRank() == Rank.GUARDIAN) {
player.setGuardianState(TregminePlayer.GuardianState.QUEUED);
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
event.setJoinMessage(null);
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (player == null) {
event.getPlayer().kickPlayer("error loading profile!");
return;
}
Rank rank = player.getRank();
// Handle invisibility, if set
List<TregminePlayer> players = plugin.getOnlinePlayers();
if (player.hasFlag(TregminePlayer.Flags.INVISIBLE)) {
player.sendMessage(ChatColor.YELLOW + "You are now invisible!");
// Hide the new player from all existing players
for (TregminePlayer current : players) {
if (!current.getRank().canVanish()) {
current.hidePlayer(player);
} else {
current.showPlayer(player);
}
}
}
else {
for (TregminePlayer current : players) {
current.showPlayer(player);
}
}
player.loadInventory("survival", false);
// Hide currently invisible players from the player that just signed on
for (TregminePlayer current : players) {
if (current.hasFlag(TregminePlayer.Flags.INVISIBLE)) {
player.hidePlayer(current);
} else {
player.showPlayer(current);
}
if (player.getRank().canVanish()) {
player.showPlayer(current);
}
}
// Set applicable game mode
if (rank == Rank.BUILDER) {
player.setGameMode(GameMode.CREATIVE);
}
else if (!rank.canUseCreative()) {
player.setGameMode(GameMode.SURVIVAL);
}
// Try to find a mentor for new players
if (rank == Rank.UNVERIFIED) {
return;
}
// Check if the player is allowed to fly
if (player.hasFlag(TregminePlayer.Flags.HARDWARNED) ||
player.hasFlag(TregminePlayer.Flags.SOFTWARNED)) {
player.sendMessage("You are warned and are not allowed to fly.");
player.setAllowFlight(false);
} else if (rank.canFly()) {
if (player.hasFlag(TregminePlayer.Flags.FLY_ENABLED)) {
player.sendMessage("Flying: Allowed and Enabled! Toggle flying with /fly");
player.setAllowFlight(true);
} else {
player.sendMessage("Flying: Allowed but Disabled! Toggle flying with /fly");
player.setAllowFlight(false);
}
} else {
player.sendMessage("no-z-cheat");
player.sendMessage("You are NOT allowed to fly");
player.setAllowFlight(false);
}
try (IContext ctx = plugin.createContext()) {
if (player.getPlayTime() > 10 * 3600 && rank == Rank.SETTLER) {
player.setRank(Rank.RESIDENT);
rank = Rank.RESIDENT;
IPlayerDAO playerDAO = ctx.getPlayerDAO();
playerDAO.updatePlayer(player);
playerDAO.updatePlayerInfo(player);
player.sendMessage(ChatColor.DARK_GREEN + "Congratulations! " +
"You are now a resident on Tregmine!");
}
// Load motd
IMotdDAO motdDAO = ctx.getMotdDAO();
String message = motdDAO.getMotd();
if (message != null) {
String[] lines = message.split("\n");
for (String line : lines) {
player.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + line);
}
}
} catch (DAOException e) {
throw new RuntimeException(e);
}
// Show a score board
if (player.isOnline()) {
ScoreboardManager manager = Bukkit.getScoreboardManager();
Scoreboard board = manager.getNewScoreboard();
Objective objective = board.registerNewObjective("1", "2");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
objective.setDisplayName("" + ChatColor.DARK_RED + ""
+ ChatColor.BOLD + "Welcome to Tregmine!");
try (IContext ctx = plugin.createContext()) {
IWalletDAO walletDAO = ctx.getWalletDAO();
// Get a fake offline player
String desc = ChatColor.BLACK + "Your Balance:";
Score score = objective.getScore(Bukkit.getOfflinePlayer(desc));
score.setScore((int)walletDAO.balance(player));
} catch (DAOException e) {
throw new RuntimeException(e);
}
try {
player.setScoreboard(board);
ScoreboardClearTask.start(plugin, player);
} catch (IllegalStateException e) {
// ignore
}
}
// Recalculate guardians
activateGuardians();
if (rank == Rank.TOURIST) {
// Try to find a mentor for tourists that rejoin
MentorCommand.findMentor(plugin, player);
}
else if (player.canMentor()) {
Queue<TregminePlayer> students = plugin.getStudentQueue();
if (students.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Mentors are needed! " +
"Type /mentor to offer your services!");
}
}
if (player.getKeyword() == null && player.getRank().mustUseKeyword()) {
player.sendMessage(ChatColor.RED + "You have not set a keyword! DO SO NOW.");
}
if (rank == Rank.DONATOR &&
!player.hasBadge(Badge.PHILANTROPIST)) {
player.awardBadgeLevel(Badge.PHILANTROPIST,
"For being a Tregmine donator!");
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event)
{
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (player == null) {
Tregmine.LOGGER.info(event.getPlayer().getName() + " was not found " +
"in players map when quitting.");
return;
}
player.saveInventory(player.getCurrentInventory());
event.setQuitMessage(null);
if (!player.isOp()) {
String message = null;
if (player.getQuitMessage() != null) {
message = player.getChatName() + " quit: " + ChatColor.YELLOW + player.getQuitMessage();
} else {
Random rand = new Random();
int msgIndex = rand.nextInt(plugin.getQuitMessages().size());
message = String.format(plugin.getQuitMessages().get(msgIndex), player.getChatName());
}
plugin.getServer().broadcastMessage(message);
}
// Look if there are any students being mentored by the exiting player
if (player.getStudent() != null) {
TregminePlayer student = player.getStudent();
try (IContext ctx = plugin.createContext()) {
IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO();
int mentorLogId = mentorLogDAO.getMentorLogId(student, player);
mentorLogDAO.updateMentorLogEvent(mentorLogId,
IMentorLogDAO.MentoringEvent.CANCELLED);
} catch (DAOException e) {
throw new RuntimeException(e);
}
student.setMentor(null);
player.setStudent(null);
student.sendMessage(ChatColor.RED + "Your mentor left. We'll try " +
"to find a new one for you as quickly as possible.");
MentorCommand.findMentor(plugin, student);
}
else if (player.getMentor() != null) {
TregminePlayer mentor = player.getMentor();
try (IContext ctx = plugin.createContext()) {
IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO();
int mentorLogId = mentorLogDAO.getMentorLogId(player, mentor);
mentorLogDAO.updateMentorLogEvent(mentorLogId,
IMentorLogDAO.MentoringEvent.CANCELLED);
} catch (DAOException e) {
throw new RuntimeException(e);
}
mentor.setStudent(null);
player.setMentor(null);
mentor.sendMessage(ChatColor.RED + "Your student left. :(");
}
plugin.removePlayer(player);
Tregmine.LOGGER.info("Unloaded settings for " + player.getName() + ".");
activateGuardians();
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event)
{
TregminePlayer player = this.plugin.getPlayer(event.getPlayer());
if (player == null) {
event.getPlayer().kickPlayer("error loading profile!");
}
}
@EventHandler
public void onPlayerBlockMove(PlayerMoveBlockEvent event)
{
TregminePlayer player = event.getPlayer();
// To add player.hasBadge for a flight badge when made
if (player.getRank().canFly() && player.isFlying() && player.isSprinting()) {
player.setFlySpeed(0.7f); // To be balanced
} else {
player.setFlySpeed(0.1f); // 0.1 is default
}
if (player.getGameMode() == GameMode.CREATIVE) {
return;
}
double pickupDistance = player.getRank().getPickupDistance();
List<Entity> entities = player.getNearbyEntities(pickupDistance, pickupDistance, pickupDistance);
for (Entity entity : entities) {
if (entity instanceof Item) {
Item item = (Item) entity;
if (item.getTicksLived() < item.getPickupDelay()) {
return;
}
HashMap<Integer, ItemStack> remaining = player.getInventory().addItem(item.getItemStack());
if (remaining.size() > 0) {
for (Entry<Integer, ItemStack> entry : remaining.entrySet()) {
item.setItemStack(entry.getValue());
}
} else {
item.remove();
}
}
}
}
/*@EventHandler
public void onDeath(PlayerDeathEvent event)
{
TregminePlayer player = plugin.getPlayer(event.getEntity());
try(IContext ctx = plugin.createContext()){
IWalletDAO dao = ctx.getWalletDAO();
dao.take(player, MathUtil.percentOf(dao.balance(player), 5));
} catch (DAOException e) {
e.printStackTrace();
}
}*/
@EventHandler
public void onPlayerFlight(PlayerToggleFlightEvent event)
{
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (player.getRank().canModifyZones()) {
return;
}
if (!player.getRank().canFly()) {
event.setCancelled(true);
}
if (player.hasFlag(TregminePlayer.Flags.HARDWARNED) ||
player.hasFlag(TregminePlayer.Flags.SOFTWARNED)) {
event.setCancelled(true);
}
Location loc = player.getLocation();
ZoneWorld world = plugin.getWorld(loc.getWorld());
Lot lot = world.findLot(new Point(loc.getBlockX(), loc.getBlockZ()));
if (lot == null) {
return;
}
if (!lot.hasFlag(Lot.Flags.FLIGHT_ALLOWED)) {
event.setCancelled(true);
}
if (loc.getWorld().getName().equalsIgnoreCase(plugin.getRulelessWorld().getName()) &&
(!player.getRank().canBypassWorld() && player.getGameMode() != GameMode.CREATIVE)) {
player.setAllowFlight(false);
player.setFlying(false);
}
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
TregminePlayer player = this.plugin.getPlayer(event.getPlayer());
if (player.getGameMode() == GameMode.CREATIVE) {
event.setCancelled(true);
return;
}
if (!player.getRank().arePickupsLogged()) {
return;
}
if (!player.getRank().canPickup()) {
event.setCancelled(true);
return;
}
try (IContext ctx = plugin.createContext()) {
Item item = event.getItem();
TregminePlayer droppedBy = droppedItems.get(item);
if (droppedBy != null && droppedBy.getId() != player.getId()) {
ItemStack stack = item.getItemStack();
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertGiveLog(droppedBy, player, stack);
player.sendMessage(ChatColor.YELLOW + "You got " +
stack.getAmount() + " " + stack.getType() + " from " +
droppedBy.getName() + ".");
if (droppedBy.isOnline()) {
droppedBy.sendMessage(ChatColor.YELLOW + "You gave " +
stack.getAmount() + " " + stack.getType() + " to " +
player.getName() + ".");
}
}
droppedItems.remove(item);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
TregminePlayer player = this.plugin.getPlayer(event.getPlayer());
if (player.getGameMode() == GameMode.CREATIVE) {
event.setCancelled(true);
return;
}
if (!player.getRank().arePickupsLogged()) {
return;
}
if (!player.getRank().canPickup()) {
event.setCancelled(true);
return;
}
Item item = event.getItemDrop();
droppedItems.put(item, player);
}
@EventHandler
public void onPlayerKick(PlayerKickEvent event)
{
event.setLeaveMessage(null);
}
@EventHandler
public void onNameTag(PlayerReceiveNameTagEvent event)
{
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (player == null) {
return;
}
event.setTag(player.getChatName());
}
private void activateGuardians()
{
// Identify all guardians and categorize them based on their current
// state
Player[] players = plugin.getServer().getOnlinePlayers();
Set<TregminePlayer> guardians = new HashSet<TregminePlayer>();
List<TregminePlayer> activeGuardians = new ArrayList<TregminePlayer>();
List<TregminePlayer> inactiveGuardians =
new ArrayList<TregminePlayer>();
List<TregminePlayer> queuedGuardians = new ArrayList<TregminePlayer>();
for (Player srvPlayer : players) {
TregminePlayer guardian = plugin.getPlayer(srvPlayer.getName());
if (guardian == null || guardian.getRank() != Rank.GUARDIAN) {
continue;
}
TregminePlayer.GuardianState state = guardian.getGuardianState();
if (state == null) {
state = TregminePlayer.GuardianState.QUEUED;
}
switch (state) {
case ACTIVE:
activeGuardians.add(guardian);
break;
case INACTIVE:
inactiveGuardians.add(guardian);
break;
case QUEUED:
queuedGuardians.add(guardian);
break;
}
guardian.setGuardianState(TregminePlayer.GuardianState.QUEUED);
guardians.add(guardian);
}
Collections.sort(activeGuardians, new RankComparator());
Collections.sort(inactiveGuardians, new RankComparator(true));
Collections.sort(queuedGuardians, new RankComparator());
int idealCount = (int) Math.ceil(Math.sqrt(players.length) / 2);
// There are not enough guardians active, we need to activate a few more
if (activeGuardians.size() <= idealCount) {
// Make a pool of every "willing" guardian currently online
List<TregminePlayer> activationList =
new ArrayList<TregminePlayer>();
activationList.addAll(activeGuardians);
activationList.addAll(queuedGuardians);
// If the pool isn't large enough to satisfy demand, we add the
// guardians
// that have made themselves inactive as well.
if (activationList.size() < idealCount) {
int diff = idealCount - activationList.size();
// If there aren't enough of these to satisfy demand, we add all
// of them
if (diff >= inactiveGuardians.size()) {
activationList.addAll(inactiveGuardians);
}
// Otherwise we just add the lowest ranked of the inactive
else {
activationList.addAll(inactiveGuardians.subList(0, diff));
}
}
// If there are more than necessarry guardians online, only activate
// the most highly ranked.
Set<TregminePlayer> activationSet;
if (activationList.size() > idealCount) {
Collections.sort(activationList, new RankComparator());
activationSet =
new HashSet<TregminePlayer>(activationList.subList(0,
idealCount));
}
else {
activationSet = new HashSet<TregminePlayer>(activationList);
}
// Perform activation
StringBuffer globalMessage = new StringBuffer();
String delim = "";
for (TregminePlayer guardian : activationSet) {
guardian.setGuardianState(TregminePlayer.GuardianState.ACTIVE);
globalMessage.append(delim);
globalMessage.append(guardian.getName());
delim = ", ";
}
Set<TregminePlayer> oldActiveGuardians =
new HashSet<TregminePlayer>(activeGuardians);
if (!activationSet.containsAll(oldActiveGuardians)
|| activationSet.size() != oldActiveGuardians.size()) {
plugin.getServer()
.broadcastMessage(
ChatColor.BLUE
+ "Active guardians are: "
+ globalMessage
+ ". Please contact any of them if you need help.");
// Notify previously active guardian of their state change
for (TregminePlayer guardian : activeGuardians) {
if (!activationSet.contains(guardian)) {
guardian.sendMessage(ChatColor.BLUE
+ "You are no longer on active duty, and should not respond to help requests, unless asked by an admin or active guardian.");
}
}
// Notify previously inactive guardians of their state change
for (TregminePlayer guardian : inactiveGuardians) {
if (activationSet.contains(guardian)) {
guardian.sendMessage(ChatColor.BLUE
+ "You have been restored to active duty and should respond to help requests.");
}
}
// Notify previously queued guardians of their state change
for (TregminePlayer guardian : queuedGuardians) {
if (activationSet.contains(guardian)) {
guardian.sendMessage(ChatColor.BLUE
+ "You are now on active duty and should respond to help requests.");
}
}
}
}
}
}
|
package com.ecyrd.jspwiki;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
/**
* Contains a number of static utility methods.
*/
public class TextUtil
{
static final String HEX_DIGITS = "0123456789ABCDEF";
/**
* java.net.URLEncoder.encode() method in JDK < 1.4 is buggy. This duplicates
* its functionality.
*/
protected static String urlEncode( byte[] rs )
{
StringBuffer result = new StringBuffer();
// Does the URLEncoding. We could use the java.net one, but
// it does not eat byte[]s.
for( int i = 0; i < rs.length; i++ )
{
char c = (char) rs[i];
switch( c )
{
case '_':
case '.':
case '*':
case '-':
result.append( c );
break;
case ' ':
result.append( '+' );
break;
default:
if( (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') )
{
result.append( c );
}
else
{
result.append( '%' );
result.append( HEX_DIGITS.charAt( (c & 0xF0) >> 4 ) );
result.append( HEX_DIGITS.charAt( c & 0x0F ) );
}
}
} // for
return result.toString();
}
protected static String urlDecode( byte[] bytes )
throws UnsupportedEncodingException,
IllegalArgumentException
{
if(bytes == null)
{
return null;
}
byte[] decodeBytes = new byte[bytes.length];
int decodedByteCount = 0;
try
{
for( int count = 0; count < bytes.length; count++ )
{
switch( bytes[count] )
{
case '+':
decodeBytes[decodedByteCount++] = (byte) ' ';
break ;
case '%':
decodeBytes[decodedByteCount++] = (byte)((HEX_DIGITS.indexOf(bytes[++count]) << 4) +
(HEX_DIGITS.indexOf(bytes[++count])) );
break ;
default:
decodeBytes[decodedByteCount++] = bytes[count] ;
}
}
}
catch (IndexOutOfBoundsException ae)
{
throw new IllegalArgumentException( "Malformed UTF-8 string?" );
}
String processedPageName = null ;
try
{
processedPageName = new String(decodeBytes, 0, decodedByteCount, "UTF-8") ;
}
catch (UnsupportedEncodingException e)
{
throw new UnsupportedEncodingException( "UTF-8 encoding not supported on this platform" );
}
return(processedPageName.toString());
}
/**
* As java.net.URLEncoder class, but this does it in UTF8 character set.
*/
public static String urlEncodeUTF8( String text )
{
byte[] rs = {};
try
{
rs = text.getBytes("UTF-8");
return urlEncode( rs );
}
catch( UnsupportedEncodingException e )
{
return java.net.URLEncoder.encode( text );
}
}
/**
* As java.net.URLDecoder class, but for UTF-8 strings.
*/
public static String urlDecodeUTF8( String utf8 )
{
String rs = null;
try
{
rs = urlDecode( utf8.getBytes("ISO-8859-1") );
}
catch( UnsupportedEncodingException e )
{
rs = java.net.URLDecoder.decode( utf8 );
}
return rs;
}
/**
* Provides encoded version of string depending on encoding.
* Encoding may be UTF-8 or ISO-8859-1 (default).
*
* <p>This implementation is the same as in
* FileSystemProvider.mangleName().
*/
public static String urlEncode( String data, String encoding )
{
// Presumably, the same caveats apply as in FileSystemProvider.
// Don't see why it would be horribly kludgy, though.
if( "UTF-8".equals( encoding ) )
return( TextUtil.urlEncodeUTF8( data ) );
else
return( TextUtil.urlEncode( data.getBytes() ) );
}
/**
* Provides decoded version of string depending on encoding.
* Encoding may be UTF-8 or ISO-8859-1 (default).
*
* <p>This implementation is the same as in
* FileSystemProvider.unmangleName().
*/
public static String urlDecode( String data, String encoding )
throws UnsupportedEncodingException,
IllegalArgumentException
{
// Presumably, the same caveats apply as in FileSystemProvider.
// Don't see why it would be horribly kludgy, though.
if( "UTF-8".equals( encoding ) )
return( TextUtil.urlDecodeUTF8( data ) );
else
return( TextUtil.urlDecode( data.getBytes() ) );
}
/**
* Replaces the relevant entities inside the String.
* All & >, <, and " are replaced by their
* respective names.
*
* @since 1.6.1
*/
public static String replaceEntities( String src )
{
src = replaceString( src, "&", "&" );
src = replaceString( src, "<", "<" );
src = replaceString( src, ">", ">" );
src = replaceString( src, "\"", """ );
return src;
}
/**
* Replaces a string with an other string.
*
* @param orig Original string. Null is safe.
* @param src The string to find.
* @param dest The string to replace <I>src</I> with.
*/
public static String replaceString( String orig, String src, String dest )
{
if( orig == null ) return null;
StringBuffer res = new StringBuffer();
int start, end = 0, last = 0;
while( (start = orig.indexOf(src,end)) != -1 )
{
res.append( orig.substring( last, start ) );
res.append( dest );
end = start+src.length();
last = start+src.length();
}
res.append( orig.substring( end ) );
return res.toString();
}
/**
* Replaces a part of a string with a new String.
*
* @param start Where in the original string the replacing should start.
* @param end Where the replacing should end.
* @param orig Original string. Null is safe.
* @param text The new text to insert into the string.
*/
public static String replaceString( String orig, int start, int end, String text )
{
if( orig == null ) return null;
StringBuffer buf = new StringBuffer(orig);
buf.replace( start, end, text );
return buf.toString();
}
/**
* Parses an integer parameter, returning a default value
* if the value is null or a non-number.
*/
public static int parseIntParameter( String value, int defvalue )
{
int val = defvalue;
try
{
val = Integer.parseInt( value );
}
catch( Exception e ) {}
return val;
}
/**
* Gets an integer-valued property from a standard Properties
* list. If the value does not exist, or is a non-integer, returns defVal.
*
* @since 2.1.48.
*/
public static int getIntegerProperty( Properties props,
String key,
int defVal )
{
String val = props.getProperty( key );
return parseIntParameter( val, defVal );
}
/**
* Gets a boolean property from a standard Properties list.
* Returns the default value, in case the key has not been set.
* <P>
* The possible values for the property are "true"/"false", "yes"/"no", or
* "on"/"off". Any value not recognized is always defined as "false".
*
* @param props A list of properties to search.
* @param key The property key.
* @param defval The default value to return.
*
* @return True, if the property "key" was set to "true", "on", or "yes".
*
* @since 2.0.11
*/
public static boolean getBooleanProperty( Properties props,
String key,
boolean defval )
{
String val = props.getProperty( key );
if( val == null ) return defval;
return isPositive( val );
}
/**
* Returns true, if the string "val" denotes a positive string. Allowed
* values are "yes", "on", and "true". Comparison is case-insignificant.
* Null values are safe.
*
* @param val Value to check.
* @return True, if val is "true", "on", or "yes"; otherwise false.
*
* @since 2.0.26
*/
public static boolean isPositive( String val )
{
if( val == null ) return false;
return ( val.equalsIgnoreCase("true") || val.equalsIgnoreCase("on") ||
val.equalsIgnoreCase("yes") );
}
/**
* Makes sure that the POSTed data is conforms to certain rules. These
* rules are:
* <UL>
* <LI>The data always ends with a newline (some browsers, such
* as NS4.x series, does not send a newline at the end, which makes
* the diffs a bit strange sometimes.
* <LI>The CR/LF/CRLF mess is normalized to plain CRLF.
* </UL>
*
* The reason why we're using CRLF is that most browser already
* return CRLF since that is the closest thing to a HTTP standard.
*/
public static String normalizePostData( String postData )
{
StringBuffer sb = new StringBuffer();
for( int i = 0; i < postData.length(); i++ )
{
switch( postData.charAt(i) )
{
case 0x0a: // LF, UNIX
sb.append( "\r\n" );
break;
case 0x0d: // CR, either Mac or MSDOS
sb.append( "\r\n" );
// If it's MSDOS, skip the LF so that we don't add it again.
if( i < postData.length()-1 && postData.charAt(i+1) == 0x0a )
{
i++;
}
break;
default:
sb.append( postData.charAt(i) );
break;
}
}
if( sb.length() < 2 || !sb.substring( sb.length()-2 ).equals("\r\n") )
{
sb.append( "\r\n" );
}
return sb.toString();
}
private static final int EOI = 0;
private static final int LOWER = 1;
private static final int UPPER = 2;
private static final int DIGIT = 3;
private static final int OTHER = 4;
private static int getCharKind(int c)
{
if (c==-1)
{
return EOI;
}
char ch = (char) c;
if (Character.isLowerCase(ch))
return LOWER;
else if (Character.isUpperCase(ch))
return UPPER;
else if (Character.isDigit(ch))
return DIGIT;
else
return OTHER;
}
/**
* Adds spaces in suitable locations of the input string. This is
* used to transform a WikiName into a more readable format.
*
* @param s String to be beautified.
* @return A beautified string.
*/
public static String beautifyString( String s )
{
return beautifyString( s, " " );
}
/**
* Adds spaces in suitable locations of the input string. This is
* used to transform a WikiName into a more readable format.
*
* @param s String to be beautified.
* @param space Use this string for the space character.
* @return A beautified string.
* @since 2.1.127
*/
public static String beautifyString( String s, String space )
{
StringBuffer result = new StringBuffer();
if( s == null || s.length() == 0 ) return "";
int cur = s.charAt(0);
int curKind = getCharKind(cur);
int prevKind = LOWER;
int nextKind = -1;
int next = -1;
int nextPos = 1;
while( curKind != EOI )
{
next = (nextPos < s.length()) ? s.charAt(nextPos++) : -1;
nextKind = getCharKind( next );
if( (prevKind == UPPER) && (curKind == UPPER) && (nextKind == LOWER) )
{
result.append(space);
result.append((char) cur);
}
else
{
result.append((char) cur);
if( ( (curKind == UPPER) && (nextKind == DIGIT) )
|| ( (curKind == LOWER) && ((nextKind == DIGIT) || (nextKind == UPPER)) )
|| ( (curKind == DIGIT) && ((nextKind == UPPER) || (nextKind == LOWER)) ))
{
result.append(space);
}
}
prevKind = curKind;
cur = next;
curKind = nextKind;
}
return result.toString();
}
public static Properties createProperties( String[] values )
throws IllegalArgumentException
{
if( values.length % 2 != 0 )
throw new IllegalArgumentException( "One value is missing.");
Properties props = new Properties();
for( int i = 0; i < values.length; i += 2 )
{
props.setProperty( values[i], values[i+1] );
}
return props;
}
public static int countSections( String pagedata )
{
int tags = 0;
int start = 0;
while( (start = pagedata.indexOf("----",start)) != -1 )
{
tags++;
start+=4;
}
return pagedata.length() > 0 ? tags+1 : 0;
}
public static String getSection( String pagedata, int section )
throws IllegalArgumentException
{
int tags = 0;
int start = 0;
int previous = 0;
while( (start = pagedata.indexOf("----",start)) != -1 )
{
if( ++tags == section )
{
return pagedata.substring( previous, start );
}
start += 4;
previous = start;
}
if( ++tags == section )
{
return pagedata.substring( previous );
}
throw new IllegalArgumentException("There is no section no. "+section+" on the page.");
}
/**
* A simple routine which just repeates the arguments. This is useful
* for creating something like a line or something.
*
* @param what String to repeat
* @param times How many times to repeat the string.
* @return Guess what?
* @since 2.1.98.
*/
public static String repeatString( String what, int times )
{
StringBuffer sb = new StringBuffer();
for( int i = 0; i < times; i++ )
{
sb.append( what );
}
return sb.toString();
}
}
|
package com.ecyrd.jspwiki;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
/**
* Contains a number of static utility methods.
*/
public class TextUtil
{
static final String HEX_DIGITS = "0123456789ABCDEF";
/**
* java.net.URLEncoder.encode() method in JDK < 1.4 is buggy. This duplicates
* its functionality.
*/
protected static String urlEncode( byte[] rs )
{
StringBuffer result = new StringBuffer();
// Does the URLEncoding. We could use the java.net one, but
// it does not eat byte[]s.
for( int i = 0; i < rs.length; i++ )
{
char c = (char) rs[i];
switch( c )
{
case '_':
case '.':
case '*':
case '-':
result.append( c );
break;
case ' ':
result.append( '+' );
break;
default:
if( (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') )
{
result.append( c );
}
else
{
result.append( '%' );
result.append( HEX_DIGITS.charAt( (c & 0xF0) >> 4 ) );
result.append( HEX_DIGITS.charAt( c & 0x0F ) );
}
}
} // for
return result.toString();
}
protected static String urlDecode( byte[] bytes )
throws UnsupportedEncodingException,
IllegalArgumentException
{
if(bytes == null)
{
return null;
}
byte[] decodeBytes = new byte[bytes.length];
int decodedByteCount = 0;
try
{
for( int count = 0; count < bytes.length; count++ )
{
switch( bytes[count] )
{
case '+':
decodeBytes[decodedByteCount++] = (byte) ' ';
break ;
case '%':
decodeBytes[decodedByteCount++] = (byte)((HEX_DIGITS.indexOf(bytes[++count]) << 4) +
(HEX_DIGITS.indexOf(bytes[++count])) );
break ;
default:
decodeBytes[decodedByteCount++] = bytes[count] ;
}
}
}
catch (IndexOutOfBoundsException ae)
{
throw new IllegalArgumentException( "Malformed UTF-8 string?" );
}
String processedPageName = null ;
try
{
processedPageName = new String(decodeBytes, 0, decodedByteCount, "UTF-8") ;
}
catch (UnsupportedEncodingException e)
{
throw new UnsupportedEncodingException( "UTF-8 encoding not supported on this platform" );
}
return(processedPageName.toString());
}
/**
* As java.net.URLEncoder class, but this does it in UTF8 character set.
*/
public static String urlEncodeUTF8( String text )
{
byte[] rs = {};
try
{
rs = text.getBytes("UTF-8");
return urlEncode( rs );
}
catch( UnsupportedEncodingException e )
{
return java.net.URLEncoder.encode( text );
}
}
/**
* As java.net.URLDecoder class, but for UTF-8 strings.
*/
public static String urlDecodeUTF8( String utf8 )
{
String rs = null;
try
{
rs = urlDecode( utf8.getBytes("ISO-8859-1") );
}
catch( UnsupportedEncodingException e )
{
rs = java.net.URLDecoder.decode( utf8 );
}
return rs;
}
/**
* Provides encoded version of string depending on encoding.
* Encoding may be UTF-8 or ISO-8859-1 (default).
*
* <p>This implementation is the same as in
* FileSystemProvider.mangleName().
*/
public static String urlEncode( String data, String encoding )
{
// Presumably, the same caveats apply as in FileSystemProvider.
// Don't see why it would be horribly kludgy, though.
if( "UTF-8".equals( encoding ) )
return( TextUtil.urlEncodeUTF8( data ) );
else
return( TextUtil.urlEncode( data.getBytes() ) );
}
/**
* Provides decoded version of string depending on encoding.
* Encoding may be UTF-8 or ISO-8859-1 (default).
*
* <p>This implementation is the same as in
* FileSystemProvider.unmangleName().
*/
public static String urlDecode( String data, String encoding )
throws UnsupportedEncodingException,
IllegalArgumentException
{
// Presumably, the same caveats apply as in FileSystemProvider.
// Don't see why it would be horribly kludgy, though.
if( "UTF-8".equals( encoding ) )
return( TextUtil.urlDecodeUTF8( data ) );
else
return( TextUtil.urlDecode( data.getBytes() ) );
}
/**
* Replaces the relevant entities inside the String.
* All & >, <, and " are replaced by their
* respective names.
*
* @since 1.6.1
*/
public static String replaceEntities( String src )
{
src = replaceString( src, "&", "&" );
src = replaceString( src, "<", "<" );
src = replaceString( src, ">", ">" );
src = replaceString( src, "\"", """ );
return src;
}
/**
* Replaces a string with an other string.
*
* @param orig Original string. Null is safe.
* @param src The string to find.
* @param dest The string to replace <I>src</I> with.
*/
public static String replaceString( String orig, String src, String dest )
{
if( orig == null ) return null;
StringBuffer res = new StringBuffer();
int start, end = 0, last = 0;
while( (start = orig.indexOf(src,end)) != -1 )
{
res.append( orig.substring( last, start ) );
res.append( dest );
end = start+src.length();
last = start+src.length();
}
res.append( orig.substring( end ) );
return res.toString();
}
/**
* Replaces a part of a string with a new String.
*
* @param start Where in the original string the replacing should start.
* @param end Where the replacing should end.
* @param orig Original string. Null is safe.
* @param text The new text to insert into the string.
*/
public static String replaceString( String orig, int start, int end, String text )
{
if( orig == null ) return null;
StringBuffer buf = new StringBuffer(orig);
buf.replace( start, end, text );
return buf.toString();
}
/**
* Parses an integer parameter, returning a default value
* if the value is null or a non-number.
*/
public static int parseIntParameter( String value, int defvalue )
{
int val = defvalue;
try
{
val = Integer.parseInt( value );
}
catch( Exception e ) {}
return val;
}
/**
* Gets an integer-valued property from a standard Properties
* list. If the value does not exist, or is a non-integer, returns defVal.
*
* @since 2.1.48.
*/
public static int getIntegerProperty( Properties props,
String key,
int defVal )
{
String val = props.getProperty( key );
return parseIntParameter( val, defVal );
}
/**
* Gets a boolean property from a standard Properties list.
* Returns the default value, in case the key has not been set.
* <P>
* The possible values for the property are "true"/"false", "yes"/"no", or
* "on"/"off". Any value not recognized is always defined as "false".
*
* @param props A list of properties to search.
* @param key The property key.
* @param defval The default value to return.
*
* @return True, if the property "key" was set to "true", "on", or "yes".
*
* @since 2.0.11
*/
public static boolean getBooleanProperty( Properties props,
String key,
boolean defval )
{
String val = props.getProperty( key );
if( val == null ) return defval;
return isPositive( val );
}
/**
* Returns true, if the string "val" denotes a positive string. Allowed
* values are "yes", "on", and "true". Comparison is case-insignificant.
* Null values are safe.
*
* @param val Value to check.
* @return True, if val is "true", "on", or "yes"; otherwise false.
*
* @since 2.0.26
*/
public static boolean isPositive( String val )
{
if( val == null ) return false;
return ( val.equalsIgnoreCase("true") || val.equalsIgnoreCase("on") ||
val.equalsIgnoreCase("yes") );
}
/**
* Makes sure that the POSTed data is conforms to certain rules. These
* rules are:
* <UL>
* <LI>The data always ends with a newline (some browsers, such
* as NS4.x series, does not send a newline at the end, which makes
* the diffs a bit strange sometimes.
* <LI>The CR/LF/CRLF mess is normalized to plain CRLF.
* </UL>
*
* The reason why we're using CRLF is that most browser already
* return CRLF since that is the closest thing to a HTTP standard.
*/
public static String normalizePostData( String postData )
{
StringBuffer sb = new StringBuffer();
for( int i = 0; i < postData.length(); i++ )
{
switch( postData.charAt(i) )
{
case 0x0a: // LF, UNIX
sb.append( "\r\n" );
break;
case 0x0d: // CR, either Mac or MSDOS
sb.append( "\r\n" );
// If it's MSDOS, skip the LF so that we don't add it again.
if( i < postData.length()-1 && postData.charAt(i+1) == 0x0a )
{
i++;
}
break;
default:
sb.append( postData.charAt(i) );
break;
}
}
if( sb.length() < 2 || !sb.substring( sb.length()-2 ).equals("\r\n") )
{
sb.append( "\r\n" );
}
return sb.toString();
}
private static final int EOI = 0;
private static final int LOWER = 1;
private static final int UPPER = 2;
private static final int DIGIT = 3;
private static final int OTHER = 4;
private static int getCharKind(int c)
{
if (c==-1)
{
return EOI;
}
char ch = (char) c;
if (Character.isLowerCase(ch))
return LOWER;
else if (Character.isUpperCase(ch))
return UPPER;
else if (Character.isDigit(ch))
return DIGIT;
else
return OTHER;
}
/**
* Adds spaces in suitable locations of the input string. This is
* used to transform a WikiName into a more readable format.
*
* @param s String to be beautified.
* @return A beautified string.
*/
public static String beautifyString( String s )
{
StringBuffer result = new StringBuffer();
if( s == null || s.length() == 0 ) return "";
int cur = s.charAt(0);
int curKind = getCharKind(cur);
int prevKind = LOWER;
int nextKind = -1;
int next = -1;
int nextPos = 1;
while( curKind != EOI )
{
next = (nextPos < s.length()) ? s.charAt(nextPos++) : -1;
nextKind = getCharKind( next );
if( (prevKind == UPPER) && (curKind == UPPER) && (nextKind == LOWER) )
{
result.append(' ');
result.append((char) cur);
}
else
{
result.append((char) cur);
if( ( (curKind == UPPER) && (nextKind == DIGIT) )
|| ( (curKind == LOWER) && ((nextKind == DIGIT) || (nextKind == UPPER)) )
|| ( (curKind == DIGIT) && ((nextKind == UPPER) || (nextKind == LOWER)) ))
{
result.append(' ');
}
}
prevKind = curKind;
cur = next;
curKind = nextKind;
}
return result.toString();
}
public static Properties createProperties( String[] values )
throws IllegalArgumentException
{
if( values.length % 2 != 0 )
throw new IllegalArgumentException( "One value is missing.");
Properties props = new Properties();
for( int i = 0; i < values.length; i += 2 )
{
props.setProperty( values[i], values[i+1] );
}
return props;
}
public static int countSections( String pagedata )
{
int tags = 0;
int start = 0;
while( (start = pagedata.indexOf("----",start)) != -1 )
{
tags++;
start+=4;
}
return pagedata.length() > 0 ? tags+1 : 0;
}
public static String getSection( String pagedata, int section )
throws IllegalArgumentException
{
int tags = 0;
int start = 0;
int previous = 0;
while( (start = pagedata.indexOf("----",start)) != -1 )
{
if( ++tags == section )
{
return pagedata.substring( previous, start );
}
start += 4;
previous = start;
}
if( ++tags == section )
{
return pagedata.substring( previous );
}
throw new IllegalArgumentException("There is no section no. "+section+" on the page.");
}
/**
* A simple routine which just repeates the arguments. This is useful
* for creating something like a line or something.
*
* @param what String to repeat
* @param times How many times to repeat the string.
* @return Guess what?
* @since 2.1.98.
*/
public static String repeatString( String what, int times )
{
StringBuffer sb = new StringBuffer();
for( int i = 0; i < times; i++ )
{
sb.append( what );
}
return sb.toString();
}
}
|
package io.flutter.preview;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.LayeredIcon;
import com.intellij.ui.SimpleTextAttributes;
import com.jetbrains.lang.dart.DartComponentType;
import com.jetbrains.lang.dart.util.DartPresentableUtil;
import org.dartlang.analysis.server.protocol.Element;
import org.dartlang.analysis.server.protocol.ElementKind;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import static com.intellij.icons.AllIcons.Nodes.*;
import static com.intellij.icons.AllIcons.Nodes.Class;
import static com.intellij.icons.AllIcons.Nodes.Enum;
import static com.intellij.icons.AllIcons.RunConfigurations.Junit;
public class DartElementPresentationUtil {
private static final LayeredIcon STATIC_FINAL_FIELD_ICON = new LayeredIcon(Field, StaticMark, FinalMark);
private static final LayeredIcon FINAL_FIELD_ICON = new LayeredIcon(Field, FinalMark);
private static final LayeredIcon STATIC_FIELD_ICON = new LayeredIcon(Field, StaticMark);
private static final LayeredIcon STATIC_METHOD_ICON = new LayeredIcon(Method, StaticMark);
private static final LayeredIcon TOP_LEVEL_FUNCTION_ICON = new LayeredIcon(Function, StaticMark);
private static final LayeredIcon TOP_LEVEL_VAR_ICON = new LayeredIcon(Variable, StaticMark);
private static final LayeredIcon CONSTRUCTOR_INVOCATION_ICON = new LayeredIcon(Class, TabPin);
private static final LayeredIcon FUNCTION_INVOCATION_ICON = new LayeredIcon(Method, TabPin);
private static final LayeredIcon TOP_LEVEL_CONST_ICON = new LayeredIcon(Variable, StaticMark, FinalMark);
@Nullable
public static Icon getIcon(@NotNull Element element) {
final boolean finalOrConst = element.isConst() || element.isFinal();
switch (element.getKind()) {
case ElementKind.CLASS:
return element.isAbstract() ? AbstractClass : Class;
case "MIXIN":
// TODO(devoncarew): Use ElementKind.MIXIN when its available.
return AbstractClass;
case ElementKind.CONSTRUCTOR:
return Method;
case ElementKind.CONSTRUCTOR_INVOCATION:
return CONSTRUCTOR_INVOCATION_ICON;
case ElementKind.ENUM:
return Enum;
case ElementKind.ENUM_CONSTANT:
return STATIC_FINAL_FIELD_ICON;
case ElementKind.FIELD:
if (finalOrConst && element.isTopLevelOrStatic()) return STATIC_FINAL_FIELD_ICON;
if (finalOrConst) return FINAL_FIELD_ICON;
if (element.isTopLevelOrStatic()) return STATIC_FIELD_ICON;
return Field;
case ElementKind.FUNCTION:
return element.isTopLevelOrStatic() ? TOP_LEVEL_FUNCTION_ICON : Function;
case ElementKind.FUNCTION_INVOCATION:
return FUNCTION_INVOCATION_ICON;
case ElementKind.FUNCTION_TYPE_ALIAS:
return DartComponentType.TYPEDEF.getIcon();
case ElementKind.GETTER:
return element.isTopLevelOrStatic() ? PropertyReadStatic : PropertyRead;
case ElementKind.METHOD:
if (element.isAbstract()) return AbstractMethod;
return element.isTopLevelOrStatic() ? STATIC_METHOD_ICON : Method;
case ElementKind.SETTER:
return element.isTopLevelOrStatic() ? PropertyWriteStatic : PropertyWrite;
case ElementKind.TOP_LEVEL_VARIABLE:
return finalOrConst ? TOP_LEVEL_CONST_ICON : TOP_LEVEL_VAR_ICON;
case ElementKind.UNIT_TEST_GROUP:
return TestSourceFolder;
case ElementKind.UNIT_TEST_TEST:
return Junit;
case ElementKind.CLASS_TYPE_ALIAS:
case ElementKind.COMPILATION_UNIT:
case ElementKind.FILE:
case ElementKind.LABEL:
case ElementKind.LIBRARY:
case ElementKind.LOCAL_VARIABLE:
case ElementKind.PARAMETER:
case ElementKind.PREFIX:
case ElementKind.TYPE_PARAMETER:
case ElementKind.UNKNOWN:
default:
return null; // unexpected
}
}
public static void renderElement(@NotNull Element element, @NotNull OutlineTreeCellRenderer renderer, boolean nameInBold) {
final SimpleTextAttributes attributes =
nameInBold ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES;
renderer.appendSearch(element.getName(), attributes);
if (!StringUtil.isEmpty(element.getTypeParameters())) {
renderer.appendSearch(element.getTypeParameters(), attributes);
}
if (!StringUtil.isEmpty(element.getParameters())) {
renderer.appendSearch(element.getParameters(), attributes);
}
if (!StringUtil.isEmpty(element.getReturnType())) {
renderer.append(" ");
renderer.append(DartPresentableUtil.RIGHT_ARROW);
renderer.append(" ");
renderer.appendSearch(element.getReturnType(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
}
|
package org.jivesoftware.admin;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.clearspace.ClearspaceManager;
import org.jivesoftware.util.*;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A model for admin tab and sidebar info. This class loads in XML definitions of the
* data and produces an in-memory model.<p>
*
* This class loads its data from the <tt>admin-sidebar.xml</tt> file which is assumed
* to be in the main application jar file. In addition, it will load files from
* <tt>META-INF/admin-sidebar.xml</tt> if they're found. This allows developers to
* extend the functionality of the admin console to provide more options. See the main
* <tt>admin-sidebar.xml</tt> file for documentation of its format.
*/
public class AdminConsole {
private static Element coreModel;
private static Map<String,Element> overrideModels;
private static Element generatedModel;
static {
overrideModels = new LinkedHashMap<String,Element>();
load();
// Detect when a new auth provider class is set to ClearspaceAuthProvider
// then rebuild the model to add the Clearspace tab
// This is to add the tab after Openfire setup
PropertyEventListener propListener = new PropertyEventListener() {
public void propertySet(String property, Map params) {
if ("provider.auth.className".equals(property)) {
String value = (String) params.get("value");
if ("org.jivesoftware.openfire.clearspace.ClearspaceAuthProvider".equals(value)) {
rebuildModel();
}
}
}
public void propertyDeleted(String property, Map params) {
//Ignore
}
public void xmlPropertySet(String property, Map params) {
//Ignore
}
public void xmlPropertyDeleted(String property, Map params) {
//Ignore
}
};
PropertyEventDispatcher.addListener(propListener);
}
/** Not instantiatable */
private AdminConsole() {
}
/**
* Adds XML stream to the tabs/sidebar model.
*
* @param name the name.
* @param in the XML input stream.
* @throws Exception if an error occurs when parsing the XML or adding it to the model.
*/
public static void addModel(String name, InputStream in) throws Exception {
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(in);
addModel(name, (Element)doc.selectSingleNode("/adminconsole"));
}
/**
* Adds an <adminconsole> Element to the tabs/sidebar model.
*
* @param name the name.
* @param element the Element
* @throws Exception if an error occurs.
*/
public static void addModel(String name, Element element) throws Exception {
overrideModels.put(name, element);
rebuildModel();
}
/**
* Removes an <adminconsole> Element from the tabs/sidebar model.
*
* @param name the name.
*/
public static void removeModel(String name) {
overrideModels.remove(name);
rebuildModel();
}
/**
* Returns the name of the application.
*
* @return the name of the application.
*/
public static synchronized String getAppName() {
Element appName = (Element)generatedModel.selectSingleNode("//adminconsole/global/appname");
if (appName != null) {
String pluginName = appName.attributeValue("plugin");
return getAdminText(appName.getText(), pluginName);
}
else {
return null;
}
}
/**
* Returns the URL of the main logo image for the admin console.
*
* @return the logo image.
*/
public static synchronized String getLogoImage() {
Element globalLogoImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/logo-image");
if (globalLogoImage != null) {
String pluginName = globalLogoImage.attributeValue("plugin");
return getAdminText(globalLogoImage.getText(), pluginName);
}
else {
return null;
}
}
/**
* Returns the URL of the login image for the admin console.
*
* @return the login image.
*/
public static synchronized String getLoginLogoImage() {
Element globalLoginLogoImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/login-image");
if (globalLoginLogoImage != null) {
String pluginName = globalLoginLogoImage.attributeValue("plugin");
return getAdminText(globalLoginLogoImage.getText(), pluginName);
}
else {
return null;
}
}
/**
* Returns the version string displayed in the admin console.
*
* @return the version string.
*/
public static synchronized String getVersionString() {
Element globalVersion = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/version");
if (globalVersion != null) {
String pluginName = globalVersion.attributeValue("plugin");
return getAdminText(globalVersion.getText(), pluginName);
}
else {
// Default to the Openfire version if none has been provided via XML.
XMPPServer xmppServer = XMPPServer.getInstance();
return xmppServer.getServerInfo().getVersion().getVersionString();
}
}
/**
* Returns the model. The model should be considered read-only.
*
* @return the model.
*/
public static synchronized Element getModel() {
return generatedModel;
}
/**
* Convenience method to select an element from the model by its ID. If an
* element with a matching ID is not found, <tt>null</tt> will be returned.
*
* @param id the ID.
* @return the element.
*/
public static synchronized Element getElemnetByID(String id) {
/**
* Returns a text element for the admin console, applying the appropriate locale.
* Internationalization logic will only be applied if the String is specially encoded
* in the format "${key.name}". If it is, the String is pulled from the resource bundle.
* If the pluginName is not <tt>null</tt>, the plugin's resource bundle will be used
* to look up the key.
*
* @param string the String.
* @param pluginName the name of the plugin that the i18n String can be found in,
* or <tt>null</tt> if the standard Openfire resource bundle should be used.
* @return the string, or if the string is encoded as an i18n key, the value from
* the appropriate resource bundle.
*/
public static String getAdminText(String string, String pluginName) {
if (string == null) {
return null;
}
// Look for the key symbol:
if (string.indexOf("${") == 0 && string.indexOf("}") == string.length()-1) {
return LocaleUtils.getLocalizedString(string.substring(2, string.length()-1), pluginName);
}
return string;
}
private static void load() {
// Load the core model as the admin-sidebar.xml file from the classpath.
InputStream in = ClassUtils.getResourceAsStream("/admin-sidebar.xml");
if (in == null) {
Log.error("Failed to load admin-sidebar.xml file from Openfire classes - admin "
+ "console will not work correctly.");
return;
}
try {
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(in);
coreModel = (Element)doc.selectSingleNode("/adminconsole");
}
catch (Exception e) {
Log.error("Failure when parsing main admin-sidebar.xml file", e);
}
try {
in.close();
}
catch (Exception ignored) {
// Ignore.
}
// Load other admin-sidebar.xml files from the classpath
ClassLoader[] classLoaders = getClassLoaders();
for (ClassLoader classLoader : classLoaders) {
URL url = null;
try {
if (classLoader != null) {
Enumeration e = classLoader.getResources("/META-INF/admin-sidebar.xml");
while (e.hasMoreElements()) {
url = (URL) e.nextElement();
try {
in = url.openStream();
addModel("admin", in);
}
finally {
try {
if (in != null) {
in.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
}
}
}
catch (Exception e) {
String msg = "Failed to load admin-sidebar.xml";
if (url != null) {
msg += " from resource: " + url.toString();
}
Log.warn(msg, e);
}
}
rebuildModel();
}
/**
* Rebuilds the generated model.
*/
private static synchronized void rebuildModel() {
Document doc = DocumentFactory.getInstance().createDocument();
generatedModel = coreModel.createCopy();
doc.add(generatedModel);
// Add in all overrides.
for (Element element : overrideModels.values()) {
// See if global settings are overriden.
Element appName = (Element)element.selectSingleNode("//adminconsole/global/appname");
if (appName != null) {
Element existingAppName = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/appname");
existingAppName.setText(appName.getText());
if (appName.attributeValue("plugin") != null) {
existingAppName.addAttribute("plugin", appName.attributeValue("plugin"));
}
}
Element appLogoImage = (Element)element.selectSingleNode("//adminconsole/global/logo-image");
if (appLogoImage != null) {
Element existingLogoImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/logo-image");
existingLogoImage.setText(appLogoImage.getText());
if (appLogoImage.attributeValue("plugin") != null) {
existingLogoImage.addAttribute("plugin", appLogoImage.attributeValue("plugin"));
}
}
Element appLoginImage = (Element)element.selectSingleNode("//adminconsole/global/login-image");
if (appLoginImage != null) {
Element existingLoginImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/login-image");
existingLoginImage.setText(appLoginImage.getText());
if (appLoginImage.attributeValue("plugin") != null) {
existingLoginImage.addAttribute("plugin", appLoginImage.attributeValue("plugin"));
}
}
Element appVersion = (Element)element.selectSingleNode("//adminconsole/global/version");
if (appVersion != null) {
Element existingVersion = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/version");
if (existingVersion != null) {
existingVersion.setText(appVersion.getText());
if (appVersion.attributeValue("plugin") != null) {
existingVersion.addAttribute("plugin", appVersion.attributeValue("plugin"));
}
}
else {
((Element)generatedModel.selectSingleNode(
"//adminconsole/global")).add(appVersion.createCopy());
}
}
// Tabs
for (Object o : element.selectNodes("//tab")) {
Element tab = (Element) o;
String id = tab.attributeValue("id");
Element existingTab = getElemnetByID(id);
// Simple case, there is no existing tab with the same id.
if (existingTab == null) {
// Make sure that the URL on the tab is set. If not, default to the
// url of the first item.
if (tab.attributeValue("url") == null) {
Element firstItem = (Element) tab.selectSingleNode(
"//item[@url]");
if (firstItem != null) {
tab.addAttribute("url", firstItem.attributeValue("url"));
}
}
generatedModel.add(tab.createCopy());
}
// More complex case -- a tab with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideTab(existingTab, tab);
}
}
}
// Special case: show a link to Clearspace admin console if it is integrated with
// Openfire.
if (ClearspaceManager.isEnabled()) {
Element clearspace = generatedModel.addElement("tab");
clearspace.addAttribute("id", "tab-clearspace");
clearspace.addAttribute("name", LocaleUtils.getLocalizedString("tab.tab-clearspace"));
clearspace.addAttribute("url", "clearspace-info.jsp");
clearspace.addAttribute("description", LocaleUtils.getLocalizedString("tab.tab-clearspace.descr"));
Element sidebar = clearspace.addElement("sidebar");
sidebar.addAttribute("id", "sidebar-clearspace-admin");
sidebar.addAttribute("name", LocaleUtils.getLocalizedString("sidebar.sidebar-clearspace-admin"));
Element item = sidebar.addElement("item");
item.addAttribute("id", "clearspace-info");
item.addAttribute("name", LocaleUtils.getLocalizedString("sidebar.clearspace-info"));
item.addAttribute("url", "clearspace-info.jsp");
item.addAttribute("description", LocaleUtils.getLocalizedString("sidebar.clearspace-info.descr"));
item = sidebar.addElement("item");
item.addAttribute("id", "clearspace-connection");
item.addAttribute("name", LocaleUtils.getLocalizedString("sidebar.clearspace-connection"));
item.addAttribute("url", "clearspace-connection.jsp");
item.addAttribute("description", LocaleUtils.getLocalizedString("sidebar.clearspace-connection.descr"));
}
}
private static void overrideTab(Element tab, Element overrideTab) {
// Override name, url, description.
if (overrideTab.attributeValue("name") != null) {
tab.addAttribute("name", overrideTab.attributeValue("name"));
}
if (overrideTab.attributeValue("url") != null) {
tab.addAttribute("url", overrideTab.attributeValue("url"));
}
if (overrideTab.attributeValue("description") != null) {
tab.addAttribute("description", overrideTab.attributeValue("description"));
}
if (overrideTab.attributeValue("plugin") != null) {
tab.addAttribute("plugin", overrideTab.attributeValue("plugin"));
}
// Override sidebar items.
for (Iterator i=overrideTab.elementIterator(); i.hasNext(); ) {
Element sidebar = (Element)i.next();
String id = sidebar.attributeValue("id");
Element existingSidebar = getElemnetByID(id);
// Simple case, there is no existing sidebar with the same id.
if (existingSidebar == null) {
tab.add(sidebar.createCopy());
}
// More complex case -- a sidebar with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideSidebar(existingSidebar, sidebar);
}
}
}
private static void overrideSidebar(Element sidebar, Element overrideSidebar) {
// Override name.
if (overrideSidebar.attributeValue("name") != null) {
sidebar.addAttribute("name", overrideSidebar.attributeValue("name"));
}
if (overrideSidebar.attributeValue("plugin") != null) {
sidebar.addAttribute("plugin", overrideSidebar.attributeValue("plugin"));
}
// Override entries.
for (Iterator i=overrideSidebar.elementIterator(); i.hasNext(); ) {
Element entry = (Element)i.next();
String id = entry.attributeValue("id");
Element existingEntry = getElemnetByID(id);
// Simple case, there is no existing sidebar with the same id.
if (existingEntry == null) {
sidebar.add(entry.createCopy());
}
// More complex case -- an entry with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideEntry(existingEntry, entry);
}
}
}
private static void overrideEntry(Element entry, Element overrideEntry) {
// Override name.
if (overrideEntry.attributeValue("name") != null) {
entry.addAttribute("name", overrideEntry.attributeValue("name"));
}
if (overrideEntry.attributeValue("url") != null) {
entry.addAttribute("url", overrideEntry.attributeValue("url"));
}
if (overrideEntry.attributeValue("description") != null) {
entry.addAttribute("description", overrideEntry.attributeValue("description"));
}
if (overrideEntry.attributeValue("plugin") != null) {
entry.addAttribute("plugin", overrideEntry.attributeValue("plugin"));
}
// Override any sidebars contained in the entry.
for (Iterator i=overrideEntry.elementIterator(); i.hasNext(); ) {
Element sidebar = (Element)i.next();
String id = sidebar.attributeValue("id");
Element existingSidebar = getElemnetByID(id);
// Simple case, there is no existing sidebar with the same id.
if (existingSidebar == null) {
entry.add(sidebar.createCopy());
}
// More complex case -- a sidebar with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideSidebar(existingSidebar, sidebar);
}
}
}
/**
* Returns an array of class loaders to load resources from.
*
* @return an array of class loaders to load resources from.
*/
private static ClassLoader[] getClassLoaders() {
ClassLoader[] classLoaders = new ClassLoader[3];
classLoaders[0] = AdminConsole.class.getClass().getClassLoader();
classLoaders[1] = Thread.currentThread().getContextClassLoader();
classLoaders[2] = ClassLoader.getSystemClassLoader();
return classLoaders;
}
}
|
package com.ecyrd.jspwiki;
import java.util.Date;
import java.util.HashMap;
import com.ecyrd.jspwiki.acl.AccessControlList;
import com.ecyrd.jspwiki.providers.WikiPageProvider;
/**
* Simple wrapper class for the Wiki page attributes. The Wiki page
* content is moved around in Strings, though.
*/
public class WikiPage
implements Cloneable
{
private String m_name;
private Date m_lastModified;
private int m_version = WikiPageProvider.LATEST_VERSION;
private String m_author = null;
private HashMap m_attributes = new HashMap();
/**
* "Summary" is a short summary of the page. It is a String.
*/
public static final String DESCRIPTION = "summary";
private AccessControlList m_accessList = null;
public WikiPage( String name )
{
m_name = name;
}
public String getName()
{
return m_name;
}
/**
* A WikiPage may have a number of attributes, which might or might not be
* available. Typically attributes are things that do not need to be stored
* with the wiki page to the page repository, but are generated
* on-the-fly. A provider is not required to save them, but they
* can do that if they really want.
*
* @param key The key using which the attribute is fetched
* @return The attribute. If the attribute has not been set, returns null.
*/
public Object getAttribute( String key )
{
return m_attributes.get( key );
}
public void setAttribute( String key, Object attribute )
{
m_attributes.put( key, attribute );
}
public Date getLastModified()
{
return m_lastModified;
}
public void setLastModified( Date date )
{
m_lastModified = date;
}
public void setVersion( int version )
{
m_version = version;
}
public int getVersion()
{
return m_version;
}
public AccessControlList getAcl()
{
return m_accessList;
}
public void setAcl( AccessControlList acl )
{
m_accessList = acl;
}
public void setAuthor( String author )
{
m_author = author;
}
/**
* Returns author name, or null, if no author has been defined.
*/
public String getAuthor()
{
return m_author;
}
public String toString()
{
return "WikiPage ["+m_name+",ver="+m_version+",mod="+m_lastModified+"]";
}
/**
* Creates a deep clone of a WikiPage. Strings are not cloned, since
* they're immutable.
*/
public Object clone()
{
WikiPage p = new WikiPage(m_name);
p.m_author = m_author;
p.m_version = m_version;
p.m_lastModified = (Date)m_lastModified.clone();
return p;
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.depot;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import com.samskivert.io.PersistenceException;
import com.samskivert.jdbc.ConnectionProvider;
import com.samskivert.jdbc.JDBCUtil;
import com.samskivert.jdbc.depot.Modifier.*;
import com.samskivert.jdbc.depot.clause.QueryClause;
import com.samskivert.jdbc.depot.clause.Where;
import com.samskivert.util.ArrayUtil;
/**
* Provides a base for classes that provide access to persistent objects. Also defines the
* mechanism by which all persistent queries and updates are routed through the distributed cache.
*/
public class DepotRepository
{
/**
* Creates a repository with the supplied connection provider and its own private persistence
* context.
*/
protected DepotRepository (ConnectionProvider conprov)
{
_ctx = new PersistenceContext(getClass().getName(), conprov);
}
/**
* Creates a repository with the supplied persistence context.
*/
protected DepotRepository (PersistenceContext context)
{
_ctx = context;
}
/**
* Loads the persistent object that matches the specified primary key.
*/
protected <T extends PersistentRecord> T load (Class<T> type, Comparable primaryKey,
QueryClause... clauses)
throws PersistenceException
{
clauses = ArrayUtil.append(clauses, _ctx.getMarshaller(type).makePrimaryKey(primaryKey));
return load(type, clauses);
}
/**
* Loads the persistent object that matches the specified primary key.
*/
protected <T extends PersistentRecord> T load (Class<T> type, String ix, Comparable val,
QueryClause... clauses)
throws PersistenceException
{
clauses = ArrayUtil.append(clauses, new Key<T>(type, ix, val));
return load(type, clauses);
}
/**
* Loads the persistent object that matches the specified two-column primary key.
*/
protected <T extends PersistentRecord> T load (Class<T> type, String ix1, Comparable val1,
String ix2, Comparable val2,
QueryClause... clauses)
throws PersistenceException
{
clauses = ArrayUtil.append(clauses, new Key<T>(type, ix1, val1, ix2, val2));
return load(type, clauses);
}
/**
* Loads the persistent object that matches the specified three-column primary key.
*/
protected <T extends PersistentRecord> T load (Class<T> type, String ix1, Comparable val1,
String ix2, Comparable val2, String ix3,
Comparable val3, QueryClause... clauses)
throws PersistenceException
{
clauses = ArrayUtil.append(clauses, new Key<T>(type, ix1, val1, ix2, val2, ix3, val3));
return load(type, clauses);
}
/**
* Loads the first persistent object that matches the supplied key.
*/
protected <T extends PersistentRecord> T load (Class<T> type, QueryClause... clauses)
throws PersistenceException
{
final DepotMarshaller<T> marsh = _ctx.getMarshaller(type);
return _ctx.invoke(new ConstructedQuery<T>(_ctx, type, clauses) {
public T invoke (Connection conn) throws SQLException {
PreparedStatement stmt = createQuery(conn);
try {
T result = null;
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
result = marsh.createObject(rs);
}
// TODO: if (rs.next()) issue warning?
rs.close();
return result;
} finally {
JDBCUtil.close(stmt);
}
}
// from Query
public void updateCache (PersistenceContext ctx, T result) {
CacheKey key = getCacheKey();
if (key == null) {
// no row-specific cache key was given
if (result == null || !marsh.hasPrimaryKey()) {
return;
}
// if we can, create a key from what was actually returned
key = marsh.getPrimaryKey(result);
}
ctx.cacheStore(key, result != null ? result.clone() : null);
}
// from Query
public T transformCacheHit (CacheKey key, T value)
{
// we do not want to return a reference to the actual cached entity
if (value == null) {
return null;
}
@SuppressWarnings("unchecked") T cvalue = (T) value.clone();
return cvalue;
}
});
}
/**
* Loads all persistent objects that match the specified key.
*/
protected <T extends PersistentRecord, C extends Collection<T>> Collection<T> findAll (
Class<T> type, QueryClause... clauses)
throws PersistenceException
{
final DepotMarshaller<T> marsh = _ctx.getMarshaller(type);
return _ctx.invoke(new ConstructedQuery<ArrayList<T>>(_ctx, type, clauses) {
public ArrayList<T> invoke (Connection conn) throws SQLException {
PreparedStatement stmt = createQuery(conn);
try {
ArrayList<T> results = new ArrayList<T>();
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
results.add(marsh.createObject(rs));
}
return results;
} finally {
JDBCUtil.close(stmt);
}
}
// from Query
public void updateCache (PersistenceContext ctx, ArrayList<T> result) {
if (marsh.hasPrimaryKey()) {
for (T bit : result) {
ctx.cacheStore(marsh.getPrimaryKey(bit), bit.clone());
}
}
}
// from Query
public ArrayList<T> transformCacheHit (CacheKey key, ArrayList<T> bits)
{
if (bits == null) {
return bits;
}
ArrayList<T> result = new ArrayList<T>();
for (T bit : bits) {
if (bit != null) {
@SuppressWarnings("unchecked") T cbit = (T) bit.clone();
result.add(cbit);
} else {
result.add(null);
}
}
return result;
}
});
}
protected <T extends PersistentRecord> int insert (T record)
throws PersistenceException
{
final DepotMarshaller marsh = _ctx.getMarshaller(record.getClass());
final Key key = marsh.getPrimaryKey(record, false);
// key will be null if record was supplied without a primary key
return _ctx.invoke(new CachingModifier<T>(record, key, key) {
public int invoke (Connection conn) throws SQLException {
// update our modifier's key so that it can cache our results
updateKey(marsh.assignPrimaryKey(conn, _result, false));
PreparedStatement stmt = marsh.createInsert(conn, _result);
try {
int mods = stmt.executeUpdate();
// check again in case we have a post-factum key generator
updateKey(marsh.assignPrimaryKey(conn, _result, true));
return mods;
} finally {
JDBCUtil.close(stmt);
}
}
});
}
protected <T extends PersistentRecord> int update (T record)
throws PersistenceException
{
final DepotMarshaller marsh = _ctx.getMarshaller(record.getClass());
final Key key = marsh.getPrimaryKey(record);
if (key == null) {
throw new IllegalArgumentException("Can't update record with null primary key.");
}
return _ctx.invoke(new CachingModifier<T>(record, key, key) {
public int invoke (Connection conn) throws SQLException {
PreparedStatement stmt = marsh.createUpdate(conn, _result, key);
try {
return stmt.executeUpdate();
} finally {
JDBCUtil.close(stmt);
}
}
});
}
protected <T extends PersistentRecord> int update (T record, final String... modifiedFields)
throws PersistenceException
{
final DepotMarshaller marsh = _ctx.getMarshaller(record.getClass());
final Key key = marsh.getPrimaryKey(record);
if (key == null) {
throw new IllegalArgumentException("Can't update record with null primary key.");
}
return _ctx.invoke(new CachingModifier<T>(record, key, key) {
public int invoke (Connection conn) throws SQLException {
PreparedStatement stmt = marsh.createUpdate(conn, _result, key, modifiedFields);
try {
return stmt.executeUpdate();
} finally {
JDBCUtil.close(stmt);
}
}
});
}
protected <T extends PersistentRecord> int updatePartial (
Class<T> type, Comparable primaryKey, Map<String,Object> updates)
throws PersistenceException
{
Object[] fieldsValues = new Object[updates.size()*2];
int idx = 0;
for (Map.Entry<String,Object> entry : updates.entrySet()) {
fieldsValues[idx++] = entry.getKey();
fieldsValues[idx++] = entry.getValue();
}
return updatePartial(type, primaryKey, fieldsValues);
}
protected <T extends PersistentRecord> int updatePartial (
Class<T> type, Comparable primaryKey, Object... fieldsValues)
throws PersistenceException
{
Key<T> key = _ctx.getMarshaller(type).makePrimaryKey(primaryKey);
return updatePartial(type, key, key, fieldsValues);
}
protected <T extends PersistentRecord> int updatePartial (
Class<T> type, String ix1, Comparable val1, String ix2, Comparable val2,
Object... fieldsValues)
throws PersistenceException
{
Key<T> key = new Key<T>(type, ix1, val1, ix2, val2);
return updatePartial(type, key, key, fieldsValues);
}
protected <T extends PersistentRecord> int updatePartial (
Class<T> type, String ix1, Comparable val1, String ix2, Comparable val2,
String ix3, Comparable val3, Object... fieldsValues)
throws PersistenceException
{
Key<T> key = new Key<T>(type, ix1, val1, ix2, val2, ix3, val3);
return updatePartial(type, key, key, fieldsValues);
}
protected <T extends PersistentRecord> int updatePartial (
Class<T> type, final Where key, CacheInvalidator invalidator, Object... fieldsValues)
throws PersistenceException
{
// separate the arguments into keys and values
final String[] fields = new String[fieldsValues.length/2];
final Object[] values = new Object[fields.length];
for (int ii = 0, idx = 0; ii < fields.length; ii++) {
fields[ii] = (String)fieldsValues[idx++];
values[ii] = fieldsValues[idx++];
}
final DepotMarshaller marsh = _ctx.getMarshaller(type);
return _ctx.invoke(new Modifier(invalidator) {
public int invoke (Connection conn) throws SQLException {
PreparedStatement stmt = marsh.createPartialUpdate(conn, key, fields, values);
try {
return stmt.executeUpdate();
} finally {
JDBCUtil.close(stmt);
}
}
});
}
protected <T extends PersistentRecord> int updateLiteral (
Class<T> type, Comparable primaryKey, String... fieldsValues)
throws PersistenceException
{
Key<T> key = _ctx.getMarshaller(type).makePrimaryKey(primaryKey);
return updateLiteral(type, key, key, fieldsValues);
}
protected <T extends PersistentRecord> int updateLiteral (
Class<T> type, String ix1, Comparable val1, String ix2, Comparable val2,
String... fieldsValues)
throws PersistenceException
{
Key<T> key = new Key<T>(type, ix1, val1, ix2, val2);
return updateLiteral(type, key, key, fieldsValues);
}
protected <T extends PersistentRecord> int updateLiteral (
Class<T> type, String ix1, Comparable val1, String ix2, Comparable val2,
String ix3, Comparable val3, String... fieldsValues)
throws PersistenceException
{
Key<T> key = new Key<T>(type, ix1, val1, ix2, val2, ix3, val3);
return updateLiteral(type, key, key, fieldsValues);
}
protected <T extends PersistentRecord> int updateLiteral (
Class<T> type, final Where key, CacheInvalidator invalidator, String... fieldsValues)
throws PersistenceException
{
// separate the arguments into keys and values
final String[] fields = new String[fieldsValues.length/2];
final String[] values = new String[fields.length];
for (int ii = 0, idx = 0; ii < fields.length; ii++) {
fields[ii] = fieldsValues[idx++];
values[ii] = fieldsValues[idx++];
}
final DepotMarshaller marsh = _ctx.getMarshaller(type);
return _ctx.invoke(new Modifier(invalidator) {
public int invoke (Connection conn) throws SQLException {
PreparedStatement stmt = marsh.createLiteralUpdate(conn, key, fields, values);
try {
return stmt.executeUpdate();
} finally {
JDBCUtil.close(stmt);
}
}
});
}
protected <T extends PersistentRecord> int store (T record)
throws PersistenceException
{
final DepotMarshaller marsh = _ctx.getMarshaller(record.getClass());
final Key key = marsh.hasPrimaryKey() ? marsh.getPrimaryKey(record) : null;
return _ctx.invoke(new CachingModifier<T>(record, key, key) {
public int invoke (Connection conn) throws SQLException {
PreparedStatement stmt = null;
try {
// if our primary key isn't null, update rather than insert the record
// before been persisted and insert
if (key != null) {
stmt = marsh.createUpdate(conn, _result, key);
int mods = stmt.executeUpdate();
if (mods > 0) {
return mods;
}
JDBCUtil.close(stmt);
}
// if the update modified zero rows or the primary key was obviously unset, do
// an insertion
updateKey(marsh.assignPrimaryKey(conn, _result, false));
stmt = marsh.createInsert(conn, _result);
int mods = stmt.executeUpdate();
updateKey(marsh.assignPrimaryKey(conn, _result, true));
return mods;
} finally {
JDBCUtil.close(stmt);
}
}
});
}
/**
* Deletes all persistent objects from the database with a primary key matching the primary key
* of the supplied object.
*
* @return the number of rows deleted by this action.
*/
protected <T extends PersistentRecord> int delete (T record)
throws PersistenceException
{
@SuppressWarnings("unchecked") Class<T> type = (Class<T>)record.getClass();
Key<T> primaryKey = _ctx.getMarshaller(type).getPrimaryKey(record);
if (primaryKey == null) {
throw new IllegalArgumentException("Can't delete record with null primary key.");
}
return deleteAll(type, primaryKey, primaryKey);
}
/**
* Deletes all persistent objects from the database with a primary key matching the supplied
* primary key.
*
* @return the number of rows deleted by this action.
*/
protected <T extends PersistentRecord> int delete (Class<T> type, Comparable primaryKeyValue)
throws PersistenceException
{
Key<T> primaryKey = _ctx.getMarshaller(type).makePrimaryKey(primaryKeyValue);
return deleteAll(type, primaryKey, primaryKey);
}
/**
* Deletes all persistent objects from the database that match the supplied key.
*
* @return the number of rows deleted by this action.
*/
protected <T extends PersistentRecord> int deleteAll (
Class<T> type, final Where key, CacheInvalidator invalidator)
throws PersistenceException
{
final DepotMarshaller marsh = _ctx.getMarshaller(type);
return _ctx.invoke(new Modifier(invalidator) {
public int invoke (Connection conn) throws SQLException {
PreparedStatement stmt = marsh.createDelete(conn, key);
try {
return stmt.executeUpdate();
} finally {
JDBCUtil.close(stmt);
}
}
});
}
protected static abstract class CollectionQuery<T extends Collection> implements Query<T>
{
public CollectionQuery (CacheKey key)
throws PersistenceException
{
_key = key;
}
public CacheKey getCacheKey ()
{
return _key;
}
public void updateCache (PersistenceContext ctx, T result)
{
ctx.cacheStore(_key, result);
}
protected CacheKey _key;
}
protected PersistenceContext _ctx;
}
|
package org.jivesoftware.spark.util.log;
import org.jivesoftware.Spark;
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* Creates and writes out messages to a a log file. This should be used for all error handling within
* the Agent application.
*/
public class Log {
private static File ERROR_LOG_FILE;
private static java.util.logging.Logger ERROR_LOGGER;
private static Logger WARNING_LOGGER;
private static File WARNING_LOG_FILE;
private Log() {
// Do not allow initialization
}
static {
if (!Spark.getLogDirectory().exists()) {
Spark.getLogDirectory().mkdirs();
}
ERROR_LOG_FILE = new File(Spark.getLogDirectory(), "errors.log");
WARNING_LOG_FILE = new File(Spark.getLogDirectory(), "warn.log");
try {
// Create an appending file handler
boolean append = true;
FileHandler errorHandler = new FileHandler(ERROR_LOG_FILE.getCanonicalPath(), append);
errorHandler.setFormatter(new SimpleFormatter());
FileHandler warnHandler = new FileHandler(WARNING_LOG_FILE.getCanonicalPath(), append);
warnHandler.setFormatter(new SimpleFormatter());
// Add to the desired logger
ERROR_LOGGER = java.util.logging.Logger.getAnonymousLogger();
ERROR_LOGGER.addHandler(errorHandler);
WARNING_LOGGER = Logger.getAnonymousLogger();
WARNING_LOGGER.addHandler(warnHandler);
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Logs all error messages to default error logger.
*
* @param message a message to append to log file.
* @param ex the exception being thrown.
*/
public static void error(String message, Throwable ex) {
ERROR_LOGGER.log(Level.SEVERE, message, ex);
}
/**
* Logs all error messages to default error logger.
*
* @param ex the exception being thrown.
*/
public static void error(Throwable ex) {
ERROR_LOGGER.log(Level.SEVERE, "", ex);
}
/**
* Log a warning message to the default logger.
*
* @param message the message to log.
* @param ex the exception.
*/
public static void warning(String message, Throwable ex) {
WARNING_LOGGER.log(Level.WARNING, message, ex);
}
public static void warning(String message) {
WARNING_LOGGER.log(Level.WARNING, message);
}
/**
* Logs all error messages to default error logger.
*
* @param message a message to append to log file.
*/
public static void error(String message) {
ERROR_LOGGER.log(Level.SEVERE, message);
}
/**
* Logs all messages to standard errout for debugging purposes.
* To use, pass in the VM Parameters debug.mode=true.
* <p/>
* ex. (-Ddebug.mode=true)
*
* @param message the message to print out.
*/
public static void debug(String message) {
if (System.getProperty("debug.mode") != null) {
ERROR_LOGGER.info(message);
}
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.velocity;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Properties;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.util.SimplePool;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import com.samskivert.servlet.HttpErrorException;
import com.samskivert.servlet.MessageManager;
import com.samskivert.servlet.RedirectException;
import com.samskivert.servlet.SiteIdentifier;
import com.samskivert.servlet.SiteResourceLoader;
import com.samskivert.servlet.util.FriendlyException;
import com.samskivert.util.ConfigUtil;
import com.samskivert.util.StringUtil;
import static com.samskivert.Log.log;
/**
* The dispatcher servlet builds upon Velocity's architecture. It does so in the following ways:
*
* <ul> <li> It defines the notion of a logic object which populates the context with data to be
* used to satisfy a particular request. The logic is not a servlet and is therefore limited in
* what it can do while populating data. Experience dictates that ultimate flexibility leads to bad
* design decisions and that this is a place where that sort of thing can be comfortably nipped in
* the bud. <br><br>
*
* <li> It allows template files to be referenced directly in the URL while maintaining the ability
* to choose a cobranded template based on information in the request. The URI is mapped to a
* servlet based on some simple mapping rules. This provides template designers with a clearer
* understanding of the structure of a web application as well as with an easy way to test their
* templates in the absence of an associated servlet. <br><br>
*
* <li> It provides a common error handling paradigm that simplifies the task of authoring web
* applications.
* </ul>
*
* <p><b>URI to servlet mapping</b><br> The mapping process allows the Velocity framework to be
* invoked for all requests ending in a particular file extension (usually <code>.wm</code>). It is
* necessary to instruct your servlet engine of choice to invoke the <code>DispatcherServlet</code>
* for all requests ending in that extension. For Apache/JServ this looks something like this:
*
* <pre>
* ApJServAction .wm /servlets/com.samskivert.velocity.Dispatcher
* </pre>
*
* The request URI then defines the path of the template that will be used to satisfy the
* request. To understand how code is selected to go along with the request, let's look at an
* example. Consider the following configuration:
*
* <pre>
* applications=whowhere
* whowhere.base_uri=/whowhere
* whowhere.base_pkg=whowhere.logic
* </pre>
*
* This defines an application identified as <code>whowhere</code>. An application is defined by
* three parameters, the application identifier, the <code>base_uri</code>, and the
* <code>base_pkg</code>. The <code>base_uri</code> defines the prefix shared by all pages served
* by the application and which serves to identify which application to invoke when processing a
* request. The <code>base_pkg</code> is used to construct the logic classname based on the URI and
* the <code>base_uri</code> parameter.
*
* <p> Now let's look at a sample request to determine how the logic classname is
* resolved. Consider the following request URI:
*
* <pre>
* /whowhere/view/trips.wm
* </pre>
*
* It begins with <code>/whowhere</code> which tells the dispatcher that it's part of the
* <code>whowhere</code> application. That application's <code>base_uri</code> is then stripped
* from the URI leaving <code>/view/trips.wm</code>. The slashes are converted into periods to map
* directories to packages, giving us <code>view.trips.wm</code>. Finally, the
* <code>base_pkg</code> is prepended and the trailing <code>.wm</code> extension removed.
*
* <p> Thus the class invoked to populate the context for this request is
* <code>whowhere.servlets.view.trips</code> (note that the classname <em>is</em> lowercase which
* is an intentional choice in resolving conflicting recommendations that classnames should always
* start with a capital letter and URLs should always be lowercase).
*
* <p> The template used to generate the result is loaded based on the full URI, essentially with a
* call to <code>getTemplate("/whowhere/view/trips.wm")</code> in this example. This is the place
* where more sophisticated cobranding support could be inserted in the future (ie. if I ever want
* to use this to develop a cobranded web site).
*
* @see Logic
*/
public class DispatcherServlet extends HttpServlet
implements MethodExceptionEventHandler
{
/** The HTTP content type context key. */
public static final String CONTENT_TYPE = "default.contentType";
/**
* Performs various initialization.
*/
public void init (ServletConfig config)
throws ServletException
{
super.init(config);
// load up our application configuration
try {
String appcl = config.getInitParameter(APP_CLASS_KEY);
if (StringUtil.isBlank(appcl)) {
_app = new Application();
} else {
Class appclass = Class.forName(appcl);
_app = (Application)appclass.newInstance();
}
// now initialize the applicaiton
String logicPkg = config.getInitParameter(LOGIC_PKG_KEY);
_app.init(config, getServletContext(),
StringUtil.isBlank(logicPkg) ? "" : logicPkg);
} catch (Throwable t) {
throw new ServletException("Error instantiating Application: " + t, t);
}
try {
Velocity.init(loadConfiguration(config));
} catch (Exception e) {
throw new ServletException("Error initializing Velocity: " + e, e);
}
_defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
// determine the character set we'll use
_charset = config.getInitParameter(CHARSET_KEY);
if (_charset == null) {
_charset = "UTF-8";
}
}
/**
* Handles HTTP <code>GET</code> requests by calling {@link #doRequest()}.
*/
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handles HTTP <code>POST</code> requests by calling {@link #doRequest()}.
*/
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Clean up after ourselves and our application.
*/
public void destroy ()
{
super.destroy();
// shutdown our application
_app.shutdown();
}
/**
* We load our velocity properties from the classpath rather than from a file.
*/
protected Properties loadConfiguration (ServletConfig config)
throws IOException
{
String propsPath = config.getInitParameter(INIT_PROPS_KEY);
if (propsPath == null) {
throw new IOException(INIT_PROPS_KEY + " must point to the velocity properties file " +
"in the servlet configuration.");
}
// config util loads properties files from the classpath
Properties props = ConfigUtil.loadProperties(propsPath);
if (props == null) {
throw new IOException("Unable to load velocity properties " +
"from file '" + INIT_PROPS_KEY + "'.");
}
// if we failed to create our application for whatever reason; bail
if (_app == null) {
return props;
}
// let the application set up velocity properties
_app.configureVelocity(config, props);
// if no file resource loader path has been set and a
// site-specific jar file path was provided, wire up our site
// resource manager
if (props.getProperty("file.resource.loader.path") == null) {
SiteResourceLoader siteLoader = _app.getSiteResourceLoader();
if (siteLoader != null) {
log.info("Velocity loading templates from site loader.");
props.setProperty(RuntimeSingleton.RESOURCE_MANAGER_CLASS,
SiteResourceManager.class.getName());
_usingSiteLoading = true;
} else {
// otherwise use a servlet context resource loader
log.info("Velocity loading templates from servlet context.");
props.setProperty(RuntimeSingleton.RESOURCE_MANAGER_CLASS,
ServletContextResourceManager.class.getName());
}
}
// wire up our #import directive
props.setProperty("userdirective", ImportDirective.class.getName());
// configure the servlet context logger
props.put(RuntimeSingleton.RUNTIME_LOG_LOGSYSTEM_CLASS,
ServletContextLogger.class.getName());
// now return our augmented properties
return props;
}
/**
* Loads up the template appropriate for this request, locates and invokes any associated logic
* class and finally returns the prepared template which will be merged with the prepared
* context.
*/
public Template handleRequest (HttpServletRequest req, HttpServletResponse rsp, Context ctx)
throws Exception
{
InvocationContext ictx = (InvocationContext)ctx;
Logic logic = null;
// listen for exceptions so that we can report them
EventCartridge ec = ictx.getEventCartridge();
if (ec == null) {
ec = new EventCartridge();
ec.attachToContext(ictx);
ec.addEventHandler(this);
}
// if our application failed to initialize, fail with a 500 response
if (_app == null) {
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null;
}
// obtain the siteid for this request and stuff that into the context
int siteId = SiteIdentifier.DEFAULT_SITE_ID;
SiteIdentifier ident = _app.getSiteIdentifier();
if (ident != null) {
siteId = ident.identifySite(req);
}
if (_usingSiteLoading) {
ctx.put("__siteid__", Integer.valueOf(siteId));
}
// put the context path in the context as well to make it easier to
// construct full paths
ctx.put("context_path", req.getContextPath());
// then select the template
Template tmpl = null;
try {
tmpl = selectTemplate(siteId, ictx);
} catch (ResourceNotFoundException rnfe) {
// send up a 404. For some annoying reason, Jetty tells Apache
// that all is okay (200) when sending its own custom error pages,
// forcing us to use Jetty's custom error page handling code rather
// than passing it up the chain to be dealt with appropriately.
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
// assume the request is in the default character set unless it has
// actually been sensibly supplied by the browser
if (req.getCharacterEncoding() == null) {
req.setCharacterEncoding(_charset);
}
// assume an HTML response in the default character set unless
// otherwise massaged by the logic
rsp.setContentType("text/html; charset=" + _charset);
Exception error = null;
try {
// insert the application into the context in case the logic or a
// tool wishes to make use of it
ictx.put(APPLICATION_KEY, _app);
// if the application provides a message manager, we want create a
// translation tool and stuff that into the context
MessageManager msgmgr = _app.getMessageManager();
if (msgmgr != null) {
I18nTool i18n = new I18nTool(req, msgmgr);
ictx.put(I18NTOOL_KEY, i18n);
}
// create a form tool for use by the template
FormTool form = new FormTool(req);
ictx.put(FORMTOOL_KEY, form);
// create a new string tool for use by the template
StringTool string = new StringTool();
ictx.put(STRINGTOOL_KEY, string);
// create a new data tool for use by the tempate
DataTool datatool = new DataTool();
ictx.put(DATATOOL_KEY, datatool);
// create a curreny tool set up to use the correct locale
CurrencyTool ctool = new CurrencyTool(req.getLocale());
ictx.put(CURRENCYTOOL_KEY, ctool);
// allow the application to prepare the context
_app.prepareContext(ictx);
// allow the application to do global access control
_app.checkAccess(ictx);
// resolve the appropriate logic class for this URI and execute it
// if it exists
String path = req.getServletPath();
logic = resolveLogic(path);
if (logic != null) {
logic.invoke(_app, ictx);
}
} catch (Exception e) {
error = e;
}
// if an error occurred processing the template, allow the application
// to convert it to something more appropriate and then handle it
String errmsg = null;
try {
if (error != null) {
throw _app.translateException(error);
}
} catch (RedirectException re) {
rsp.sendRedirect(re.getRedirectURL());
return null;
} catch (HttpErrorException hee) {
String msg = hee.getErrorMessage();
if (msg != null) {
rsp.sendError(hee.getErrorCode(), msg);
} else {
rsp.sendError(hee.getErrorCode());
}
return null;
} catch (FriendlyException fe) {
// grab the error message, we'll deal with it shortly
errmsg = fe.getMessage();
} catch (Exception e) {
errmsg = _app.handleException(req, logic, e);
}
// if we have an error message, insert it into the template
if (errmsg != null) {
// try using the application to localize the error message
// before we insert it
MessageManager msgmgr = _app.getMessageManager();
if (msgmgr != null) {
errmsg = msgmgr.getMessage(req, errmsg);
}
ictx.put(ERROR_KEY, errmsg);
}
return tmpl;
}
/**
* Called when a method throws an exception during template
* evaluation.
*/
public Object methodException (Class clazz, String method, Exception e)
throws Exception
{
log.log(Level.WARNING, "Exception [class=" + clazz.getName() +
", method=" + method + "].", e);
return "";
}
/**
* Returns the reference to the application that is handling this
* request.
*
* @return The application in effect for this request or null if no
* application was selected to handle the request.
*/
public static Application getApplication (InvocationContext context)
{
return (Application)context.get(APPLICATION_KEY);
}
/**
* Handles all requests (by default).
*
* @param request HttpServletRequest object containing client request.
* @param response HttpServletResponse object for the response.
*/
protected void doRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Context context = null;
try {
context = new InvocationContext(request, response);
setContentType(request, response);
Template template = handleRequest(request, response, context);
if (template != null) {
mergeTemplate(template, context, response);
}
} catch (Exception e) {
log.log(Level.WARNING, "doRequest failed [uri=" + request.getRequestURI() + "].", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
/**
* Sets the content type of the response, defaulting to {@link #defaultContentType} if not
* overriden. Delegates to {@link #chooseCharacterEncoding(HttpServletRequest)} to select the
* appropriate character encoding.
*/
protected void setContentType (HttpServletRequest request, HttpServletResponse response)
{
String contentType = _defaultContentType;
int index = contentType.lastIndexOf(';') + 1;
if (index <= 0 || (index < contentType.length() &&
contentType.indexOf("charset", index) == -1)) {
// append the character encoding which we'd like to use
String encoding = chooseCharacterEncoding(request);
if (!DEFAULT_OUTPUT_ENCODING.equalsIgnoreCase(encoding)) {
contentType += "; charset=" + encoding;
}
}
response.setContentType(contentType);
}
/**
* Chooses the output character encoding to be used as the value for the "charset=" portion of
* the HTTP Content-Type header (and thus returned by
* <code>response.getCharacterEncoding()</code>). Called by {@link #setContentType} if an
* encoding isn't already specified by Content-Type. By default, chooses the value of
* RuntimeSingleton's <code>output.encoding</code> property.
*/
protected String chooseCharacterEncoding (HttpServletRequest request)
{
return RuntimeSingleton.getString(
RuntimeConstants.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING);
}
/**
* This method is called to select the appropriate template for this request. The default
* implementation simply loads the template using Velocity's default template loading services
* based on the URI provided in the request.
*
* @param ctx The context of this request.
*
* @return The template to be used in generating the response.
*/
protected Template selectTemplate (int siteId, InvocationContext ctx)
throws ResourceNotFoundException, ParseErrorException, Exception
{
String path = ctx.getRequest().getServletPath();
if (_usingSiteLoading) {
// if we're using site resource loading, we need to prefix the path with the site
// identifier
path = siteId + ":" + path;
}
// log.info("Loading template [path=" + path + "].");
return RuntimeSingleton.getTemplate(path);
}
protected void mergeTemplate (Template template, Context context, HttpServletResponse response)
throws ResourceNotFoundException, ParseErrorException, MethodInvocationException,
IOException, UnsupportedEncodingException, Exception
{
ServletOutputStream output = response.getOutputStream();
// ASSUMPTION: response.setContentType() has been called.
String encoding = response.getCharacterEncoding();
VelocityWriter vw = null;
try {
vw = (VelocityWriter)_writerPool.get();
if (vw == null) {
vw = new VelocityWriter(new OutputStreamWriter(output, encoding), 4 * 1024, true);
} else {
vw.recycle(new OutputStreamWriter(output, encoding));
}
template.merge(context, vw);
} finally {
if (vw != null) {
try {
// flush and put back into the pool don't close to allow us to play nicely with
// others.
vw.flush();
} catch (IOException e) {
// do nothing
}
// Clear the VelocityWriter's reference to its internal OutputStreamWriter to allow
// the latter to be GC'd while vw is pooled.
vw.recycle(null);
_writerPool.put(vw);
}
}
}
/**
* This method is called to select the appropriate logic for this request URI.
*
* @return The logic to be used in generating the response or null if no logic could be
* matched.
*/
protected Logic resolveLogic (String path)
{
// look for a cached logic instance
String lclass = _app.generateClass(path);
Logic logic = _logic.get(lclass);
if (logic == null) {
try {
Class pcl = Class.forName(lclass);
logic = (Logic)pcl.newInstance();
} catch (ClassNotFoundException cnfe) {
// nothing interesting to report
} catch (Throwable t) {
log.log(Level.WARNING, "Unable to instantiate logic for application [path=" + path +
", lclass=" + lclass + "].", t);
}
// if something failed, use a dummy in it's place so that we don't sit around all day
// freaking out about our inability to instantiate the proper logic class
if (logic == null) {
logic = new DummyLogic();
}
// cache the resolved logic instance
_logic.put(lclass, logic);
}
return logic;
}
/** The application being served by this dispatcher servlet. */
protected Application _app;
/** A table of resolved logic instances. */
protected HashMap<String,Logic> _logic = new HashMap<String,Logic>();
/** The character set in which serve our responses. */
protected String _charset;
/** Set to true if we're using the {@link SiteResourceLoader}. */
protected boolean _usingSiteLoading;
/** Our default content type. */
protected String _defaultContentType;
/** A pool of VelocityWriter instances. */
protected static SimplePool _writerPool = new SimplePool(40);
/** Describes the location of our properties. */
protected static final String INIT_PROPS_KEY = "org.apache.velocity.properties";
/** This is the key used in the context for error messages. */
protected static final String ERROR_KEY = "error";
/** This is the key used to store a reference back to the dispatcher servlet in our invocation
* context. */
protected static final String APPLICATION_KEY = "%_app_%";
/** The key used to store the translation tool in the context. */
protected static final String I18NTOOL_KEY = "i18n";
/** The key used to store the form tool in the context. */
protected static final String FORMTOOL_KEY = "form";
/** The key used to store the string tool in the context. */
protected static final String STRINGTOOL_KEY = "string";
/** The key used to store the data tool in the context. */
protected static final String DATATOOL_KEY = "data";
/** The key used to store the currency tool in the context. */
protected static final String CURRENCYTOOL_KEY = "cash";
/** The servlet parameter key specifying the application class. */
protected static final String APP_CLASS_KEY = "app_class";
/** The servlet parameter key specifying the base logic package. */
protected static final String LOGIC_PKG_KEY = "logic_package";
/** The servlet parameter key specifying the default character set. */
protected static final String CHARSET_KEY = "charset";
/** The default content type for responses. */
protected static final String DEFAULT_CONTENT_TYPE = "text/html";
/** The default encoding for the output stream. */
protected static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1";
}
|
package com.gh4a;
import android.annotation.TargetApi;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EdgeEffect;
import android.widget.LinearLayout;
import com.gh4a.loader.LoaderCallbacks;
import com.gh4a.utils.UiUtils;
import com.gh4a.widget.SwipeRefreshLayout;
import java.lang.reflect.Field;
public abstract class BasePagerActivity extends BaseActivity implements
SwipeRefreshLayout.ChildScrollDelegate, ViewPager.OnPageChangeListener {
private FragmentAdapter mAdapter;
private TabLayout mTabs;
private ViewPager mPager;
private int[][] mTabHeaderColors;
private boolean mScrolling;
private boolean mErrorViewVisible;
private int mCurrentHeaderColor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new FragmentAdapter();
setContentView(R.layout.view_pager);
mCurrentHeaderColor = UiUtils.resolveColor(this, R.attr.colorPrimary);
mTabHeaderColors = getTabHeaderColors();
mPager = setupPager();
updateTabVisibility();
setChildScrollDelegate(this);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
onPageMoved(0, 0);
}
protected void invalidateFragments() {
mAdapter.notifyDataSetChanged();
updateTabVisibility();
}
protected void invalidateTabs() {
invalidateFragments();
mTabHeaderColors = getTabHeaderColors();
if (mTabHeaderColors != null) {
onPageMoved(0, 0);
} else {
int[] colorAttrs = getHeaderColors();
if (colorAttrs != null) {
transitionHeaderToColor(colorAttrs[0], colorAttrs[1]);
} else {
transitionHeaderToColor(R.attr.colorPrimary, R.attr.colorPrimaryDark);
}
}
tryUpdatePagerColor();
}
protected ViewPager getPager() {
return mPager;
}
@Override
protected void setErrorViewVisibility(boolean visible) {
mErrorViewVisible = visible;
updateTabVisibility();
super.setErrorViewVisibility(visible);
}
@Override
public void onRefresh() {
for (int i = 0; i < mAdapter.getCount(); i++) {
Fragment f = mAdapter.getExistingFragment(i);
if (f instanceof LoaderCallbacks.ParentCallback) {
((LoaderCallbacks.ParentCallback) f).onRefresh();
}
}
super.onRefresh();
}
@Override
public boolean canChildScrollUp() {
Fragment item = mAdapter.getCurrentFragment();
if (item != null && item instanceof SwipeRefreshLayout.ChildScrollDelegate) {
return ((SwipeRefreshLayout.ChildScrollDelegate) item).canChildScrollUp();
}
return false;
}
private ViewPager setupPager() {
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(mAdapter);
pager.addOnPageChangeListener(this);
mTabs = (TabLayout) getLayoutInflater().inflate(R.layout.tab_bar, null);
mTabs.setupWithViewPager(pager);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.addView(mTabs, new Toolbar.LayoutParams(
Toolbar.LayoutParams.WRAP_CONTENT,
Toolbar.LayoutParams.MATCH_PARENT));
} else {
addHeaderView(mTabs, false);
}
return pager;
}
private void updateTabVisibility() {
int count = mAdapter.getCount();
// We never have many pages, make sure to keep them all alive
mPager.setOffscreenPageLimit(Math.max(1, count - 1));
mTabs.setVisibility(count > 1 && !mErrorViewVisible ? View.VISIBLE : View.GONE);
setToolbarScrollable(count > 1
&& getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE);
LinearLayout tabStrip = (LinearLayout) mTabs.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
View tab = tabStrip.getChildAt(i);
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tab.getLayoutParams();
lp.width = LinearLayout.LayoutParams.WRAP_CONTENT;
lp.weight = 1;
tab.setLayoutParams(lp);
}
}
@Override
protected void setHeaderColor(int color, int statusBarColor) {
super.setHeaderColor(color, statusBarColor);
mCurrentHeaderColor = color;
}
@Override
protected void transitionHeaderToColor(int colorAttrId, int statusBarColorAttrId) {
super.transitionHeaderToColor(colorAttrId, statusBarColorAttrId);
mCurrentHeaderColor = UiUtils.resolveColor(this, colorAttrId);
}
protected abstract int[] getTabTitleResIds();
protected abstract Fragment getFragment(int position);
protected boolean fragmentNeedsRefresh(Fragment object) {
return false;
}
/* expected format: int[tabCount][2] - 0 is header, 1 is status bar */
protected int[][] getTabHeaderColors() {
return null;
}
/* expected format: int[2] - 0 is header, 1 is status bar */
protected int[] getHeaderColors() {
return null;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
onPageMoved(position, positionOffset);
}
@Override
public void onPageSelected(int position) {
if (!mScrolling) {
onPageMoved(position, 0);
}
}
@Override
public void onPageScrollStateChanged(int state) {
mScrolling = state != ViewPager.SCROLL_STATE_IDLE;
if (!mScrolling) {
tryUpdatePagerColor();
}
}
protected void onPageMoved(int position, float fraction) {
if (mTabHeaderColors != null) {
int nextIndex = Math.max(position, mTabHeaderColors.length - 1);
int headerColor = UiUtils.mixColors(mTabHeaderColors[position][0],
mTabHeaderColors[nextIndex][0], fraction);
int statusBarColor = UiUtils.mixColors(mTabHeaderColors[position][1],
mTabHeaderColors[nextIndex][1], fraction);
setHeaderColor(headerColor, statusBarColor);
}
}
private class FragmentAdapter extends FragmentStatePagerAdapter {
private final SparseArray<Fragment> mFragments = new SparseArray<>();
private Fragment mCurrentFragment;
public FragmentAdapter() {
super(getSupportFragmentManager());
}
@Override
public int getCount() {
int[] titleResIds = getTabTitleResIds();
return titleResIds != null ? titleResIds.length : 0;
}
@Override
public Fragment getItem(int position) {
return getFragment(position);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment f = (Fragment) super.instantiateItem(container, position);
mFragments.put(position, f);
return f;
}
private Fragment getExistingFragment(int position) {
return mFragments.get(position);
}
private Fragment getCurrentFragment() {
return mCurrentFragment;
}
@Override
public CharSequence getPageTitle(int position) {
return getString(getTabTitleResIds()[position]);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mFragments.remove(position);
if (object == mCurrentFragment) {
mCurrentFragment = null;
}
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
mCurrentFragment = (Fragment) object;
super.setPrimaryItem(container, position, object);
}
@Override
public int getItemPosition(Object object) {
if (object instanceof Fragment && fragmentNeedsRefresh((Fragment) object)) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
}
private void tryUpdatePagerColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ViewPagerEdgeColorHelper helper =
(ViewPagerEdgeColorHelper) mPager.getTag(R.id.EdgeColorHelper);
if (helper == null) {
helper = new ViewPagerEdgeColorHelper(mPager);
mPager.setTag(R.id.EdgeColorHelper, helper);
}
helper.setColor(mCurrentHeaderColor);
}
}
@TargetApi(21)
private static class ViewPagerEdgeColorHelper {
private final ViewPager mPager;
private int mColor;
private EdgeEffect mLeftEffect, mRightEffect;
private static Field sLeftEffectField, sRightEffectField;
public ViewPagerEdgeColorHelper(ViewPager pager) {
mPager = pager;
mColor = 0;
}
public void setColor(int color) {
mColor = color;
applyIfPossible();
}
private void applyIfPossible() {
if (!ensureStaticFields()) {
return;
}
if (mLeftEffect == null || mRightEffect == null) {
try {
Object leftEffect = sLeftEffectField.get(mPager);
Object rightEffect = sRightEffectField.get(mPager);
final Field edgeField = leftEffect.getClass().getDeclaredField("mEdgeEffect");
edgeField.setAccessible(true);
mLeftEffect = (EdgeEffect) edgeField.get(leftEffect);
mRightEffect = (EdgeEffect) edgeField.get(rightEffect);
} catch (IllegalAccessException | NoSuchFieldException e) {
mLeftEffect = mRightEffect = null;
}
}
applyColor(mLeftEffect);
applyColor(mRightEffect);
}
private void applyColor(EdgeEffect effect) {
if (effect != null) {
final int alpha = Color.alpha(effect.getColor());
effect.setColor(Color.argb(alpha, Color.red(mColor),
Color.green(mColor), Color.blue(mColor)));
}
}
private boolean ensureStaticFields() {
if (sLeftEffectField != null && sRightEffectField != null) {
return true;
}
try {
sLeftEffectField = ViewPager.class.getDeclaredField("mLeftEdge");
sLeftEffectField.setAccessible(true);
sRightEffectField = ViewPager.class.getDeclaredField("mRightEdge");
sRightEffectField.setAccessible(true);
return true;
} catch (NoSuchFieldException e) {
// ignored
}
return false;
}
}
}
|
package com.opencms.file;
import org.opencms.security.CmsAccessControlEntry;
import com.opencms.core.A_OpenCms;
import com.opencms.core.CmsException;
import com.opencms.core.I_CmsConstants;
import com.opencms.flex.util.CmsUUID;
import com.opencms.report.CmsShellReport;
import com.opencms.report.I_CmsReport;
import com.opencms.template.A_CmsXmlContent;
import com.opencms.util.Utils;
import com.opencms.workplace.I_CmsWpConstants;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class CmsExport implements I_CmsConstants, Serializable {
// the tags for the manifest
public static String C_EXPORT_TAG_FILES = "files";
public static String C_EXPORT_TAG_CHANNELS = "channels";
public static String C_EXPORT_TAG_MASTERS = "masters";
/** The xml elemtent to store user data and further information in */
private Element m_userdataElement;
/** Indicates if the system should be included to the export */
private boolean m_excludeSystem;
/** Indicated if the unchanged resources should be included to the export */
private boolean m_excludeUnchanged;
/** Indicates if the user data and group data should be included to the export */
private boolean m_exportUserdata;
/** Max file age of contents to export */
private long m_contentAge = 0;
/** Indicates if the current project it the online project */
private boolean m_isOnlineProject;
/** Cache for previously added super folders */
private Vector m_superFolders;
/** Set to store the names of page files in, required for later page body file export */
private Set m_exportedPageFiles = null;
/** Set of all exported files, required for later page body file export */
private Set m_exportedResources = null;
/** Indicates if module data is exported */
protected boolean m_exportingModuleData = false;
/** The export ZIP file to store resources in */
protected String m_exportFile;
/** The export ZIP stream to write resources to */
protected ZipOutputStream m_exportZipStream = null;
/** The CmsObject to do the operations */
protected CmsObject m_cms;
/** The xml manifest-file */
protected Document m_docXml;
/** The xml element to store file information in */
protected Element m_filesElement;
/** The xml-element to store masters information in */
protected Element m_mastersElement;
/** The report for the log messages */
protected I_CmsReport m_report = null;
/** The channelid and the resourceobject of the exported channels */
protected Set m_exportedChannelIds = new HashSet();
/**
* Constructs a new uninitialized export, required for the module data export.<p>
*
* @see CmsExportModuledata
*/
public CmsExport() {
// empty constructor
}
/**
* Constructs a new export.<p>
*
* @param cms the cmsObject to work with
* @param exportFile the file or folder to export to
* @param resourcesToExport the paths of folders and files to export
* @param excludeSystem if true, the system folder is excluded, if false all the resources in
* resourcesToExport are included
* @param excludeUnchanged <code>true</code>, if unchanged files should be excluded
*
* @throws CmsException if something goes wrong
*/
public CmsExport(
CmsObject cms,
String exportFile,
String[] resourcesToExport,
boolean excludeSystem,
boolean excludeUnchanged
) throws CmsException {
this(cms, exportFile, resourcesToExport, excludeSystem, excludeUnchanged, null, false, 0, new CmsShellReport());
}
/**
* Constructs a new export.<p>
*
* @param cms the cmsObject to work with
* @param exportFile the file or folder to export to
* @param resourcesToExport the paths of folders and files to export
* @param excludeSystem if true, the system folder is excluded, if false all the resources in
* resourcesToExport are included
* @param excludeUnchanged <code>true</code>, if unchanged files should be excluded
* @param moduleNode module informations in a Node for module export
* @param exportUserdata if true, the user and grou pdata will also be exported
* @param contentAge export contents changed after this date/time
* @param report to handle the log messages
*
* @throws CmsException if something goes wrong
*/
public CmsExport(
CmsObject cms,
String exportFile,
String[] resourcesToExport,
boolean excludeSystem,
boolean excludeUnchanged,
Node moduleNode,
boolean exportUserdata,
long contentAge,
I_CmsReport report
) throws CmsException {
m_exportFile = exportFile;
m_cms = cms;
m_excludeSystem = excludeSystem;
m_excludeUnchanged = excludeUnchanged;
m_exportUserdata = exportUserdata;
m_isOnlineProject = cms.getRequestContext().currentProject().isOnlineProject();
m_contentAge = contentAge;
m_report = report;
m_exportingModuleData = false;
openExportFile(moduleNode);
// export all the resources
exportAllResources(resourcesToExport);
// export userdata and groupdata if desired
if (m_exportUserdata) {
exportGroups();
exportUsers();
}
closeExportFile();
}
/**
* Opens the export ZIP file and initializes the internal XML document for the manifest.<p>
*
* @param moduleNode optional modul node if a module is to be exported
* @throws CmsException if something goes wrong
*/
protected void openExportFile(Node moduleNode) throws CmsException {
// open the export resource
getExportResource();
// create the xml-config file
getXmlConfigFile(moduleNode);
}
/**
* Closes the export ZIP file and saves the internal XML document for the manifest.<p>
*
* @throws CmsException if something goes wrong
*/
protected void closeExportFile() throws CmsException {
// write the document to the zip-file
writeXmlConfigFile();
try {
m_exportZipStream.close();
} catch (IOException exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Exports all resources and possible sub-folders form the provided list of resources.
*
* @param resourcesToExport the list of resources to export
* @throws CmsException if something goes wrong
*/
protected void exportAllResources(String[] resourcesToExport) throws CmsException {
// distinguish folder and file names
Vector folderNames = new Vector();
Vector fileNames = new Vector();
for (int i=0; i<resourcesToExport.length; i++) {
if (resourcesToExport[i].endsWith(C_FOLDER_SEPARATOR)) {
folderNames.addElement(resourcesToExport[i]);
} else {
fileNames.addElement(resourcesToExport[i]);
}
}
// remove the possible redundancies in the list of resources
checkRedundancies(folderNames, fileNames);
// init sets required for the body file exports
m_exportedPageFiles = new HashSet();
m_exportedResources = new HashSet();
// export the folders
for (int i=0; i<folderNames.size(); i++) {
String path = (String) folderNames.elementAt(i);
// first add superfolders to the xml-config file
addSuperFolders(path);
exportResources(path);
m_exportedResources.add(path);
}
// export the single files
addSingleFiles(fileNames);
// export all body files that have not already been exported
addPageBodyFiles();
}
/**
* Adds a CDATA element to the XML document.<p>
*
* @param docXml Document to create the new element in
* @param element the element to add the subelement to
* @param name the name of the new subelement
* @param value the value of the element
*/
protected void addCdataElement(Document docXml, Element element, String name, String value) {
Element newElement = docXml.createElement(name);
element.appendChild(newElement);
CDATASection text = docXml.createCDATASection(value);
newElement.appendChild(text);
}
/**
* Adds a text element to the XML document.<p>
*
* @param docXml Document to create the new element in
* @param element the element to add the subelement to
* @param name the name of the new subelement
* @param value the value of the element
*/
protected void addElement(Document docXml, Element element, String name, String value) {
Element newElement = docXml.createElement(name);
element.appendChild(newElement);
Text text = docXml.createTextNode(value);
newElement.appendChild(text);
}
/**
* Creates the export XML file and appends the initial tags to it.<p>
*
* @param moduleNode a node with module informations
* @throws CmsException if something goes wrong
*/
private void getXmlConfigFile(Node moduleNode) throws CmsException {
try {
// creates the document
if (m_exportingModuleData) {
// module (COS) data is exported
m_docXml = A_CmsXmlContent.getXmlParser().createEmptyDocument(C_EXPORT_TAG_MODULEXPORT);
} else {
// standard export, only VFS resources are exported
m_docXml = A_CmsXmlContent.getXmlParser().createEmptyDocument(C_EXPORT_TAG_EXPORT);
}
// abbends the initital tags
Node exportNode = m_docXml.getFirstChild();
// add the info element. it contains all infos for this export
Element info = m_docXml.createElement(C_EXPORT_TAG_INFO);
m_docXml.getDocumentElement().appendChild(info);
addElement(m_docXml, info, C_EXPORT_TAG_CREATOR, m_cms.getRequestContext().currentUser().getName());
addElement(m_docXml, info, C_EXPORT_TAG_OC_VERSION, A_OpenCms.getVersionName());
addElement(m_docXml, info, C_EXPORT_TAG_DATE, Utils.getNiceDate(new Date().getTime()));
addElement(m_docXml, info, C_EXPORT_TAG_PROJECT, m_cms.getRequestContext().currentProject().getName());
addElement(m_docXml, info, C_EXPORT_TAG_VERSION, C_EXPORT_VERSION);
if (moduleNode != null) {
// this is a module export - import module informations here
exportNode.appendChild(A_CmsXmlContent.getXmlParser().importNode(m_docXml, moduleNode));
// now remove the unused file informations
NodeList files = ((Element)exportNode).getElementsByTagName("files");
if (files.getLength() == 1) {
files.item(0).getParentNode().removeChild(files.item(0));
}
}
if (m_exportingModuleData) {
// add the root element for the channels
m_filesElement = m_docXml.createElement(C_EXPORT_TAG_CHANNELS);
m_docXml.getDocumentElement().appendChild(m_filesElement);
// add the root element for the masters
m_mastersElement = m_docXml.createElement(C_EXPORT_TAG_MASTERS);
m_docXml.getDocumentElement().appendChild(m_mastersElement);
} else {
// standard export, add not for the files
m_filesElement = m_docXml.createElement(C_EXPORT_TAG_FILES);
m_docXml.getDocumentElement().appendChild(m_filesElement);
}
if (m_exportUserdata) {
// add userdata
m_userdataElement = m_docXml.createElement(C_EXPORT_TAG_USERGROUPDATA);
m_docXml.getDocumentElement().appendChild(m_userdataElement);
}
} catch (Exception exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Writes the <code>manifex.xml</code> configuration file to the esport zip file.<p>
*
* @throws CmsException if something goes wrong
*/
private void writeXmlConfigFile() throws CmsException {
try {
ZipEntry entry = new ZipEntry(C_EXPORT_XMLFILENAME);
m_exportZipStream.putNextEntry(entry);
A_CmsXmlContent.getXmlParser().getXmlText(m_docXml, m_exportZipStream, A_OpenCms.getDefaultEncoding());
m_exportZipStream.closeEntry();
} catch (Exception exc) {
m_report.println(exc);
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Gets the export resource and stores it in a member variable.<p>
*
* @throws CmsException if something goes wrong
*/
private void getExportResource() throws CmsException {
try {
// add zip-extension, if needed
if (!m_exportFile.toLowerCase().endsWith(".zip")) {
m_exportFile += ".zip";
}
// create the export-zipstream
m_exportZipStream = new ZipOutputStream(new FileOutputStream(m_exportFile));
} catch (Exception exc) {
m_report.println(exc);
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Exports all page body files that have not explicityl been added by the user.<p>
*
* @throws CmsException if something goes wrong
*/
private void addPageBodyFiles() throws CmsException {
Iterator i;
Vector bodyFileNames = new Vector();
String bodyPath = I_CmsWpConstants.C_VFS_PATH_BODIES.substring(0, I_CmsWpConstants.C_VFS_PATH_BODIES.lastIndexOf("/"));
// check all exported page files if their body has already been exported
i = m_exportedPageFiles.iterator();
while (i.hasNext()) {
String body = bodyPath + (String)i.next();
if (! isRedundant(body)) {
bodyFileNames.add(body);
}
}
// now export the body files that have not already been exported
addSingleFiles(bodyFileNames);
}
/**
* Adds all files with names in fileNames to the xml-config file.<p>
*
* @param fileNames Vector of path Strings, e.g. <code>/folder/index.html</code>
* @throws CmsException if something goes wrong
*/
private void addSingleFiles(Vector fileNames) throws CmsException {
if (fileNames != null) {
for (int i = 0; i < fileNames.size(); i++) {
String fileName = (String) fileNames.elementAt(i);
try {
CmsFile file = m_cms.readFile(fileName);
if ((file.getState() != C_STATE_DELETED) && (!file.getResourceName().startsWith("~"))) {
addSuperFolders(fileName);
exportResource(file);
m_exportedResources.add(fileName);
}
} catch (CmsException exc) {
if (exc.getType() != CmsException.C_RESOURCE_DELETED) {
throw exc;
}
}
}
}
}
/**
* Adds the superfolders of path to the config file, starting at the top,
* excluding the root folder.<p>
*
* @param path the path of the folder in the virtual files system (VFS)
* @throws CmsException if something goes wrong
*/
private void addSuperFolders(String path) throws CmsException {
// Initialize the "previously added folder cache"
if (m_superFolders == null) {
m_superFolders = new Vector();
}
Vector superFolders = new Vector();
// Check, if the path is really a folder
if (path.lastIndexOf(C_ROOT) != (path.length() - 1)) {
path = path.substring(0, path.lastIndexOf(C_ROOT) + 1);
}
while (path.length() > C_ROOT.length()) {
superFolders.addElement(path);
path = path.substring(0, path.length() - 1);
path = path.substring(0, path.lastIndexOf(C_ROOT) + 1);
}
for (int i = superFolders.size() - 1; i >= 0; i
String addFolder = (String)superFolders.elementAt(i);
if (!m_superFolders.contains(addFolder)) {
// This super folder was NOT added previously. Add it now!
CmsFolder folder = m_cms.readFolder(addFolder);
writeXmlEntrys(folder);
// Remember that this folder was added
m_superFolders.addElement(addFolder);
}
}
}
/**
* Checks if a given resource is already included in the export
* or not.<p>
*
* @param resourcename the VFS resource name to check
* @return <code>true</code> if the resource must not be exported again, <code>false</code> otherwise
*/
private boolean isRedundant(String resourcename) {
if (m_exportedResources == null)
return false;
Iterator i = m_exportedResources.iterator();
while (i.hasNext()) {
String s = (String)i.next();
if (resourcename.startsWith(s))
return true;
}
return false;
}
/**
* Checks whether some of the resources are redundant because a superfolder has also
* been selected or a file is included in a folder.<p>
*
* @param folderNames contains the full pathnames of all folders
* @param fileNames contains the full pathnames of all files
*/
private void checkRedundancies(Vector folderNames, Vector fileNames) {
int i, j;
if (folderNames == null) {
return;
}
Vector redundant = new Vector();
int n = folderNames.size();
if (n > 1) {
// otherwise no check needed, because there is only one resource
for (i = 0; i < n; i++) {
redundant.addElement(new Boolean(false));
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (((String)folderNames.elementAt(i)).length() < ((String)folderNames.elementAt(j)).length()) {
if (((String)folderNames.elementAt(j)).startsWith((String)folderNames.elementAt(i))) {
redundant.setElementAt(new Boolean(true), j);
}
} else {
if (((String)folderNames.elementAt(i)).startsWith((String)folderNames.elementAt(j))) {
redundant.setElementAt(new Boolean(true), i);
}
}
}
}
for (i = n - 1; i >= 0; i
if (((Boolean)redundant.elementAt(i)).booleanValue()) {
folderNames.removeElementAt(i);
}
}
}
// now remove the files who are included automatically in a folder
// otherwise there would be a zip exception
for (i = fileNames.size() - 1; i >= 0; i
for (j = 0; j < folderNames.size(); j++) {
if (((String)fileNames.elementAt(i)).startsWith((String)folderNames.elementAt(j))) {
fileNames.removeElementAt(i);
}
}
}
}
/**
* Exports one single file with all its data and content.<p>
*
* @param file the file to be exported
* @throws CmsException if something goes wrong
*/
private void exportResource(CmsFile file) throws CmsException {
String source = getSourceFilename(m_cms.readAbsolutePath(file));
m_report.print(m_report.key("report.exporting"), I_CmsReport.C_FORMAT_NOTE);
m_report.print(m_cms.readAbsolutePath(file));
m_report.print(m_report.key("report.dots"), I_CmsReport.C_FORMAT_NOTE);
try {
// create the manifest-entrys
writeXmlEntrys(file);
// store content in zip-file
ZipEntry entry = new ZipEntry(source);
m_exportZipStream.putNextEntry(entry);
m_exportZipStream.write(file.getContents());
m_exportZipStream.closeEntry();
} catch (Exception exc) {
m_report.println(exc);
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
if (file.getType() == CmsResourceTypePage.C_RESOURCE_TYPE_ID) {
m_exportedPageFiles.add(m_cms.readAbsolutePath(file));
}
m_report.println(m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
}
/**
* Exports all needed sub-resources to the zip-file.<p>
*
* @param path to complete path to the resource to export
* @throws CmsException if something goes wrong
*/
private void exportResources(String path) throws CmsException {
if (m_exportingModuleData) {
// collect channel id information if required
String channelId = m_cms.readProperty(path, I_CmsConstants.C_PROPERTY_CHANNELID);
if (channelId != null) {
if (! m_exportedChannelIds.contains(channelId)) {
m_exportedChannelIds.add(channelId);
}
}
}
// get all subFolders
List subFolders = m_cms.getSubFolders(path);
// get all files in folder
List subFiles = m_cms.getFilesInFolder(path);
// walk through all files and export them
for (int i = 0; i < subFiles.size(); i++) {
CmsResource file = (CmsResource)subFiles.get(i);
int state = file.getState();
long age = file.getDateLastModified();
if (m_isOnlineProject || (!m_excludeUnchanged) || state == C_STATE_NEW || state == C_STATE_CHANGED) {
if ((state != C_STATE_DELETED) && (!file.getResourceName().startsWith("~")) && (age >= m_contentAge)) {
exportResource(m_cms.readFile(m_cms.readAbsolutePath(file)));
}
}
// release file header memory
subFiles.set(i, null);
}
// all files are exported, release memory
subFiles = null;
// walk through all subfolders and export them
for (int i = 0; i < subFolders.size(); i++) {
CmsResource folder = (CmsResource)subFolders.get(i);
if (folder.getState() != C_STATE_DELETED) {
// check if this is a system-folder and if it should be included.
String export = m_cms.readAbsolutePath(folder);
if (// new VFS, always export "/system/" OR
(I_CmsWpConstants.C_VFS_NEW_STRUCTURE
&& export.equalsIgnoreCase(I_CmsWpConstants.C_VFS_PATH_SYSTEM))
|| // new VFS, always export "/system/bodies/" OR
(
I_CmsWpConstants.C_VFS_NEW_STRUCTURE && export.startsWith(I_CmsWpConstants.C_VFS_PATH_BODIES))
|| // new VFS, always export "/system/galleries/" OR
(
I_CmsWpConstants.C_VFS_NEW_STRUCTURE
&& export.startsWith(I_CmsWpConstants.C_VFS_PATH_GALLERIES))
|| // option "exclude system folder" selected AND
!(
m_excludeSystem
&& // export folder is a system folder
(
export.startsWith(I_CmsWpConstants.C_VFS_PATH_SYSTEM)
|| // if new VFS, ignore old system folders (are below "/system" in new VFS)
(
(!I_CmsWpConstants.C_VFS_NEW_STRUCTURE) && export.startsWith("/pics/system/"))
|| ((!I_CmsWpConstants.C_VFS_NEW_STRUCTURE) && export.startsWith("/moduledemos/"))))) {
// export this folder
if (folder.getDateLastModified() >= m_contentAge) {
// only export folder data to manifest.xml if it has changed
writeXmlEntrys(folder);
}
// export all resources in this folder
exportResources(m_cms.readAbsolutePath(folder));
}
}
// release folder memory
subFolders.set(i, null);
}
}
/**
* Substrings the source filename, so it is shrinked to the needed part for export.<p>
*
* @param absoluteName the absolute path of the resource
* @return the shrinked path
*/
private String getSourceFilename(String absoluteName) {
String path = absoluteName; // keep absolute name to distinguish resources
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path;
}
/**
* Writes the data for a resource (like access-rights) to the <code>manifest.xml</code> file.<p>
*
* @param resource the resource to get the data from
* @throws CmsException if something goes wrong
*/
private void writeXmlEntrys(CmsResource resource) throws CmsException {
// define the file node
Element file = m_docXml.createElement(C_EXPORT_TAG_FILE);
m_filesElement.appendChild(file);
// only write <source> if resource is a file
if (resource.isFile()) {
addElement(m_docXml, file, C_EXPORT_TAG_SOURCE, getSourceFilename(m_cms.readAbsolutePath(resource)));
} else {
// output something to the report for the folder
m_report.print(m_report.key("report.exporting"), I_CmsReport.C_FORMAT_NOTE);
m_report.print(m_cms.readAbsolutePath(resource));
m_report.print(m_report.key("report.dots"), I_CmsReport.C_FORMAT_NOTE);
m_report.println(m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
}
// <destination>
addElement(m_docXml, file, C_EXPORT_TAG_DESTINATION, getSourceFilename(m_cms.readAbsolutePath(resource)));
// <type>
addElement(m_docXml, file, C_EXPORT_TAG_TYPE, m_cms.getResourceType(resource.getType()).getResourceTypeName());
// <link>
addElement(m_docXml, file, C_EXPORT_TAG_LINK, String.valueOf(resource.getVfsLinkType()));
// <uuidstructure>
//addElement(m_docXml, file, C_EXPORT_TAG_UUIDSTRUCTURE,resource.getId().toString());
// <uuidresource>
addElement(m_docXml, file, C_EXPORT_TAG_UUIDRESOURCE, resource.getResourceId().toString());
// <uuidcontent>
addElement(m_docXml, file, C_EXPORT_TAG_UUIDCONTENT, resource.getFileId().toString());
// <datelastmodified>
addElement(m_docXml, file, C_EXPORT_TAG_DATELASTMODIFIED, String.valueOf(resource.getDateLastModified()));
// <userlastmodified>
addElement(m_docXml, file, C_EXPORT_TAG_USERLASTMODIFIED, resource.getUserLastModified().toString());
// <datecreated>
addElement(m_docXml, file, C_EXPORT_TAG_DATECREATED, String.valueOf(resource.getDateCreated()));
// <usercreated>
addElement(m_docXml, file, C_EXPORT_TAG_USERCREATED, resource.getUserCreated().toString());
// <flags>
addElement(m_docXml, file, C_EXPORT_TAG_FLAGS, String.valueOf(resource.getFlags()));
// append the node for properties
Element properties = m_docXml.createElement(C_EXPORT_TAG_PROPERTIES);
file.appendChild(properties);
// read the properties
Map fileProperties = m_cms.readProperties(m_cms.readAbsolutePath(resource));
Iterator i = fileProperties.keySet().iterator();
// create xml-elements for the properties
while (i.hasNext()) {
String key = (String)i.next();
// make sure channel id property is not exported with module data
if ((! m_exportingModuleData) || (! I_CmsConstants.C_PROPERTY_CHANNELID.equals(key))) {
// append the node for a property
Element property = m_docXml.createElement(C_EXPORT_TAG_PROPERTY);
properties.appendChild(property);
addElement(m_docXml, property, C_EXPORT_TAG_NAME, key);
addElement(m_docXml, property, C_EXPORT_TAG_TYPE, m_cms.readPropertydefinition(key, resource.getType()).getType() + "");
addCdataElement(m_docXml, property, C_EXPORT_TAG_VALUE, (String)fileProperties.get(key));
}
}
// append the nodes for access control entries
Element acentries = m_docXml.createElement(C_EXPORT_TAG_ACCESSCONTROL_ENTRIES);
file.appendChild(acentries);
// read the access control entries
Vector fileAcEntries = m_cms.getAccessControlEntries(m_cms.readAbsolutePath(resource), false);
i = fileAcEntries.iterator();
// create xml elements for each access control entry
while (i.hasNext()) {
CmsAccessControlEntry ace = (CmsAccessControlEntry)i.next();
Element acentry = m_docXml.createElement(C_EXPORT_TAG_ACCESSCONTROL_ENTRY);
acentries.appendChild(acentry);
addElement(m_docXml, acentry, C_EXPORT_TAG_ACCESSCONTROL_PRINCIPAL, ace.getPrincipal().toString());
addElement(m_docXml, acentry, C_EXPORT_TAG_FLAGS, new Integer(ace.getFlags()).toString());
Element acpermissionset = m_docXml.createElement(C_EXPORT_TAG_ACCESSCONTROL_PERMISSIONSET);
acentry.appendChild(acpermissionset);
addElement(m_docXml, acpermissionset, C_EXPORT_TAG_ACCESSCONTROL_ALLOWEDPERMISSIONS, new Integer(ace.getAllowedPermissions()).toString());
addElement(m_docXml, acpermissionset, C_EXPORT_TAG_ACCESSCONTROL_DENIEDPERMISSIONS, new Integer(ace.getDeniedPermissions()).toString());
}
}
/**
* Exports all groups with all data.<p>
*
* @throws CmsException if something goes wrong
*/
private void exportGroups() throws CmsException {
Vector allGroups = m_cms.getGroups();
for (int i = 0; i < allGroups.size(); i++) {
exportGroup((CmsGroup)allGroups.elementAt(i));
}
}
/**
* Exports all users with all data.<p>
*
* @throws CmsException if something goes wrong
*/
private void exportUsers() throws CmsException {
Vector allUsers = m_cms.getUsers();
for (int i = 0; i < allUsers.size(); i++) {
exportUser((CmsUser)allUsers.elementAt(i));
}
}
/**
* Exports one single group with all it's data.<p>
*
* @param group the group to be exported
* @throws CmsException if something goes wrong
*/
private void exportGroup(CmsGroup group) throws CmsException {
m_report.print(m_report.key("report.exporting_group"), I_CmsReport.C_FORMAT_NOTE);
m_report.print(group.getName());
m_report.print(m_report.key("report.dots"), I_CmsReport.C_FORMAT_NOTE);
try {
// create the manifest entries
writeXmlGroupEntrys(group);
} catch (Exception e) {
m_report.println(e);
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, e);
}
m_report.println(m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
}
/**
* Exports one single user with all its data.<p>
*
* @param user the user to be exported
* @throws CmsException if something goes wrong
*/
private void exportUser(CmsUser user) throws CmsException {
m_report.print(m_report.key("report.exporting_user"), I_CmsReport.C_FORMAT_NOTE);
m_report.print(user.getName());
m_report.print(m_report.key("report.dots"), I_CmsReport.C_FORMAT_NOTE);
try {
// create the manifest entries
writeXmlUserEntrys(user);
} catch (Exception e) {
m_report.println(e);
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, e);
}
m_report.println(m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
}
/**
* Writes the data for a group to the <code>manifest.xml</code> file.<p>
*
* @param group the group to get the data from
* @throws CmsException if something goes wrong
*/
private void writeXmlGroupEntrys(CmsGroup group) throws CmsException {
String id, name, description, flags, parentgroup;
// get all needed information from the group
id = group.getId().toString();
name = group.getName();
description = group.getDescription();
flags = Integer.toString(group.getFlags());
CmsUUID parentId = group.getParentId();
if (!parentId.isNullUUID()) {
parentgroup = m_cms.getParent(name).getName();
} else {
parentgroup = "";
}
// write these informations to the xml-manifest
Element groupdata = m_docXml.createElement(C_EXPORT_TAG_GROUPDATA);
m_userdataElement.appendChild(groupdata);
addElement(m_docXml, groupdata, C_EXPORT_TAG_ID, id);
addElement(m_docXml, groupdata, C_EXPORT_TAG_NAME, name);
addCdataElement(m_docXml, groupdata, C_EXPORT_TAG_DESCRIPTION, description);
addElement(m_docXml, groupdata, C_EXPORT_TAG_FLAGS, flags);
addElement(m_docXml, groupdata, C_EXPORT_TAG_PARENTGROUP, parentgroup);
}
/**
* Writes the data for a user to the <code>manifest.xml</code> file.<p>
*
* @param user The user to write into the manifest.
* @throws CmsException if something goes wrong
*/
private void writeXmlUserEntrys(CmsUser user) throws CmsException {
String id, name, password, recoveryPassword, description, firstname;
String lastname, email, flags, defaultGroup, address, section, type;
String datfileName = new String();
Hashtable info = new Hashtable();
Vector userGroups = new Vector();
sun.misc.BASE64Encoder enc;
ObjectOutputStream oout;
// get all needed information from the group
id = user.getId().toString();
name = user.getName();
password = user.getPassword();
recoveryPassword = user.getRecoveryPassword();
description = user.getDescription();
firstname = user.getFirstname();
lastname = user.getLastname();
email = user.getEmail();
flags = Integer.toString(user.getFlags());
info = user.getAdditionalInfo();
defaultGroup = user.getDefaultGroup().getName();
address = user.getAddress();
section = user.getSection();
type = Integer.toString(user.getType());
userGroups = m_cms.getDirectGroupsOfUser(user.getName());
// write these informations to the xml-manifest
Element userdata = m_docXml.createElement(C_EXPORT_TAG_USERDATA);
m_userdataElement.appendChild(userdata);
addElement(m_docXml, userdata, C_EXPORT_TAG_ID, id);
addElement(m_docXml, userdata, C_EXPORT_TAG_NAME, name);
//Encode the info value, using any base 64 decoder
enc = new sun.misc.BASE64Encoder();
String passwd = new String(enc.encodeBuffer(password.getBytes()));
addCdataElement(m_docXml, userdata, C_EXPORT_TAG_PASSWORD, passwd);
enc = new sun.misc.BASE64Encoder();
String recPasswd = new String(enc.encodeBuffer(recoveryPassword.getBytes()));
addCdataElement(m_docXml, userdata, C_EXPORT_TAG_RECOVERYPASSWORD, recPasswd);
addCdataElement(m_docXml, userdata, C_EXPORT_TAG_DESCRIPTION, description);
addElement(m_docXml, userdata, C_EXPORT_TAG_FIRSTNAME, firstname);
addElement(m_docXml, userdata, C_EXPORT_TAG_LASTNAME, lastname);
addElement(m_docXml, userdata, C_EXPORT_TAG_EMAIL, email);
addElement(m_docXml, userdata, C_EXPORT_TAG_FLAGS, flags);
addElement(m_docXml, userdata, C_EXPORT_TAG_DEFAULTGROUP, defaultGroup);
addCdataElement(m_docXml, userdata, C_EXPORT_TAG_ADDRESS, address);
addElement(m_docXml, userdata, C_EXPORT_TAG_SECTION, section);
addElement(m_docXml, userdata, C_EXPORT_TAG_TYPE, type);
// serialize the hashtable and write the info into a file
try {
datfileName = "/~" + C_EXPORT_TAG_USERINFO + "/" + name + ".dat";
ByteArrayOutputStream bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(info);
oout.close();
byte[] serializedInfo = bout.toByteArray();
// store the userinfo in zip-file
ZipEntry entry = new ZipEntry(datfileName);
m_exportZipStream.putNextEntry(entry);
m_exportZipStream.write(serializedInfo);
m_exportZipStream.closeEntry();
} catch (IOException ioex) {
m_report.println(ioex);
}
// create tag for userinfo
addCdataElement(m_docXml, userdata, C_EXPORT_TAG_USERINFO, datfileName);
// append the node for groups of user
Element usergroup = m_docXml.createElement(C_EXPORT_TAG_USERGROUPS);
userdata.appendChild(usergroup);
for (int i = 0; i < userGroups.size(); i++) {
String groupName = ((CmsGroup)userGroups.elementAt(i)).getName();
Element group = m_docXml.createElement(C_EXPORT_TAG_GROUPNAME);
usergroup.appendChild(group);
addElement(m_docXml, group, C_EXPORT_TAG_NAME, groupName);
}
}
}
|
/*
* Gameboi
*/
package gameboi;
// for testing
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Z80 Gameboy CPU
*
* Implementation of a gameboy cpu. Eight registers (a,b,c,d,e,f,h,l), a
* stack pointer, program counter, and timers
*
* @author tomis007
*/
public class CPU {
// registers
private final GBRegisters registers;
// stack pointer, program counter
private int sp;
private int pc;
//for debugging
private GPU gpu;
private boolean debug;
private int[] executed_opcodes;
//associated memory to use with CPU
private final GBMem memory;
private final int clockSpeed;
private int timerCounter;
private int divideCounter;
private boolean executionHalted;
private int[] extended_opcodes;
/**
* Interrupt state of cpu
* Represents the Interrupt Master Enable Flag
*/
private enum InterruptCpuState {
DISABLED, DELAY_ON, DELAY_OFF, ENABLED;
}
//constants
private static final InterruptCpuState DISABLED = InterruptCpuState.DISABLED;
private static final InterruptCpuState DELAY_ON = InterruptCpuState.DELAY_ON;
private static final InterruptCpuState DELAY_OFF = InterruptCpuState.DELAY_OFF;
private static final InterruptCpuState ENABLED = InterruptCpuState.ENABLED;
private InterruptCpuState interruptState;
//constants
private static final GBRegisters.Reg A = GBRegisters.Reg.A;
private static final GBRegisters.Reg B = GBRegisters.Reg.B;
private static final GBRegisters.Reg C = GBRegisters.Reg.C;
private static final GBRegisters.Reg D = GBRegisters.Reg.D;
private static final GBRegisters.Reg E = GBRegisters.Reg.E;
private static final GBRegisters.Reg F = GBRegisters.Reg.F;
private static final GBRegisters.Reg H = GBRegisters.Reg.H;
private static final GBRegisters.Reg L = GBRegisters.Reg.L;
private static final GBRegisters.Reg HL = GBRegisters.Reg.HL;
private static final GBRegisters.Reg BC = GBRegisters.Reg.BC;
private static final GBRegisters.Reg DE = GBRegisters.Reg.DE;
private static final GBRegisters.Reg AF = GBRegisters.Reg.AF;
//flag bitnum constants
private static final int ZERO_F = 7;
private static final int SUBTRACT_F = 6;
private static final int HALFCARRY_F = 5;
private static final int CARRY_F = 4;
/**
* Constructor for gameboy z80 CPU
*
* @param memory GBMem object to associate with this cpu
*/
public CPU(GBMem memory) {
//for bios
pc = 0x100;
sp = 0xfffe;//0xfffe;
this.memory = memory;
registers = new GBRegisters();
clockSpeed = 4194304;
timerCounter = 1024;
divideCounter = clockSpeed / 16382;
interruptState = DISABLED;
executed_opcodes = new int[0xff];
extended_opcodes = new int[0xff];
for (int i = 0; i < executed_opcodes.length; ++i) {
executed_opcodes[i] = 0;
extended_opcodes[i] = 0;
}
debug = false;
}
/**
* for debug mode
*
*/
public void setGPU(GPU gpu) {
this.gpu = gpu;
}
/**
* returns registers (for testing)
*/
public GBRegisters getReg() {
return registers;
}
/**
* Execute the next opcode in memory, and update the CPU timers
*
* @return clock cycles taken to execute the opcode
*/
public int ExecuteOpcode() {
if (executionHalted) {
return 4; // to keep other things running
}
//handle interrupt state change
if (interruptState == DELAY_ON) {
interruptState = ENABLED;
} else if (interruptState == DELAY_OFF) {
interruptState = DISABLED;
}
if (pc == 0xc27d && !debug) {
// enterDebugMode();
}
int opcode = memory.readByte(pc);
if (debug) {
System.out.println("0x" + Integer.toHexString(opcode));
}
pc++;
// System.out.println("Opcode: 0x" + Integer.toHexString(opcode));
// dumpRegisters();
executed_opcodes[opcode]++;
int cycles = runInstruction(opcode);
if (!executionHalted) {
updateDivideRegister(cycles); //TODO
updateTimers(cycles); //TODO
checkInterrupts();
}
return cycles;
}
/**
* Debug mode for cpu instructions
* runs one instruction at a time, prints registers
*
*/
private void enterDebugMode() {
debug = true;
Scanner sc = new Scanner(System.in);
String input;
System.out.print(" > ");
input = sc.nextLine();
while (!"q".equals(input)) {
if ("n".equals(input)) {
int cycles = ExecuteOpcode();
gpu.updateGraphics(cycles);
}
System.out.print(" > ");
input = sc.nextLine();
}
debug = false;
}
/**
*
* for debugging
*
*
* prints every executed opcode and the
* number of times they have been executed
*
*/
public void printOpcodeCount() {
try {
PrintWriter writer = new PrintWriter("output_opcodes.txt");
for (int i = 0; i < 0xff; ++i) {
if (executed_opcodes[i] > 0) {
writer.println("opcode: 0x" + Integer.toHexString(i) + " count: " + executed_opcodes[i]);
}
}
writer.println("EXTENDED OPCODES");
for (int i = 0; i < 0xff; ++i) {
if (extended_opcodes[i] > 0) {
writer.println("opcode: 0x" + Integer.toHexString(i) + " count: " + extended_opcodes[i]);
}
}
writer.close();
} catch (IOException e) {
System.err.println("exception");
}
}
/**
* Opcode Instructions for the Gameboy Z80 Chip.
*
* <p>
* Runs the instruction associated with the opcode, and returns the
* clock cycles taken.
*
* TODO HALT,STOP
* @param opcode (required) opcode to execute
* @return number of cycles taken to execute
*/
private int runInstruction(int opcode) {
switch (opcode) {
case 0x0: return 4; //NOP
// LD nn,n
case 0x06: return ld_NN_N(B);
case 0x0e: return ld_NN_N(C);
case 0x16: return ld_NN_N(D);
case 0x1e: return ld_NN_N(E);
case 0x26: return ld_NN_N(H);
case 0x2e: return ld_NN_N(L);
//LD r1,r2
case 0x7f: return eightBitLdR1R2(A, A);
case 0x78: return eightBitLdR1R2(A, B);
case 0x79: return eightBitLdR1R2(A, C);
case 0x7a: return eightBitLdR1R2(A, D);
case 0x7b: return eightBitLdR1R2(A, E);
case 0x7c: return eightBitLdR1R2(A, H);
case 0x7d: return eightBitLdR1R2(A, L);
case 0x7e: return eightBitLdR1R2(A, HL);
case 0x40: return eightBitLdR1R2(B, B);
case 0x41: return eightBitLdR1R2(B, C);
case 0x42: return eightBitLdR1R2(B, D);
case 0x43: return eightBitLdR1R2(B, E);
case 0x44: return eightBitLdR1R2(B, H);
case 0x45: return eightBitLdR1R2(B, L);
case 0x46: return eightBitLdR1R2(B, HL);
case 0x48: return eightBitLdR1R2(C, B);
case 0x49: return eightBitLdR1R2(C, C);
case 0x4a: return eightBitLdR1R2(C, D);
case 0x4b: return eightBitLdR1R2(C, E);
case 0x4c: return eightBitLdR1R2(C, H);
case 0x4d: return eightBitLdR1R2(C, L);
case 0x4e: return eightBitLdR1R2(C, HL);
case 0x50: return eightBitLdR1R2(D, B);
case 0x51: return eightBitLdR1R2(D, C);
case 0x52: return eightBitLdR1R2(D, D);
case 0x53: return eightBitLdR1R2(D, E);
case 0x54: return eightBitLdR1R2(D, H);
case 0x55: return eightBitLdR1R2(D, L);
case 0x56: return eightBitLdR1R2(D, HL);
case 0x58: return eightBitLdR1R2(E, B);
case 0x59: return eightBitLdR1R2(E, C);
case 0x5a: return eightBitLdR1R2(E, D);
case 0x5b: return eightBitLdR1R2(E, E);
case 0x5c: return eightBitLdR1R2(E, H);
case 0x5d: return eightBitLdR1R2(E, L);
case 0x5e: return eightBitLdR1R2(E, HL);
case 0x60: return eightBitLdR1R2(H, B);
case 0x61: return eightBitLdR1R2(H, C);
case 0x62: return eightBitLdR1R2(H, D);
case 0x63: return eightBitLdR1R2(H, E);
case 0x64: return eightBitLdR1R2(H, H);
case 0x65: return eightBitLdR1R2(H, L);
case 0x66: return eightBitLdR1R2(H, HL);
case 0x68: return eightBitLdR1R2(L, B);
case 0x69: return eightBitLdR1R2(L, C);
case 0x6a: return eightBitLdR1R2(L, D);
case 0x6b: return eightBitLdR1R2(L, E);
case 0x6c: return eightBitLdR1R2(L, H);
case 0x6d: return eightBitLdR1R2(L, L);
case 0x6e: return eightBitLdR1R2(L, HL);
case 0x70: return eightBitLdR1R2(HL, B);
case 0x71: return eightBitLdR1R2(HL, C);
case 0x72: return eightBitLdR1R2(HL, D);
case 0x73: return eightBitLdR1R2(HL, E);
case 0x74: return eightBitLdR1R2(HL, H);
case 0x75: return eightBitLdR1R2(HL, L);
// special 8 bit load from memory
case 0x36: return eightBitLoadFromMem();
// LD A,n
case 0x0a: return eightBitLdAN(BC);
case 0x1a: return eightBitLdAN(DE);
case 0xfa: return eightBitALoadMem(true);
case 0x3e: return eightBitALoadMem(false);
// LD n,A
case 0x47: return eightBitLdR1R2(B, A);
case 0x4f: return eightBitLdR1R2(C, A);
case 0x57: return eightBitLdR1R2(D, A);
case 0x5f: return eightBitLdR1R2(E, A);
case 0x67: return eightBitLdR1R2(H, A);
case 0x6f: return eightBitLdR1R2(L, A);
case 0x02: return eightBitLdR1R2(BC, A);
case 0x12: return eightBitLdR1R2(DE, A);
case 0x77: return eightBitLdR1R2(HL, A);
case 0xea: return eightBitLoadToMem();
case 0xf2: return eightBitLDfromAC();
case 0xe2: return eightBitLDtoAC();
// LDD A,(HL)
case 0x3a: return eightBitLDAHl();
// LDD (HL), A
case 0x32: return eightBitStoreHL();
// LDI (HL), A
case 0x2a: return eightBitLDIA();
// LDI (HL), A
case 0x22: return LDI_HL_A();
// LDH (n), A, LDH A,(n)
case 0xe0: return eightBitLdhA(true);
case 0xf0: return eightBitLdhA(false);
//LD n, nn
case 0x01: return ld_N_NN(BC);
case 0x11: return ld_N_NN(DE);
case 0x21: return ld_N_NN(HL);
case 0x31: return ld_SP_NN();
//LD SP,HL
case 0xf9: return sixteenBitLdSpHl();
case 0xf8: return sixteenBitLdHlSp();
//LD (nn), SP
case 0x08: return sixteenBitLdNnSp();
//Push nn to stack
case 0xf5: return pushNN(AF);
case 0xc5: return pushNN(BC);
case 0xd5: return pushNN(DE);
case 0xe5: return pushNN(HL);
//POP nn off stack
case 0xf1: return popNN(AF);
case 0xc1: return popNN(BC);
case 0xd1: return popNN(DE);
case 0xe1: return popNN(HL);
//ADD A,n
case 0x87: return addAN(A, false, false);
case 0x80: return addAN(B, false, false);
case 0x81: return addAN(C, false, false);
case 0x82: return addAN(D, false, false);
case 0x83: return addAN(E, false, false);
case 0x84: return addAN(H, false, false);
case 0x85: return addAN(L, false, false);
case 0x86: return addAN(HL, false, false);
case 0xc6: return addAN(A, false, true);
//ADC A,n
case 0x8f: return addAN(A, true, false);
case 0x88: return addAN(B, true, false);
case 0x89: return addAN(C, true, false);
case 0x8a: return addAN(D, true, false);
case 0x8b: return addAN(E, true, false);
case 0x8c: return addAN(H, true, false);
case 0x8d: return addAN(L, true, false);
case 0x8e: return addAN(HL, true, false);
case 0xce: return addAN(A, true, true);
//SUB n
case 0x97: return subAN(A, false, false);
case 0x90: return subAN(B, false, false);
case 0x91: return subAN(C, false, false);
case 0x92: return subAN(D, false, false);
case 0x93: return subAN(E, false, false);
case 0x94: return subAN(H, false, false);
case 0x95: return subAN(L, false, false);
case 0x96: return subAN(HL, false, false);
case 0xd6: return subAN(A, false, true);
//SUBC A,n
case 0x9f: return subAN(A, true, false);
case 0x98: return subAN(B, true, false);
case 0x99: return subAN(C, true, false);
case 0x9a: return subAN(D, true, false);
case 0x9b: return subAN(E, true, false);
case 0x9c: return subAN(H, true, false);
case 0x9d: return subAN(L, true, false);
case 0x9e: return subAN(HL, true, false);
case 0xde: return subAN(A, true, true);
//AND N
case 0xa7: return andN(A, false);
case 0xa0: return andN(GBRegisters.Reg.B, false);
case 0xa1: return andN(GBRegisters.Reg.C, false);
case 0xa2: return andN(GBRegisters.Reg.D, false);
case 0xa3: return andN(GBRegisters.Reg.E, false);
case 0xa4: return andN(GBRegisters.Reg.H, false);
case 0xa5: return andN(GBRegisters.Reg.L, false);
case 0xa6: return andN(GBRegisters.Reg.HL, false);
case 0xe6: return andN(A, true);
//OR N
case 0xb7: return orN(A, false);
case 0xb0: return orN(B, false);
case 0xb1: return orN(C, false);
case 0xb2: return orN(D, false);
case 0xb3: return orN(E, false);
case 0xb4: return orN(H, false);
case 0xb5: return orN(L, false);
case 0xb6: return orN(HL, false);
case 0xf6: return orN(A, true);
// XOR n
case 0xaf: return xorN(A, false);
case 0xa8: return xorN(B, false);
case 0xa9: return xorN(C, false);
case 0xaa: return xorN(D, false);
case 0xab: return xorN(E, false);
case 0xac: return xorN(H, false);
case 0xad: return xorN(L, false);
case 0xae: return xorN(HL, false);
case 0xee: return xorN(A, true);
// CP n
case 0xbf: return cpN(A, false);
case 0xb8: return cpN(B, false);
case 0xb9: return cpN(C, false);
case 0xba: return cpN(D, false);
case 0xbb: return cpN(E, false);
case 0xbc: return cpN(H, false);
case 0xbd: return cpN(L, false);
case 0xbe: return cpN(HL, false);
case 0xfe: return cpN(A, true);
// INC n
case 0x3c: return incN(A);
case 0x04: return incN(B);
case 0x0c: return incN(C);
case 0x14: return incN(D);
case 0x1c: return incN(E);
case 0x24: return incN(H);
case 0x2c: return incN(L);
case 0x34: return incN(HL);
// DEC n
case 0x3d: return decN(A);
case 0x05: return decN(B);
case 0x0d: return decN(C);
case 0x15: return decN(D);
case 0x1d: return decN(E);
case 0x25: return decN(H);
case 0x2d: return decN(L);
case 0x35: return decN(HL);
//ADD HL,n
case 0x09: return sixteenBitAdd(BC, false);
case 0x19: return sixteenBitAdd(DE, false);
case 0x29: return sixteenBitAdd(HL, false);
case 0x39: return sixteenBitAdd(BC, true);
//ADD SP,n
case 0xe8: return addSPN();
//INC nn
case 0x03: return incNN(BC, false);
case 0x13: return incNN(DE, false);
case 0x23: return incNN(HL, false);
case 0x33: return incNN(BC, true);
//DEC nn
case 0x0B: return decNN(GBRegisters.Reg.BC, false);
case 0x1B: return decNN(GBRegisters.Reg.DE, false);
case 0x2B: return decNN(GBRegisters.Reg.HL, false);
case 0x3B: return decNN(GBRegisters.Reg.BC, true);
// extended
case 0xcb: return extendedOpcode();
// DAA TODO
case 0x27: return decAdjust();
//CPL
case 0x2f: return cplRegA();
//CCF
case 0x3f: return ccf();
//SCF
case 0x37: return scf();
//Jumps
case 0xc3: return jump();
// conditional jump
case 0xc2: return jumpC(opcode);
case 0xca: return jumpC(opcode);
case 0xd2: return jumpC(opcode);
case 0xda: return jumpC(opcode);
// JP (HL)
case 0xe9: return jumpHL();
//JR n
case 0x18: return jumpN();
//JR cc, n
case 0x20: return jumpCN(opcode);
case 0x28: return jumpCN(opcode);
case 0x30: return jumpCN(opcode);
case 0x38: return jumpCN(opcode);
//TODO HALT,STOP
case 0x76: System.out.println("HALT");return halt();
case 0x10: return stop();
case 0xf3: return disableInterrupts();
case 0xfb: return enableInterrupts();
//calls
case 0xcd: return call();
case 0xc4: return callC(opcode);
case 0xcc: return callC(opcode);
case 0xd4: return callC(opcode);
case 0xdc: return callC(opcode);
//restarts
case 0xc7: return restart(0x00);
case 0xcf: return restart(0x08);
case 0xd7: return restart(0x10);
case 0xdf: return restart(0x18);
case 0xe7: return restart(0x20);
case 0xef: return restart(0x28);
case 0xf7: return restart(0x30);
case 0xff: return restart(0x38);
//RETURNs
case 0xc9: return ret();
case 0xc0: return retC(opcode);
case 0xc8: return retC(opcode);
case 0xd0: return retC(opcode);
case 0xd8: return retC(opcode);
//RETI
case 0xd9: return retI();
//ROTATES AND SHIFTS
//RLCA
case 0x07: return rlcA();
//RLA
case 0x17: return rlA();
//RRCA
case 0x0f: return rrcA();
case 0x1f: return rrN(A, false);
default:
System.err.println("Unimplemented opcode: 0x" +
Integer.toHexString(opcode));
System.exit(1);
}
return 0;
}
private int extendedOpcode() {
int opcode = memory.readByte(pc);
pc++;
switch(opcode) {
//SWAP N
case 0x37: return swapN(A);
case 0x30: return swapN(B);
case 0x31: return swapN(C);
case 0x32: return swapN(D);
case 0x33: return swapN(E);
case 0x34: return swapN(H);
case 0x35: return swapN(L);
case 0x36: return swapN(HL);
//RLC n
case 0x07: return rlcN(A);
case 0x00: return rlcN(B);
case 0x01: return rlcN(C);
case 0x02: return rlcN(D);
case 0x03: return rlcN(E);
case 0x04: return rlcN(H);
case 0x05: return rlcN(L);
case 0x06: return rlcN(HL);
//RL n
case 0x17: return rlN(A);
case 0x10: return rlN(B);
case 0x11: return rlN(C);
case 0x12: return rlN(D);
case 0x13: return rlN(E);
case 0x14: return rlN(H);
case 0x15: return rlN(L);
case 0x16: return rlN(HL);
//RRC n
case 0x0f: return rrcN(A);
case 0x08: return rrcN(B);
case 0x09: return rrcN(C);
case 0x0a: return rrcN(D);
case 0x0b: return rrcN(E);
case 0x0c: return rrcN(H);
case 0x0d: return rrcN(L);
case 0x0e: return rrcN(HL);
//RR n
case 0x1f: return rrN(A, true);
case 0x18: return rrN(B, true);
case 0x19: return rrN(C, true);
case 0x1a: return rrN(D, true);
case 0x1b: return rrN(E, true);
case 0x1c: return rrN(H, true);
case 0x1d: return rrN(L, true);
case 0x1e: return rrN(HL, true);
//SLA n
case 0x27: return slAN(A);
case 0x20: return slAN(B);
case 0x21: return slAN(C);
case 0x22: return slAN(D);
case 0x23: return slAN(E);
case 0x24: return slAN(H);
case 0x25: return slAN(L);
case 0x26: return slAN(HL);
//SRA n
case 0x2f: return srAL(A, false);
case 0x28: return srAL(B, false);
case 0x29: return srAL(C, false);
case 0x2a: return srAL(D, false);
case 0x2b: return srAL(E, false);
case 0x2c: return srAL(H, false);
case 0x2d: return srAL(L, false);
case 0x2e: return srAL(HL, false);
//SRL n
case 0x3f: return srAL(A, true);
case 0x38: return srAL(B, true);
case 0x39: return srAL(C, true);
case 0x3a: return srAL(D, true);
case 0x3b: return srAL(E, true);
case 0x3c: return srAL(H, true);
case 0x3d: return srAL(L, true);
case 0x3e: return srAL(HL, true);
//Bit opcodes
case 0x47: return bitBR(0, A);
case 0x40: return bitBR(0, B);
case 0x41: return bitBR(0, C);
case 0x42: return bitBR(0, D);
case 0x43: return bitBR(0, E);
case 0x44: return bitBR(0, H);
case 0x45: return bitBR(0, L);
case 0x46: return bitBR(0, HL);
case 0x4f: return bitBR(1, A);
case 0x48: return bitBR(1, B);
case 0x49: return bitBR(1, C);
case 0x4a: return bitBR(1, D);
case 0x4b: return bitBR(1, E);
case 0x4c: return bitBR(1, H);
case 0x4d: return bitBR(1, L);
case 0x4e: return bitBR(1, HL);
case 0x57: return bitBR(2, A);
case 0x50: return bitBR(2, B);
case 0x51: return bitBR(2, C);
case 0x52: return bitBR(2, D);
case 0x53: return bitBR(2, E);
case 0x54: return bitBR(2, H);
case 0x55: return bitBR(2, L);
case 0x56: return bitBR(2, HL);
case 0x5f: return bitBR(3, A);
case 0x58: return bitBR(3, B);
case 0x59: return bitBR(3, C);
case 0x5a: return bitBR(3, D);
case 0x5b: return bitBR(3, E);
case 0x5c: return bitBR(3, H);
case 0x5d: return bitBR(3, L);
case 0x5e: return bitBR(3, HL);
case 0x67: return bitBR(4, A);
case 0x60: return bitBR(4, B);
case 0x61: return bitBR(4, C);
case 0x62: return bitBR(4, D);
case 0x63: return bitBR(4, E);
case 0x64: return bitBR(4, H);
case 0x65: return bitBR(4, L);
case 0x66: return bitBR(4, HL);
case 0x6f: return bitBR(5, A);
case 0x68: return bitBR(5, B);
case 0x69: return bitBR(5, C);
case 0x6a: return bitBR(5, D);
case 0x6b: return bitBR(5, E);
case 0x6c: return bitBR(5, H);
case 0x6d: return bitBR(5, L);
case 0x6e: return bitBR(5, HL);
case 0x77: return bitBR(6, A);
case 0x70: return bitBR(6, B);
case 0x71: return bitBR(6, C);
case 0x72: return bitBR(6, D);
case 0x73: return bitBR(6, E);
case 0x74: return bitBR(6, H);
case 0x75: return bitBR(6, L);
case 0x76: return bitBR(6, HL);
case 0x7f: return bitBR(7, A);
case 0x78: return bitBR(7, B);
case 0x79: return bitBR(7, C);
case 0x7a: return bitBR(7, D);
case 0x7b: return bitBR(7, E);
case 0x7c: return bitBR(7, H);
case 0x7d: return bitBR(7, L);
case 0x7e: return bitBR(7, HL);
case 0xc7: return setBR(1, 0, A);
case 0xc0: return setBR(1, 0, B);
case 0xc1: return setBR(1, 0, C);
case 0xc2: return setBR(1, 0, D);
case 0xc3: return setBR(1, 0, E);
case 0xc4: return setBR(1, 0, H);
case 0xc5: return setBR(1, 0, L);
case 0xc6: return setBR(1, 0, HL);
case 0xcf: return setBR(1, 1, A);
case 0xc8: return setBR(1, 1, B);
case 0xc9: return setBR(1, 1, C);
case 0xca: return setBR(1, 1, D);
case 0xcb: return setBR(1, 1, E);
case 0xcc: return setBR(1, 1, H);
case 0xcd: return setBR(1, 1, L);
case 0xce: return setBR(1, 1, HL);
case 0xd7: return setBR(1, 2, A);
case 0xd0: return setBR(1, 2, B);
case 0xd1: return setBR(1, 2, C);
case 0xd2: return setBR(1, 2, D);
case 0xd3: return setBR(1, 2, E);
case 0xd4: return setBR(1, 2, H);
case 0xd5: return setBR(1, 2, L);
case 0xd6: return setBR(1, 2, HL);
case 0xdf: return setBR(1, 3, A);
case 0xd8: return setBR(1, 3, B);
case 0xd9: return setBR(1, 3, C);
case 0xda: return setBR(1, 3, D);
case 0xdb: return setBR(1, 3, E);
case 0xdc: return setBR(1, 3, H);
case 0xdd: return setBR(1, 3, L);
case 0xde: return setBR(1, 3, HL);
case 0xe7: return setBR(1, 4, A);
case 0xe0: return setBR(1, 4, B);
case 0xe1: return setBR(1, 4, C);
case 0xe2: return setBR(1, 4, D);
case 0xe3: return setBR(1, 4, E);
case 0xe4: return setBR(1, 4, H);
case 0xe5: return setBR(1, 4, L);
case 0xe6: return setBR(1, 4, HL);
case 0xef: return setBR(1, 5, A);
case 0xe8: return setBR(1, 5, B);
case 0xe9: return setBR(1, 5, C);
case 0xea: return setBR(1, 5, D);
case 0xeb: return setBR(1, 5, E);
case 0xec: return setBR(1, 5, H);
case 0xed: return setBR(1, 5, L);
case 0xee: return setBR(1, 5, HL);
case 0xf7: return setBR(1, 6, A);
case 0xf0: return setBR(1, 6, B);
case 0xf1: return setBR(1, 6, C);
case 0xf2: return setBR(1, 6, D);
case 0xf3: return setBR(1, 6, E);
case 0xf4: return setBR(1, 6, H);
case 0xf5: return setBR(1, 6, L);
case 0xf6: return setBR(1, 6, HL);
case 0xff: return setBR(1, 7, A);
case 0xf8: return setBR(1, 7, B);
case 0xf9: return setBR(1, 7, C);
case 0xfa: return setBR(1, 7, D);
case 0xfb: return setBR(1, 7, E);
case 0xfc: return setBR(1, 7, H);
case 0xfd: return setBR(1, 7, L);
case 0xfe: return setBR(1, 7, HL);
case 0x87: return setBR(0, 0, A);
case 0x80: return setBR(0, 0, B);
case 0x81: return setBR(0, 0, C);
case 0x82: return setBR(0, 0, D);
case 0x83: return setBR(0, 0, E);
case 0x84: return setBR(0, 0, H);
case 0x85: return setBR(0, 0, L);
case 0x86: return setBR(0, 0, HL);
case 0x8f: return setBR(0, 1, A);
case 0x88: return setBR(0, 1, B);
case 0x89: return setBR(0, 1, C);
case 0x8a: return setBR(0, 1, D);
case 0x8b: return setBR(0, 1, E);
case 0x8c: return setBR(0, 1, H);
case 0x8d: return setBR(0, 1, L);
case 0x8e: return setBR(0, 1, HL);
case 0x97: return setBR(0, 2, A);
case 0x90: return setBR(0, 2, B);
case 0x91: return setBR(0, 2, C);
case 0x92: return setBR(0, 2, D);
case 0x93: return setBR(0, 2, E);
case 0x94: return setBR(0, 2, H);
case 0x95: return setBR(0, 2, L);
case 0x96: return setBR(0, 2, HL);
case 0x9f: return setBR(0, 3, A);
case 0x98: return setBR(0, 3, B);
case 0x99: return setBR(0, 3, C);
case 0x9a: return setBR(0, 3, D);
case 0x9b: return setBR(0, 3, E);
case 0x9c: return setBR(0, 3, H);
case 0x9d: return setBR(0, 3, L);
case 0x9e: return setBR(0, 3, HL);
case 0xa7: return setBR(0, 4, A);
case 0xa0: return setBR(0, 4, B);
case 0xa1: return setBR(0, 4, C);
case 0xa2: return setBR(0, 4, D);
case 0xa3: return setBR(0, 4, E);
case 0xa4: return setBR(0, 4, H);
case 0xa5: return setBR(0, 4, L);
case 0xa6: return setBR(0, 4, HL);
case 0xaf: return setBR(0, 5, A);
case 0xa8: return setBR(0, 5, B);
case 0xa9: return setBR(0, 5, C);
case 0xaa: return setBR(0, 5, D);
case 0xab: return setBR(0, 5, E);
case 0xac: return setBR(0, 5, H);
case 0xad: return setBR(0, 5, L);
case 0xae: return setBR(0, 5, HL);
case 0xb7: return setBR(0, 6, A);
case 0xb0: return setBR(0, 6, B);
case 0xb1: return setBR(0, 6, C);
case 0xb2: return setBR(0, 6, D);
case 0xb3: return setBR(0, 6, E);
case 0xb4: return setBR(0, 6, H);
case 0xb5: return setBR(0, 6, L);
case 0xb6: return setBR(0, 6, HL);
case 0xbf: return setBR(0, 7, A);
case 0xb8: return setBR(0, 7, B);
case 0xb9: return setBR(0, 7, C);
case 0xba: return setBR(0, 7, D);
case 0xbb: return setBR(0, 7, E);
case 0xbc: return setBR(0, 7, H);
case 0xbd: return setBR(0, 7, L);
case 0xbe: return setBR(0, 7, HL);
default:
System.err.println("Unimplemented opcode: 0xcb" +
Integer.toHexString(opcode));
dumpRegisters();
System.exit(1);
}
return 0;
}
/**
* LD nn,n. Put value nn into n.
*
* nn = B,C,D,E,H,L
* n = 8 bit immediate value
*
* @param reg (required) register to load to
*/
private int ld_NN_N(GBRegisters.Reg reg) {
int data = memory.readByte(pc);
pc++;
registers.setReg(reg, data);
return 8;
}
/**
* Put value r1 into r2.
*
* <p> Use with: r1,r2 = A,B,C,D,E,H,L,(HL)
*
* @param dest destination register
* @param src source register
*/
private int eightBitLdR1R2(GBRegisters.Reg dest, GBRegisters.Reg src) {
if (src == HL) {
int data = memory.readByte(registers.getReg(HL));
registers.setReg(dest, data);
return 8;
} else if ((dest == HL) || (dest == BC) || (dest == DE)) {
memory.writeByte(registers.getReg(dest), registers.getReg(src));
return 8;
} else {
registers.setReg(dest, registers.getReg(src));
return 4;
}
}
/**
* Special function for opcode 0x36
*
* LD (HL), n
*/
private int eightBitLoadFromMem() {
int data = memory.readByte(pc);
pc++;
memory.writeByte(registers.getReg(GBRegisters.Reg.HL), data);
return 12;
}
/**
* LD n,a
* put value A into n
* (nn) is two byte immediate value pointing to address
* to write data
*
* LSB is first
* Special function for opcode 0xea
*/
private int eightBitLoadToMem() {
int address = readWordFromMem(pc);
pc += 2;
memory.writeByte(address, registers.getReg(A));
return 16;
}
/**
* LD A,n
*
* Put value n into A. For opcodes 0x0a, 0x1a
*
*
* @param src value n
*/
private int eightBitLdAN(GBRegisters.Reg src) {
int data = memory.readByte(registers.getReg(src));
registers.setReg(A, data);
return 8;
}
/**
* LD A,n (where n is located in rom, or an address in rom)
*
* For opcodes: 0xfa, 0x3e
*
* @param isPointer If true, next two bytes are address in memory to load
* from. If false, eight bit immediate value is loaded.
*/
private int eightBitALoadMem(boolean isPointer) {
if (isPointer) {
int address = readWordFromMem(pc);
pc += 2;
registers.setReg(A, memory.readByte(address));
return 16;
} else {
int data = memory.readByte(pc);
pc++;
registers.setReg(A, data);
return 8;
}
}
private int eightBitLDfromAC() {
int data = memory.readByte(registers.getReg(C) + 0xff00);
registers.setReg(A, data);
return 8;
}
private int eightBitLDtoAC() {
int address = registers.getReg(C);
int data = registers.getReg(A);
memory.writeByte(address + 0xff00, data);
return 8;
}
/**
* halts the cpu until an interrupt occurs
* TODO
* @return 0
*/
private int halt() {
if (interruptState != DISABLED) {
executionHalted = true;
System.out.println("halting");
} else {
//interrupts not Enabled behavior skips next instruction
pc++;
}
return 4;
}
/** LDD A, (HL)
*
* Put value at address HL into A, decrement HL
*
*/
private int eightBitLDAHl() {
int address = registers.getReg(GBRegisters.Reg.HL);
registers.setReg(GBRegisters.Reg.A, memory.readByte(address));
registers.setReg(GBRegisters.Reg.HL, address - 1);
return 8;
}
/**
* LDD (HL), A
* Put A into memory address HL, Decrement HL
*
*/
private int eightBitStoreHL() {
int address = registers.getReg(HL);
int data = registers.getReg(A);
memory.writeByte(address, data);
registers.setReg(GBRegisters.Reg.HL, address - 1);
return 8;
}
/**
* Put value at address HL into A, increment HL
*
*/
private int eightBitLDIA() {
int address = registers.getReg(HL);
registers.setReg(A, memory.readByte(address));
registers.setReg(HL, address + 1);
return 8;
}
private int LDI_HL_A() {
int address = registers.getReg(HL);
int data = registers.getReg(A);
memory.writeByte(address, data);
registers.setReg(HL, address + 1);
return 8;
}
/**
* LDH (n), A and LDH A, (n)
*
* LDH (n), A - Put A into memory address $FF00 + n
* LDH A,(n) - Put memory address $FF00+n into A
*
* @param writeToMem (required) if true LDH (n),A. if false LDH A,(n)
*
*/
private int eightBitLdhA(boolean writeToMem) {
int offset = memory.readByte(pc);
pc++;
if (writeToMem) {
int data = registers.getReg(A);
memory.writeByte(0xff00 + offset, data);
} else {
int data = memory.readByte(0xff00 + offset);
registers.setReg(A, data);
}
return 12;
}
/**
* LD n, nn
*
* Put value nn into n
*
* nn - 16 Bit immediate value, n = BC, DE, HL
*
*/
private int ld_N_NN(GBRegisters.Reg reg) {
int data = readWordFromMem(pc);
pc += 2;
registers.setReg(reg, data);
return 12;
}
/**
* LD n, nn
* Put 2 byte immediate
* value nn into SP
*
*/
private int ld_SP_NN() {
sp = readWordFromMem(pc);
pc += 2;
return 12;
}
/**
* LD SP,HL
*
* Put HL into SP
*/
private int sixteenBitLdSpHl() {
sp = registers.getReg(GBRegisters.Reg.HL);
return 8;
}
/**
* LDHL SP,n
*
* Put SP+n effective address into HL
*
* <p>n = one byte signed immediate value
* Z - reset
* N - reset
* H - set or reset according to operation
* C - set or reset according to operation
*
*/
private int sixteenBitLdHlSp() {
byte offset = (byte)memory.readByte(pc);
pc++;
registers.setReg(HL, offset + sp);
registers.resetAll();
if ((sp & 0xf)+ (offset & 0xf) > 0xf) {
registers.setH();
}
if ((sp & 0xff) + (offset & 0xff) > 0xff) {
registers.setC();
}
return 12;
}
/**
* Put SP at address n (2 byte immediate address)
* stored little endian
*/
private int sixteenBitLdNnSp() {
int address = memory.readByte(pc);
pc++;
address = address | (memory.readByte(pc) << 8);
pc++;
memory.writeByte(address, sp & 0xff);
memory.writeByte(address + 1, ((sp & 0xff00) >> 8));
return 20;
}
/**
* Push Register Pair value to stack
*
* @param src (required) register pair to push to stack
*/
private int pushNN(GBRegisters.Reg src) {
int reg = registers.getReg(src);
writeWordToMem(reg);
return 16;
}
/**
* pop value off stack to a register pair
*
* @param dest (required) register to store data in
*/
private int popNN(GBRegisters.Reg dest) {
//todo OAM?
int data = readWordFromMem(sp);
sp += 2;
registers.setReg(dest, data);
return 12;
}
/**
* ADD A,n
*
* Add n to A
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - set if carry from bit 3
* C - set if carry from bit 7
*
* @param src (source to add from)
* @param addCarry true if adding carry
* @param readMem true if reading immediate value from memory
* (immediate value) if true, src ignored
*/
private int addAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) {
int cycles;
int regA = registers.getReg(A);
int toAdd;
if (readMem) {
toAdd = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
toAdd = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
toAdd = registers.getReg(src);
cycles = 4;
}
//if adding carry and carry is set add 1
int carryBit = (addCarry && isSet(registers.getReg(F), CARRY_F)) ? 1 : 0;
registers.setReg(A, (toAdd + regA + carryBit) & 0xff);
//flags
registers.resetAll();
if (registers.getReg(A) == 0) {
registers.setZ();
}
if ((regA & 0xf) + (toAdd & 0xf) + carryBit > 0xf) {
registers.setH();
}
if (toAdd + regA + carryBit > 0xff) {
registers.setC();
}
return cycles;
}
/**
* SUB n, SUBC A,n
* Subtract N from A
* Z- Set if result is zero
* N - Set
* H - set if no borrow from bit 4
* C - set if no borrow
*
*/
private int subAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) {
int cycles;
int regA = registers.getReg(A);
int toSub;
if (readMem) {
toSub = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
toSub = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
toSub = registers.getReg(src);
cycles = 4;
}
//if subtracting carry and carry is set
int carryBit = (addCarry && isSet(registers.getReg(F), CARRY_F)) ? 1 : 0;
//sub
registers.setReg(A, regA - toSub - carryBit);
//flags
registers.resetAll();
if (registers.getReg(A) == 0) {
registers.setZ();
}
registers.setN();
if ((regA & 0xf) < (toSub & 0xf) + carryBit) {
registers.setH();
}
if (regA < (toSub + carryBit)) {
registers.setC();
}
return cycles;
}
/**
* And N with A, result in A
*
* FLAGS:
* Z - Set if result is 0
* N - Reset
* H - Set
* C - Reset
*
* @param src (required) N to and
* @param readMem (required) true if reading immediate value from
* memory (if true, src is ignored)
*/
private int andN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.setReg(A, data & regA);
registers.resetAll();
if (((data & regA) & 0xff) == 0) {
registers.setZ();
}
registers.setH();
return cycles;
}
/**
* OR N with A, result in A
*
* FLAGS:
* Z - Set if result is 0
* N - Reset
* H - Reset
* C - Reset
*
* @param src (required) N to and
* @param readMem (required) true if reading immediate value from
* memory (if true, src is ignored)
*/
private int orN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.setReg(A, data | regA);
registers.resetAll();
if (((data | regA) & 0xff) == 0) {
registers.setZ();
}
return cycles;
}
/**
* XOR n
*
* Logical XOR n, with A, result in A
*
* FLAGS
* Z - set if result is 0
* N, H, C = Reset
* @param src (required) src register
* @param readMem (required) true if reading immediate value from
* memory (if true src ignored)
* @return clock cycles taken
*/
private int xorN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.setReg(A, data ^ regA);
registers.resetAll();
if (((data ^ regA) & 0xff) == 0) {
registers.setZ();
}
return cycles;
}
/**
* CP n
*
* Compare A with n. Basically A - n subtraction but
* results are thrown away
*
* FLAGS
* Z - set if result is 0 (if A == n)
* N - set
* H - Set if no borrow from bit 4
* C = set if no morrow (Set if A is less than n)
*
* @param src (required) src register
* @param readMem (required) true if reading immediate value from
* memory (if true src ignored)
* @return clock cycles taken
*/
private int cpN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.resetAll();
if (regA == data) {
registers.setZ();
}
registers.setN();
if ((regA & 0xf) < (data & 0xf)) {
registers.setH(); //no borrow from bit 4
}
if (regA < data) { //no borrow
registers.setC();
}
return cycles;
}
/**
* INC n
*
* Increment register n.
*
* FLAGS:
* Z - Set if result is 0
* N - Reset
* H - Set if carry from bit 3
* C - Not affected
* @param src (required) register to increment
*/
private int incN(GBRegisters.Reg src) {
int reg;
if (src == HL) {
reg = memory.readByte(registers.getReg(src));
memory.writeByte(registers.getReg(src), reg + 1);
} else {
reg = registers.getReg(src);
registers.setReg(src, reg + 1);
}
registers.resetZ();
if (((reg + 1) & 0xff) == 0) {
registers.setZ();
}
registers.resetN();
registers.resetH();
if ((reg & 0xf) == 0xf) {
registers.setH();
}
return (src == HL) ? 12 : 4;
}
/**
* DEC n
*
* Decrement register n.
*
* FLAGS:
* Z - Set if result is 0
* N - Set
* H - Set if no borrow from bit 4
* C - Not affected
* @param src (required) register to decrement
*/
private int decN(GBRegisters.Reg src) {
int reg;
if (src == HL) {
reg = memory.readByte(registers.getReg(src));
reg -= 1;
memory.writeByte(registers.getReg(src), reg & 0xff);
} else {
reg = registers.getReg(src);
reg -= 1;
registers.setReg(src, reg & 0xff);
}
registers.resetZ();
if (reg == 0) {
registers.setZ();
}
registers.setN();
registers.resetH();
if (((reg + 1) & 0xf0) != (reg & 0xf0)) {
registers.setH();
}
return (src == HL) ? 12 : 4;
}
/**
* ADD HL,n
*
* Add n to HL
*
* n = BC,DE,HL,SP
*
* Flags
* Z - Not affected
* N - Reset
* H - Set if carry from bit 11
* C - Set if carry from bit 15
*
* @param src source register to add
* @param addSP boolean (if true, adds stackpointer instead of register
* to HL, ignores src)
* @return clock cycles taken
*/
private int sixteenBitAdd(GBRegisters.Reg src, boolean addSP) {
int toAdd;
int regVal = registers.getReg(HL);
if (addSP) {
toAdd = sp;
} else {
toAdd = registers.getReg(src);
}
registers.setReg(HL, regVal + toAdd);
//flags
registers.resetN();
registers.resetH();
if ((regVal & 0xfff) + (toAdd & 0xfff) > 0xfff) {
registers.setH();
}
registers.resetC();
if ((regVal + toAdd) > 0xffff) {
registers.setC();
}
return 8;
}
/**
* ADD SP,n
* Add n to sp
*
* Flags:
* Z, N - Reset
* H, C - Set/reset according to operation????
*/
private int addSPN() {
byte offset = (byte)memory.readByte(pc);
pc++;
registers.resetAll();
if ((sp & 0xf) + (offset & 0xf) > 0xf) {
registers.setH();
}
if ((sp & 0xff) + (offset & 0xff) > 0xff) {
registers.setC();
}
sp += offset;
return 16;
}
/**
* INC nn
*
* Increment register nn
*
* Affects NO FLAGS
*
* @param reg register to increment (ignored if incSP is true)
* @param incSP boolean if true, ignore reg and increment sp
*/
private int incNN(GBRegisters.Reg reg, boolean incSP) {
if (incSP) {
sp++;
sp &= 0xffff;
} else {
int value = registers.getReg(reg);
registers.setReg(reg, (value + 1) & 0xffff);
}
return 8;
}
/**
* DEC nn
*
* Decrement register nn
*
* no flags affected
*
* @param reg register to increment (ignored if incSP is true)
* @param decSP boolean if true, ignore reg and increment sp
*/
private int decNN(GBRegisters.Reg reg, boolean decSP) {
if (decSP) {
sp
} else {
int value = registers.getReg(reg);
registers.setReg(reg, value - 1);
}
return 8;
}
/**
* Swap N
*
* swap upper and lower nibbles of n
*
* Flags Affected:
* Z - set if result is 0
* NHC - reset
*
* @param reg (required) register to swap
*/
private int swapN(GBRegisters.Reg reg) {
int data;
if (reg == HL) {
data = memory.readByte(registers.getReg(reg));
} else {
data = registers.getReg(reg);
}
int lowNib = data & 0xf;
int highNib = (data & 0xf0) >> 4;
data = highNib | (lowNib << 4);
if (reg == HL) {
memory.writeByte(registers.getReg(reg), data);
} else {
registers.setReg(reg, data);
}
registers.resetAll();
if (data == 0) {
registers.setZ();
}
return (reg == HL) ? 16 : 8;
}
private int decAdjust() {
int flags = registers.getReg(F);
int regA = registers.getReg(A);
if (!isSet(flags, SUBTRACT_F)) {
if (isSet(flags, HALFCARRY_F) || (regA & 0x0f) > 0x09) {
regA += 0x06;
}
if (isSet(flags, CARRY_F) || (regA > 0x9f)) {
regA += 0x60;
}
} else {
if (isSet(flags, HALFCARRY_F)) {
regA = (regA - 0x06) & 0xff;
}
if (isSet(flags, CARRY_F)) {
regA -= 0x60;
}
}
if ((regA & 0x100) == 0x100) {
registers.setC();
}
regA &= 0xff;
registers.resetH();
if (regA == 0) {
registers.setZ();
} else {
registers.resetZ();
}
registers.setReg(A, regA);
return 4;
}
/**
* Complement register A
*
* (toggles all bits)
*
* Flags: Sets N, H
*/
private int cplRegA() {
int reg = registers.getReg(A);
registers.setReg(A, reg ^ 0xff);
registers.setN();
registers.setH();
return 4;
}
/**
* Complement carry flag
*
* FLAGS:
* Z - not affected
* H, N - reset
* C - Complemented
*/
private int ccf() {
if (isSet(registers.getReg(F), CARRY_F)) {
registers.resetC();
} else {
registers.setC();
}
registers.resetN();
registers.resetH();
return 4;
}
/**
* Set carry flag
* Flags:
* Z - Not affected
* N,H - reset
* C - Set
*/
private int scf() {
registers.resetH();
registers.resetN();
registers.setC();
return 4;
}
/**
* Jump to address
* LSB first
*/
private int jump() {
pc = readWordFromMem(pc);
return 12;
}
/**
* Conditional jump
*
*/
private int jumpC(int opcode) {
int flags = registers.getReg(GBRegisters.Reg.F);
int address = memory.readByte(pc);
pc++;
address = address | (memory.readByte(pc) << 8);
pc++;
switch (opcode) {
case 0xca:
if ((flags & 0x80) == 0x80) {
pc = address;
}
break;
case 0xc2:
if ((flags & 0x80) == 0x0) {
pc = address;
}
break;
case 0xda:
if ((flags & 0x10) == 0x10) {
pc = address;
}
break;
case 0xd2:
if ((flags & 0x10) == 0x0) {
pc = address;
}
break;
default:
break;
}
return 12;
}
/**
* JP (HL)
*
* Jump to address contained in HL
*/
private int jumpHL() {
pc = registers.getReg(HL);
return 4;
}
/**
* JR n
*
* add n to current address and jump to it
*/
private int jumpN() {
byte offset = (byte)memory.readByte(pc);
pc++;
pc += offset;
return 8;
}
/**
* JR cc,n
*
* Conditional Jump with immediate offset
*
* @param opcode (required) opcode for jump condition
*/
private int jumpCN(int opcode) {
int flags = registers.getReg(GBRegisters.Reg.F);
byte offset = (byte)memory.readByte(pc);
pc++;
switch (opcode) {
case 0x28:
if (isSet(flags, ZERO_F)) {
pc += offset;
}
/* if ((flags & 0x80) == 0x80) {
pc += offset;
}*/
break;
case 0x20:
if (!isSet(flags, ZERO_F)) {
pc += offset;
}
/* if ((flags & 0x80) == 0x0) {
pc += offset;
}*/
break;
case 0x38:
if (isSet(flags, CARRY_F)) {
pc += offset;
}
/* if ((flags & 0x10) == 0x10) {
pc += offset;
}*/
break;
case 0x30:
if (!isSet(flags, CARRY_F)) {
pc += offset;
}
/* if ((flags & 0x10) == 0x0) {
pc += offset;
}*/
break;
default:
break;
}
return 8;
}
/**
* Call nn
*
* push address of next instruction onto stack and jump to address
* nn (nn is 16 bit immediate value)
*
*/
private int call() {
int address = readWordFromMem(pc);
pc += 2;
pushWordToStack(pc);
pc = address;
return 12;
}
/**
* CALL cc,nn
*
* Call address n if following condition is true
* Z flag set /reset
* C flag set/reset
* @param opcode opcode to check for condition
*/
private int callC(int opcode) {
int flags = registers.getReg(GBRegisters.Reg.F);
switch(opcode) {
case 0xc4:
if (!isSet(flags, ZERO_F)) {
return call();
}
break;
case 0xcc:
if (isSet(flags, ZERO_F)) {
return call();
}
break;
case 0xd4:
if (!isSet(flags, CARRY_F)) {
return call();
}
break;
case 0xd0:
if (isSet(flags, CARRY_F)) {
return call();
}
break;
default:
break;
}
return 12;
}
/**
* RET
*
* pop two bytes from stack and jump to that address
*/
private int ret() {
pc = readWordFromMem(sp);
sp += 2;
return 8;
}
/**
* RETI
*
* pop two bytes from stack and jump to that address
* enable interrupts
*/
private int retI() {
interruptState = DELAY_ON;
pc = readWordFromMem(sp);
sp += 2;
return 8;
}
/**
* Pushes a 16 bit word to the stack
* MSB pushed first
*/
private void pushWordToStack(int word) {
sp
memory.writeByte(sp, (word & 0xff00) >> 8);
sp
memory.writeByte(sp, word & 0xff);
}
/**
* RST n
*
* Push present address onto stack, jump to address 0x0000 +n
*
*/
private int restart(int offset) {
pushWordToStack(pc);
pc = offset;
return 32;
}
/**
* RET C
*
* Return if following condition is true
*
*/
private int retC(int opcode) {
int flags = registers.getReg(F);
switch(opcode) {
case 0xc0:
if (!isSet(flags, ZERO_F)) {
return ret();
}
break;
case 0xc8:
if (isSet(flags, ZERO_F)) {
return ret();
}
break;
case 0xd0:
if (!isSet(flags, CARRY_F)) {
return ret();
}
break;
case 0xd8:
if (isSet(flags, CARRY_F)) {
return ret();
}
break;
default:
break;
}
return 8;
}
/**
* RCLA
*
* Rotate A left, Old bit 7 to Carry flag
*
* Flags
* Z - set if result is 0
* H,N - Reset
* C - Contains old bit 7 data
*
*/
private int rlcA() {
int reg = registers.getReg(GBRegisters.Reg.A);
int msb = (reg & 0x80) >> 7;
// rotate left
reg = reg << 1;
// set lsb to previous msb
reg |= msb;
registers.resetAll();
if (msb == 0x1) {
registers.setC();
}
registers.setReg(GBRegisters.Reg.A, reg);
return 4;
}
/**
* RLA
* Rotate A left through Carry Flag
*
* Flags Affected:
* Z - Set if result is 0 (reset?)
* N,H - Reset
* C - contains old bit 7 data
*
*/
private int rlA() {
int reg = registers.getReg(GBRegisters.Reg.A);
int flags = registers.getReg(GBRegisters.Reg.F);
// rotate left
reg = reg << 1;
// set lsb to FLAG C
reg |= (flags & 0x10) >> 4;
registers.resetAll();
if ((reg & 0x100) == 0x100) {
registers.setC();
}
registers.setReg(GBRegisters.Reg.A, reg);
return 4;
}
/**
* RRCA
*
* Rotate A right, Old bit 0 to Carry flag
*
* Flags
* Z - set if result is 0
* H,N - Reset
* C - Contains old bit 0 data
*
*/
private int rrcA() {
int reg = registers.getReg(GBRegisters.Reg.A);
int lsb = reg & 0x1;
// rotate right
reg = reg >> 1;
// set msb to previous lsb
reg |= lsb << 7;
registers.resetAll();
if (lsb == 1) {
registers.setC();
}
registers.setReg(GBRegisters.Reg.A, reg);
return 4;
}
/**
* RLC n
*
* Rotate n left. Old bit 7 to carry flag
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - Reset
* C - Contains old bit 7 data
*
*/
private int rlcN(GBRegisters.Reg src) {
int data;
int cycles;
if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int msb = (data & 0x80) >> 7;
data = data << 1;
data |= msb;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (msb == 1) {
registers.setC();
}
if (src == GBRegisters.Reg.HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return cycles;
}
/**
* RL n
*
* Rotate n left through carry flag
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - Reset
* C - Contains old bit 7 data
*/
private int rlN(GBRegisters.Reg src) {
int data;
int cycles;
int flags = registers.getReg(F);
if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int msb = ((data & 0x80) >> 7) & 0x1;
int carryIn = isSet(flags, CARRY_F) ? 1 : 0;
data = (data << 1 | carryIn) & 0xff;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (msb != 0) {
registers.setC();
}
if (src == HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return cycles;
}
/**
* RrCn n
*
* Rotate n Right. Old bit 0 to carry flag
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - Reset
* C - Contains old bit 0 data
*
*/
private int rrcN(GBRegisters.Reg src) {
int data;
int cycles;
if (src == GBRegisters.Reg.HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int lsb = data & 0x1;
data = data >> 1;
data |= lsb << 7;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (lsb == 1) {
registers.setC();
}
if (src == GBRegisters.Reg.HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return cycles;
}
/**
* RR n
*
* Rotate n right through carry flag
*
* Flags:
* Z - Reset
* N - Reset
* H - Reset
* C - Contains old bit 0 data
*/
private int rrN(GBRegisters.Reg src, boolean setZeroFlag) {
int data;
int cycles;
int flags = registers.getReg(F);
if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int lsb = data & 0x1;
int carryIn = isSet(flags, CARRY_F) ? 1 : 0;
data = (data >> 1) | (carryIn << 7);
data &= 0xff;
registers.resetAll();
if (setZeroFlag && data == 0) {
registers.setZ();
}
if (lsb != 0) {
registers.setC();
}
if (src == HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return cycles;
}
/**
* Shift n left into Carry, lsb of n set to 0
*
* Flags
* Z - set if 0
* H, N - reset
* C - contains old bit 7 data
*/
private int slAN(GBRegisters.Reg reg) {
int cycles;
int data;
if (reg == GBRegisters.Reg.HL) {
data = memory.readByte(registers.getReg(reg));
cycles = 16;
} else {
data = registers.getReg(reg);
cycles = 8;
}
int msb = (data & 0x80) & 0xff;
data = (data << 1) & 0xff;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (msb != 0) {
registers.setC();
}
if (reg == GBRegisters.Reg.HL) {
memory.writeByte(registers.getReg(reg), data);
} else {
registers.setReg(reg, data);
}
return cycles;
}
/**
* SRA n/SRL n
*
* Shift n right into carry, sign extended if SRA, unsigned if SRL
*
* Z - set if result is zero
* N,H - reset
* C - contains old bit 0 data
* @param unsignedShift if true SRL, if false SRA
*/
private int srAL(GBRegisters.Reg reg, boolean unsignedShift) {
int cycles;
int data;
if (reg == HL) {
data = memory.readByte(registers.getReg(reg));
cycles = 16;
} else {
data = registers.getReg(reg);
cycles = 8;
}
int lsb = data & 0x1;
if (unsignedShift) {
data = data >> 1;
if (isSet(data, 7)) {
data = data & 0x3f;
}
} else {
int bit7 = data & 0x80;
data = data >> 1;
data |= bit7;
}
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (lsb == 1) {
registers.setC();
}
if (reg == GBRegisters.Reg.HL) {
memory.writeByte(registers.getReg(reg), data);
} else {
registers.setReg(reg, data);
}
return cycles;
}
/**
* Prints the contents of the registers to STDOUT
*
*
*/
public void dumpRegisters() {
System.out.println("A: 0x" + Integer.toHexString(registers.getReg(A)));
System.out.println("B: 0x" + Integer.toHexString(registers.getReg(B)));
System.out.println("C: 0x" + Integer.toHexString(registers.getReg(C)));
System.out.println("D: 0x" + Integer.toHexString(registers.getReg(D)));
System.out.println("E: 0x" + Integer.toHexString(registers.getReg(E)));
System.out.println("F: 0x" + Integer.toHexString(registers.getReg(F)));
System.out.println("H: 0x" + Integer.toHexString(registers.getReg(H)));
System.out.println("L: 0x" + Integer.toHexString(registers.getReg(L)));
System.out.println("PC: 0x" + Integer.toHexString(pc));
System.out.println("SP: 0x" + Integer.toHexString(sp));
}
/**
* Test bit b in register r
*
* Flags affected:
* Z - set if bit b of register r is 0
* N - reset
* H - set
* C - not affected
*
* @param bit bit number to check
* @param reg register to check
*
*/
private int bitBR(int bit, GBRegisters.Reg reg) {
int data;
int cycles;
if (reg == GBRegisters.Reg.HL) {
data = memory.readByte(registers.getReg(reg));
cycles = 16;
} else {
data = registers.getReg(reg);
cycles = 8;
}
registers.resetZ();
if (!isSet(data, bit)) {
registers.setZ();
}
registers.setH();
registers.resetN();
return cycles;
}
/**
* isSet
*
* Tests the num if the bitNum bit is set
*
* @param num number to test
* @param bitNum bitnumber to test
*/
private boolean isSet(int num, int bitNum) {
return (((num >> bitNum) & 0x1) == 1);
}
/**
* Set bit bitNum in reg to val
*
* @param val value to set
* @param bitNum bit to set
* @param reg register to set
*/
private int setBR(int val, int bitNum, GBRegisters.Reg reg) {
if (reg == GBRegisters.Reg.HL) {
int data = memory.readByte(registers.getReg(reg));
data = setBit(val, bitNum, data);
memory.writeByte(registers.getReg(reg), data);
return 16;
} else {
int data = registers.getReg(reg);
data = setBit(val, bitNum, data);
registers.setReg(reg, data);
return 8;
}
}
/**
* sets bit bitNum to val in num
*/
private int setBit(int val, int bitNum, int num) {
if (val == 1) {
return num | 1 << bitNum;
} else {
return num & ~(1 << bitNum);
}
}
/**
* updateDivideRegister
*
* updates the divide register
* ASSUMES CLOCKSPEED OF 4194304
*
* @param cycles (clock cycles passed this instruction)
*/
private void updateDivideRegister(int cycles) {
divideCounter += cycles;
if (divideCounter >= 0xff) {
divideCounter = 0;
memory.incrementDivider();
}
}
/**
* updateTimers
*
* updates the CPU timers in memory
* @param cycles number of cycles that have passed
*/
private void updateTimers(int cycles) {
//check the enable
if (!isSet(memory.readByte(0xff07), 2)) {
return;
}
timerCounter -= cycles;
//update the counter in memory
if (timerCounter <= 0) {
timerCounter = getCountFrequency();
if (memory.readByte(0xff05) == 0xff) {
memory.writeByte(0xff05, memory.readByte(0xff06));
requestInterrupt(0x2);
} else {
memory.writeByte(0xff05, memory.readByte(0xff05) + 1);
}
}
}
/**
* returns the counting frequency of the timer in memory
*
* checks the timer controller register 0xff07
* and returns the appropriate clock cycle update
*/
private int getCountFrequency() {
int freq = memory.readByte(0xff07) & 0x3;
switch (freq) {
case 0: return clockSpeed / 4096;
case 1: return clockSpeed / 262144;
case 2: return clockSpeed / 65526;
case 3: return clockSpeed / 16384;
default: return clockSpeed / 4096;
}
}
/**
* requests an interrupt to be serviced by the CPU
*
* id can be:
* 0 - V-Blank interrupt
* 1 - LCD Timer interrupt
* 2 - Timer interrupt
* 3 - (Serial) Not handled NOTE: TODO
* 4 - Joypad interrupt
*
* 0xff0f - IF Interrupt Flag
* 0xffff - IE Interrupt Enable
*
* @param id interrupt to request
*/
public void requestInterrupt(int id) {
if (executionHalted) System.out.println("interrupt requested");
int flags = memory.readByte(0xff0f);
flags = setBit(1, id, flags);
memory.writeByte(0xff0f, flags);
checkInterrupts();
}
/**
* Checks interrupts and services them if required
*/
private void checkInterrupts() {
if (interruptState != ENABLED) {
return; //IME flag not set
}
int interruptFlag = memory.readByte(0xff0f);
int interruptEnable = memory.readByte(0xffff);
//resumed with ANY interrupt
if (executionHalted && interruptFlag > 0) {
for (int i = 0; i < 5; ++i) {
if (isSet(interruptFlag, i)) {
System.out.println("resuming");
executionHalted = false;
handleInterrupt(i);
break;
}
}
} else if (interruptFlag > 0 && interruptEnable > 0) {
for (int i = 0; i < 5; ++i) {
if (isSet(interruptFlag, i) && isSet(interruptEnable, i)) {
handleInterrupt(i);
}
}
}
}
/**
* Handles the interrupt
*
* id can be:
* 0 - V-Blank interrupt
* 1 - LCD Timer interrupt
* 2 - Timer interrupt
* 4 - Joypad interrupt
*
* @param id interrupt to handle
*/
private void handleInterrupt(int id) {
//clear IME flag
interruptState = DISABLED;
if (executionHalted) {
System.out.println("resuming");
}
//reset the interrupt bit
int flags = memory.readByte(0xff0f);
flags = setBit(0, id, flags);
memory.writeByte(0xff0f, flags);
pushWordToStack(pc);
switch (id) {
case 0: pc = 0x40;
break;
case 1: pc = 0x48;
break;
case 2: pc = 0x50;
break;
case 3: System.err.println("Requested a Serial interrupt...");
break;
case 4: pc = 0x60;
break;
default: System.err.println("Invalid Interrupt Requested. Exiting");
System.exit(1);
}
}
/**
* DI
*
* disables interrupts
*/
private int disableInterrupts() {
interruptState = DELAY_OFF;
return 4;
}
/**
* EI
*
* enables interrupts
*
* TODO read one more opcode
*/
private int enableInterrupts() {
//System.out.println("enabled interrupts");
interruptState = DELAY_ON;
return 4;
}
/**
* waits until a button is pressed
* TODO
*
*/
private int stop() {
pc++;
return 4;
}
/**
* reads a 16 bit word from
* memory in little endian order
* (least significant byte first)
* located at pc
*
* @return 16bit word from memory
*/
private int readWordFromMem(int address) {
int data = memory.readByte(address);
data = (memory.readByte(address + 1) << 8) | data;
return data;
}
/**
* writes a 16 bit word to address in memory
* at sp, decrements stack pointer twice
*
*
* @param word to write to memory
*/
private void writeWordToMem(int word) {
sp
memory.writeByte(sp, (word & 0xff00) >> 8);
sp
memory.writeByte(sp, word & 0xff);
}
}
|
package com.opencms.file;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import com.opencms.core.*;
import com.opencms.template.*;
import org.w3c.dom.*;
import com.opencms.util.*;
public class CmsExport implements I_CmsConstants, Serializable {
/**
* The export-zipfile to store resources to
*/
private String m_exportFile;
/**
* The export-stream (zip) to store resources to
*/
private ZipOutputStream m_exportZipStream = null;
/**
* The export-path to read resources from the cms.
*/
private String m_exportPath;
/**
* The cms-object to do the operations.
*/
private CmsObject m_cms;
/**
* The xml manifest-file.
*/
private Document m_docXml;
/**
* The xml-elemtent to store fileinformations to.
*/
private Element m_filesElement;
/**
* The xml-elemtent to store userdatainformations to.
*/
private Element m_userdataElement;
/**
* Decides, if the system should be included to the export.
*/
private boolean m_excludeSystem;
/**
* Decides, if the unchanged resources should be included to the export.
*/
private boolean m_excludeUnchanged;
/**
* Decides, if the userdata and groupdata should be included to the export.
*/
private boolean m_exportUserdata;
/**
* Is the current project the online project?
*/
private boolean m_isOnlineProject;
/**
* Cache for previously added super folders
*/
private Vector m_superFolders;
/**
* This constructs a new CmsImport-object which imports the resources.
*
* @param importFile the file or folder to import from.
* @param importPath the path to the cms to import into.
* @param cms the cms-object to work with.
* @exception CmsException the CmsException is thrown if something goes wrong.
*/
public CmsExport(String exportFile, String[] exportPaths, CmsObject cms)
throws CmsException {
this(exportFile, exportPaths, cms, false, false);
}
/**
* This constructs a new CmsImport-object which imports the resources.
*
* @param importFile the file or folder to import from.
* @param importPath the path to the cms to import into.
* @param cms the cms-object to work with.
* @param Node moduleNode module informations in a Node for module-export.
* @exception CmsException the CmsException is thrown if something goes wrong.
*/
public CmsExport(String exportFile, String[] exportPaths, CmsObject cms, Node moduleNode)
throws CmsException {
this(exportFile, exportPaths, cms, false, false, moduleNode);
}
/**
* This constructs a new CmsImport-object which imports the resources.
*
* @param importFile the file or folder to import from.
* @param exportPaths the paths of folders and files to write into the exportFile
* @param cms the cms-object to work with.
* @param excludeSystem if true, the system folder is excluded, if false exactly the resources in
* exportPaths are included
* @param excludeUnchanged <code>true</code>, if unchanged files should be excluded.
* @exception CmsException the CmsException is thrown if something goes wrong.
*/
public CmsExport(String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged) throws CmsException {
this(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged, null);
}
/**
* This constructs a new CmsImport-object which imports the resources.
*
* @param importFile the file or folder to import from.
* @param exportPaths the paths of folders and files to write into the exportFile
* @param cms the cms-object to work with.
* @param excludeSystem if true, the system folder is excluded, if false exactly the resources in
* exportPaths are included
* @param excludeUnchanged <code>true</code>, if unchanged files should be excluded.
* @param Node moduleNode module informations in a Node for module-export.
* @exception CmsException the CmsException is thrown if something goes wrong.
*/
public CmsExport(String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged, Node moduleNode)
throws CmsException {
this(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged, moduleNode, false);
}
/**
* This constructs a new CmsImport-object which imports the resources.
*
* @param importFile the file or folder to import from.
* @param exportPaths the paths of folders and files to write into the exportFile
* @param cms the cms-object to work with.
* @param excludeSystem if true, the system folder is excluded, if false exactly the resources in
* exportPaths are included
* @param excludeUnchanged <code>true</code>, if unchanged files should be excluded.
* @param Node moduleNode module informations in a Node for module-export.
* @param exportUserdata if true, the userdata and groupdata are exported
* @exception CmsException the CmsException is thrown if something goes wrong.
*/
public CmsExport(String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged, Node moduleNode, boolean exportUserdata)
throws CmsException {
m_exportFile = exportFile;
m_cms = cms;
m_excludeSystem = excludeSystem;
m_excludeUnchanged = excludeUnchanged;
m_exportUserdata = exportUserdata;
m_isOnlineProject = cms.getRequestContext().currentProject().equals(cms.onlineProject());
Vector folderNames = new Vector();
Vector fileNames = new Vector();
for (int i=0; i<exportPaths.length; i++) {
if (exportPaths[i].endsWith(C_ROOT)) {
folderNames.addElement(exportPaths[i]);
} else {
fileNames.addElement(exportPaths[i]);
}
}
// open the import resource
getExportResource();
// create the xml-config file
getXmlConfigFile(moduleNode);
// remove the possible redundancies in the list of paths
checkRedundancies(folderNames, fileNames);
// export the folders
for (int i=0; i<folderNames.size(); i++) {
String path = (String) folderNames.elementAt(i);
// first add superfolders to the xml-config file
addSuperFolders(path);
exportResources(path);
}
// export the single files
addSingleFiles(fileNames);
// export userdata and groupdata if desired
if(m_exportUserdata){
exportGroups();
exportUsers();
}
// write the document to the zip-file
writeXmlConfigFile( );
try {
m_exportZipStream.close();
} catch(IOException exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Adds a element to the xml-document.
* @param element The element to add the subelement to.
* @param name The name of the new subelement.
* @param value The value of the element.
*/
private void addCdataElement(Element element, String name, String value) {
Element newElement = m_docXml.createElement(name);
element.appendChild(newElement);
CDATASection text = m_docXml.createCDATASection(value);
newElement.appendChild(text);
}
/**
* Adds a element to the xml-document.
* @param element The element to add the subelement to.
* @param name The name of the new subelement.
* @param value The value of the element.
*/
private void addElement(Element element, String name, String value) {
Element newElement = m_docXml.createElement(name);
element.appendChild(newElement);
Text text = m_docXml.createTextNode(value);
newElement.appendChild(text);
}
public void addSingleFiles(Vector fileNames) throws CmsException {
if (fileNames != null) {
for (int i = 0; i < fileNames.size(); i++) {
String fileName = (String) fileNames.elementAt(i);
try {
CmsFile file = m_cms.readFile(fileName);
if((file.getState() != C_STATE_DELETED) && (!file.getName().startsWith("~"))) {
addSuperFolders(fileName);
exportFile(file);
}
} catch(CmsException exc) {
if(exc.getType() != exc.C_RESOURCE_DELETED) {
throw exc;
}
}
}
}
}
public void addSuperFolders(String path) throws CmsException {
// Initialize the "previously added folder cache"
if(m_superFolders == null) {
m_superFolders = new Vector();
}
Vector superFolders = new Vector();
// Check, if the path is really a folder
if(path.lastIndexOf(C_ROOT) != (path.length()-1)) {
path = path.substring(0, path.lastIndexOf(C_ROOT)+1);
}
while (path.length() > C_ROOT.length()) {
superFolders.addElement(path);
path = path.substring(0, path.length() - 1);
path = path.substring(0, path.lastIndexOf(C_ROOT)+1);
}
for (int i = superFolders.size()-1; i >= 0; i
String addFolder = (String)superFolders.elementAt(i);
if(!m_superFolders.contains(addFolder)) {
// This super folder was NOT added previously. Add it now!
CmsFolder folder = m_cms.readFolder(addFolder);
writeXmlEntrys(folder);
// Remember that this folder was added
m_superFolders.addElement(addFolder);
}
}
}
/** Check whether some of the resources are redundant because a superfolder has also
* been selected or a file is included in a folder and change the parameter Vectors
*
* @param folderNames contains the full pathnames of all folders
* @param fileNames contains the full pathnames of all files
*/
private void checkRedundancies(Vector folderNames, Vector fileNames) {
int i, j;
if (folderNames == null) {
return;
}
Vector redundant = new Vector();
int n = folderNames.size();
if (n > 1) {
// otherwise no check needed, because there is only one resource
for (i = 0; i < n; i++) {
redundant.addElement(new Boolean(false));
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (((String) folderNames.elementAt(i)).length() < ((String) folderNames.elementAt(j)).length()) {
if (((String) folderNames.elementAt(j)).startsWith((String) folderNames.elementAt(i))) {
redundant.setElementAt(new Boolean(true), j);
}
} else {
if (((String) folderNames.elementAt(i)).startsWith((String) folderNames.elementAt(j))) {
redundant.setElementAt(new Boolean(true), i);
}
}
}
}
for (i = n - 1; i >= 0; i
if (((Boolean) redundant.elementAt(i)).booleanValue()) {
folderNames.removeElementAt(i);
}
}
}
// now remove the files who are included automatically in a folder
// otherwise there would be a zip exception
for (i = fileNames.size() - 1; i >= 0; i
for (j = 0; j < folderNames.size(); j++) {
if (((String) fileNames.elementAt(i)).startsWith((String) folderNames.elementAt(j))) {
fileNames.removeElementAt(i);
}
}
}
}
/**
* Exports one single file with all its data and content.
*
* @param file the file to be exported,
* @exception throws a CmsException if something goes wrong.
*/
private void exportFile(CmsFile file)
throws CmsException {
String source = getSourceFilename(file.getAbsolutePath());
System.out.print("Exporting " + source + " ...");
try {
// create the manifest-entrys
writeXmlEntrys((CmsResource) file);
// store content in zip-file
ZipEntry entry = new ZipEntry(source);
m_exportZipStream.putNextEntry(entry);
m_exportZipStream.write(file.getContents());
m_exportZipStream.closeEntry();
} catch(Exception exc) {
System.out.println("Error");
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
System.out.println("OK");
}
/**
* Exports all needed sub-resources to the zip-file.
*
* @param path to complete path to the resource to export
* @exception throws CmsException if something goes wrong.
*/
private void exportResources(String path)
throws CmsException {
// get all subFolders
Vector subFolders = m_cms.getSubFolders(path);
// get all files in folder
Vector subFiles = m_cms.getFilesInFolder(path);
// walk through all files and export them
for(int i = 0; i < subFiles.size(); i++) {
CmsResource file = (CmsResource) subFiles.elementAt(i);
int state = file.getState();
if(m_isOnlineProject || (!m_excludeUnchanged) || state == C_STATE_NEW || state == C_STATE_CHANGED) {
if((state != C_STATE_DELETED) && (!file.getName().startsWith("~"))) {
exportFile(m_cms.readFile(file.getAbsolutePath()));
}
}
}
// walk through all subfolders and export them
for(int i = 0; i < subFolders.size(); i++) {
CmsResource folder = (CmsResource) subFolders.elementAt(i);
if(folder.getState() != C_STATE_DELETED){
// check if this is a system-folder and if it should be included.
if(folder.getAbsolutePath().startsWith("/system/") ||
folder.getAbsolutePath().startsWith("/pics/system/") ||
folder.getAbsolutePath().startsWith("/moduledemos/")) {
if(!m_excludeSystem) {
// export this folder
writeXmlEntrys(folder);
// export all resources in this folder
exportResources(folder.getAbsolutePath());
}
} else {
// export this folder
writeXmlEntrys(folder);
// export all resources in this folder
exportResources(folder.getAbsolutePath());
}
}
}
}
/**
* Gets the import resource and stores it in object-member.
*/
private void getExportResource()
throws CmsException {
try {
// add zip-extension, if needed
if( !m_exportFile.toLowerCase().endsWith(".zip") ) {
m_exportFile += ".zip";
}
// create the export-zipstream
m_exportZipStream = new ZipOutputStream(new FileOutputStream(m_exportFile));
} catch(Exception exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Substrings the source-filename, so it is shrinked to the needed part for
* import/export.
* @param absoluteName The absolute path of the resource.
* @return The shrinked path.
*/
private String getSourceFilename(String absoluteName) {
// String path = absoluteName.substring(m_exportPath.length());
String path = absoluteName; // keep absolute name to distinguish resources
if (path.startsWith("/")) {
path = path.substring(1);
}
if(path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path;
}
/**
* Creates the xml-file and appends the initial tags to it.
* @param Node moduleNode a node with module informations.
*/
private void getXmlConfigFile(Node moduleNode)
throws CmsException {
try {
// creates the document
m_docXml = A_CmsXmlContent.getXmlParser().createEmptyDocument(C_EXPORT_TAG_EXPORT);
// abbends the initital tags
Node exportNode = m_docXml.getFirstChild();
// add the info element. it contains all infos for this export
Element info = m_docXml.createElement(C_EXPORT_TAG_INFO);
m_docXml.getDocumentElement().appendChild(info);
addElement(info, C_EXPORT_TAG_CREATOR, m_cms.getRequestContext().currentUser().getName());
addElement(info, C_EXPORT_TAG_OC_VERSION, m_cms.version());
addElement(info, C_EXPORT_TAG_DATE, Utils.getNiceDate(new Date().getTime()));
addElement(info, C_EXPORT_TAG_PROJECT, m_cms.getRequestContext().currentProject().getName());
addElement(info, C_EXPORT_TAG_VERSION, C_EXPORT_VERSION);
if(moduleNode != null) {
// this is a module export - import module informations here
exportNode.appendChild(A_CmsXmlContent.getXmlParser().importNode(m_docXml, moduleNode));
// now remove the unused file informations
NodeList files = ((Element)exportNode).getElementsByTagName("files");
if(files.getLength() == 1) {
files.item(0).getParentNode().removeChild(files.item(0));
}
}
m_filesElement = m_docXml.createElement(C_EXPORT_TAG_FILES);
m_docXml.getDocumentElement().appendChild(m_filesElement);
// add userdata
if (m_exportUserdata){
m_userdataElement = m_docXml.createElement(C_EXPORT_TAG_USERGROUPDATA);
m_docXml.getDocumentElement().appendChild(m_userdataElement);
}
} catch(Exception exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Writes the xml-config file (manifest) to the zip-file.
*/
private void writeXmlConfigFile()
throws CmsException {
try {
ZipEntry entry = new ZipEntry(C_EXPORT_XMLFILENAME);
m_exportZipStream.putNextEntry(entry);
A_CmsXmlContent.getXmlParser().getXmlText(m_docXml, m_exportZipStream);
m_exportZipStream.closeEntry();
} catch(Exception exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Writes the data for a resources (like acces-rights) to the manifest-xml-file.
* @param resource The resource to get the data from.
* @exception throws a CmsException if something goes wrong.
*/
private void writeXmlEntrys(CmsResource resource)
throws CmsException {
String source, type, user, group, access, launcherStartClass;
// get all needed informations from the resource
source = getSourceFilename(resource.getAbsolutePath());
type = m_cms.getResourceType(resource.getType()).getResourceTypeName();
user = m_cms.readOwner(resource).getName();
group = m_cms.readGroup(resource).getName();
access = resource.getAccessFlags() + "";
launcherStartClass = resource.getLauncherClassname();
// write these informations to the xml-manifest
Element file = m_docXml.createElement(C_EXPORT_TAG_FILE);
m_filesElement.appendChild(file);
// only write source if resource is a file
if(resource.isFile()) {
addElement(file, C_EXPORT_TAG_SOURCE, source);
}
addElement(file, C_EXPORT_TAG_DESTINATION, source);
addElement(file, C_EXPORT_TAG_TYPE, type);
addElement(file, C_EXPORT_TAG_USER, user);
addElement(file, C_EXPORT_TAG_GROUP, group);
addElement(file, C_EXPORT_TAG_ACCESS, access);
if(launcherStartClass != null && !"".equals(launcherStartClass) && !C_UNKNOWN_LAUNCHER.equals(launcherStartClass)) {
addElement(file, C_EXPORT_TAG_LAUNCHER_START_CLASS, launcherStartClass);
}
// append the node for properties
Element properties = m_docXml.createElement(C_EXPORT_TAG_PROPERTIES);
file.appendChild(properties);
// read the properties
Hashtable fileProperties = m_cms.readAllProperties(resource.getAbsolutePath());
Enumeration keys = fileProperties.keys();
// create xml-elements for the properties
while(keys.hasMoreElements()) {
// append the node for a property
Element property = m_docXml.createElement(C_EXPORT_TAG_PROPERTY);
properties.appendChild(property);
String key = (String) keys.nextElement();
String value = (String) fileProperties.get(key);
String propertyType = m_cms.readPropertydefinition(key, type).getType() + "";
addElement(property, C_EXPORT_TAG_NAME, key);
addElement(property, C_EXPORT_TAG_TYPE, propertyType);
addCdataElement(property, C_EXPORT_TAG_VALUE, value);
}
}
/**
* Exports groups with all data.
*
* @exception throws a CmsException if something goes wrong.
*/
private void exportGroups()
throws CmsException {
Vector allGroups = m_cms.getGroups();
for (int i = 0; i < allGroups.size(); i++){
exportGroup((CmsGroup)allGroups.elementAt(i));
}
}
/**
* Exports users with all data.
*
* @exception throws a CmsException if something goes wrong.
*/
private void exportUsers()
throws CmsException {
Vector allUsers = m_cms.getUsers();
for (int i = 0; i < allUsers.size(); i++){
exportUser((CmsUser)allUsers.elementAt(i));
}
}
/**
* Exports one single group with all its data.
*
* @param group the group to be exported,
* @exception throws a CmsException if something goes wrong.
*/
private void exportGroup(CmsGroup group)
throws CmsException {
System.out.print("Exporting group "+group.getName()+" ...");
try {
// create the manifest entries
writeXmlGroupEntrys(group);
} catch(Exception e) {
System.out.println("Error");
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, e);
}
System.out.println("OK");
}
/**
* Exports one single user with all its data.
*
* @param user the user to be exported,
* @exception throws a CmsException if something goes wrong.
*/
private void exportUser(CmsUser user)
throws CmsException {
System.out.print("Exporting user "+user.getName()+" ...");
try {
// create the manifest entries
writeXmlUserEntrys(user);
} catch(Exception e) {
System.out.println("Error");
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, e);
}
System.out.println("OK");
}
/**
* Writes the data for a group to the manifest-xml-file.
* @param group The group to get the data from.
* @exception throws a CmsException if something goes wrong.
*/
private void writeXmlGroupEntrys(CmsGroup group)
throws CmsException {
String name, description, flags, parentgroup;
// get all needed information from the group
name = group.getName();
description = group.getDescription();
flags = Integer.toString(group.getFlags());
int parentId = group.getParentId();
if (parentId != C_UNKNOWN_ID) {
parentgroup = m_cms.getParent(name).getName();
} else {
parentgroup = "";
}
// write these informations to the xml-manifest
Element groupdata = m_docXml.createElement(C_EXPORT_TAG_GROUPDATA);
m_userdataElement.appendChild(groupdata);
addElement(groupdata, C_EXPORT_TAG_NAME, name);
addCdataElement(groupdata, C_EXPORT_TAG_DESCRIPTION, description);
addElement(groupdata, C_EXPORT_TAG_FLAGS, flags);
addElement(groupdata, C_EXPORT_TAG_PARENTGROUP, parentgroup);
}
/**
* Writes the data for a user to the manifest-xml-file.
* @param group The group to get the data from.
* @exception throws a CmsException if something goes wrong.
*/
private void writeXmlUserEntrys(CmsUser user)
throws CmsException {
String name, password, recoveryPassword, description, firstname;
String lastname, email, flags, defaultGroup, address, section, type;
String datfileName = new String();
String infostr = new String();
Hashtable info = new Hashtable();
Vector userGroups = new Vector();
sun.misc.BASE64Encoder enc;
ObjectOutputStream oout;
// get all needed information from the group
name = user.getName();
password = user.getPassword();
recoveryPassword = user.getRecoveryPassword();
description = user.getDescription();
firstname = user.getFirstname();
lastname = user.getLastname();
email = user.getEmail();
flags = Integer.toString(user.getFlags());
info = user.getAdditionalInfo();
defaultGroup = user.getDefaultGroup().getName();
address = user.getAddress();
section = user.getSection();
type = Integer.toString(user.getType());
userGroups = m_cms.getDirectGroupsOfUser(user.getName());
// write these informations to the xml-manifest
Element userdata = m_docXml.createElement(C_EXPORT_TAG_USERDATA);
m_userdataElement.appendChild(userdata);
addElement(userdata, C_EXPORT_TAG_NAME, name);
//Encode the info value, using any base 64 decoder
enc = new sun.misc.BASE64Encoder();
String passwd = new String(enc.encodeBuffer(password.getBytes()));
addCdataElement(userdata, C_EXPORT_TAG_PASSWORD, passwd);
enc = new sun.misc.BASE64Encoder();
String recPasswd = new String(enc.encodeBuffer(recoveryPassword.getBytes()));
addCdataElement(userdata, C_EXPORT_TAG_RECOVERYPASSWORD, recPasswd);
addCdataElement(userdata, C_EXPORT_TAG_DESCRIPTION, description);
addElement(userdata, C_EXPORT_TAG_FIRSTNAME, firstname);
addElement(userdata, C_EXPORT_TAG_LASTNAME, lastname);
addElement(userdata, C_EXPORT_TAG_EMAIL, email);
addElement(userdata, C_EXPORT_TAG_FLAGS, flags);
addElement(userdata, C_EXPORT_TAG_DEFAULTGROUP, defaultGroup);
addCdataElement(userdata, C_EXPORT_TAG_ADDRESS, address);
addElement(userdata, C_EXPORT_TAG_SECTION, section);
addElement(userdata, C_EXPORT_TAG_TYPE, type);
// serialize the hashtable and write the info into a file
try{
datfileName = "/~"+C_EXPORT_TAG_USERINFO+"/"+name+".dat";
ByteArrayOutputStream bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(info);
oout.close();
byte[] serializedInfo = bout.toByteArray();
// store the userinfo in zip-file
ZipEntry entry = new ZipEntry(datfileName);
m_exportZipStream.putNextEntry(entry);
m_exportZipStream.write(serializedInfo);
m_exportZipStream.closeEntry();
} catch (IOException ioex){
System.out.println("IOException: "+ioex.getMessage());
}
// create tag for userinfo
addCdataElement(userdata, C_EXPORT_TAG_USERINFO, datfileName);
// append the node for groups of user
Element usergroup = m_docXml.createElement(C_EXPORT_TAG_USERGROUPS);
userdata.appendChild(usergroup);
for (int i = 0; i < userGroups.size(); i++){
String groupName = ((CmsGroup)userGroups.elementAt(i)).getName();
Element group = m_docXml.createElement(C_EXPORT_TAG_GROUPNAME);
usergroup.appendChild(group);
addElement(group, C_EXPORT_TAG_NAME, groupName);
}
}
}
|
package com.opencms.setup;
import java.util.*;
import java.io.*;
import com.opencms.file.*;
import com.opencms.core.*;
import java.lang.reflect.*;
public class CmsShell implements I_CmsConstants {
/**
* The resource broker to get access to the cms.
*/
private A_CmsObject m_cms;
/**
* The main entry point for the commandline interface to the opencms.
*
* @param args Array of parameters passed to the application
* via the command line.
*/
public static void main (String[] args) {
CmsShell shell = new CmsShell();
try {
if( (args.length == 0) || (args.length > 3) ) {
// print out usage-information.
shell.usage();
} else {
// initializes the db and connects to it
shell.init(args);
// print the version-string
shell.version();
shell.copyright();
// wait for user-input
shell.commands();
}
} catch(Exception exc) {
exc.printStackTrace();
}
}
/**
* Inits the database.
*
* @param args A Array of args to get connected.
*/
private void init(String[] args)
throws Exception {
m_cms = new CmsObject();
m_cms.init(((A_CmsInit) Class.forName(args[0]).newInstance() ).init(args[1], args[2]));
m_cms.init(null, null, C_USER_GUEST, C_GROUP_GUEST, C_PROJECT_ONLINE);
}
/**
* The commandlineinterface.
*/
private void commands() {
try{
Reader reader = new FileReader(java.io.FileDescriptor.in);
StreamTokenizer tokenizer = new StreamTokenizer(reader);
tokenizer.eolIsSignificant(true);
Vector input;
System.out.println("Type help to get a list of commands.");
for(;;) { // ever
System.out.print("> ");
input = new Vector();
while(tokenizer.nextToken() != tokenizer.TT_EOL) {
if(tokenizer.ttype == tokenizer.TT_NUMBER) {
input.addElement(tokenizer.nval + "");
} else {
input.addElement(tokenizer.sval);
}
}
// call the command
call(input);
}
}catch(Exception exc){
printException(exc);
}
}
/**
* Gives the usage-information to the user.
*/
private void usage() {
System.out.println("Usage: java com.opencms.setup.CmsShell initializer-classname sqldriver-classname connectstring");
}
/**
* Calls a command
*
* @param command The command to be called.
*/
private void call(Vector command) {
if((command == null) || (command.size() == 0)) {
return;
}
String splittet[] = new String[command.size()];
String toCall;
command.copyInto(splittet);
toCall = splittet[0];
Class paramClasses[] = new Class[splittet.length - 1];
String params[] = new String[splittet.length - 1];
for(int z = 0; z < splittet.length - 1; z++) {
params[z] = splittet[z+1];
paramClasses[z] = String.class;
}
try {
getClass().getMethod(toCall, paramClasses).invoke(this,params);
} catch(Exception exc) {
printException(exc);
}
}
/**
* Reads a given file from the local harddisk and uploads
* it to the OpenCms system.
* Used in the OpenCms console only.
*
* @author Alexander Lucas
* @param filename Local file to be uploaded.
* @return Byte array containing the file content.
* @throws CmsException
*/
private byte[] importFile(String filename) throws CmsException {
File file = null;
long len = 0;
FileInputStream importInput = null;
byte[] result;
// First try to load the file
try {
file = new File(filename);
} catch(Exception e) {
file = null;
}
if(file == null) {
throw new CmsException("Could not load local file " + filename, CmsException.C_NOT_FOUND);
}
// File was loaded successfully.
// Now try to read the content.
try {
len = file.length();
result = new byte[(int)len];
importInput = new FileInputStream(file);
importInput.read(result);
importInput.close();
} catch(Exception e) {
throw new CmsException(e.toString() , CmsException.C_UNKNOWN_EXCEPTION);
}
return result;
}
/**
* Prints a exception with the stacktrace.
*
* @param exc The exception to print.
*/
private void printException(Exception exc) {
exc.printStackTrace();
}
// All methods, that may be called by the user:
/**
* Exits the commandline-interface
*/
public void exit() {
System.exit(0);
}
/**
* Prints all possible commands.
*/
public void help() {
Method meth[] = getClass().getMethods();
for(int z=0 ; z < meth.length ; z++) {
if( ( meth[z].getDeclaringClass() == getClass() ) &&
( meth[z].getModifiers() == Modifier.PUBLIC ) ) {
System.out.print(meth[z].getName() + "(");
System.out.println(meth[z].getParameterTypes().length + ")");
}
}
}
/**
* Echos the input to output.
*
* @param echo The echo to be written to output.
*/
public void echo(String echo) {
System.out.println(echo);
}
/**
* Returns the current user.
*/
public void whoami() {
System.out.println(m_cms.getRequestContext().currentUser());
}
/**
* Logs a user into the system.
*
* @param username The name of the user to log in.
* @param password The password.
*/
public void login(String username, String password) {
try {
m_cms.loginUser(username, password);
whoami();
} catch( Exception exc ) {
printException(exc);
System.out.println("Login failed!");
}
}
/**
* Returns all users of the cms.
*/
public void getUsers() {
try {
Vector users = m_cms.getUsers();
for( int i = 0; i < users.size(); i++ ) {
System.out.println( (A_CmsUser)users.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns all users of the cms.
*/
public void getGroups() {
try {
Vector groups = m_cms.getGroups();
for( int i = 0; i < groups.size(); i++ ) {
System.out.println( (A_CmsGroup)groups.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Determines, if the user is Admin.
*/
public void isAdmin() {
try {
System.out.println( m_cms.getRequestContext().isAdmin() );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Determines, if the user is Projectleader.
*/
public void isProjectManager() {
try {
System.out.println( m_cms.getRequestContext().isProjectManager() );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns all groups of a user.
*
* @param username The name of the user.
*/
public void getGroupsOfUser(String username) {
try {
Vector groups = m_cms.getGroupsOfUser(username);
for( int i = 0; i < groups.size(); i++ ) {
System.out.println( (A_CmsGroup)groups.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a user to the cms.
*
* @param name The new name for the user.
* @param password The new password for the user.
* @param group The default groupname for the user.
* @param description The description for the user.
*/
public void addUser( String name, String password,
String group, String description) {
try {
System.out.println(m_cms.addUser( name, password, group,
description, new Hashtable(),
C_FLAG_ENABLED) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a user to the cms.
*
* @param name The new name for the user.
* @param password The new password for the user.
* @param group The default groupname for the user.
* @param description The description for the user.
* @param flags The flags for the user.
*/
public void addUser( String name, String password,
String group, String description, String flags) {
try {
System.out.println(m_cms.addUser( name, password, group,
description, new Hashtable(),
Integer.parseInt(flags)) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a user to the cms.
*
* @param name The new name for the user.
* @param password The new password for the user.
* @param group The default groupname for the user.
* @param description The description for the user.
* @param flags The flags for the user.
*/
public void addUser( String name, String password,
String group, String description,
String firstname, String lastname, String email) {
try {
A_CmsUser user = m_cms.addUser( name, password, group,
description, new Hashtable(), C_FLAG_ENABLED);
user.setEmail(email);
user.setFirstname(firstname);
user.setLastname(lastname);
user.setAdditionalInfo("test", "AS");
m_cms.writeUser(user);
System.out.println(user);
System.out.println(user.getFirstname());
System.out.println(user.getLastname());
System.out.println(user.getEmail());
System.out.println(user.getAdditionalInfo("test"));
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Deletes a user from the Cms.
*
* @param name The name of the user to be deleted.
*/
public void deleteUser( String name ) {
try {
m_cms.deleteUser( name );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Writes a user to the Cms.
*
* @param name The name of the user to be written.
* @param flags The flags of the user to be written.
*/
public void writeUser( String name, String flags ) {
try {
// get the user, which has to be written
A_CmsUser user = m_cms.readUser(name);
if(Integer.parseInt(flags) == C_FLAG_DISABLED) {
user.setDisabled();
} else {
user.setEnabled();
}
// write it back
m_cms.writeUser(user);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a Group to the cms.
*
* @param name The name of the new group.
* @param description The description for the new group.
* @int flags The flags for the new group.
* @param name The name of the parent group (or null).
*/
public void addGroup(String name, String description, String flags, String parent) {
try {
m_cms.addGroup( name, description, Integer.parseInt(flags), parent );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a Group to the cms.
*
* @param name The name of the new group.
* @param description The description for the new group.
*/
public void addGroup(String name, String description) {
try {
m_cms.addGroup( name, description, C_FLAG_ENABLED, null );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a group in the Cms.
*
* @param groupname The name of the group to be returned.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void readGroup(String groupname) {
try {
System.out.println( m_cms.readGroup( groupname ) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns all groups of a user.
*
* @param groupname The name of the group.
*/
public void getUsersOfGroup(String groupname) {
try {
Vector users = m_cms.getUsersOfGroup(groupname);
for( int i = 0; i < users.size(); i++ ) {
System.out.println( (A_CmsUser)users.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Checks if a user is member of a group.<P/>
*
* @param nameuser The name of the user to check.
* @param groupname The name of the group to check.
*/
public void userInGroup(String username, String groupname)
{
try {
System.out.println( m_cms.userInGroup( username, groupname ) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Writes a group to the Cms.
*
* @param name The name of the group to be written.
* @param flags The flags of the user to be written.
*/
public void writeGroup( String name, String flags ) {
try {
// get the group, which has to be written
A_CmsGroup group = m_cms.readGroup(name);
if(Integer.parseInt(flags) == C_FLAG_DISABLED) {
group.setDisabled();
} else {
group.setEnabled();
}
// write it back
m_cms.writeGroup(group);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Delete a group from the Cms.<BR/>
*
* @param delgroup The name of the group that is to be deleted.
*/
public void deleteGroup(String delgroup) {
try {
m_cms.deleteGroup( delgroup );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a user to a group.
*
* @param username The name of the user that is to be added to the group.
* @param groupname The name of the group.
*/
public void addUserToGroup(String username, String groupname) {
try {
m_cms.addUserToGroup( username, groupname );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Removes a user from a group.
*
* @param username The name of the user that is to be removed from the group.
* @param groupname The name of the group.
*/
public void removeUserFromGroup(String username, String groupname) {
try {
m_cms.removeUserFromGroup( username, groupname );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns all child groups of a group<P/>
*
* @param groupname The name of the group.
*/
public void getChild(String groupname) {
try {
Vector groups = m_cms.getChild(groupname);
for( int i = 0; i < groups.size(); i++ ) {
System.out.println( (A_CmsGroup)groups.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Sets the password for a user.
*
* @param username The name of the user.
* @param newPassword The new password.
*/
public void setPassword(String username, String newPassword) {
try {
m_cms.setPassword( username, newPassword );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a new CmsMountPoint.
* A new mountpoint for a mysql filesystem is added.
*
* @param mountpoint The mount point in the Cms filesystem.
* @param driver The driver for the db-system.
* @param connect The connectstring to access the db-system.
* @param name A name to describe the mountpoint.
*/
public void addMountPoint(String mountpoint, String driver,
String connect, String name) {
try {
m_cms.addMountPoint( mountpoint, driver, connect, name );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a new CmsMountPoint.
* A new mountpoint for a disc filesystem is added.
*
* @param mountpoint The mount point in the Cms filesystem.
* @param mountpath The physical location this mount point directs to.
* @param name The name of this mountpoint.
* @param user The default user for this mountpoint.
* @param group The default group for this mountpoint.
* @param type The default resourcetype for this mountpoint.
* @param accessFLags The access-flags for this mountpoint.
*/
public void addMountPoint(String mountpoint, String mountpath,
String name, String user, String group,
String type, String accessFlags) {
try {
m_cms.addMountPoint( mountpoint, mountpath, name, user, group, type,
Integer.parseInt(accessFlags) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Gets a CmsMountPoint.
* A mountpoint will be returned.
*
* @param mountpoint The mount point in the Cms filesystem.
*
* @return the mountpoint - or null if it doesen't exists.
*/
public void readMountPoint(String mountpoint ) {
try {
System.out.println( m_cms.readMountPoint( mountpoint ) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Gets all CmsMountPoints.
* All mountpoints will be returned.
*
* @return the mountpoints - or null if they doesen't exists.
*/
public void getAllMountPoints() {
try {
Hashtable mountPoints = m_cms.getAllMountPoints();
Enumeration keys = mountPoints.keys();
while(keys.hasMoreElements()) {
System.out.println(mountPoints.get(keys.nextElement()));
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Deletes a CmsMountPoint.
* A mountpoint will be deleted.
*
* @param mountpoint The mount point in the Cms filesystem.
*/
public void deleteMountPoint(String mountpoint ) {
try {
m_cms.deleteMountPoint(mountpoint);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Creates a project.
*
* @param name The name of the project to read.
* @param description The description for the new project.
* @param groupname the name of the group to be set.
*/
public void createProject(String name, String description, String groupname,
String managergroupname) {
try {
m_cms.createProject(name, description, groupname, managergroupname);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads a project from the Cms.
*
* @param name The name of the project to read.
*/
public void readProject(String name) {
try {
System.out.println( m_cms.readProject(name) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads a the online-project from the Cms.
*/
public void onlineProject() {
try {
System.out.println( m_cms.onlineProject() );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Tests if the user can access the project.
*
* @param projectname the name of the project.
*/
public void accessProject(String projectname) {
try {
System.out.println( m_cms.accessProject(projectname) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a user object.<P/>
*
* @param username The name of the user that is to be read.
*/
public void readUser(String username) {
try {
System.out.println( m_cms.readUser(username) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns all projects, which the user may access.
*
* @return a Vector of projects.
*/
public void getAllAccessibleProjects() {
try {
Vector projects = m_cms.getAllAccessibleProjects();
for( int i = 0; i < projects.size(); i++ ) {
System.out.println( (A_CmsProject)projects.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads a folder from the Cms.<BR/>
*
* @param folder The complete path to the folder that will be read.
*/
public void readFolder(String folder) {
try {
System.out.println( m_cms.readFolder(folder, "") );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Creates a new folder.
*
* @param folder The complete path to the folder in which the new folder
* will be created.
* @param newFolderName The name of the new folder (No pathinformation allowed).
*/
public void createFolder(String folder, String newFolderName) {
try {
System.out.println( m_cms.createFolder(folder, newFolderName) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns all I_CmsResourceTypes.
*/
public void getAllResourceTypes() {
try {
Hashtable resourceTypes = m_cms.getAllResourceTypes();
Enumeration keys = resourceTypes.keys();
while(keys.hasMoreElements()) {
System.out.println(resourceTypes.get(keys.nextElement()));
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a A_CmsResourceTypes.
*
* @param resourceType the name of the resource to get.
*/
public void getResourceType(String resourceType) {
try {
System.out.println( m_cms.getResourceType(resourceType) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Adds a CmsResourceTypes.
*
* @param resourceType the name of the resource to get.
* @param launcherType the launcherType-id
* @param launcherClass the name of the launcher-class normaly ""
*/
public void addResourceType(String resourceType, String launcherType,
String launcherClass) {
try {
System.out.println( m_cms.addResourceType(resourceType,
Integer.parseInt(launcherType),
launcherClass) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads all metadefinitions for the given resource type.
*
* @param resourcetype The name of the resource type to read the
* metadefinitions for.
*/
public void readAllMetadefinitions(String resourcetype) {
try {
Vector metadefs = m_cms.readAllMetadefinitions(resourcetype);
for( int i = 0; i < metadefs.size(); i++ ) {
System.out.println( (A_CmsMetadefinition)metadefs.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Creates the metadefinition for the resource type.<BR/>
*
* @param name The name of the metadefinition to overwrite.
* @param resourcetype The name of the resource-type for the metadefinition.
* @param type The type of the metadefinition (normal|mandatory|optional)
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void createMetadefinition(String name, String resourcetype, String type)
throws CmsException {
try {
System.out.println( m_cms.createMetadefinition(name, resourcetype,
Integer.parseInt(type)) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads all metadefinitions for the given resource type.
*
* @param resourcetype The name of the resource type to read the
* metadefinitions for.
* @param type The type of the metadefinition (normal|mandatory|optional).
*/
public void readAllMetadefinitions(String resourcetype, String type) {
try {
Vector metadefs = m_cms.readAllMetadefinitions(resourcetype,
Integer.parseInt(type));
for( int i = 0; i < metadefs.size(); i++ ) {
System.out.println( (A_CmsMetadefinition)metadefs.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads the Metadefinition for the resource type.<BR/>
*
* @param name The name of the Metadefinition to read.
* @param resourcetype The name of the resource type for the Metadefinition.
*/
public void readMetadefinition(String name, String resourcetype) {
try {
System.out.println( m_cms.readMetadefinition(name, resourcetype) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Writes the Metadefinition for the resource type.<BR/>
*
* @param name The name of the Metadefinition to overwrite.
* @param resourcetype The name of the resource type to read the
* metadefinitions for.
* @param type The new type of the metadefinition (normal|mandatory|optional).
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void writeMetadefinition(String name,
String resourcetype,
String type) {
try {
A_CmsMetadefinition metadef = m_cms.readMetadefinition(name, resourcetype);
metadef.setMetadefType(Integer.parseInt(type));
System.out.println( m_cms.writeMetadefinition(metadef) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Delete the Metadefinition for the resource type.<BR/>
*
* @param name The name of the Metadefinition to overwrite.
* @param resourcetype The name of the resource-type for the Metadefinition.
*/
public void deleteMetadefinition(String name, String resourcetype) {
try {
m_cms.deleteMetadefinition(name, resourcetype);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a Metainformation of a file or folder.
*
* @param name The resource-name of which the Metainformation has to be read.
* @param meta The Metadefinition-name of which the Metainformation has to be read.
*/
public void readMetainformation(String name, String meta) {
try {
System.out.println( m_cms.readMetainformation(name, meta) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Writes a Metainformation for a file or folder.
*
* @param name The resource-name of which the Metainformation has to be set.
* @param meta The Metadefinition-name of which the Metainformation has to be set.
* @param value The value for the metainfo to be set.
*/
public void writeMetainformation(String name, String meta, String value) {
try {
m_cms.writeMetainformation(name, meta, value);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a list of all Metainformations of a file or folder.
*
* @param resource The name of the resource of which the Metainformation has to be
* read.
*/
public void readAllMetainformations(String resource) {
try {
Hashtable metainfos = m_cms.readAllMetainformations(resource);
Enumeration keys = metainfos.keys();
Object key;
while(keys.hasMoreElements()) {
key = keys.nextElement();
System.out.print(key + "=");
System.out.println(metainfos.get(key));
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Deletes all Metainformation for a file or folder.
*
* @param resource The name of the resource of which the Metainformations
* have to be deleted.
*/
public void deleteAllMetainformations(String resource) {
try {
m_cms.deleteAllMetainformations(resource);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Deletes a Metainformation for a file or folder.
*
* @param resourcename The resource-name of which the Metainformation has to be delteted.
* @param meta The Metadefinition-name of which the Metainformation has to be set.
*/
public void deleteMetainformation(String resourcename, String meta) {
try {
m_cms.deleteMetainformation(resourcename, meta);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns the anonymous user object.
*/
public void anonymousUser() {
try {
System.out.println( m_cms.anonymousUser() );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns the default group of the current user.
*/
public void userDefaultGroup() {
System.out.println(m_cms.getRequestContext().currentUser().getDefaultGroup());
}
/**
* Returns the current group of the current user.
*/
public void userCurrentGroup() {
System.out.println(m_cms.getRequestContext().currentGroup());
}
/**
* Sets the current group of the current user.
*/
public void setUserCurrentGroup(String groupname) {
try {
m_cms.getRequestContext().setCurrentGroup(groupname);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns the current project for the user.
*/
public void getCurrentProject() {
System.out.println(m_cms.getRequestContext().currentProject());
}
/**
* Sets the current project for the user.
*
* @param projectname The name of the project to be set as current.
*/
public void setCurrentProject(String projectname) {
try {
System.out.println( m_cms.getRequestContext().setCurrentProject(projectname) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a version-string for this OpenCms.
*/
public void version() {
System.out.println(m_cms.version());
}
public void copyright() {
String[] copy = m_cms.copyright();
for(int i = 0; i < copy.length; i++) {
System.out.println(copy[i]);
}
}
/**
* Copies a resource from the online project to a new, specified project.<br>
* Copying a resource will copy the file header or folder into the specified
* offline project and set its state to UNCHANGED.
*
* @param resource The name of the resource.
*/
public void copyResourceToProject(String resource) {
try {
m_cms.copyResourceToProject(resource);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Deletes the folder.
*
* @param foldername The complete path of the folder.
*/
public void deleteFolder(String foldername) {
try {
m_cms.deleteFolder(foldername);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a Vector with all subfolders.<BR/>
*
* @param foldername the complete path to the folder.
*/
public void getSubFolders(String foldername)
throws CmsException {
try {
Vector folders = m_cms.getSubFolders(foldername);
for( int i = 0; i < folders.size(); i++ ) {
System.out.println( (CmsFolder)folders.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Locks a resource<BR/>
*
* A user can lock a resource, so he is the only one who can write this
* resource.
*
* @param resource The complete path to the resource to lock.
*/
public void lockResource(String resource) {
try {
m_cms.lockResource(resource);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Unlocks a resource<BR/>
*
* A user can unlock a resource, so other users may lock this file.
*
* @param resource The complete path to the resource to lock.
*/
public void unlockResource(String resource) {
try {
m_cms.unlockResource(resource);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Loads a File up to the cms from the lokal disc.
*
* @param lokalfile The lokal file to load up.
* @param folder The folder in the cms to put the new file
* @param filename The name of the new file.
* @param type the filetype of the new file in the cms.
*/
public void uploadFile(String lokalfile, String folder, String filename, String type) {
try {
System.out.println(m_cms.createFile(folder, filename,
importFile(lokalfile), type));
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads a file from the Cms.<BR/>
*
* @param filename The complete path to the file
*/
public void readFile(String filename) {
try {
System.out.println(m_cms.readFile(filename));
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Publishes a project.
*
* @param name The name of the project to be published.
*/
public void publishProject(String name) {
try {
Vector resources = m_cms.publishProject(name);
for( int i = 0; i < resources.size(); i++ ) {
System.out.println( (String)resources.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param filename The complete path of the file to be read.
*/
public void readFileHeader(String filename) {
try {
System.out.println( m_cms.readFileHeader(filename) );
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Renames the file to the new name.
*
* @param oldname The complete path to the resource which will be renamed.
* @param newname The new name of the resource (No path information allowed).
*/
public void renameFile(String oldname, String newname) {
try {
m_cms.renameFile(oldname, newname);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Deletes the file.
*
* @param filename The complete path of the file.
*/
public void deleteFile(String filename) {
try {
m_cms.deleteFile(filename);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Copies the file.
*
* @param source The complete path of the sourcefile.
* @param destination The complete path of the destination.
*
* @exception CmsException will be thrown, if the file couldn't be copied.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*/
public void copyFile(String source, String destination) {
try {
m_cms.copyFile(source, destination);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Changes the flags for this resource<BR/>
*
* The user may change the flags, if he is admin of the resource.
*
* @param filename The complete path to the resource.
* @param flags The new flags for the resource.
*/
public void chmod(String filename, String flags) {
try {
m_cms.chmod(filename, Integer.parseInt(flags));
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Changes the owner for this resource<BR/>
*
* The user may change this, if he is admin of the resource.
*
* @param filename The complete path to the resource.
* @param newOwner The name of the new owner for this resource.
*/
public void chown(String filename, String newOwner) {
try {
m_cms.chown(filename, newOwner);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Changes the group for this resource<BR/>
*
* The user may change this, if he is admin of the resource.
*
* @param filename The complete path to the resource.
* @param newGroup The new of the new group for this resource.
*/
public void chgrp(String filename, String newGroup) {
try {
m_cms.chgrp(filename, newGroup);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns a Vector with all subfiles.<BR/>
*
* @param foldername the complete path to the folder.
*
* @return subfiles A Vector with all subfiles for the overgiven folder.
*
* @exception CmsException will be thrown, if the user has not the rights
* for this resource.
*/
public void getFilesInFolder(String foldername) {
try {
Vector files = m_cms.getFilesInFolder(foldername);
for( int i = 0; i < files.size(); i++ ) {
System.out.println( (CmsFile)files.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Reads all file headers of a file in the OpenCms.<BR>
* This method returns a vector with the histroy of all file headers, i.e.
* the file headers of a file, independent of the project they were attached to.<br>
*
* The reading excludes the filecontent.
*
* @param filename The name of the file to be read.
*/
public void readAllFileHeaders(String filename) {
try {
Vector files = m_cms.readAllFileHeaders(filename);
for( int i = 0; i < files.size(); i++ ) {
System.out.println( (A_CmsResource)files.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns the parent group of a group<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param groupname The name of the group.
*/
public void getParent(String groupname) {
try {
System.out.println(m_cms.getParent(groupname));
} catch( Exception exc ) {
printException(exc);
}
}
/**
* Returns all child groups of a group<P/>
* This method also returns all sub-child groups of the current group.
*
* @param groupname The name of the group.
*/
public void getChilds(String groupname) {
try {
Vector groups = m_cms.getChilds(groupname);
for( int i = 0; i < groups.size(); i++ ) {
System.out.println( (A_CmsGroup)groups.elementAt(i) );
}
} catch( Exception exc ) {
printException(exc);
}
}
/**
* This method can be called, to determine if the file-system was changed
* in the past. A module can compare its previosly stored number with this
* returned number. If they differ, a change was made.
*
* @return the number of file-system-changes.
*/
public void getFileSystemChanges() {
System.out.println( m_cms.getFileSystemChanges() );
}
/**
* exports database (files, groups, users) into a specified file
*
* @param exportFile the name (absolute Path) for the XML file
* @param exportPath the name (absolute Path) for the folder to export
*/
public void exportDb(String exportFile, String exportPath){
try {
m_cms.exportDb(exportFile, exportPath, C_EXPORTONLYFILES);
} catch( Exception exc ) {
printException(exc);
}
}
/**
* imports a (files, groups, users) XML file into database
*
* @param importPath the name (absolute Path) of folder in which should be imported
* @param importFile the name (absolute Path) of the XML import file
*/
public void importDb(String importFile, String importPath ){
try {
m_cms.importDb(importFile, importPath);
} catch( Exception exc ) {
printException(exc);
}
}
}
|
package biweekly.io.text;
import static biweekly.util.StringUtils.NEWLINE;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import biweekly.ICalVersion;
import biweekly.parameter.ICalParameters;
import biweekly.util.StringUtils;
public class ICalRawReader implements Closeable {
private final FoldedLineReader reader;
private final List<String> components = new ArrayList<String>();
private boolean caretDecodingEnabled = true;
private ICalVersion version = null;
/**
* Creates a new reader.
* @param reader the reader to the data stream
*/
public ICalRawReader(Reader reader) {
this.reader = new FoldedLineReader(reader);
}
/**
* Gets the line number of the last line that was read.
* @return the line number
*/
public int getLineNum() {
return reader.getLineNum();
}
/**
* Gets the iCalendar version that the reader is currently parsing with.
* @return the iCalendar version or null if unknown
*/
public ICalVersion getVersion() {
return version;
}
/**
* Parses the next line of the iCalendar file.
* @return the next line or null if there are no more lines
* @throws ICalParseException if a line cannot be parsed
* @throws IOException if there's a problem reading from the input stream
*/
public ICalRawLine readLine() throws IOException {
String line = reader.readLine();
if (line == null) {
return null;
}
String propertyName = null;
ICalParameters parameters = new ICalParameters();
String value = null;
char escapeChar = 0; //is the next char escaped?
boolean inQuotes = false; //are we inside of double quotes?
StringBuilder buffer = new StringBuilder();
String curParamName = null;
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (escapeChar != 0) {
//this character was escaped
if (escapeChar == '\\') {
//backslash escaping in parameter values is not part of the standard
if (ch == '\\') {
buffer.append(ch);
} else if (ch == 'n' || ch == 'N') {
//newlines
buffer.append(NEWLINE);
} else if (ch == '"' && version != ICalVersion.V1_0) {
//incase a double quote is escaped with a backslash
buffer.append(ch);
} else if (ch == ';' && version == ICalVersion.V1_0) {
//semi-colons can only be escaped in 1.- parameter values
//if a 2.0 param value has semi-colons, the value should be surrounded in double quotes
buffer.append(ch);
} else {
//treat the escape character as a normal character because it's not a valid escape sequence
buffer.append(escapeChar).append(ch);
}
} else if (escapeChar == '^') {
if (ch == '^') {
buffer.append(ch);
} else if (ch == 'n') {
buffer.append(NEWLINE);
} else if (ch == '\'') {
buffer.append('"');
} else {
//treat the escape character as a normal character because it's not a valid escape sequence
buffer.append(escapeChar).append(ch);
}
}
escapeChar = 0;
continue;
}
if (ch == '\\' || (ch == '^' && version != ICalVersion.V1_0 && caretDecodingEnabled)) {
//an escape character was read
escapeChar = ch;
continue;
}
if ((ch == ';' || ch == ':') && !inQuotes) {
if (propertyName == null) {
//property name
propertyName = buffer.toString();
} else {
//parameter value
String paramValue = buffer.toString();
if (version == ICalVersion.V1_0) {
//1.0 allows whitespace to surround the "=", so remove it
paramValue = StringUtils.ltrim(paramValue);
}
parameters.put(curParamName, paramValue);
curParamName = null;
}
buffer.setLength(0);
if (ch == ':') {
//the rest of the line is the property value
if (i < line.length() - 1) {
value = line.substring(i + 1);
} else {
value = "";
}
break;
}
continue;
}
if (ch == ',' && !inQuotes && version != ICalVersion.V1_0) {
//multi-valued parameter
parameters.put(curParamName, buffer.toString());
buffer.setLength(0);
continue;
}
if (ch == '=' && curParamName == null) {
//parameter name
curParamName = buffer.toString();
if (version == ICalVersion.V1_0) {
//2.1 allows whitespace to surround the "=", so remove it
curParamName = StringUtils.rtrim(curParamName);
}
buffer.setLength(0);
continue;
}
if (ch == '"' && version != ICalVersion.V1_0) {
//1.0 doesn't use the quoting mechanism
inQuotes = !inQuotes;
continue;
}
buffer.append(ch);
}
if (propertyName == null || value == null) {
throw new ICalParseException(line);
}
if ("BEGIN".equalsIgnoreCase(propertyName)) {
components.add(value.toUpperCase());
} else if ("END".equalsIgnoreCase(propertyName)) {
int index = components.lastIndexOf(value.toUpperCase());
if (index >= 0) {
components.subList(index, components.size()).clear();
}
} else if ("VERSION".equalsIgnoreCase(propertyName) && isUnderVCalendar()) {
//only look at VERSION properties that are directly under the VCALENDAR component
ICalVersion version = ICalVersion.get(value);
if (version != null) {
//if the value is a valid version, then skip this property and parse the next
this.version = version;
return readLine();
}
}
return new ICalRawLine(propertyName, parameters, value);
}
private boolean isUnderVCalendar() {
int firstIndex = components.indexOf("VCALENDAR");
if (firstIndex < 0) {
return false;
}
int lastIndex = components.lastIndexOf("VCALENDAR");
return firstIndex == lastIndex && firstIndex == components.size() - 1;
}
public boolean isCaretDecodingEnabled() {
return caretDecodingEnabled;
}
public void setCaretDecodingEnabled(boolean enable) {
caretDecodingEnabled = enable;
}
/**
* Gets the character encoding of the reader.
* @return the character encoding or null if none is defined
*/
public Charset getEncoding() {
return reader.getEncoding();
}
/**
* Closes the underlying {@link Reader} object.
*/
public void close() throws IOException {
reader.close();
}
}
|
package com.rapid.data;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import com.rapid.data.ConnectionAdapter.ConnectionAdapterException;
import com.rapid.server.RapidRequest;
public class DataFactory {
public static class Parameter {
public static final int NULL = 1;
public static final int STRING = 2;
public static final int DATE = 3;
public static final int INTEGER = 4;
public static final int FLOAT = 5;
public static final int DOUBLE = 6;
public static final int LONG = 7;
private int _type;
private String _string;
private Date _date;
private int _int;
private float _float;
private double _double;
private long _long;
public Parameter() {
_type = NULL;
}
public Parameter(String value) {
_type = STRING;
_string = value;
}
public Parameter(Date value) {
_type = DATE;
_date = value;
}
public Parameter(java.util.Date value) {
Date date = new Date(value.getTime());
_type = DATE;
_date = date;
}
public Parameter(int value) {
_type = INTEGER;
_int = value;
}
public Parameter(float value) {
_type = FLOAT;
_float = value;
}
public Parameter(double value) {
_type = DOUBLE;
_double = value;
}
public Parameter(long value) {
_type = LONG;
_long = value;
}
public int getType() { return _type; }
public String getString() { return _string; }
public Date getDate() { return _date; }
public int getInteger() { return _int; }
public float getFloat() { return _float; }
public double getDouble() { return _double; }
public long getLong() { return _long; }
@Override
public String toString() {
switch (_type) {
case NULL : return "null";
case STRING : return _string;
case DATE : return _date.toString();
case INTEGER : return Integer.toString(_int);
case FLOAT : return Float.toString(_float);
case DOUBLE : return Double.toString(_double);
case LONG : return Long.toString(_long);
}
return "unknown type";
}
}
@SuppressWarnings("serial")
public static class Parameters extends ArrayList<Parameter> {
public void addNull() { this.add(new Parameter()); }
public void addString(String value) { this.add(new Parameter(value)); }
public void addInt(int value) { this.add(new Parameter(value)); }
public void addDate(Date value) { this.add(new Parameter(value)); }
public void addFloat(float value) { this.add(new Parameter(value)); }
public void addDouble(double value) { this.add(new Parameter(value)); }
public void addLong(long value) { this.add(new Parameter(value)); }
public void add() { this.add(new Parameter()); }
public void add(String value) { this.add(new Parameter(value)); }
public void add(int value) { this.add(new Parameter(value)); }
public void add(Date value) { this.add(new Parameter(value)); }
public void add(java.util.Date value) { this.add(new Parameter(value)); }
public void add(float value) { this.add(new Parameter(value)); }
public void add(double value) { this.add(new Parameter(value)); }
public void add(long value) { this.add(new Parameter(value)); }
public Parameters() {}
public Parameters(Object...parameters) {
if (parameters != null) {
for (Object object : parameters) {
if (object== null) {
this.add(new Parameter());
} else if (object instanceof String) {
String v = (String) object;
this.add(new Parameter(v));
} else if (object instanceof Integer) {
Integer v = (Integer) object;
this.add(new Parameter(v));
} else if (object instanceof Date) {
Date v = (Date) object;
this.add(new Parameter(v));
} else if (object instanceof java.util.Date) {
java.util.Date v = (java.util.Date) object;
this.add(new Parameter(v));
} else if (object instanceof Float) {
Float v = (Float) object;
this.add(new Parameter(v));
} else if (object instanceof Double) {
Double v = (Double) object;
this.add(new Parameter(v));
} else if (object instanceof Long) {
Long v = (Long) object;
this.add(new Parameter(v));
}
}
}
}
@Override
public String toString() {
String parametersString = "";
for (int i = 0; i < this.size(); i++) {
Parameter parameter = this.get(i);
if (parameter.getString() == null) {
parametersString += parameter.toString();
} else {
parametersString += "'" + parameter.toString() + "'";
}
if (i < this.size() - 1) parametersString += ", ";
}
return parametersString;
}
}
private ConnectionAdapter _connectionAdapter;
private String _sql;
private boolean _autoCommit, _readOnly;
private Connection _connection;
private PreparedStatement _preparedStatement;
private ResultSet _resultset;
public DataFactory(ConnectionAdapter connectionAdapter) {
_connectionAdapter = connectionAdapter;
_autoCommit = true;
}
public DataFactory(ConnectionAdapter connectionAdapter, boolean autoCommit) {
_connectionAdapter = connectionAdapter;
_autoCommit = autoCommit;
}
public Connection getConnection(RapidRequest rapidRequest) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
_connection = _connectionAdapter.getConnection(rapidRequest);
_connection.setAutoCommit(_autoCommit);
_connection.setReadOnly(_readOnly);
return _connection;
}
public boolean getReadOnly(boolean readOnly) { return _readOnly; }
public void setReadOnly(boolean readOnly) { _readOnly = readOnly; }
private void populateStatement(PreparedStatement statement, ArrayList<Parameter> parameters, int startColumn) throws SQLException {
ParameterMetaData parameterMetaData = statement.getParameterMetaData();
if (parameters == null) {
if (parameterMetaData.getParameterCount() > 0) throw new SQLException("SQL has " + parameterMetaData.getParameterCount() + " parameters, none provided");
} else {
if (parameterMetaData.getParameterCount() - startColumn != parameters.size()) throw new SQLException("SQL has " + parameterMetaData.getParameterCount() + " parameters, " + (parameters.size() - startColumn) + " provided");
int i = startColumn;
for (Parameter parameter : parameters) {
i++;
switch (parameter.getType()) {
case Parameter.NULL :
statement.setNull(i, Types.NULL);
break;
case Parameter.STRING :
if (parameter.getString() == null) {
statement.setNull(i, Types.NULL);
} else {
statement.setString(i, parameter.getString());
}
break;
case Parameter.DATE :
if (parameter.getDate() == null) {
statement.setNull(i, Types.NULL);
} else {
statement.setTimestamp(i, new Timestamp(parameter.getDate().getTime()));
}
break;
case Parameter.INTEGER :
statement.setInt(i, parameter.getInteger());
break;
case Parameter.FLOAT :
statement.setFloat(i, parameter.getFloat());
break;
case Parameter.DOUBLE :
statement.setDouble(i, parameter.getDouble());
break;
case Parameter.LONG :
statement.setLong(i, parameter.getLong());
break;
}
}
}
}
public PreparedStatement getPreparedStatement(RapidRequest rapidRequest, String sql, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
// some jdbc drivers need various modifications to the sql
if (_connectionAdapter.getDriverClass().contains("sqlserver")) {
// line breaks in the sql replacing - here's looking at you MS SQL!
_sql = sql.replace("\n", " ");
} else {
// otherwise just retain
_sql = sql;
}
if (_connection == null) _connection = getConnection(rapidRequest);
if (_preparedStatement != null) _preparedStatement.close();
_preparedStatement = _connection.prepareStatement(_sql);
populateStatement(_preparedStatement, parameters, 0);
return _preparedStatement;
}
public ResultSet getPreparedResultSet(RapidRequest rapidRequest, String sql, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
_resultset = getPreparedStatement(rapidRequest, sql, parameters).executeQuery();
return _resultset;
}
public ResultSet getPreparedResultSet(RapidRequest rapidRequest, String sql, Object... parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
Parameters params = new Parameters(parameters);
_resultset = getPreparedStatement(rapidRequest, sql, params).executeQuery();
return _resultset;
}
public ResultSet getPreparedResultSet(RapidRequest rapidRequest, String sql) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
_resultset = getPreparedStatement(rapidRequest, sql, null).executeQuery();
return _resultset;
}
public int getPreparedUpdate(RapidRequest rapidRequest, String sql, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
return getPreparedStatement(rapidRequest, sql, parameters).executeUpdate();
}
public int getPreparedUpdate(RapidRequest rapidRequest, String SQL, Object... parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
Parameters params = new Parameters(parameters);
return getPreparedStatement(rapidRequest, SQL, params).executeUpdate();
}
public String getPreparedScalar(RapidRequest rapidRequest, String SQL, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
String result = null;
if (SQL != null) {
String sqlCheck = SQL.trim().toLowerCase();
if (sqlCheck.startsWith("select")) {
_resultset = getPreparedStatement(rapidRequest, SQL, parameters).executeQuery();
if (_resultset.next()) result = _resultset.getString(1);
} else if (sqlCheck.startsWith("insert") || sqlCheck.startsWith("update") || sqlCheck.startsWith("delete")) {
result = Integer.toString(getPreparedUpdate(rapidRequest, SQL, parameters));
} else {
if (_connection == null) _connection = getConnection(rapidRequest);
CallableStatement st = _connection.prepareCall("{? = call " + SQL + "}");
_preparedStatement = st;
populateStatement(st, parameters, 1);
st.registerOutParameter(1, Types.NVARCHAR);
st.execute();
result = st.getString(1);
}
}
return result;
}
public String getPreparedScalar(RapidRequest rapidRequest, String SQL, Object... parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
Parameters params = new Parameters(parameters);
return getPreparedScalar(rapidRequest, SQL, params);
}
public void commit() throws SQLException {
if (_connection != null) _connection.commit();
}
public void rollback() throws SQLException {
if (_connection != null) _connection.rollback();
}
public void close() throws SQLException {
if (_preparedStatement != null) _preparedStatement.close();
if (_connectionAdapter != null && _connection != null) {
_connectionAdapter.closeConnection(_connection);
} else if (_connection != null) {
_connection.close();
}
}
}
|
package genTest;
import java.util.LinkedList;
import java.util.List;
import tools.Individual;
import tools.SNP;
import tools.Window;
import tools.ExtendedHaplotype;
public class EHH {
private static double SIGNIFICANT_EHH = 0.05;
// private static int MAX_DISTANCE = 5000000;
private double cur_ehh_value;
private double last_ehh_value;
private LinkedList<ExtendedHaplotype> group;
private LinkedList<Double> all_ehh_values;
private LinkedList<Integer> all_ehh_positions;
private List<Window> all_win;
private SNP core_snp;//the core haplotype
private SNP dwnstrm_snp;
private SNP upstrm_snp;
private SNP last_snp;
private Window core_win;
private Window dwnstrm_win;
private Window upstrm_win;
private Individual[] individuals;
private ExtendedHaplotype all_haplo;
public EHH(Window core_win, Individual[] individuals, SNP core_snp,
ExtendedHaplotype all_haplo, List<Window> all_win) {
this.core_win = core_win;
this.individuals = individuals;
this.core_snp = core_snp;
this.all_win = all_win;
this.all_haplo = all_haplo;
cur_ehh_value = 1.0;
last_ehh_value = 1.0;
dwnstrm_snp = this.core_snp;
upstrm_snp = this.core_snp;
last_snp = this.core_snp;
dwnstrm_win = this.core_win;
upstrm_win = this.core_win;
all_ehh_values = new LinkedList<Double>();
all_ehh_positions = new LinkedList<Integer>();
group = new LinkedList<ExtendedHaplotype>();
group.add(all_haplo);
}
public void calcEhhToPosition(int end_pos) {
//This is the EHH denominator
int ct_comb_2 = combineSetBy2(all_haplo);
all_ehh_values.add(1.0);
all_ehh_positions.add(core_snp.getPosition());
//Boundary position check for EHH calculation
while(isValidPosition(end_pos, last_snp.getPosition())) {
SNP nxt_snp = getClosestSNP();
//incorporates the new SNP into all extended haplotypes (increase length by 1)
group = createNewExtHaploGroup(nxt_snp);
cur_ehh_value = calcEHH(ct_comb_2);
if(cur_ehh_value == 1)
break;
saveEHH(cur_ehh_value, nxt_snp);
}
}
/**
* Does not consider the core SNP for EHH analysis and grouping.
* Organizes all Extended Haplotypes until there are insignificant
* homozygosity levels (EHH <= 0.05)
*
* @return return true if the analysis generated significant results
*/
public boolean calcSignificantEhhValues(double ehh_cutoff) {
//This is the EHH denominator
int ct_comb_2 = combineSetBy2(all_haplo);
all_ehh_values.add(1.0);
all_ehh_positions.add(core_snp.getPosition());
//Significance check of EHH value
while(cur_ehh_value > ehh_cutoff) {
SNP nxt_snp = getClosestSNP();
//incorporates the new SNP into all extended haplotypes (increase length by 1)
group = createNewExtHaploGroup(nxt_snp);
cur_ehh_value = calcEHH(ct_comb_2);
if(cur_ehh_value == 1)//means that the group is size 1 and cannont get any smaller???
break;
saveEHH(cur_ehh_value, nxt_snp);
if(core_snp.getPosition() == 9583837 || core_snp.getPosition() == 9733220)
System.out.println(nxt_snp + "\t" + cur_ehh_value);
// if(Math.abs(nxt_snp.getPosition() - core_snp.getPosition()) > MAX_DISTANCE) {
// cur_ehh_value = -1;
// break;
}
return true;
}
public boolean calcSignificantEhhValues() {
return calcSignificantEhhValues(SIGNIFICANT_EHH);
}
public double[] getEhhValues() {
return convertAllEhhValuesToArray();
}
public int[] getEhhPositions() {
return convertAllEhhPositionsToArray();
}
public double getLastEhhValue() {
return last_ehh_value;
}
public SNP getLastSNP() {
return last_snp;
}
private boolean isValidPosition(int boundary_pos, int prev_pos) {
int boundary = Math.abs(core_snp.getPosition() - boundary_pos);
int prev_range = Math.abs(core_snp.getPosition() - prev_pos);
if(boundary >= prev_range)
return true;
return false;
}
private double[] convertAllEhhValuesToArray() {
double[] all_ehh = new double[all_ehh_values.size()];
for(int i = 0; i < all_ehh_values.size(); i++)
all_ehh[i] = all_ehh_values.get(i);
return all_ehh;
}
private int[] convertAllEhhPositionsToArray() {
int[] all_pos = new int[all_ehh_positions.size()];
for(int i = 0; i < all_ehh_positions.size(); i++)
all_pos[i] = all_ehh_positions.get(i);
return all_pos;
}
private void saveEHH(double ehh, SNP nxt_snp) {
if(nxt_snp.getPosition() >= core_snp.getPosition()) {
all_ehh_values.addLast(ehh);
all_ehh_positions.addLast(nxt_snp.getPosition());
}
else {
all_ehh_values.addFirst(ehh);
all_ehh_positions.addFirst(nxt_snp.getPosition());
}
last_ehh_value = ehh;
last_snp = nxt_snp;
}
private double calcEHH(int ct_comb_2) {
int sum = 0;
for(ExtendedHaplotype eh : group) {
sum += combineSetBy2(eh);
}
double ehh = (double) sum / (double) ct_comb_2;
return ehh;
}
private int combineSetBy2(ExtendedHaplotype set) {
int size = set.size();
int score = 0;
for(int i = 0; i < size; i++)
score += size - (i + 1);
return score;
}
private LinkedList<ExtendedHaplotype> createNewExtHaploGroup(SNP nxt_snp) {
if(nxt_snp == null)
return null;
LinkedList<ExtendedHaplotype> updated_group = new LinkedList<ExtendedHaplotype>();
int nxt_snp_index = -1;
if(nxt_snp.getPosition() >= core_snp.getPosition())
nxt_snp_index = upstrm_win.getSnpIndex(nxt_snp);
else
nxt_snp_index = dwnstrm_win.getSnpIndex(nxt_snp);
for(ExtendedHaplotype eh : group) {
//if the ExtHaplo is size = 1 it is by definition already completely unique
//and doen't need to be checked for more uniqueness
if(eh.size() == 1){
updated_group.add(eh);
}
else {
ExtendedHaplotype eh_0 = new ExtendedHaplotype();
ExtendedHaplotype eh_1 = new ExtendedHaplotype();
while(!eh.isEmpty()) {
int id = eh.getNextID();
int strand = eh.getNextStrand();
Individual indv = individuals[id];
int allele = -1;
if(strand == 1)
allele = indv.getStrand1Allele(nxt_snp_index);
if(strand == 2)
allele = indv.getStrand2Allele(nxt_snp_index);
if(allele == 0)
eh_0.add(id, strand);
if(allele == 1)
eh_1.add(id, strand);
eh.removeFirst();
}
if(eh_0.size() > 0)
updated_group.add(eh_0);
if(eh_1.size() > 0)
updated_group.add(eh_1);
}
}
return updated_group;
}
private SNP getClosestSNP() {
SNP temp_dwnstrm_snp = getNextDownstreamSNP();
SNP temp_upstrm_snp = getNextUpstreamSNP();
int dwnstrm_snp_length = -1;
if(temp_dwnstrm_snp != null)
dwnstrm_snp_length = Math.abs(core_snp.getPosition() - temp_dwnstrm_snp.getPosition());
int upstrm_snp_length = -1;
if(temp_upstrm_snp != null)
upstrm_snp_length = Math.abs(core_snp.getPosition() - temp_upstrm_snp.getPosition());
// if(core_snp.getPosition() == 9583837) {
// System.out.println("UP:\t" + upstrm_snp);
// System.out.println("DOWN:\t" + dwnstrm_snp);
if(upstrm_snp_length == -1 && dwnstrm_snp_length == -1) {
System.out.println("CORE:\t" + core_snp);
System.out.println("UP:\t" + upstrm_snp);
System.out.println("DOWN:\t" + dwnstrm_snp);
return null;
} else if(upstrm_snp_length == -1) {
return incrementDownstream(temp_dwnstrm_snp);
} else if(dwnstrm_snp_length == -1) {
return incrementUpstream(temp_upstrm_snp);
} else if(dwnstrm_snp_length < upstrm_snp_length) {
return incrementDownstream(temp_dwnstrm_snp);
} else if(upstrm_snp_length <= dwnstrm_snp_length){
return incrementUpstream(temp_upstrm_snp);
}
return null;
}
private SNP incrementUpstream(SNP temp_upstrm_snp) {
int old_index = upstrm_win.getSnpIndex(upstrm_snp);// a check for incrementing the window
upstrm_snp = temp_upstrm_snp;
//this is done only if the new upstrm_snp is outside of the current window
if(!upstrm_win.containsIndex(old_index + 1))
upstrm_win = findWindow(old_index + 1);
return upstrm_snp;
}
private SNP incrementDownstream(SNP temp_dwnstrm_snp) {
int old_index = dwnstrm_win.getSnpIndex(dwnstrm_snp);// a check for incrementing the window
dwnstrm_snp = temp_dwnstrm_snp;
//this is done only if the new dwnstrm_snp is outside of the current window
if(!dwnstrm_win.containsIndex(old_index - 1))
dwnstrm_win = findWindow(old_index - 1);
return dwnstrm_snp;
}
private SNP getNextDownstreamSNP() {
//to skip this function if you have reached the boundary of the chr
if(dwnstrm_snp == null || dwnstrm_win == null)
return null;
SNP nxt_dwn_snp = new SNP();
int nxt_index = dwnstrm_win.getSnpIndex(dwnstrm_snp) - 1;
if(dwnstrm_win.containsIndex(nxt_index))
nxt_dwn_snp = dwnstrm_win.getSNP(nxt_index);
else {
Window temp_dwnstrm_win = findWindow(nxt_index);
if(temp_dwnstrm_win == null) {
dwnstrm_win = null;
dwnstrm_snp = null;
return null;
}
nxt_dwn_snp = temp_dwnstrm_win.getSNP(nxt_index);
}
return nxt_dwn_snp;
}
private SNP getNextUpstreamSNP() {
//to skip this function if you have reached the boundary of the chr
if(upstrm_snp == null || upstrm_win == null)
return null;
SNP nxt_up_snp = new SNP();
int nxt_index = upstrm_win.getSnpIndex(upstrm_snp) + 1;
if(upstrm_win.containsIndex(nxt_index))
nxt_up_snp = upstrm_win.getSNP(nxt_index);
else {
Window temp_upstrm_win = findWindow(nxt_index);
if(temp_upstrm_win == null) {
upstrm_win = null;
upstrm_snp = null;
return null;
}
nxt_up_snp = temp_upstrm_win.getSNP(nxt_index);
}
return nxt_up_snp;
}
private Window findWindow(int index) {
for(Window w : all_win) {
if(w.containsIndex(index))
return w;
}
return null;
}
}
|
package biweekly.property;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import biweekly.ICalendar;
import biweekly.component.ICalComponent;
import biweekly.component.VTimezone;
import biweekly.parameter.ICalParameters;
/**
* Base class for all iCalendar properties.
* @author Michael Angstadt
*/
public abstract class ICalProperty {
/**
* The property parameters.
*/
protected ICalParameters parameters = new ICalParameters();
/**
* Gets the property's parameters.
* @return the parameters
*/
public ICalParameters getParameters() {
return parameters;
}
/**
* Sets the property's parameters
* @param parameters the parameters
*/
public void setParameters(ICalParameters parameters) {
this.parameters = parameters;
}
/**
* Gets the first value of a parameter with the given name.
* @param name the parameter name (case insensitive, e.g. "LANGUAGE")
* @return the parameter value or null if not found
*/
public String getParameter(String name) {
return parameters.first(name);
}
/**
* Gets all values of a parameter with the given name.
* @param name the parameter name (case insensitive, e.g. "LANGUAGE")
* @return the parameter values
*/
public List<String> getParameters(String name) {
return parameters.get(name);
}
/**
* Adds a value to a parameter.
* @param name the parameter name (case insensitive, e.g. "LANGUAGE")
* @param value the parameter value
*/
public void addParameter(String name, String value) {
parameters.put(name, value);
}
/**
* Replaces all existing values of a parameter with the given value.
* @param name the parameter name (case insensitive, e.g. "LANGUAGE")
* @param value the parameter value
*/
public void setParameter(String name, String value) {
parameters.replace(name, value);
}
/**
* Replaces all existing values of a parameter with the given values.
* @param name the parameter name (case insensitive, e.g. "LANGUAGE")
* @param values the parameter values
*/
public void setParameter(String name, Collection<String> values) {
parameters.replace(name, values);
}
/**
* Removes a parameter from the property.
* @param name the parameter name (case insensitive, e.g. "LANGUAGE")
*/
public void removeParameter(String name) {
parameters.removeAll(name);
}
//Note: The following parameter helper methods are package-scoped to prevent them from cluttering up the Javadocs
String getAltRepresentation() {
return parameters.getAltRepresentation();
}
void setAltRepresentation(String uri) {
parameters.setAltRepresentation(uri);
}
String getFormatType() {
return parameters.getFormatType();
}
void setFormatType(String formatType) {
parameters.setFormatType(formatType);
}
String getLanguage() {
return parameters.getLanguage();
}
void setLanguage(String language) {
parameters.setLanguage(language);
}
String getTimezoneId() {
return parameters.getTimezoneId();
}
void setTimezoneId(String timezoneId) {
parameters.setTimezoneId(timezoneId);
}
void setTimezone(VTimezone timezone) {
if (timezone == null) {
setTimezoneId(null);
return;
}
TimezoneId tzid = timezone.getTimezoneId();
if (tzid != null) {
setTimezoneId(tzid.getValue());
}
}
String getSentBy() {
return parameters.getSentBy();
}
void setSentBy(String uri) {
parameters.setSentBy(uri);
}
String getCommonName() {
return parameters.getCommonName();
}
void setCommonName(String commonName) {
parameters.setCommonName(commonName);
}
String getDirectoryEntry() {
return parameters.getDirectoryEntry();
}
void setDirectoryEntry(String uri) {
parameters.setDirectoryEntry(uri);
}
/**
* Checks the property for data consistency problems or deviations from the
* spec. These problems will not prevent the property from being written to
* a data stream, but may prevent it from being parsed correctly by the
* consuming application. These problems can largely be avoided by reading
* the Javadocs of the property class, or by being familiar with the
* iCalendar standard.
* @param components the hierarchy of components that the property belongs
* to
* @see ICalendar#validate
* @return a list of warnings or an empty list if no problems were found
*/
public final List<String> validate(List<ICalComponent> components) {
List<String> warnings = new ArrayList<String>(0);
validate(components, warnings);
return warnings;
}
/**
* Checks the property for data consistency problems or deviations from the
* spec. Meant to be overridden by child classes that wish to provide
* validation logic.
* @param components the hierarchy of components that the property belongs
* to
* @param warnings the list to add the warnings to
*/
protected void validate(List<ICalComponent> components, List<String> warnings) {
//do nothing
}
}
|
package com.rapid.data;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import com.rapid.data.ConnectionAdapter.ConnectionAdapterException;
import com.rapid.server.RapidRequest;
public class DataFactory {
public static class Parameter {
public static final int NULL = 1;
public static final int STRING = 2;
public static final int DATE = 3;
public static final int INTEGER = 4;
public static final int FLOAT = 5;
public static final int DOUBLE = 6;
public static final int LONG = 7;
private int _type;
private String _string;
private Date _date;
private int _int;
private float _float;
private double _double;
private long _long;
public Parameter() {
_type = NULL;
}
public Parameter(String value) {
_type = STRING;
_string = value;
}
public Parameter(Date value) {
_type = DATE;
_date = value;
}
public Parameter(java.util.Date value) {
Date date = new Date(value.getTime());
_type = DATE;
_date = date;
}
public Parameter(int value) {
_type = INTEGER;
_int = value;
}
public Parameter(float value) {
_type = FLOAT;
_float = value;
}
public Parameter(double value) {
_type = DOUBLE;
_double = value;
}
public Parameter(long value) {
_type = LONG;
_long = value;
}
public int getType() { return _type; }
public String getString() { return _string; }
public Date getDate() { return _date; }
public int getInteger() { return _int; }
public float getFloat() { return _float; }
public double getDouble() { return _double; }
public long getLong() { return _long; }
@Override
public String toString() {
switch (_type) {
case NULL : return "null";
case STRING : return _string;
case DATE : return _date.toString();
case INTEGER : return Integer.toString(_int);
case FLOAT : return Float.toString(_float);
case DOUBLE : return Double.toString(_double);
case LONG : return Long.toString(_long);
}
return "unknown type";
}
}
@SuppressWarnings("serial")
public static class Parameters extends ArrayList<Parameter> {
public void addNull() { this.add(new Parameter()); }
public void addString(String value) { this.add(new Parameter(value)); }
public void addInt(int value) { this.add(new Parameter(value)); }
public void addDate(Date value) { this.add(new Parameter(value)); }
public void addFloat(float value) { this.add(new Parameter(value)); }
public void addDouble(double value) { this.add(new Parameter(value)); }
public void addLong(long value) { this.add(new Parameter(value)); }
public void add() { this.add(new Parameter()); }
public void add(String value) { this.add(new Parameter(value)); }
public void add(int value) { this.add(new Parameter(value)); }
public void add(Date value) { this.add(new Parameter(value)); }
public void add(java.util.Date value) { this.add(new Parameter(value)); }
public void add(float value) { this.add(new Parameter(value)); }
public void add(double value) { this.add(new Parameter(value)); }
public void add(long value) { this.add(new Parameter(value)); }
public Parameters() {}
public Parameters(Object...parameters) {
if (parameters != null) {
for (Object object : parameters) {
if (object== null) {
this.add(new Parameter());
} else if (object instanceof String) {
String v = (String) object;
this.add(new Parameter(v));
} else if (object instanceof Integer) {
Integer v = (Integer) object;
this.add(new Parameter(v));
} else if (object instanceof Date) {
Date v = (Date) object;
this.add(new Parameter(v));
} else if (object instanceof java.util.Date) {
java.util.Date v = (java.util.Date) object;
this.add(new Parameter(v));
} else if (object instanceof Float) {
Float v = (Float) object;
this.add(new Parameter(v));
} else if (object instanceof Double) {
Double v = (Double) object;
this.add(new Parameter(v));
} else if (object instanceof Long) {
Long v = (Long) object;
this.add(new Parameter(v));
}
}
}
}
@Override
public String toString() {
String parametersString = "";
for (int i = 0; i < this.size(); i++) {
Parameter parameter = this.get(i);
if (parameter.getString() == null) {
parametersString += parameter.toString();
} else {
parametersString += "'" + parameter.toString() + "'";
}
if (i < this.size() - 1) parametersString += ", ";
}
return parametersString;
}
}
private ConnectionAdapter _connectionAdapter;
private String _sql;
private boolean _autoCommit, _readOnly;
private Connection _connection;
private PreparedStatement _preparedStatement;
private ResultSet _resultset;
public DataFactory(ConnectionAdapter connectionAdapter) {
_connectionAdapter = connectionAdapter;
_autoCommit = true;
}
public DataFactory(ConnectionAdapter connectionAdapter, boolean autoCommit) {
_connectionAdapter = connectionAdapter;
_autoCommit = autoCommit;
}
public Connection getConnection(RapidRequest rapidRequest) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
_connection = _connectionAdapter.getConnection(rapidRequest);
_connection.setAutoCommit(_autoCommit);
_connection.setReadOnly(_readOnly);
return _connection;
}
public boolean getReadOnly(boolean readOnly) { return _readOnly; }
public void setReadOnly(boolean readOnly) { _readOnly = readOnly; }
private void populateStatement(PreparedStatement statement, ArrayList<Parameter> parameters, int startColumn) throws SQLException {
ParameterMetaData parameterMetaData = statement.getParameterMetaData();
if (parameters == null) {
if (parameterMetaData.getParameterCount() > 0) throw new SQLException("SQL has " + parameterMetaData.getParameterCount() + " parameters, none provided");
} else {
if (parameterMetaData.getParameterCount() - startColumn != parameters.size()) throw new SQLException("SQL has " + parameterMetaData.getParameterCount() + " parameters, " + (parameters.size() - startColumn) + " provided");
int i = startColumn;
for (Parameter parameter : parameters) {
i++;
switch (parameter.getType()) {
case Parameter.NULL :
statement.setNull(i, Types.NULL);
break;
case Parameter.STRING :
if (parameter.getString() == null) {
statement.setNull(i, Types.NULL);
} else {
statement.setString(i, parameter.getString());
}
break;
case Parameter.DATE :
if (parameter.getDate() == null) {
statement.setNull(i, Types.NULL);
} else {
statement.setTimestamp(i, new Timestamp(parameter.getDate().getTime()));
}
break;
case Parameter.INTEGER :
statement.setInt(i, parameter.getInteger());
break;
case Parameter.FLOAT :
statement.setFloat(i, parameter.getFloat());
break;
case Parameter.DOUBLE :
statement.setDouble(i, parameter.getDouble());
break;
case Parameter.LONG :
statement.setLong(i, parameter.getLong());
break;
}
}
}
}
public PreparedStatement getPreparedStatement(RapidRequest rapidRequest, String sql, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
// some jdbc drivers need various modifications to the sql
if (_connectionAdapter.getDriverClass().contains("sqlserver")) {
// line breaks in the sql replacing - here's looking at you MS SQL!
_sql = sql.replace("\n", " ");
} else {
// otherwise just retain
_sql = sql;
}
if (_connection == null) _connection = getConnection(rapidRequest);
if (_preparedStatement != null) _preparedStatement.close();
_preparedStatement = _connection.prepareStatement(_sql);
populateStatement(_preparedStatement, parameters, 0);
return _preparedStatement;
}
public ResultSet getPreparedResultSet(RapidRequest rapidRequest, String sql, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
_resultset = getPreparedStatement(rapidRequest, sql, parameters).executeQuery();
return _resultset;
}
public ResultSet getPreparedResultSet(RapidRequest rapidRequest, String sql, Object... parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
Parameters params = new Parameters(parameters);
_resultset = getPreparedStatement(rapidRequest, sql, params).executeQuery();
return _resultset;
}
public ResultSet getPreparedResultSet(RapidRequest rapidRequest, String sql) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
_resultset = getPreparedStatement(rapidRequest, sql, null).executeQuery();
return _resultset;
}
public int getPreparedUpdate(RapidRequest rapidRequest, String sql, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
if (sql.trim().toLowerCase().startsWith("begin")) {
CallableStatement cs = getConnection(rapidRequest).prepareCall(_sql);
populateStatement(cs, parameters, 0);
cs.execute();
return cs.getUpdateCount();
} else {
return getPreparedStatement(rapidRequest, sql, parameters).executeUpdate();
}
}
public int getPreparedUpdate(RapidRequest rapidRequest, String SQL, Object... parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
Parameters params = new Parameters(parameters);
return getPreparedStatement(rapidRequest, SQL, params).executeUpdate();
}
public String getPreparedScalar(RapidRequest rapidRequest, String SQL, ArrayList<Parameter> parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
String result = null;
if (SQL != null) {
String sqlCheck = SQL.trim().toLowerCase();
if (sqlCheck.startsWith("select")) {
_resultset = getPreparedStatement(rapidRequest, SQL, parameters).executeQuery();
if (_resultset.next()) result = _resultset.getString(1);
} else if (sqlCheck.startsWith("insert") || sqlCheck.startsWith("update") || sqlCheck.startsWith("delete")) {
result = Integer.toString(getPreparedUpdate(rapidRequest, SQL, parameters));
} else {
if (_connection == null) _connection = getConnection(rapidRequest);
CallableStatement st = _connection.prepareCall("{? = call " + SQL + "}");
_preparedStatement = st;
populateStatement(st, parameters, 1);
st.registerOutParameter(1, Types.NVARCHAR);
st.execute();
result = st.getString(1);
}
}
return result;
}
public String getPreparedScalar(RapidRequest rapidRequest, String SQL, Object... parameters) throws SQLException, ClassNotFoundException, ConnectionAdapterException {
Parameters params = new Parameters(parameters);
return getPreparedScalar(rapidRequest, SQL, params);
}
public void commit() throws SQLException {
if (_connection != null) _connection.commit();
}
public void rollback() throws SQLException {
if (_connection != null) _connection.rollback();
}
public void close() throws SQLException {
if (_preparedStatement != null) _preparedStatement.close();
if (_connectionAdapter != null && _connection != null) {
_connectionAdapter.closeConnection(_connection);
} else if (_connection != null) {
_connection.close();
}
}
}
|
package org.znerd.logdoc.internal;
import org.znerd.logdoc.LogLevel;
/**
* Logdoc-internal logging.
*
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
*/
public final class InternalLogging {
// Class functions
/**
* Logs a debug message.
*
* @param message
* the message, or <code>null</code>.
*/
public static void debug(String message) {
log(LogLevel.DEBUG, message);
}
/**
* Logs an informational message.
*
* @param message
* the message, or <code>null</code>.
*/
public static void info(String message) {
log(LogLevel.INFO, message);
}
/**
* Logs an informational message that should typically be noticed.
*
* @param message
* the message, or <code>null</code>.
*/
public static void notice(String message) {
log(LogLevel.NOTICE, message);
}
/**
* Logs a warning message.
*
* @param message
* the message, or <code>null</code>.
*/
public static void warn(String message) {
log(LogLevel.WARNING, message);
}
/**
* Logs an error message.
*
* @param message
* the message, or <code>null</code>.
*/
public static void error(String message) {
log(LogLevel.ERROR, message);
}
/**
* Logs a fatal error message.
*
* @param message
* the message, or <code>null</code>.
*/
public static void fatal(String message) {
log(LogLevel.FATAL, message);
}
private static void log(LogLevel level, String message) {
System.err.println("" + level.name().charAt(0) + ' ' + message);
}
// Constructors
/**
* Constructs a new <code>InternalLogging</code> object.
*/
private InternalLogging() {
// empty
}
}
|
package com.sudoku.data.model;
import java.sql.Timestamp;
import java.util.*;
public class Grid {
private UUID id;
private String title;
private String description;
private int difficulty;
private boolean published;
private List<Comment> comments;
private List<Tag> tags;
private Cell[][] grid;
private User createUser;
private String createPseudo;
private String createSalt; // Salt of the creator used as an UUID
private Date createDate;
private Date updateDate;
public Grid() {
}
public Grid(String t, User u) {
id = UUID.randomUUID();
title = t;
description = "";
difficulty = 0;
published = false;
comments = new ArrayList<>();
tags = new ArrayList<>();
grid = new Cell[9][9];
for (byte i = 0; i < 9; i++) {
for (byte j = 0; j < 9; j++) {
grid[i][j] = new EmptyCell(i, j);
}
}
createUser = u;
createPseudo = u.getPseudo();
createSalt = u.getSalt();
Calendar cal = new GregorianCalendar();
createDate = cal.getTime();
updateDate = createDate;
}
public static Grid buildFromAvroGrid(com.sudoku.comm.generated.Grid grid) {
Grid resultGrid = new Grid();
resultGrid.id = UUID.fromString(grid.getId());
resultGrid.title = grid.getTitle();
resultGrid.description = grid.getDescription();
resultGrid.difficulty = grid.getDifficulty();
resultGrid.published = grid.getPublished();
resultGrid.createDate = Timestamp.valueOf(grid.getCreateDate());
resultGrid.updateDate = Timestamp.valueOf(grid.getUpdateDate());
resultGrid.createUser = User.buildFromAvroUser(grid.getCreateUser());
for (com.sudoku.comm.generated.Comment comment : grid.getComments()) {
resultGrid.comments.add(Comment.buildFromAvroComment(comment));
}
for (String tag : grid.getTags()) {
resultGrid.tags.add(new Tag(tag));
}
List<List<Integer>> matrix = grid.getMatrix();
for (byte i = 0; i < matrix.size(); i++) {
List<Integer> row = matrix.get(i);
for (byte j = 0; j < row.size(); j++) {
if (row.get(j) != null) {
resultGrid.grid[i][j] = new FixedCell(i, j, row.get(j).byteValue());
} else {
resultGrid.grid[i][j] = new EmptyCell(i, j);
}
}
}
return resultGrid;
}
public void setEmptyCell(byte x, byte y) throws IllegalArgumentException {
if (x < 0 || x > 9 || y < 0 || y > 9) {
throw new IllegalArgumentException(Cell.Errors.Cell_illegal_position);
}
grid[x][y] = new EmptyCell(x, y);
}
public void setFixedCell(byte x, byte y, byte value)
throws IllegalArgumentException {
if (value < 1 || value > 9) {
throw new IllegalArgumentException(Cell.Errors.Cell_illegal_value);
}
if (x < 0 || x > 9 || y < 0 || y > 9) {
throw new IllegalArgumentException(Cell.Errors.Cell_illegal_position);
}
if (grid[x][y] instanceof FixedCell) {
((FixedCell) grid[x][y]).setValue(value);
} else {
grid[x][y] = new FixedCell(x, y, value);
}
}
public Cell getCell(int x, int y) throws IllegalArgumentException {
if (x < 0 || x >= 9 || y < 0 || y >= 9) {
throw new IllegalArgumentException(Cell.Errors.Cell_illegal_position);
}
return grid[x][y];
}
public Cell[][] getGrid() {
return this.grid;
}
public void setGrid(Cell[][] grid) throws IllegalArgumentException {
if (grid.length != 9 || grid[0].length != 9) {
throw new IllegalArgumentException(Grid.errors.Grid_invalid_grid_array);
}
this.grid = grid;
}
public String getTitle() {
return title;
}
public void setTitle(String titre) {
this.title = titre;
}
public int getMeanGrades() { //Give the mean, or 0 if there is no grades
int i = 0, result = 0;
for (Comment comment : comments) {
result += comment.getGrade();
i++;
}
if (i != 0)
return result / i;
else
return 0;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getDifficulty() {
return difficulty;
}
public void setDifficulty(int difficulty) {
this.difficulty = difficulty;
}
public boolean isPublished() {
return published;
}
public void setPublished(boolean published) {
this.published = published;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public User getCreateUser() {
return createUser;
}
public void setCreateUser(User createUser) {
this.createUser = createUser;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Timestamp createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Timestamp updateDate) {
this.updateDate = updateDate;
}
public double getAverageGrade() {
double averageGrade = 0.0;
for (Comment comment : comments) {
averageGrade += comment.getGrade();
}
return averageGrade / comments.size();
}
public void addTag(Tag tag) {
if (tag != null && tag.getName() != null && !tag.getName().isEmpty()) {
for (Tag t : tags) {
if (t.getName().equals(tag.getName())) {
return;
}
}
tags.add(tag);
}
}
public void removeTag(Tag tag) {
if (tag != null && tag.getName() != null && !tag.getName().isEmpty()) {
for (Tag t : tags) {
if (t.getName().equals(tag.getName())) {
tags.remove(t);
return;
}
}
}
}
public void addComment(Comment comment) {
if (comment != null && comment.getComment() != null &&
!comment.getComment().isEmpty()) {
comments.add(comment);
}
}
public void removeComment(Comment comment) {
if (comment != null && comment.getComment() != null &&
!comment.getComment().isEmpty()) {
for (Comment c : comments) {
if (c.getComment().equals(comment.getComment()) &&
c.getGrade().equals(comment.getGrade())) {
comments.remove(c);
return;
}
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
sb.append(grid[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
public class errors {
public static final String Grid_invalid_grid_array =
"The grid must be a 9x9 cell array";
}
}
|
package org.jaxen.test;
import java.util.List;
import junit.framework.TestCase;
import org.jaxen.JaxenException;
import org.jaxen.javabean.JavaBeanXPath;
import org.jaxen.saxpath.helpers.XPathReaderFactory;
public class JavaBeanNavigatorTest
extends TestCase
{
protected void setUp() throws Exception
{
System.setProperty( XPathReaderFactory.DRIVER_PROPERTY,
"" );
}
public void testSomething() throws JaxenException {
// The position() function does not really have any meaning
// for JavaBeans, but we know three of them will come before the fourth,
// even if we don't know which ones.
JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );
Person bob = new Person( "bob", 30 );
bob.addBrother( new Person( "billy", 34 ) );
bob.addBrother( new Person( "seth", 29 ) );
bob.addBrother( new Person( "dave", 32 ) );
bob.addBrother( new Person( "jim", 29 ) );
bob.addBrother( new Person( "larry", 42 ) );
bob.addBrother( new Person( "ted", 22 ) );
List result = (List) xpath.evaluate( bob );
assertEquals(3, result.size());
}
}
|
package ch.bind.philib.lang;
/**
* TODO
*
* @author Philipp Meinen
*/
public abstract class StringUtil {
protected StringUtil() {
}
public static String extractBack(String s, char delim) {
if (s == null || s.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int l = s.length(), i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == delim) {
sb.setLength(0);
} else {
sb.append(c);
}
}
return sb.toString();
}
public static StringBuilder start(Object obj) {
StringBuilder sb = new StringBuilder();
sb.append(obj.getClass().getSimpleName());
sb.append('[');
return sb;
}
public static String end(StringBuilder sb) {
return sb.append(']').toString();
}
public static void firstObj(StringBuilder sb, String name, Object obj) {
sb.append(name);
sb.append('=');
sb.append(obj);
}
public static void addObj(StringBuilder sb, String name, Object obj) {
sb.append(", ");
firstObj(sb, name, obj);
}
public static void addObj(StringBuilder sb, Object obj) {
sb.append(", ");
sb.append(obj);
}
public static void firstInt(StringBuilder sb, String name, int v) {
sb.append(name);
sb.append('=');
sb.append(v);
}
public static void addInt(StringBuilder sb, String name, int v) {
sb.append(", ");
firstInt(sb, name, v);
}
public static void addInt(StringBuilder sb, int v) {
sb.append(", ");
sb.append(v);
}
public static void firstLong(StringBuilder sb, String name, long v) {
sb.append(name);
sb.append('=');
sb.append(v);
}
public static void addLong(StringBuilder sb, String name, long v) {
sb.append(", ");
firstLong(sb, name, v);
}
public static void addLong(StringBuilder sb, long v) {
sb.append(", ");
sb.append(v);
}
}
|
package ch.bind.philib.lang;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.bind.philib.validation.Validation;
/**
* @author Philipp Meinen
*/
public abstract class ThreadUtil {
private static final Logger LOG = LoggerFactory.getLogger(ThreadUtil.class);
protected ThreadUtil() {
}
public static void sleepUntilMs(long time) throws InterruptedException {
long diff = time - System.currentTimeMillis();
if (diff <= 0) {
return;
}
Thread.sleep(diff);
}
/**
* @param t
* the thread which must be interrupted and joined with a default
* timeout
* @return {@code true} for OK, {@code false} in case of an error.
*/
public static boolean interruptAndJoin(Thread t) {
return interruptAndJoin(t, 0);
}
/**
* @param t
* the thread which must be interrupted
* @param waitTime
* a specific timeout for the join operation. A negative or zero
* value means to no timeout is implied.
* @return {@code true} for OK, {@code false} in case of an error.
*/
public static boolean interruptAndJoin(Thread t, long waitTime) {
if (t == null)
return true;
if (!t.isAlive())
return true;
t.interrupt();
try {
if (waitTime <= 0) {
t.join();
} else {
t.join(waitTime);
}
} catch (InterruptedException e) {
LOG.warn("interrupted while waiting for a thread to finish: " + e.getMessage(), e);
}
if (t.isAlive()) {
LOG.warn("thread is still alive: " + t.getName());
return false;
}
return true;
}
/**
* Wrapper for a runnable. The wrapper will delegate calls to Runnable.run()
* to the wrapped object. If the wrapped run() method terminates
* unexpectedly the run method will be called again.
*/
public static final class ForeverRunner implements Runnable {
private final Runnable runnable;
public ForeverRunner(Runnable runnable) {
Validation.notNull(runnable);
this.runnable = runnable;
}
@Override
public void run() {
while (true) {
try {
runnable.run();
// regular shutdown
return;
} catch (Exception e) {
LOG.warn("runnable crashed, restarting it. thread: " + Thread.currentThread().getName(), e);
} catch (Throwable e) {
LOG.error("runnable crashed with an error, will not restart. thread: " + Thread.currentThread().getName(), e);
}
}
}
}
public static final ThreadFactory DEFAULT_THREAD_FACTORY = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
};
/**
* Creates a thread for each non-null runnable in the provided array.<br/>
* A standard {@link ThreadFactory} is used to create threads.<br/>
* The newly created threads are not started.
*
* @param runnables -
*/
public static Thread[] createThreads(Runnable[] runnables) {
return createThreads(runnables, DEFAULT_THREAD_FACTORY);
}
/**
* Creates a thread for each non-null runnable in the provided array.<br/>
* The provided {@link ThreadFactory} is used to create threads.<br/>
* The newly created threads are not started.
*
* @param runnables -
* @param threadFactory -
*/
public static Thread[] createThreads(Runnable[] runnables, ThreadFactory threadFactory) {
if (runnables == null) {
return new Thread[0];
}
if (threadFactory == null) {
threadFactory = DEFAULT_THREAD_FACTORY;
}
List<Thread> ts = new ArrayList<Thread>(runnables.length);
for (Runnable r : runnables) {
if (r != null) {
ts.add(threadFactory.newThread(r));
}
}
return ArrayUtil.toArray(Thread.class, ts);
}
/**
*
* @param threads
* @return {@code true} if all threads were shut down, {@code false} otherwise.
*/
public static boolean interruptAndJoinThreads(Thread[] threads) {
return interruptAndJoinThreads(threads, 0);
}
/**
* @param threads
* @param waitTimePerThread
* @return {@code true} if all threads were shut down, {@code false} otherwise.
*/
public static boolean interruptAndJoinThreads(Thread[] threads, long waitTimePerThread) {
boolean allOk = true;
if (threads != null && threads.length > 0) {
for (Thread t : threads) {
if (!interruptAndJoin(t, waitTimePerThread)) {
allOk = false;
}
}
}
return allOk;
}
/**
* @param threads
* @return {@code true} if all threads were shut down, {@code false} otherwise.
*/
public static boolean interruptAndJoinThreads(Collection<? extends Thread> threads) {
return interruptAndJoinThreads(threads, 0);
}
/**
* @param threads
* @param waitTimePerThread
* @return {@code true} if all threads were shut down, {@code false} otherwise.
*/
public static boolean interruptAndJoinThreads(Collection<? extends Thread> threads, long waitTimePerThread) {
Thread[] ts = ArrayUtil.toArray(Thread.class, threads);
return interruptAndJoinThreads(ts, waitTimePerThread);
}
public static void startThreads(Thread[] threads) {
if (threads != null && threads.length > 0) {
for (Thread t : threads) {
if (t != null) {
t.start();
}
}
}
}
public static void startThreads(Collection<? extends Thread> threads) {
Thread[] ts = ArrayUtil.toArray(Thread.class, threads);
startThreads(ts);
}
}
|
package jmetest.renderer.loader;
import com.jme.app.SimpleGame;
import com.jme.scene.shape.Box;
import com.jme.scene.shape.Sphere;
import com.jme.math.Vector3f;
import com.jme.math.Quaternion;
import com.jme.animation.SpatialTransformer;
import com.jme.bounding.BoundingBox;
import com.jme.bounding.BoundingSphere;
import com.jme.renderer.ColorRGBA;
public class TestSpatialTransformer extends SimpleGame{
public static void main(String[] args) {
new TestSpatialTransformer().start();
}
protected void simpleInitGame() {
Box b=new Box("box",new Vector3f(-1,-1,-1),new Vector3f(1,1,1));
for (int i=0;i<b.getVertQuantity();i++)
b.setColor(i,ColorRGBA.randomColor());
Sphere s=new Sphere("sphere",new Vector3f(0,0,5),10,10,1);
for (int i=0;i<s.getVertQuantity();i++)
s.setColor(i,ColorRGBA.randomColor());
SpatialTransformer st=new SpatialTransformer(2);
st.setObject(b,0,-1);
st.setObject(s,1,0);
Quaternion x0=new Quaternion();
x0.fromAngleAxis(0,new Vector3f(0,1,0));
Quaternion x90=new Quaternion();
x90.fromAngleAxis((float) (Math.PI/2),new Vector3f(0,1,0));
Quaternion x180=new Quaternion();
x180.fromAngleAxis((float) (Math.PI),new Vector3f(0,1,0));
Quaternion x270=new Quaternion();
x270.fromAngleAxis((float) (3*Math.PI/2),new Vector3f(0,1,0));
st.setRotation(0,0,x0);
st.setRotation(0,1,x90);
st.setRotation(0,2,x180);
st.setRotation(0,3,x270);
st.setRotation(0,4,x0);
st.setScale(0,0,new Vector3f(.5f,.5f,1));
st.setScale(0,2,new Vector3f(2,2,2));
st.setScale(0,4,new Vector3f(.5f,.5f,1));
st.setPosition(0,0,new Vector3f(0,10,0));
st.setPosition(0,2,new Vector3f(0,0,0));
st.setPosition(0,4,new Vector3f(0,10,0));
st.setPosition(1,0,new Vector3f(0,0,0));
st.setPosition(1,2,new Vector3f(0,0,-5));
st.setPosition(1,4,new Vector3f(0,0,0));
st.interpolateMissing();
b.addController(st);
b.setModelBound(new BoundingSphere());
b.updateModelBound();
s.setModelBound(new BoundingSphere());
s.updateModelBound();
rootNode.attachChild(b);
rootNode.attachChild(s);
lightState.detachAll();
}
}
|
package com.xrtb.bidder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.redisson.RedissonClient;
import org.redisson.core.MessageListener;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xrtb.commands.BasicCommand;
import com.xrtb.commands.ClickLog;
import com.xrtb.commands.ConvertLog;
import com.xrtb.commands.DeleteCreative;
import com.xrtb.commands.Echo;
import com.xrtb.commands.LogMessage;
import com.xrtb.commands.PixelClickConvertLog;
import com.xrtb.commands.PixelLog;
import com.xrtb.commands.ShutdownNotice;
import com.xrtb.common.Campaign;
import com.xrtb.common.Configuration;
import com.xrtb.common.ForensiqLog;
import com.xrtb.pojo.BidRequest;
import com.xrtb.pojo.BidResponse;
import com.xrtb.pojo.NobidResponse;
import com.xrtb.pojo.WinObject;
import com.xrtb.tools.Performance;
/**
* A class for handling REDIS based commands to the RTB server. The Controller
* open REDIS channels to the requested channels to handle commands, and logging
* channels for log messages, win notifications, bid requests and bids. The idea
* is to transmit all this information through REDIS so that you can\ build your
* own database, accounting, and analytic processes outside of the bidding
* engine.
*
* Another job of the Controller is to create the REDIS cache. There could be
* multiple bidders running in the infrastructure, but handling a win
* notification requires that you have information about the original bid. This
* means the system receiving the notification may not be the same system that
* made the bid. The bid is stored in the cache as a map so the win handling
* system can handle the win, even though it did not actually make the bid.
*
* @author Ben M. Faul
*
*/
public enum Controller {
INSTANCE;
/** Add campaign REDIS command id */
public static final int ADD_CAMPAIGN = 0;
/** Delete campaign REDIS command id */
public static final int DEL_CAMPAIGN = 1;
/** Stop the bidder REDIS command id */
public static final int STOP_BIDDER = 2;
/** Start the bidder REDIS command id */
public static final int START_BIDDER = 3;
/** The percentage REDIS command id */
public static final int PERCENTAGE = 4;
/** The echo status REDIS command id */
public static final int ECHO = 5;
/** The set log level command */
public static final int SETLOGLEVEL = 6;
/** The notice that bidder is terminating */
public static final int SHUTDOWNNOTICE = 7;
/** Set the no bid reason flag */
public static final int NOBIDREASON = 8;
/** Remove a creative */
public static final int DELETE_CREATIVE = 9;
/** The REDIS channel for sending commands to the bidders */
public static final String COMMANDS = "commands";
/** The REDIS channel the bidder sends command responses out on */
public static final String RESPONSES = "responses";
/** Publisher for commands */
static Publisher commandsQueue;
/** The JEDIS object for creating bid hash objects */
static JedisPool bidCachePool;
/** The loop object used for reading commands */
static CommandLoop loop;
/** The queue for posting responses on */
static Publisher responseQueue;
/** Queue used to send wins */
static Publisher winsQueue;
/** Queue used to send bids */
static Publisher bidQueue;
/** Queue used to send nobid responses */
static Publisher nobidQueue;
/** Queue used for requests */
static Publisher requestQueue;
/** Queue for sending log messages */
static LogPublisher loggerQueue;
/** Queue for sending clicks */
static ClicksPublisher clicksQueue;
/** Formatter for printing forensiqs messages */
static ForensiqsPublisher forensiqsQueue;
/** Formatter for printing log messages */
static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
/* The configuration object used bu the controller */
static Configuration config = Configuration.getInstance();
private static String password = "yabbadabbadoo";
/** A factory object for making timnestamps */
static final JsonNodeFactory factory = JsonNodeFactory.instance;
/**
* Private construcotr with specified hosts
*
* @throws Exception
* on REDIS errors.
*/
public static Controller getInstance() throws Exception {
/** the cache of bid adms */
if (bidCachePool == null) {
JedisPoolConfig cfg = new JedisPoolConfig();
cfg.setMaxTotal(1000);
bidCachePool = new JedisPool(cfg, Configuration.cacheHost,
Configuration.cachePort, 10000, Configuration.password);
commandsQueue = new Publisher(config.redisson, COMMANDS);
commandsQueue.getChannel().addListener(new CommandLoop());
responseQueue = new Publisher(config.redisson, RESPONSES);
if (config.REQUEST_CHANNEL != null) {
if (config.REQUEST_CHANNEL.startsWith("file:
requestQueue = new Publisher(config.REQUEST_CHANNEL);
else
requestQueue = new Publisher(config.redisson,config.REQUEST_CHANNEL);
}
if (config.WINS_CHANNEL != null)
winsQueue = new Publisher(config.redisson, config.WINS_CHANNEL);
if (config.BIDS_CHANNEL != null)
bidQueue = new Publisher(config.redisson, config.BIDS_CHANNEL);
if (config.NOBIDS_CHANNEL != null)
nobidQueue = new Publisher(config.redisson,
config.NOBIDS_CHANNEL);
if (config.LOG_CHANNEL != null)
loggerQueue = new LogPublisher(config.redisson,
config.LOG_CHANNEL);
if (config.CLICKS_CHANNEL != null) {
clicksQueue = new ClicksPublisher(config.redisson,
config.CLICKS_CHANNEL);
}
if (config.FORENSIQ_CHANNEL != null) {
forensiqsQueue = new ForensiqsPublisher(config.redisson,
config.FORENSIQ_CHANNEL);
}
}
return INSTANCE;
}
/**
* Simplest form of the add campaign
*
* @param c
* Campaign. The campaign to add.
* @throws Exception
* on redis errors.
*/
public void addCampaign(Campaign c) throws Exception {
Configuration.getInstance().deleteCampaign(c.owner, c.adId);
Configuration.getInstance().addCampaign(c);
}
/**
* Add a campaign from REDIS
*
* @param c
* BasiCommand. The command to add
* @throws Exception
* on REDIS errors.
*/
public void addCampaign(BasicCommand c) throws Exception {
System.out.println("ADDING " + c.owner + "/" + c.target);
Campaign camp = WebCampaign.getInstance().db.getCampaign(c.owner,
c.target);
BasicCommand m = new BasicCommand();
m.owner = c.owner;
m.to = c.from;
m.from = Configuration.getInstance().instanceName;
m.id = c.id;
m.type = c.type;
if (camp == null) {
m.status = "Error";
m.msg = "Campaign load failed, could not find " + c.owner + "/"
+ c.target;
responseQueue.add(m);
} else {
System.out.println("
Configuration.getInstance().deleteCampaign(camp.owner, camp.adId);
Configuration.getInstance().addCampaign(camp);
// System.out.println(camp.toJson());
m.msg = "Campaign " + camp.owner + "/" + camp.adId + " loaded ok";
m.name = "AddCampaign Response";
sendLog(1, "AddCampaign", m.msg + " by " + c.owner);
responseQueue.add(m);
}
System.out.println(m.msg);
}
/**
* Delete a campaign.
*
* @param id
* String. The Map of this command.
* @throws Exception
* if there is a JSON parse error.
*/
public void deleteCampaign(String owner, String name) throws Exception {
Configuration.getInstance().deleteCampaign(owner, name);
}
/**
* From REDIS delete campaign
*
* @param cmd
* BasicCommand. The delete command
*/
public void deleteCampaign(BasicCommand cmd) throws Exception {
boolean b = Configuration.getInstance().deleteCampaign(cmd.owner,
cmd.target);
BasicCommand m = new BasicCommand();
if (!b) {
m.msg = "error, no such campaign " + cmd.owner + "/" + cmd.target;
m.status = "error";
} else
m.msg = "Campaign deleted: " + cmd.owner + "/" + cmd.target;
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.type = cmd.type;
m.name = "DeleteCommand Response";
responseQueue.add(m);
if (cmd.name == null) {
Configuration.getInstance().campaignsList.clear();
this.sendLog(1, "deleteCampaign", "All campaigns cleared by "
+ cmd.from);
} else
this.sendLog(1, "DeleteCampaign", cmd.msg + " by " + cmd.owner);
}
/**
* Stop the bidder from REDIS
*
* @param cmd
* BasicCommand. The command as a map.
* @throws Exception
* if there is a JSON parsing error.
*/
public void stopBidder(BasicCommand cmd) throws Exception {
RTBServer.stopped = true;
BasicCommand m = new BasicCommand();
m.msg = "stopped";
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.type = cmd.type;
m.name = "StopBidder Response";
responseQueue.add(m);
this.sendLog(1, "stopBidder", "Bidder stopped by command from "
+ cmd.from);
}
/**
* Start the bidder from REDIS
*
* @param cmd
* BasicCmd. The command.
* @throws Exception
* if there is a JSON parsing error.
*/
public void startBidder(BasicCommand cmd) throws Exception {
if (Configuration.deadmanSwitch != null) {
if (Configuration.deadmanSwitch.canRun() == false) {
BasicCommand m = new BasicCommand();
m.msg = "Error, the deadmanswitch is not present";
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.type = cmd.type;
m.name = "StartBidder Response";
responseQueue.add(m);
this.sendLog(1, "startBidder",
"Error: attempted start bidder by command from "
+ cmd.from + " failed, deadmanswitch is thrown");
return;
}
}
RTBServer.stopped = false;
BasicCommand m = new BasicCommand();
m.msg = "running";
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.type = cmd.type;
m.name = "StartBidder Response";
responseQueue.add(m);
this.sendLog(1, "startBidder", "Bidder started by command from "
+ cmd.from);
}
/**
* Set the throttle percentage from REDIS
*
* @param node
* . JsoNode - JSON of the command. TODO: this needs
* implementation.
*/
public void setPercentage(JsonNode node) {
responseQueue.add(new BasicCommand());
}
/**
* Retrieve a member RTB status from REDIS
*
* @param member
* String. The member's instance name.
* @return Map. A Hash,ap of data.
*/
public Map getMemberStatus(String member) {
Map values = new HashMap();
Map<String, String> m = null;
Response<Map<String, String>> response = null;
Jedis bidCache = bidCachePool.getResource();
m = bidCache.hgetAll(member);
if (m != null) {
if (m.get("total") != null)
values.put("total", Long.parseLong(m.get("total")));
else
values.put("total",0);
if (m.get("request") != null)
values.put("request", Long.parseLong((m.get("request"))));
else
values.put("request", 0);
if (m.get("bid") !=null)
values.put("bid", Long.parseLong((m.get("bid"))));
else
values.put("bid", 0);
if (m.get("nobid")!= null)
values.put("nobid", Long.parseLong((m.get("nobid"))));
else
values.put("nobid", 0);
if (m.get("win") != null)
values.put("win", Long.parseLong((m.get("win"))));
else
values.put("win", 0);
if (m.get("clicks") != null)
values.put("clicks", Long.parseLong((m.get("clicks"))));
else
values.put("clicks", 0);
if (m.get("pixels") != null)
values.put("pixels", Long.parseLong((m.get("pixels"))));
else
values.put("pixels", 0);
if (m.get("errors") != null)
values.put("errors", Long.parseLong((m.get("errors"))));
else
values.put("error", 0);
if (m.get("adspend") != null)
values.put("adspend", m.get("adspend"));
else
values.put("adspend", 0);
if (m.get("qps") != null)
values.put("qps", m.get("qps"));
else
values.put("qps", 0);
if (m.get("avgx") != null)
values.put("avgx", m.get("avgx"));
else
values.put("avgx", 0);
if (m.get("fraud") != null)
values.put("fraud", m.get("fraud"));
else
values.put("fraud", 0);
values.put("stopped", RTBServer.stopped);
values.put("ncampaigns",
Configuration.getInstance().campaignsList.size());
values.put("loglevel", Configuration.getInstance().logLevel);
values.put("nobidreason",
Configuration.getInstance().printNoBidReason);
}
bidCachePool.returnResourceObject(bidCache);
return values;
}
/**
* Record the member stats in REDIS
*
* @param e
* Echo. The status of this campaign.
*/
public void setMemberStatus(Echo e) {
String member = Configuration.getInstance().instanceName;
Jedis bidCache = bidCachePool.getResource();
Pipeline p = bidCache.pipelined();
try {
p.hset(member, "total", "" + e.handled);
p.hset(member, "request", "" + e.request);
p.hset(member, "bid", "" + e.bid);
p.hset(member, "nobid", "" + e.nobid);
p.hset(member, "win", "" + e.win);
p.hset(member, "clicks", "" + e.clicks);
p.hset(member, "pixels", "" + e.pixel);
p.hset(member, "errors", "" + e.error);
p.hset(member, "adspend", "" + e.adspend);
p.hset(member, "qps", "" + e.qps);
p.hset(member, "avgx", "" + e.avgx);
p.hset(member, "fraud", "" + e.fraud);
p.hset(member, "time", "" + System.currentTimeMillis());
p.hset(member, "cpu", Performance.getCpuPerfAsString());
p.hset(member, "diskpctfree", Performance.getPercFreeDisk());
p.hset(member, "threads", ""+Performance.getThreadCount());
p.hset(member, "cores", ""+Performance.getCores());
p.hset(member, "stopped", "" + RTBServer.stopped);
p.hset(member, "ncampaigns", ""
+ Configuration.getInstance().campaignsList.size());
p.hset(member, "loglevel", ""
+ Configuration.getInstance().logLevel);
p.hset(member, "nobidreason", ""
+ Configuration.getInstance().printNoBidReason);
p.expire(member,RTBServer.PERIODIC_UPDATE_TIME/1000+15);
p.exec();
} catch (Exception error) {
} finally {
p.sync();
}
bidCachePool.returnResourceObject(bidCache);
}
/**
* THe echo command and its response.
*
* @param cmd
* BasicCommand. The command used
* @throws Exception
* if there is a JSON parsing error.
*/
public void echo(BasicCommand cmd) throws Exception {
Echo m = RTBServer.getStatus();
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.name = "Echo Response";
responseQueue.add(m);
}
/**
* Send a shutdown notice to all concerned!
*
* @throws Exception
* on Redisson errors.
*/
public void sendShutdown() throws Exception {
ShutdownNotice cmd = new ShutdownNotice(
Configuration.getInstance().instanceName);
responseQueue.writeFast(cmd);
}
public void setLogLevel(BasicCommand cmd) throws Exception {
int old = Configuration.getInstance().logLevel;
Configuration.getInstance().logLevel = Integer.parseInt(cmd.target);
Echo m = RTBServer.getStatus();
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.msg = "Log level changed from " + old + " to " + cmd.target;
m.name = "SetLogLevel Response";
responseQueue.add(m);
this.sendLog(1, "setLogLevel", m.msg + ", by " + cmd.from);
}
/**
* This will whack a creative out of a campaign. This stops the bidding on
* it
*
* @param cmd
* BasicCommand. The command.
* @throws Exception
*/
public void deleteCreative(DeleteCreative cmd) throws Exception {
String owner = cmd.owner;
String campaignid = cmd.name;
String creativeid = cmd.target;
Echo m = RTBServer.getStatus();
m.owner = cmd.owner;
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
try {
Configuration.getInstance().deleteCampaignCreative(owner,
campaignid, creativeid);
m.msg = "Delete campaign creative " + owner + "/" + campaignid
+ "/" + creativeid + " succeeded";
} catch (Exception error) {
m.msg = "Delete campaign creative " + owner + "/" + campaignid
+ "/" + creativeid + " failed, reason: "
+ error.getMessage();
}
m.name = "DeleteCampaign Response";
responseQueue.add(m);
this.sendLog(1, "setLogLevel", m.msg + ", by " + cmd.from);
}
public void setNoBidReason(BasicCommand cmd) throws Exception {
boolean old = Configuration.getInstance().printNoBidReason;
Configuration.getInstance().printNoBidReason = Boolean
.parseBoolean(cmd.target);
Echo m = RTBServer.getStatus();
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.msg = "Print no bid reason level changed from " + old + " to "
+ cmd.target;
m.name = "SetNoBidReason Response";
responseQueue.add(m);
this.sendLog(1, "setNoBidReason", m.msg + ", by " + cmd.from);
}
/*
* The not handled response to the command entity. Used when an unrecognized
* command is sent.
*
* @param cmd. BasicCommand - the error message.
*
* @throws Exception if there is a JSON parsing error.
*/
public void notHandled(BasicCommand cmd) throws Exception {
Echo m = RTBServer.getStatus();
m.msg = "error, unhandled event";
m.status = "error";
m.to = cmd.from;
m.from = Configuration.getInstance().instanceName;
m.id = cmd.id;
m.name = "Unhandled Response";
responseQueue.add(m);
}
/**
* Sends an RTB request out on the appropriate REDIS queue
*
* @param br
* BidRequest. The request
*/
public void sendRequest(BidRequest br) {
if (requestQueue != null) {
ObjectNode original = (ObjectNode) br.getOriginal();
ObjectNode child = factory.objectNode();
child.put("timestamp", System.currentTimeMillis());
child.put("exchange", br.exchange);
original.put("ext", child);
requestQueue.add(original);
}
}
/**
* Sends an RTB bid out on the appropriate REDIS queue
*
* @param bid
* BidResponse. The bid
*/
public void sendBid(BidResponse bid) {
if (bidQueue != null)
bidQueue.add(bid);
}
/**
* Channel to send no bid information
*
* @param nobid
* NobidResponse. Info about the no bid
*/
public void sendNobid(NobidResponse nobid) {
if (nobidQueue != null)
nobidQueue.add(nobid);
}
/**
* Sends an RTB win out on the appropriate REDIS queue
*
* @param hash
* String. The bid id.
* @param cost
* String. The cost component of the win.
* @param lat
* String. The latitude component of the win.
* @param lon
* String. The longitude component of the win.
* @param adId
* String. The campaign adid of this win.
* @param cridId
* String. The creative id of this win.
* @param pubId
* String. The publisher id component of this win/
* @param image
* String. The image part of the win.
* @param forward
* String. The forward URL of the win.
* @param price
* String. The bid price of the win.
* @param adm
* String. the adm that was returned on the win notification. If
* null, it means nothing was returned.
*/
public void sendWin(String hash, String cost, String lat, String lon,
String adId, String cridId, String pubId, String image,
String forward, String price, String adm) {
if (winsQueue != null)
winsQueue.add(new WinObject(hash, cost, lat, lon, adId, cridId,
pubId, image, forward, price, adm));
}
/**
* Sends a log message on the appropriate REDIS queue
*
* @param level
* int. The log level of this message.
* @param field
* String. An identification field for this message.
* @param msg
* String. The JSON of the message
*/
public void sendLog(int level, String field, String msg) {
int checkLog = config.logLevel;
if (checkLog < 0)
checkLog = -checkLog;
if (level > checkLog)
return;
if (loggerQueue == null)
return;
LogMessage ms = new LogMessage(level, config.instanceName, field, msg);
if (checkLog >= level && config.logLevel < 0) {
System.out.format("[%s] - %d - %s - %s - %s\n",
sdf.format(new Date()), ms.sev, ms.source, ms.field,
ms.message);
}
loggerQueue.add(ms);
}
/**
* Send click info.
*
* @param target
* String. The URI of this click data
*/
public void publishClick(String target) {
if (clicksQueue != null) {
ClickLog log = new ClickLog(target);
clicksQueue.add(log);
}
}
/**
* Send pixel info. This fires when the ad actually loads into the users web
* page.
*
* @param target
* String. The URI of this pixel data
*/
public void publishPixel(String target) {
if (clicksQueue != null) {
PixelLog log = new PixelLog(target);
clicksQueue.add(log);
}
}
public void publishFraud(ForensiqLog m) {
if (forensiqsQueue != null) {
forensiqsQueue.add(m);
}
}
/**
* Send pixel info. This fires when the ad actually loads into the users web
* page.
*
* @param target
* String. The URI of this pixel data
*/
public void publishConvert(String target) {
if (clicksQueue != null) {
ConvertLog log = new ConvertLog(target);
clicksQueue.add(log);
}
}
/**
* Record a bid in REDIS
*
* @param br
* BidResponse. The bid response that we made earlier.
* @throws Exception
* on redis errors.
*/
public void recordBid(BidResponse br) throws Exception {
Map m = new HashMap();
Jedis bidCache = bidCachePool.getResource();
Pipeline p = bidCache.pipelined();
m.put("ADM", br.getAdmAsString());
m.put("PRICE", "" + br.creat.price);
if (br.capSpec != null) {
m.put("SPEC", br.capSpec);
m.put("EXPIRY", br.creat.capTimeout);
}
try {
p.hmset(br.oidStr, m);
p.sync();
p.expire(br.oidStr, Configuration.getInstance().ttl);
p.sync();
} catch (Exception error) {
error.printStackTrace();
} finally {
}
bidCachePool.returnResourceObject(bidCache);
}
public int getCapValue(String capSpec) {
Response<String> response = null;
Jedis bidCache = bidCachePool.getResource();
Pipeline p = bidCache.pipelined();
try {
response = p.get(capSpec);
p.exec();
} catch (Exception error) {
} finally {
p.sync();
}
String s = response.get();
bidCachePool.returnResourceObject(bidCache);
if (s == null) {
return -1;
}
return Integer.parseInt(s);
}
/**
* Remove a bid object from the cache.
*
* @param hash
* String. The bid object id.
*/
public void deleteBidFromCache(String hash) {
Response<Map<String, String>> response = null;
Map<String, String> map = null;
Jedis bidCache = bidCachePool.getResource();
try {
Pipeline p = bidCache.pipelined();
response = p.hgetAll(hash);
p.sync();
if (response != null) {
map = response.get();
String capSpec = map.get("SPEC");
if (capSpec != null) {
String s = map.get("EXPIRY");
int n = Integer.parseInt(s);
Response<Long> r = p.incr(capSpec);
p.sync();
if (r.get() == 1) {
p.expire(capSpec, n);
p.sync();
}
}
}
p.del(hash);
p.sync();
} catch (Exception error) {
} finally {
}
bidCachePool.returnResourceObject(bidCache);
}
/**
* Retrieve previously recorded bid data
*
* @param oid
* String. The object id of the bid.
* @return Map. A map of the returned data, will be null if not found.
*/
public Map getBidData(String oid) {
Map m = null;
Response r = null;
Jedis bidCache = bidCachePool.getResource();
m = bidCache.hgetAll(oid);
bidCachePool.returnResourceObject(bidCache);
return m;
}
}
/**
* A class to retrieve RTBServer commands from REDIS.
*
*
* @author Ben M. Faul
*
*/
class CommandLoop implements MessageListener<BasicCommand> {
/** The thread this command loop uses to process REDIS subscription messages */
/** The configuration object */
Configuration config = Configuration.getInstance();
/**
* On a message from REDIS, handle the command.
*
* @param arg0
* . String - the channel of this message.
* @param arg1
* . String - the JSON encoded message.
*/
@Override
public void onMessage(String arg0, BasicCommand item) {
try {
if (item.to != null && (item.to.equals("*") == false)) {
boolean mine = Configuration.getInstance().instanceName
.matches(item.to);
if (item.to.equals("") == false && !mine) {
Controller.getInstance().sendLog(5,
"Controller:onMessage:" + item,
"Message was not for me: " + item);
return;
}
}
} catch (Exception error) {
try {
Echo m = new Echo();
m.from = Configuration.getInstance().instanceName;
m.to = item.from;
m.id = item.id;
m.status = "error";
m.msg = error.toString();
Controller.getInstance().responseQueue.add(m);
Controller.getInstance().sendLog(1,
"Controller:onMessage:" + item,
"Error: " + error.toString());
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
}
try {
Runnable task = null;
Thread thread;
switch (item.cmd) {
case Controller.ADD_CAMPAIGN:
task = () -> {
try {
Controller.getInstance().addCampaign(item);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
thread = new Thread(task);
thread.start();
break;
case Controller.DEL_CAMPAIGN:
task = () -> {
try {
Controller.getInstance().deleteCampaign(item);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
thread = new Thread(task);
thread.start();
break;
case Controller.STOP_BIDDER:
Controller.getInstance().stopBidder(item);
break;
case Controller.START_BIDDER:
Controller.getInstance().startBidder(item);
break;
case Controller.ECHO:
Controller.getInstance().echo(item);
break;
case Controller.SETLOGLEVEL:
Controller.getInstance().setLogLevel(item);
break;
case Controller.DELETE_CREATIVE:
Controller.getInstance().deleteCreative((DeleteCreative) item);
break;
default:
Controller.getInstance().notHandled(item);
}
} catch (Exception error) {
try {
item.msg = error.toString();
item.to = item.from;
item.from = Configuration.getInstance().instanceName;
item.status = "error";
Controller.getInstance().responseQueue.add(item);
error.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
error.printStackTrace();
}
}
}
/**
* A type of Publisher, but used specifically for clicks logging, contains the
* instance name and the current time in EPOCH.
*
* @author Ben M. Faul
*
*/
class ClicksPublisher extends Publisher {
/**
* Constructor for clicls publisher class.
*
* @param conn
* Jedis. The REDIS connection.
* @param channel
* String. The topic name to publish on.
*/
public ClicksPublisher(RedissonClient redisson, String channel)
throws Exception {
super(redisson, channel);
}
/**
* Process, pixels, clicks, and conversions
*/
@Override
public void run() {
PixelClickConvertLog event = null;
while (true) {
try {
if ((event = (PixelClickConvertLog) queue.poll()) != null) {
logger.publishAsync(event);
}
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
}
class ForensiqsPublisher extends Publisher {
/**
* Constructor for clicls publisher class.
*
* @param conn
* Jedis. The REDIS connection.
* @param channel
* String. The topic name to publish on.
*/
public ForensiqsPublisher(RedissonClient redisson, String channel)
throws Exception {
super(redisson, channel);
}
/**
* Process, pixels, clicks, and conversions
*/
@Override
public void run() {
ForensiqLog event = null;
while (true) {
try {
if ((event = (ForensiqLog) queue.poll()) != null) {
logger.publishAsync(event);
}
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
}
|
package com.bazaarvoice.jolt;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonUtils {
public static Object cloneJson(Object json) {
// deep copy a map:
if (json instanceof Map ) {
Map<String, Object> jsonMap = (Map<String, Object>) json;
Map retvalue = new HashMap();
for (String key: jsonMap.keySet()) {
retvalue.put( key, cloneJson( jsonMap.get( key ) ) );
}
return retvalue;
}
// deep copy a list
if (json instanceof List ) {
List jsonList = (List) json;
List retvalue = new ArrayList( jsonList.size() );
for (Object sub: jsonList) {
retvalue.add( cloneJson( sub ) );
}
return retvalue;
}
// string, number, null doesn't need copying
return json;
}
/**
* Removes a key recursively from anywhere in a JSON document.
* NOTE: mutates its input.
*
* @param json the Jackson Object version of the JSON document
* (contents changed by this call)
* @param keyToRemove the key to remove from the document
*/
public static void removeRecursive(Object json, String keyToRemove) {
if ((json == null) || (keyToRemove == null)) {
return;
}
if (json instanceof Map) {
Map<String, Object> jsonMap = (Map<String, Object>) json;
jsonMap.remove( keyToRemove );
for (String subkey: jsonMap.keySet()) {
Object value = jsonMap.get( subkey );
removeRecursive( value, keyToRemove );
}
}
if (json instanceof List) {
for (Object value: (List) json) {
removeRecursive( value, keyToRemove );
}
}
}
public static Map<String, Object> jsonToMap(String json)
throws IOException {
return jsonToMap( new ByteArrayInputStream( json.getBytes() ) );
}
public static Object jsonToObject(String json)
throws IOException {
return jsonToObject( new ByteArrayInputStream( json.getBytes() ) );
}
private static final ObjectMapper OBJECT_MAPPER;
static {
JsonFactory factory = new JsonFactory();
OBJECT_MAPPER = new ObjectMapper(factory);
}
public static Object jsonToObject(InputStream in)
throws IOException {
return OBJECT_MAPPER.readValue(in, Object.class);
}
public static Map<String, Object> jsonToMap(InputStream in)
throws IOException {
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> o = OBJECT_MAPPER.readValue(in, typeRef);
return o;
}
public static <T> T jsonTo(InputStream in, TypeReference<T> typeRef)
throws IOException {
return OBJECT_MAPPER.readValue(in, typeRef);
}
public static String toJsonString(Object map)
throws IOException {
return OBJECT_MAPPER.writeValueAsString( map );
}
}
|
package org.videolan;
import java.awt.Container;
import java.awt.EventQueue;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.microedition.xlet.UnavailableContainerException;
import org.dvb.application.AppID;
import org.dvb.application.AppProxy;
import org.dvb.application.AppsDatabase;
import org.havi.ui.HSceneFactory;
import org.videolan.bdjo.AppCache;
import org.videolan.bdjo.AppEntry;
public class BDJXletContext implements javax.tv.xlet.XletContext, javax.microedition.xlet.XletContext {
public BDJXletContext(AppEntry entry, AppCache[] caches, Container container) {
this.appid = entry.getIdentifier();
this.args = entry.getParams();
this.loader = BDJClassLoader.newInstance(
caches,
entry.getBasePath(),
entry.getClassPathExt(),
entry.getInitialClass());
this.container = container;
this.threadGroup = new BDJThreadGroup(Integer.toHexString(appid.getOID()) + "." +
Integer.toHexString(appid.getAID()) + "." +
entry.getInitialClass(),
this);
}
public Object getXletProperty(String key) {
if (key.equals(javax.tv.xlet.XletContext.ARGS) ||
key.equals(javax.microedition.xlet.XletContext.ARGS))
return args;
else if (key.equals("dvb.org.id"))
return Integer.toHexString(appid.getOID());
else if (key.equals("dvb.app.id"))
return Integer.toHexString(appid.getAID());
else if (key.equals("org.dvb.application.appid"))
return appid;
return null;
}
public void notifyDestroyed() {
AppProxy proxy = AppsDatabase.getAppsDatabase().getAppProxy(appid);
if (proxy instanceof BDJAppProxy)
((BDJAppProxy)proxy).notifyDestroyed();
}
public void notifyPaused() {
AppProxy proxy = AppsDatabase.getAppsDatabase().getAppProxy(appid);
if (proxy instanceof BDJAppProxy)
((BDJAppProxy)proxy).notifyPaused();
}
public void resumeRequest() {
AppProxy proxy = AppsDatabase.getAppsDatabase().getAppProxy(appid);
if (proxy instanceof BDJAppProxy)
((BDJAppProxy)proxy).resume();
}
public Container getContainer() throws UnavailableContainerException {
if (container == null) {
logger.error("getContainer(): container is null");
throw new UnavailableContainerException();
}
return container;
}
public ClassLoader getClassLoader() {
return loader;
}
public BDJThreadGroup getThreadGroup() {
return threadGroup;
}
protected void setEventQueue(EventQueue eq) {
eventQueue = eq;
}
public EventQueue getEventQueue() {
return eventQueue;
}
protected int numEventQueueThreads() {
int cnt = 0;
if (eventQueue != null) {
Thread t = java.awt.BDJHelper.getEventDispatchThread(eventQueue);
if (t != null && t.isAlive()) {
cnt++;
}
}
return cnt;
}
public void setSceneFactory(HSceneFactory f) {
sceneFactory = f;
}
public HSceneFactory getSceneFactory() {
return sceneFactory;
}
public static BDJXletContext getCurrentContext() {
Object obj = AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
while ((group != null) && !(group instanceof BDJThreadGroup))
group = group.getParent();
return group;
}
}
);
if (obj == null)
return null;
return ((BDJThreadGroup)obj).getContext();
}
protected void setArgs(String[] args) {
this.args = args;
}
protected void update(AppEntry entry, AppCache[] caches) {
args = entry.getParams();
loader.update(
caches,
entry.getBasePath(),
entry.getClassPathExt(),
entry.getInitialClass());
}
protected void release() {
if (sceneFactory != null) {
sceneFactory.dispose();
sceneFactory = null;
}
EventQueue eq = eventQueue;
eventQueue = null;
if (eq != null) {
java.awt.BDJHelper.stopEventQueue(eq);
}
container = null;
}
private String[] args;
private AppID appid;
private BDJClassLoader loader;
private Container container;
private EventQueue eventQueue = null;
private HSceneFactory sceneFactory = null;
private BDJThreadGroup threadGroup = null;
private static final Logger logger = Logger.getLogger(BDJXletContext.class.getName());
}
|
package com.bradcypert.ginger;
import com.bradcypert.ginger.helpers.RequestHelpers;
import spark.Response;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import static spark.Spark.*;
public class Resource {
private Class resourceClass;
private ArrayList<String> exposedProperties;
private ArrayList<String> methods;
public Resource(Class clazz) {
this.resourceClass = clazz;
this.exposedProperties = new ArrayList<String>();
this.methods = new ArrayList<String>();
generateExposedProperties();
generateResourceMethods();
}
private void generateExposedProperties() {
Field[] fields = this.resourceClass.getDeclaredFields();
Arrays.asList(fields).forEach(field ->
Arrays.asList(field.getDeclaredAnnotations()).forEach(annotation -> {
if(annotation.toString().endsWith("ginger.Exposed()")){
System.out.println(field.getName());
this.exposedProperties.add(field.getName());
}
})
);
}
private void generateResourceMethods() {
Annotation[] annotations = this.resourceClass.getAnnotations();
Arrays.asList(annotations).forEach(annotation ->
Arrays.asList(((Methods) annotation).value()).forEach(value -> this.methods.add(value))
);
}
public void generateRoutes() {
String name = this.resourceClass.getSimpleName().toLowerCase();
for(String method: this.methods){
switch(method){
case "GET":
get("/"+name+"/:id", this::handleGet);
break;
case "PUT":
put("/"+name+"/", this::handlePut);
break;
case "DELETE":
delete("/"+name+"/", this::handleDelete);
break;
case "POST":
post("/" + name + "/", this::handlePost);
}
}
}
private String handleGet(spark.Request request, Response response) throws Exception {
Method fetch = this.resourceClass.getMethod("fetch");
return (String) fetch.invoke(this.resourceClass.newInstance());
}
private String handlePut(spark.Request request, Response response) {
return "";
}
private String handleDelete(spark.Request request, Response response) {
return "";
}
private String handlePost(spark.Request request, Response response) throws Exception {
if(!this.exposedProperties.isEmpty() && !RequestHelpers.containsParams(request, this.exposedProperties)){
response.status(400);
return "{error: 'missing required parameters'}";
} else {
Method save = this.resourceClass.getMethod("save");
PropertyMap map = new PropertyMap(request, this.exposedProperties);
response.status(201);
return (String) save.invoke(this.resourceClass.newInstance());
}
}
}
|
package common.graph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* <p>A base class for implementations of the Graph interface.</p>
* @author fiveham
* @author fiveham
*
* @param <T> the type of the vertices of this Graph
* @param <T> the type of the vertices of this Graph@param <T> the type of the vertices of this
* @param <T> the type of the vertices of this GraphGraph
*/
public abstract class AbstractGraph<T extends Vertex<T>> implements Graph<T>{
/**
* <p>The backing collection of vertices in this Graph.</p>
*/
protected final ArrayList<T> nodes;
/**
* <p>The list of connected-component contraction event-listeners for this Graph.</p>
*/
protected final List<Supplier<Consumer<Set<T>>>> contractEventListenerFactories;
/**
* <p>Constructs an AbstractGraph with an empty list of vertices and an empty list of
* connected-component contraction event-listeners.</p>
*/
public AbstractGraph() {
nodes = new ArrayList<>();
contractEventListenerFactories = new ArrayList<>();
}
/**
* <p>Constructs an AbstractGraph whose backing collection of vertices is initialized empty but
* with a capacity of {@code size}.</p>
* @param size the capacity which the backing collection of vertices will have
*/
public AbstractGraph(int size) {
nodes = new ArrayList<>(size);
contractEventListenerFactories = new ArrayList<>();
}
/**
* <p>Constructs an AbstractGraph having the elements of {@code coll} as vertices.</p>
* @param coll vertices for this Graph
*/
public AbstractGraph(Collection<? extends T> coll){
nodes = new ArrayList<>(coll);
contractEventListenerFactories = new ArrayList<>();
}
/**
* <p>Constructs an AbstractGraph having the elements of {@code coll} as vertices and having all
* the elements of {@code factories} as event-listener sources.</p>
* @param coll vertices for this Graph
* @param factories connected-component contraction event-listers for this Graph
*/
public AbstractGraph(Collection<? extends T> coll, List<Supplier<Consumer<Set<T>>>> factories) {
nodes = new ArrayList<>(coll);
contractEventListenerFactories = new ArrayList<>(factories);
}
/**
* <p>Add to {@code contractEventListenerFactories} the specified object that supplies a list of
* event-listeners for when a ConnectedComponent
* {@link ConnectedComponent#contract() contracts}.</p>
* @param newEL an event-listener
* @return this Graph
*/
@Override
public Graph<T> addGrowthListenerFactory(Supplier<Consumer<Set<T>>> newEL){
contractEventListenerFactories.add(newEL);
return this;
}
@Override
public int size(){
return nodes.size();
}
@Override
public Iterator<T> iterator(){
return nodes.iterator();
}
@Override
public Stream<T> nodeStream(){
return nodes.stream();
}
private final Function<List<T>, T> STD_CONCOM_SEED_SRC =
(unassigned) -> unassigned.remove(unassigned.size()-1);
@Override
public Collection<Graph<T>> connectedComponents(){
return connectedComponents(growthListeners(), STD_CONCOM_SEED_SRC);
}
@Override
public Collection<Graph<T>> connectedComponents(List<Consumer<Set<T>>> contractEventListenerSrc,
Function<List<T>,T> seedSrc){
List<Graph<T>> result = new ArrayList<>();
List<T> unassignedNodes = new ArrayList<>(nodes);
while( !unassignedNodes.isEmpty() ){
Graph<T> component = component(unassignedNodes, seedSrc, contractEventListenerSrc);
result.add(component);
}
return result;
}
@Override
public Graph<T> component(
List<T> unassignedNodes,
Function<List<T>,T> seedSrc,
List<Consumer<Set<T>>> contractEventListeners){
ConnectedComponent<T> newComponent = new ConnectedComponent<T>(
nodes.size(),
unassignedNodes, contractEventListeners);
{
int initUnassignedCount = unassignedNodes.size();
T seed = seedSrc.apply(unassignedNodes);
if(unassignedNodes.size() == initUnassignedCount){
unassignedNodes.remove(seed);
}
newComponent.add(seed); //seed now in cuttingEdge
}
while(!newComponent.cuttingEdgeIsEmpty()){
newComponent.contract(); //move cuttingEdge into edge and old edge into core
newComponent.grow(); //add unincorporated nodes to cuttingEdge
}
return new BasicGraph<T>(newComponent.contract());
}
/**
* <p>Returns a list of objects that will respond to a ConnectedComponent
* {@link ConnectedComponent#contract() contracting} to move its vertices inward toward its
* core. The returned list contains all the contents of all the lists produced by the individual
* event-listener factories in {@code contractEventListenerFactories}.</p>
* @return
*/
@Override
public List<Consumer<Set<T>>> growthListeners(){
List<Consumer<Set<T>>> result = new ArrayList<>();
for(Supplier<Consumer<Set<T>>> contractEventListenerFactory : contractEventListenerFactories){
result.add(contractEventListenerFactory.get());
}
return result;
}
@Override
public int distance(T v1, T v2){
int index1 = nodes.indexOf(v1);
int index2 = nodes.indexOf(v2);
if( index1 < 0 || index2 < 0 ){
throw new IllegalArgumentException(
"At least one of the specified nodes is not in this graph.");
}
if(index1 == index2){
return 0;
}
final boolean[][] adjacencyMatrix = new boolean[nodes.size()][nodes.size()];
for(int i = 0; i < nodes.size(); ++i){
for(int j = 0; j < i; ++j){
adjacencyMatrix[i][j] =
adjacencyMatrix[j][i] =
nodes.get(i).neighbors().contains(nodes.get(j));
}
adjacencyMatrix[i][i] = false;
}
//adjacency matrix raised to a power (initially the power of 1)
boolean[][] adjPower = new boolean[nodes.size()][nodes.size()];
for(int i = 0; i < adjPower.length; ++i){
adjPower[i] = Arrays.copyOf(adjacencyMatrix[i], adjacencyMatrix.length);
}
for(int n = 1; n<nodes.size(); ++n){
if(adjPower[index1][index2]){
return n;
} else{
adjPower = times(adjPower, adjacencyMatrix);
}
}
return NO_CONNECTION;
}
public static final int NO_CONNECTION = -1;
/**
* <p>Matrix-multiplies the specified boolean matrices under the assumption that they are both
* symmetrical about the main diagonal and that they are both square and both have the same
* dimensions, all of which will be true for all calls to this method because method is private
* and is called from only one place, where those assumptions hold true.</p> <p>Since the
* elements of the matrices involved are boolean values instead of numbers, the operations of
* (scalar) multiplication and addition used in combining the elements of matrices whose
* elements are numbers when multiplying those matrices are replaced here with {@code and (&&)}
* and {@code or (||)}.</p>
* @param a a square symmetrical matrix of boolean values
* @param b a square symmetrical matrix of boolean values
* @return a square symmetrical matrix of boolean values corresponding to the matrix-product of
* {@code a} and {@code b}
*/
private boolean[][] times(boolean[][] a, boolean[][] b){
boolean[][] result = new boolean[a.length][a.length];
for(int i = 0; i < nodes.size(); ++i){
for(int j = 0; j < i; ++j){
result[i][j] = result[j][i] = dot(a[j], b[i]);
}
result[i][i] = dot(a[i], b[i]);
}
return result;
}
/**
* <p>Returns the dot product of two boolean vectors. Assumes that {@code a} and {@code b} are
* the same length. The operations of multiplication and addition used in calculating the dot
* product of two numerical vectors are replaced with {@code and (&&)} and {@code or (||)}
* respectively.</p>
* @param a a vector
* @param b a vector
* @return the boolean dot product of two boolean vectors
*/
private boolean dot(boolean[] a, boolean[] b){
for(int i = 0; i < a.length; ++i){
if(a[i] && b[i]){
return true;
}
}
return false;
}
/**
* <p>Determines the distance between vertices {@code t1} and {@code t2} if both are in this
* graph and in the same connected component by building a connected component around
* {@code t1}.</p>
* @param t1 a vertex in this Graph
* @param t2 a vertex in this Graph
* @return the distance between {@code t1} and {@code t2} in this Graph, or -1 if there is no
* path connecting them
*/
public int distance2(final T t1, final T t2){
if(!nodes.contains(t1) || !nodes.contains(t2)){
throw new IllegalArgumentException("At least one of the specified Nodes is not in this graph.");
}
if(t1 == t2){
return 0;
}
class DistFinder implements Consumer<Set<T>>{
int dist = 0;
boolean foundTarget = false;
@Override
public void accept(Set<T> cuttingEdge){
if(!foundTarget){
if(cuttingEdge.contains(t2)){
foundTarget = true;
} else{
++dist;
}
}
}
};
DistFinder distFinder = new DistFinder();
component(new ArrayList<>(nodes), (list) -> t1, Collections.singletonList(distFinder));
return distFinder.dist;
}
@Override
public List<T> path(T t1, T t2){
//reverse args so parent-path goes in order from t1 to t2
Branch implicitPath = findPath(t2, t1);
List<T> result = new ArrayList<>();
for(Branch pointer = implicitPath; pointer != null; pointer = pointer.parent){
result.add(pointer.wrapped);
}
return result;
}
private Branch findPath(T to, T from){
if(!(nodes.contains(to) && nodes.contains(from))){
throw new IllegalStateException(to + " and/or " + from + " not present in this graph");
}
Set<Branch> cuttingEdge = new HashSet<>();
Branch init = new Branch(to, null);
if(to.equals(from)){
return init;
} else{
cuttingEdge.add(init);
}
Set<Branch> edge = new HashSet<>();
Set<T> unassigned = new HashSet<>(nodes);
unassigned.remove(to);
while(!cuttingEdge.isEmpty()){
//contract
edge = cuttingEdge;
cuttingEdge = new HashSet<>();
//grow
for(Branch b : edge){
Set<? extends T> n = new HashSet<>(b.wrapped.neighbors());
n.retainAll(unassigned);
unassigned.removeAll(n);
for(T t : n){
Branch newBranch = new Branch(t, b);
if(t.equals(from)){
return newBranch;
} else{
cuttingEdge.add(newBranch);
}
}
}
}
throw new IllegalArgumentException(
"Cannot find path between specified nodes: " + from + " and " + to);
}
private class Branch{
private final T wrapped;
private final Branch parent;
private Branch(T wrapped, Branch parent){
this.wrapped = wrapped;
this.parent = parent;
}
@Override
public boolean equals(Object o){
if(o instanceof AbstractGraph.Branch){
AbstractGraph<?>.Branch b = (AbstractGraph<?>.Branch) o;
return wrapped.equals(b.wrapped)
&& (parent == null
? b.parent == null
: parent.equals(b.parent));
}
return false;
}
@Override
public int hashCode(){
return wrapped.hashCode();
}
}
@Override
public int hashCode(){
return nodeStream()
.map(Object::hashCode)
.reduce(0, Integer::sum);
}
@Override
public String toString(){
StringBuilder out = new StringBuilder()
.append(getClass())
.append(" size ")
.append(size())
.append(System.lineSeparator())
.append(nodes)
.append(System.lineSeparator());
for(T node : nodes){
out
.append(node).append(": ")
.append(System.lineSeparator())
.append(node.neighbors())
.append(System.lineSeparator());
}
return out.toString();
}
}
|
package at.fhtw.mcs.model;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.UnsupportedAudioFileException;
import javazoom.jl.converter.Converter;
import javazoom.jl.decoder.JavaLayerException;
import org.apache.commons.io.FilenameUtils;
import at.fhtw.mcs.util.AudioOuput;
import at.fhtw.mcs.util.FormatDetection;
import at.fhtw.mcs.util.TrackFactory.UnsupportedFormatException;
public class JavaxJavazoomTrack implements Track {
private static final int BUFFER_LENGTH = 1024;
/**
* Percentage used for start point calculation. Has been empirically
* determined.
*/
private static final double EXPECTED_START_POINT_PERCENTAGE = 0.8;
private String name;
private File file;
private Property<String> comment = new SimpleObjectProperty<String>("");
private Clip clip;
private float loudness;
private float dynamicRange;
private float deltaVolume = 0;
private float[] audioData;
private int numberOfChannels = 0;
private int startOffsetFrames;
private long startOffsetMicroseconds;
/**
* Creates the track using the given {@link FormatDetection}.
*
* @throws UnsupportedFormatException
* In case the format of the track is not supported.
*/
public JavaxJavazoomTrack(FormatDetection formatDetection, String path, String projectDirectory) {
Format format = formatDetection.detectFormat(path);
name = FilenameUtils.getBaseName(path);
String pathToLoad;
switch (format) {
case AIFF:
case WAV:
pathToLoad = path;
break;
case MP3:
pathToLoad = convertMp3ToWav(path, projectDirectory);
break;
default:
throw new UnsupportedFormatException(format);
}
file = new File(pathToLoad);
numberOfChannels = this.setNumberOfChannels();
clip = AudioOuput.openClip(file);
try {
storeAudioData();
calculateLoudness();
calculateDynamicRange();
} catch (UnsupportedAudioFileException | IOException e) {
throw new RuntimeException("Unexpected error during audio analysis", e);
}
}
public void applyStartPointOffset() {
int startPoint = findStartPoint();
startOffsetFrames = startPoint / 2;
startOffsetMicroseconds = framesToMicroseconds(startOffsetFrames);
clip.setFramePosition(startOffsetFrames);
}
public void resetStartPointOffset() {
startOffsetFrames = 0;
startOffsetMicroseconds = 0;
}
private int findStartPoint() {
/*
* The basic idea here is that we're looking for the first rise of the
* level. This actual level we're looking for depends on the loudness:
* For louder tracks, it will be higher. That's why we effectively
* multiply 1 (the absolute maximum level) with the float factor of the
* loudness (e.g. 0.25 for -6dB). The resulting value is reduced by an
* empirically determined percentage so that the expected value is found
* earlier.
*/
double expextedStartValue = 1 * decibelToFloat(loudness) * EXPECTED_START_POINT_PERCENTAGE;
int middledStartIndex = 0;
int firstIndexAboveThreshold = -1;
for (int i = 0; i < audioData.length; i++) {
float value = Math.abs(audioData[i]);
if (firstIndexAboveThreshold == -1 && value >= expextedStartValue) {
firstIndexAboveThreshold = i;
} else if (firstIndexAboveThreshold > -1 && value < expextedStartValue) {
middledStartIndex = (i + firstIndexAboveThreshold) / 2;
break;
}
}
return middledStartIndex;
}
private String convertMp3ToWav(String path, String projectDirectory) {
// TODO uppercase, e.g. MP3
// TODO test: josh.new.mp3.mp3
String newPath;
Converter converter = new Converter();
int positionOfMp3 = path.lastIndexOf(".mp3");
int startOfFilename = path.lastIndexOf("/");
// newPath = path.substring(0, positionOfMp3) + ".wav";
newPath = projectDirectory + path.substring(startOfFilename, positionOfMp3) + ".wav";
try {
converter.convert(path, newPath);
} catch (JavaLayerException e) {
throw new UnsupportedFormatException(Format.MP3,
"There was an error while converting the MP3 to WAV. Try consulting JavaZoom documentation.", e);
}
// throw exception if converted file does not exist
if (!Files.exists(Paths.get(newPath))) {
throw new UnsupportedFormatException(Format.MP3,
"There was an error while converting the MP3 to WAV. Try consulting JavaZoom documentation.");
}
return newPath;
}
private void storeAudioData() throws UnsupportedAudioFileException, IOException, UnsupportedFormatException {
AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
AudioFormat audioFormat = fileFormat.getFormat();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
if (audioFormat.getSampleSizeInBits() > 16) {
System.out.println(audioFormat.getSampleSizeInBits());
throw new UnsupportedFormatException(Format.WAV);
}
int nBufferSize = BUFFER_LENGTH * audioFormat.getFrameSize();
final int normalBytes = normalBytesFromBits(audioFormat.getSampleSizeInBits());
byte[] bytes = new byte[nBufferSize];
AudioInputStream inputAIS = AudioSystem.getAudioInputStream(file);
int bytesRead;
while ((bytesRead = inputAIS.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, bytesRead);
}
byte[] byteAudioData = byteArrayOutputStream.toByteArray();
float[] samples = new float[(byteAudioData.length / normalBytes)];
unpack(byteAudioData, samples, byteAudioData.length, audioFormat);
audioData = samples;
}
@Override
public void play() {
clip.start();
}
@Override
public void pause() {
clip.stop();
}
@Override
public void togglePlayPause() {
if (clip.isRunning()) {
pause();
} else {
play();
}
}
@Override
public void stop() {
clip.stop();
clip.setFramePosition(startOffsetFrames);
}
/**
* Copied from com.sun.media.sound.Toolkit.frames2micros(AudioFormat, long)
*/
private long framesToMicroseconds(long frames) {
return (long) (((double) frames) / clip.getFormat().getFrameRate() * 1000000.0d);
}
@Override
public long getCurrentMicroseconds() {
long currentMicroseconds = clip.getMicrosecondPosition() - startOffsetMicroseconds;
/*
* Ensure that this method never returns a negative value, which can
* happend if the startOffsetMicroseconds has been calculated but the
* frame position has not (yet) affected the microsecondPosition.
*/
return currentMicroseconds < 0 ? 0 : currentMicroseconds;
}
@Override
public long getTotalMicroseconds() {
return clip.getMicrosecondLength() - startOffsetMicroseconds;
}
@Override
public String getName() {
return name;
}
/**
* some formats allow for bit depths in non-multiples of 8. they will,
* however, typically pad so the samples are stored that way. AIFF is one of
* these formats.
*
* so the expression:
*
* bitsPerSample + 7 >> 3
*
* computes a division of 8 rounding up (for positive numbers).
*
* this is basically equivalent to:
*
* (int)Math.ceil(bitsPerSample / 8.0)
*
*/
private static int normalBytesFromBits(int bitsPerSample) {
return bitsPerSample + 7 >> 3;
}
public static void unpack(byte[] bytes, float[] samples, int bvalid, AudioFormat fmt) {
if (fmt.getEncoding() != AudioFormat.Encoding.PCM_SIGNED
&& fmt.getEncoding() != AudioFormat.Encoding.PCM_UNSIGNED) {
throw new UnsupportedFormatException("Only PCM Encodings are suppported! Encoding:" + fmt.getEncoding());
}
long[] transfer = new long[samples.length];
final int bitsPerSample = fmt.getSampleSizeInBits();
final int normalBytes = normalBytesFromBits(bitsPerSample);
// TODO: maybe combine loops (keep performance in mind!)
if (fmt.isBigEndian()) {
for (int i = 0, k = 0, b; i < bvalid; i += normalBytes, k++) {
transfer[k] = 0L;
int least = i + normalBytes - 1;
for (b = 0; b < normalBytes; b++) {
transfer[k] |= (bytes[least - b] & 0xffL) << (8 * b);
}
}
} else {
for (int i = 0, k = 0, b; i < bvalid; i += normalBytes, k++) {
transfer[k] = 0L;
for (b = 0; b < normalBytes; b++) {
transfer[k] |= (bytes[i + b] & 0xffL) << (8 * b);
}
}
}
// fullScale is the maximum possible value
final long fullScale = (long) Math.pow(2.0, bitsPerSample - 1);
/*
* the OR is not quite enough to convert, the signage needs to be
* corrected.
*/
if (fmt.getEncoding() == AudioFormat.Encoding.PCM_SIGNED) {
final long signShift = 64L - bitsPerSample;
for (int i = 0; i < transfer.length; i++) {
transfer[i] = ((transfer[i] << signShift) >> signShift);
}
} else {
/*
* unsigned samples are easier since they will be read correctly in
* to the long.
*
* so just sign them: subtract 2^(bits - 1) so the center is 0.
*/
for (int i = 0; i < transfer.length; i++) {
transfer[i] -= fullScale;
}
}
/* finally normalize to range of -1.0f to 1.0f */
for (int i = 0; i < transfer.length; i++) {
samples[i] = (float) transfer[i] / (float) fullScale;
}
}
@Override
public float[] getAudioData() {
if (startOffsetFrames > 0) {
return Arrays.copyOfRange(audioData, startOffsetFrames * 2, audioData.length);
}
return audioData;
}
@Override
public int getLength() {
return (clip.getFrameLength() - startOffsetFrames);
}
@Override
public int getLengthWeighted() {
return (int) ((clip.getFrameLength() - startOffsetFrames) * (44100 / clip.getFormat().getSampleRate()));
}
/**
* @return the dB Value of a float (-1.0 to 1.0)
*/
private float floatToDecibel(float sample) {
float db;
sample = Math.abs(sample);
if (sample != 0.0f) {
db = (float) (20.0f * Math.log10(sample));
} else {
db = -144.0f;
}
return db;
}
/**
* @return a float (-1.0 to 1.0) of a dB-Value
*/
private float decibelToFloat(float dB) {
float sample;
if (dB != -144.0f) {
sample = (float) Math.pow(10, (dB / 20));
} else {
sample = 0.0f;
}
return sample;
}
private void calculateLoudness() {
float loudnessFloat = 0;
AudioFormat audioFormat = clip.getFormat();
int channels = audioFormat.getChannels();
int audioFileLength = this.getLength();
int x = 0;
float sum = 0;
/*
* RMS (Root mean square) loudness calculation
*/
for (int j = 0; j < audioFileLength * channels; j += channels) {
float mean = 0;
float leftChannel = audioData[j];
if (channels == 2) {
float rightChannel = audioData[j + 1];
mean = (leftChannel + rightChannel) / 2;
} else {
mean = leftChannel;
}
x++;
sum += Math.pow(mean, 2);
}
loudnessFloat = (float) Math.sqrt(sum / x);
loudness = floatToDecibel(loudnessFloat);
}
private int setNumberOfChannels() {
AudioFileFormat fileFormat;
try {
fileFormat = AudioSystem.getAudioFileFormat(file);
} catch (UnsupportedAudioFileException | IOException e) {
throw new UnsupportedFormatException(Format.WAV);
}
AudioFormat audioFormat = fileFormat.getFormat();
return audioFormat.getChannels();
}
@Override
public int getNumberOfChannels() {
return this.numberOfChannels;
}
@Override
public void reload() {
/*
* Fetch important clip data and dispose of the old clip.
*/
boolean wasRunning = clip.isRunning();
clip.stop();
int framePosition = clip.getFramePosition();
float gain = getGainControl(clip).getValue();
clip.close();
/*
* Open a new clip with the same properties as the old one.
*/
Clip newClip = AudioOuput.openClip(file);
newClip.setFramePosition(framePosition);
getGainControl(newClip).setValue(gain);
if (wasRunning) {
newClip.start();
}
clip = newClip;
}
@Override
public float getLoudness() {
return this.loudness;
}
private FloatControl getGainControl(Clip clip) {
return (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
}
@Override
public void setVolume(float lowest) {
if (this.loudness == lowest) {
return;
}
FloatControl gainController = getGainControl(this.clip);
float deltaDBValue = this.loudness - lowest;
this.deltaVolume = deltaDBValue * 1.05f;
gainController.setValue(0 - this.deltaVolume);
}
@Override
public void setCurrentMicroseconds(long currentMicroseconds) {
clip.setMicrosecondPosition(currentMicroseconds + startOffsetMicroseconds);
}
@Override
public boolean isPlaying() {
return clip.isRunning();
}
@Override
public void changeVolume(double delta) {
FloatControl gainController = getGainControl(this.clip);
gainController.setValue(0 - this.deltaVolume);
float temp = (float) (40f * delta);
gainController.setValue(temp - 40 - this.deltaVolume);
}
/**
* calculates dynamic range of track (as difference between peak and rms)
*/
private void calculateDynamicRange() {
int channels = this.getNumberOfChannels();
int audioFileLength = this.getLength();
float peak = 0;
float meanPrevious = 0;
float meanCurrent = 0;
float meanNext = 0;
for (int j = 0; j < audioFileLength * channels; j += channels) {
// first sample
if (j == 0) {
float leftChannel = audioData[j];
if (channels == 2) {
float rightChannel = audioData[j + 1];
meanCurrent = Math.abs((leftChannel + rightChannel) / 2);
} else {
meanCurrent = Math.abs(leftChannel);
}
}
// next sample
if (j + channels < audioFileLength * channels) {
float leftChannel = audioData[j + channels];
if (channels == 2) {
float rightChannel = audioData[j + channels + 1];
meanNext = Math.abs((leftChannel + rightChannel) / 2);
} else {
meanNext = Math.abs(leftChannel);
}
} else {
meanNext = 0;
}
// check if sample is peak
if (meanPrevious < meanCurrent && meanCurrent > meanNext && meanCurrent > peak) {
peak = meanCurrent;
}
// set current as previous and next as current sample
meanPrevious = meanCurrent;
meanCurrent = meanNext;
}
dynamicRange = this.getLoudness() - this.floatToDecibel(peak);
}
@Override
public void registerCommentChangeListener(ChangeListener<? super String> listener) {
this.comment.addListener(listener);
}
@Override
public float getDynamicRange() {
return this.dynamicRange;
}
@Override
public String getComment() {
return comment.getValue();
}
@Override
public void setComment(String comment) {
this.comment.setValue(comment);
}
@Override
public String getPath() {
return file.getAbsolutePath();
}
public void setName(String name) {
this.name = name;
}
@Override
public String getFileName() {
return String.format("%s.%s", name, FilenameUtils.getExtension(file.getPath()));
}
public void saveAs(File destination) throws IOException {
Files.copy(file.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
file = destination;
}
@Override
public long getStartPointOffset() {
return startOffsetMicroseconds;
}
@Override
public float getSampleRate() {
return clip.getFormat().getSampleRate();
}
@Override
public Property<String> commentProperty() {
return comment;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.