diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/com/modcrafting/ultrabans/commands/Kick.java b/src/com/modcrafting/ultrabans/commands/Kick.java
index 0507f8f..19e751b 100644
--- a/src/com/modcrafting/ultrabans/commands/Kick.java
+++ b/src/com/modcrafting/ultrabans/commands/Kick.java
@@ -1,146 +1,149 @@
package com.modcrafting.ultrabans.commands;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.modcrafting.ultrabans.UltraBan;
public class Kick implements CommandExecutor{
public static final Logger log = Logger.getLogger("Minecraft");
UltraBan plugin;
public Kick(UltraBan ultraBan) {
this.plugin = ultraBan;
}
public boolean autoComplete;
public String expandName(String p) {
int m = 0;
String Result = "";
for (int n = 0; n < plugin.getServer().getOnlinePlayers().length; n++) {
String str = plugin.getServer().getOnlinePlayers()[n].getName();
if (str.matches("(?i).*" + p + ".*")) {
m++;
Result = str;
if(m==2) {
return null;
}
}
if (str.equalsIgnoreCase(p))
return str;
}
if (m == 1)
return Result;
if (m > 1) {
return null;
}
if (m < 1) {
return p;
}
return p;
}
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.kick")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1) return false;
String p = args[0].toLowerCase();
if(autoComplete)
p = expandName(p);
// Reason stuff
String reason = "not sure";
boolean broadcast = true;
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
reason = combineSplit(2, args, " ");
}else
reason = combineSplit(1, args, " ");
}
if(p.equals("*")){
if (sender instanceof Player)
if (plugin.setupPermissions()){
if (!plugin.permission.has(player, "ultraban.kick.all")) return true;
}else{
if (!player.isOp()) return true; //defaulting to Op if no vault doesn't take or node
}
log.log(Level.INFO, "[UltraBan] " + admin + " kicked Everyone Reason: " + reason);
- for (Player pl : plugin.getServer().getOnlinePlayers()) {
+ Player[] pl = plugin.getServer().getOnlinePlayers();
+ for (int i=0; i<pl.length; i++){
+ if (!plugin.permission.has(pl[i], "ultraban.kick.all")){
String adminMsg = config.getString("messages.kickAllMsg", "Everyone has been kicked by %admin%. Reason: %reason%");
adminMsg = adminMsg.replaceAll("%admin%", admin);
adminMsg = adminMsg.replaceAll("%reason%", reason);
- pl.kickPlayer(formatMessage(adminMsg));
- return true;
+ pl[i].kickPlayer(formatMessage(adminMsg));
+ }
}
+ return true;
}
if(plugin.autoComplete)
p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
if(victim == null){
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
plugin.db.addPlayer(victim.getName(), reason, admin, 0, 3);
log.log(Level.INFO, "[UltraBan] " + admin + " kicked player " + victim.getName() + ". Reason: " + reason);
String adminMsg = config.getString("messages.kickMsgVictim", "You have been kicked by %admin%. Reason: %reason%");
adminMsg = adminMsg.replaceAll("%admin%", admin);
adminMsg = adminMsg.replaceAll("%reason%", reason);
victim.kickPlayer(formatMessage(adminMsg));
if(broadcast){
String kickMsgBroadcast = config.getString("messages.kickMsgBroadcast", "%victim% has been kicked by %admin%. Reason: %reason%");
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%admin%", admin);
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%victim%", victim.getName());
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%reason%", reason);
plugin.getServer().broadcastMessage(formatMessage(kickMsgBroadcast));
}else{
String kickMsgBroadcast = config.getString("messages.kickMsgBroadcast", "%victim% has been kicked by %admin%. Reason: %reason%");
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%admin%", admin);
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%victim%", victim.getName());
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%reason%", reason);
sender.sendMessage(formatMessage(":S:" + kickMsgBroadcast));
}
return true;
}
public String combineSplit(int startIndex, String[] string, String seperator) {
StringBuilder builder = new StringBuilder();
for (int i = startIndex; i < string.length; i++) {
builder.append(string[i]);
builder.append(seperator);
}
builder.deleteCharAt(builder.length() - seperator.length()); // remove
return builder.toString();
}
public String formatMessage(String str){
String funnyChar = new Character((char) 167).toString();
str = str.replaceAll("&", funnyChar);
return str;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.kick")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1) return false;
String p = args[0].toLowerCase();
if(autoComplete)
p = expandName(p);
// Reason stuff
String reason = "not sure";
boolean broadcast = true;
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
reason = combineSplit(2, args, " ");
}else
reason = combineSplit(1, args, " ");
}
if(p.equals("*")){
if (sender instanceof Player)
if (plugin.setupPermissions()){
if (!plugin.permission.has(player, "ultraban.kick.all")) return true;
}else{
if (!player.isOp()) return true; //defaulting to Op if no vault doesn't take or node
}
log.log(Level.INFO, "[UltraBan] " + admin + " kicked Everyone Reason: " + reason);
for (Player pl : plugin.getServer().getOnlinePlayers()) {
String adminMsg = config.getString("messages.kickAllMsg", "Everyone has been kicked by %admin%. Reason: %reason%");
adminMsg = adminMsg.replaceAll("%admin%", admin);
adminMsg = adminMsg.replaceAll("%reason%", reason);
pl.kickPlayer(formatMessage(adminMsg));
return true;
}
}
if(plugin.autoComplete)
p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
if(victim == null){
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
plugin.db.addPlayer(victim.getName(), reason, admin, 0, 3);
log.log(Level.INFO, "[UltraBan] " + admin + " kicked player " + victim.getName() + ". Reason: " + reason);
String adminMsg = config.getString("messages.kickMsgVictim", "You have been kicked by %admin%. Reason: %reason%");
adminMsg = adminMsg.replaceAll("%admin%", admin);
adminMsg = adminMsg.replaceAll("%reason%", reason);
victim.kickPlayer(formatMessage(adminMsg));
if(broadcast){
String kickMsgBroadcast = config.getString("messages.kickMsgBroadcast", "%victim% has been kicked by %admin%. Reason: %reason%");
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%admin%", admin);
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%victim%", victim.getName());
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%reason%", reason);
plugin.getServer().broadcastMessage(formatMessage(kickMsgBroadcast));
}else{
String kickMsgBroadcast = config.getString("messages.kickMsgBroadcast", "%victim% has been kicked by %admin%. Reason: %reason%");
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%admin%", admin);
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%victim%", victim.getName());
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%reason%", reason);
sender.sendMessage(formatMessage(":S:" + kickMsgBroadcast));
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.kick")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1) return false;
String p = args[0].toLowerCase();
if(autoComplete)
p = expandName(p);
// Reason stuff
String reason = "not sure";
boolean broadcast = true;
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
reason = combineSplit(2, args, " ");
}else
reason = combineSplit(1, args, " ");
}
if(p.equals("*")){
if (sender instanceof Player)
if (plugin.setupPermissions()){
if (!plugin.permission.has(player, "ultraban.kick.all")) return true;
}else{
if (!player.isOp()) return true; //defaulting to Op if no vault doesn't take or node
}
log.log(Level.INFO, "[UltraBan] " + admin + " kicked Everyone Reason: " + reason);
Player[] pl = plugin.getServer().getOnlinePlayers();
for (int i=0; i<pl.length; i++){
if (!plugin.permission.has(pl[i], "ultraban.kick.all")){
String adminMsg = config.getString("messages.kickAllMsg", "Everyone has been kicked by %admin%. Reason: %reason%");
adminMsg = adminMsg.replaceAll("%admin%", admin);
adminMsg = adminMsg.replaceAll("%reason%", reason);
pl[i].kickPlayer(formatMessage(adminMsg));
}
}
return true;
}
if(plugin.autoComplete)
p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
if(victim == null){
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
plugin.db.addPlayer(victim.getName(), reason, admin, 0, 3);
log.log(Level.INFO, "[UltraBan] " + admin + " kicked player " + victim.getName() + ". Reason: " + reason);
String adminMsg = config.getString("messages.kickMsgVictim", "You have been kicked by %admin%. Reason: %reason%");
adminMsg = adminMsg.replaceAll("%admin%", admin);
adminMsg = adminMsg.replaceAll("%reason%", reason);
victim.kickPlayer(formatMessage(adminMsg));
if(broadcast){
String kickMsgBroadcast = config.getString("messages.kickMsgBroadcast", "%victim% has been kicked by %admin%. Reason: %reason%");
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%admin%", admin);
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%victim%", victim.getName());
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%reason%", reason);
plugin.getServer().broadcastMessage(formatMessage(kickMsgBroadcast));
}else{
String kickMsgBroadcast = config.getString("messages.kickMsgBroadcast", "%victim% has been kicked by %admin%. Reason: %reason%");
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%admin%", admin);
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%victim%", victim.getName());
kickMsgBroadcast = kickMsgBroadcast.replaceAll("%reason%", reason);
sender.sendMessage(formatMessage(":S:" + kickMsgBroadcast));
}
return true;
}
|
diff --git a/branches/4.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/maskedtextbox/MaskedTextBoxBaseFormatter.java b/branches/4.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/maskedtextbox/MaskedTextBoxBaseFormatter.java
index 04ca7604c..12d7ce7b6 100644
--- a/branches/4.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/maskedtextbox/MaskedTextBoxBaseFormatter.java
+++ b/branches/4.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/maskedtextbox/MaskedTextBoxBaseFormatter.java
@@ -1,54 +1,54 @@
/*
* Copyright 2011 cruxframework.org.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.cruxframework.crux.widgets.client.maskedtextbox;
import org.cruxframework.crux.core.client.formatter.MaskedFormatter;
import com.google.gwt.user.client.ui.Widget;
/**
* Base class for MaskedTextBox Formatters
* @author Thiago da Rosa de Bustamante
*/
public abstract class MaskedTextBoxBaseFormatter implements MaskedFormatter
{
public void applyMask(Widget widget)
{
if (widget instanceof MaskedTextBox)
{
((MaskedTextBox) widget).setMaskedInput(new MaskedInput((MaskedTextBox) widget, getMask(), getPlaceHolder()));
}
}
public void removeMask(Widget widget)
{
if (widget instanceof MaskedTextBox)
{
MaskedTextBox maskedTxt = (MaskedTextBox) widget;
MaskedInput maskedInput = maskedTxt.getMaskedInput();
- if (maskedInput != null && maskedInput.getTextBox() != null && maskedInput.getTextBox().equals(widget))
+ if (maskedInput != null && maskedInput.getTextBox() != null)
{
maskedInput.removeMask();
}
}
}
protected char getPlaceHolder()
{
return '_';
}
}
| true | true | public void removeMask(Widget widget)
{
if (widget instanceof MaskedTextBox)
{
MaskedTextBox maskedTxt = (MaskedTextBox) widget;
MaskedInput maskedInput = maskedTxt.getMaskedInput();
if (maskedInput != null && maskedInput.getTextBox() != null && maskedInput.getTextBox().equals(widget))
{
maskedInput.removeMask();
}
}
}
| public void removeMask(Widget widget)
{
if (widget instanceof MaskedTextBox)
{
MaskedTextBox maskedTxt = (MaskedTextBox) widget;
MaskedInput maskedInput = maskedTxt.getMaskedInput();
if (maskedInput != null && maskedInput.getTextBox() != null)
{
maskedInput.removeMask();
}
}
}
|
diff --git a/src/de/geotweeter/Conversation.java b/src/de/geotweeter/Conversation.java
index ceab6be..21b7e3b 100644
--- a/src/de/geotweeter/Conversation.java
+++ b/src/de/geotweeter/Conversation.java
@@ -1,141 +1,145 @@
package de.geotweeter;
import java.security.AccessControlException;
import java.util.List;
import android.os.AsyncTask;
import de.geotweeter.activities.TimelineActivity;
import de.geotweeter.apiconn.TwitterApiAccess;
import de.geotweeter.exceptions.TweetAccessException;
import de.geotweeter.timelineelements.DirectMessage;
import de.geotweeter.timelineelements.ErrorMessageDisguisedAsTweet;
import de.geotweeter.timelineelements.TimelineElement;
import de.geotweeter.timelineelements.Tweet;
/**
* Retrieves a conversation based on a given endpoint
*
* @author Lutz Krumme (@el_emka)
*
*/
public class Conversation {
private TimelineElementAdapter tea;
private TwitterApiAccess api;
private boolean backwards;
private MessageHashMap dm_conversations;
/**
* Creates the conversation object and starts the retrieval task
*
* @param tea The timeline containing the conversation endpoint as the only element
* @param current_account The timeline owning account
* @param backwards If true the conversation is shown beginning at its end point
* @param onStack If true the timeline is put on the shown timeline stack
*/
public Conversation(TimelineElementAdapter tea, Account current_account, boolean backwards, boolean onStack) {
this.tea = tea;
this.backwards = backwards;
api = current_account.getApi();
dm_conversations = current_account.getDMConversations();
if (onStack) {
current_account.pushTimeline(tea);
}
if (!tea.isEmpty()) {
new LoadConversationTask().execute(tea.getItem(0));
}
}
/**
* Loads the actual conversation
*/
private class LoadConversationTask extends AsyncTask<TimelineElement, TimelineElement, Void> {
@Override
/**
* Builds the conversation from memory and in case of tweets it fetches
* missing ones from the API
*
* @param params The conversation endpoint as first element. Other content will be ignored
*/
protected Void doInBackground(TimelineElement... params) {
if (params == null) {
throw new NullPointerException("Conversation Task parameters are null");
}
if (params[0] == null) {
throw new NullPointerException("Conversation Task parameter is null");
}
TimelineElement current_element = params[0];
if (current_element.getClass() != Tweet.class) {
List<DirectMessage> messages = dm_conversations.getConversation(getRespondent(current_element));
if (messages != null) {
for (DirectMessage msg : messages) {
publishProgress(msg);
}
}
return null;
}
Tweet current = (Tweet) current_element;
while (current.in_reply_to_status_id != 0) {
long predecessor_id = current.in_reply_to_status_id;
try {
current = (Tweet) TimelineActivity.availableTweets.get(predecessor_id);
} catch (NullPointerException e) {
current = null;
}
if (current == null) {
try {
current = api.getTweet(predecessor_id);
} catch (TweetAccessException e) {
publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_protected));
break;
} catch (Exception e) {
e.printStackTrace();
publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_loading_failed));
break;
}
+ if (current == null) {
+ publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_loading_failed));
+ break;
+ }
}
publishProgress(current);
}
return null;
}
/**
* Gets the respondent of a direct message conversation
*
* @param current_element Element of the conversation
* @return Twitter id of the respondent
*/
private long getRespondent(TimelineElement current_element) {
assert (current_element.getClass() == DirectMessage.class);
DirectMessage current_msg = (DirectMessage) current_element;
if (current_msg.sender.id == dm_conversations.getOwnerId()) {
return current_msg.recipient.id;
} else if (current_msg.recipient.id == dm_conversations.getOwnerId()) {
return current_msg.sender.id;
} else {
/* Shouldn't actually happen */
throw new AccessControlException("Message does not belong to given user's timeline");
}
}
/**
* Pushes the timeline element to the conversation timeline
*/
protected void onProgressUpdate(TimelineElement... params) {
if (params[0] == null) {
return;
}
if (tea.getItem(0).getID() == params[0].getID()) {
return;
}
if (backwards) {
tea.add(params[0]);
} else {
tea.addAsFirst(params[0]);
}
}
}
}
| true | true | protected Void doInBackground(TimelineElement... params) {
if (params == null) {
throw new NullPointerException("Conversation Task parameters are null");
}
if (params[0] == null) {
throw new NullPointerException("Conversation Task parameter is null");
}
TimelineElement current_element = params[0];
if (current_element.getClass() != Tweet.class) {
List<DirectMessage> messages = dm_conversations.getConversation(getRespondent(current_element));
if (messages != null) {
for (DirectMessage msg : messages) {
publishProgress(msg);
}
}
return null;
}
Tweet current = (Tweet) current_element;
while (current.in_reply_to_status_id != 0) {
long predecessor_id = current.in_reply_to_status_id;
try {
current = (Tweet) TimelineActivity.availableTweets.get(predecessor_id);
} catch (NullPointerException e) {
current = null;
}
if (current == null) {
try {
current = api.getTweet(predecessor_id);
} catch (TweetAccessException e) {
publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_protected));
break;
} catch (Exception e) {
e.printStackTrace();
publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_loading_failed));
break;
}
}
publishProgress(current);
}
return null;
}
| protected Void doInBackground(TimelineElement... params) {
if (params == null) {
throw new NullPointerException("Conversation Task parameters are null");
}
if (params[0] == null) {
throw new NullPointerException("Conversation Task parameter is null");
}
TimelineElement current_element = params[0];
if (current_element.getClass() != Tweet.class) {
List<DirectMessage> messages = dm_conversations.getConversation(getRespondent(current_element));
if (messages != null) {
for (DirectMessage msg : messages) {
publishProgress(msg);
}
}
return null;
}
Tweet current = (Tweet) current_element;
while (current.in_reply_to_status_id != 0) {
long predecessor_id = current.in_reply_to_status_id;
try {
current = (Tweet) TimelineActivity.availableTweets.get(predecessor_id);
} catch (NullPointerException e) {
current = null;
}
if (current == null) {
try {
current = api.getTweet(predecessor_id);
} catch (TweetAccessException e) {
publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_protected));
break;
} catch (Exception e) {
e.printStackTrace();
publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_loading_failed));
break;
}
if (current == null) {
publishProgress(new ErrorMessageDisguisedAsTweet(R.string.error_tweet_loading_failed));
break;
}
}
publishProgress(current);
}
return null;
}
|
diff --git a/src/main/java/com/crumbdev/chris/Danroth/Danroth.java b/src/main/java/com/crumbdev/chris/Danroth/Danroth.java
index 7c52ca8..723743c 100644
--- a/src/main/java/com/crumbdev/chris/Danroth/Danroth.java
+++ b/src/main/java/com/crumbdev/chris/Danroth/Danroth.java
@@ -1,81 +1,81 @@
package com.crumbdev.chris.Danroth;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: chris
* Date: 1/12/11
* Time: 9:16 PM
* To change this template use File | Settings | File Templates.
*/
public class Danroth {
public static void main(String[] args)
{
Boolean usenickserv = false;
String nickserv = "";
String server = "irc.esper.net";
int port = 6667;
List channels = new ArrayList();
String nick = "Danroth";
String ident = "Danroth";
for(int i = 0; i < args.length; i++)
{
if(args[i].toLowerCase().equalsIgnoreCase("--help"))
{
System.out.println("Help page here :P");
System.out.println("Arguments list:");
System.out.println("\t--help Shows this page");
System.out.println("\t--nickserv=[Password] Identifies the bot to nickserv upon connect using the specified password");
System.out.println("\t--server=[IRC Server Address] The address of the IRC server. Default Esper");
System.out.println("\t--port=[Port] The port to connect to the server using. Default 6667");
System.out.println("\t--nick=[Nick] The nickname for the bot to use");
System.out.println("\t--ident=[Ident] The ident/username for the bot to use");
System.out.println("");
System.exit(0);
return;
}
}
for(int i = 0; i < args.length; i++)
{
//System.out.println(args[i]);
if(args[i].toLowerCase().startsWith("--nickserv="))
{
usenickserv = true;
nickserv = args[i].substring("--nickserv=".length(), args[i].length());
System.out.println("Using NickServ authentication.");
}
else if(args[i].toLowerCase().startsWith("--server="))
{
server = args[i].toLowerCase().substring("--server=".length(), args[i].length());
System.out.println("Using " + server + " as the server.");
}
else if(args[i].toLowerCase().startsWith("--port="))
{
port = Integer.parseInt(args[i].substring("--port=".length(), args[i].length()));
System.out.println("Using port " + port);
}
else if(args[i].toLowerCase().startsWith("--nick="))
{
nick = args[i].substring("--nick=".length(), args[i].length());
System.out.println("Using nick " + nick);
}
else if(args[i].toLowerCase().startsWith("--ident="))
{
nick = args[i].substring("--ident=".length(), args[i].length());
System.out.println("Using ident " + ident);
}
else if(args[i].startsWith("#"))
{
channels.add(args[i]);
}
}
System.out.println("Channel List");
for(int i = 0; i < channels.toArray().length; i++)
{
- System.out.println("\t" + channels.get(i));
+ System.out.println("\t" + channels.toArray()[i]);
}
}
}
| true | true | public static void main(String[] args)
{
Boolean usenickserv = false;
String nickserv = "";
String server = "irc.esper.net";
int port = 6667;
List channels = new ArrayList();
String nick = "Danroth";
String ident = "Danroth";
for(int i = 0; i < args.length; i++)
{
if(args[i].toLowerCase().equalsIgnoreCase("--help"))
{
System.out.println("Help page here :P");
System.out.println("Arguments list:");
System.out.println("\t--help Shows this page");
System.out.println("\t--nickserv=[Password] Identifies the bot to nickserv upon connect using the specified password");
System.out.println("\t--server=[IRC Server Address] The address of the IRC server. Default Esper");
System.out.println("\t--port=[Port] The port to connect to the server using. Default 6667");
System.out.println("\t--nick=[Nick] The nickname for the bot to use");
System.out.println("\t--ident=[Ident] The ident/username for the bot to use");
System.out.println("");
System.exit(0);
return;
}
}
for(int i = 0; i < args.length; i++)
{
//System.out.println(args[i]);
if(args[i].toLowerCase().startsWith("--nickserv="))
{
usenickserv = true;
nickserv = args[i].substring("--nickserv=".length(), args[i].length());
System.out.println("Using NickServ authentication.");
}
else if(args[i].toLowerCase().startsWith("--server="))
{
server = args[i].toLowerCase().substring("--server=".length(), args[i].length());
System.out.println("Using " + server + " as the server.");
}
else if(args[i].toLowerCase().startsWith("--port="))
{
port = Integer.parseInt(args[i].substring("--port=".length(), args[i].length()));
System.out.println("Using port " + port);
}
else if(args[i].toLowerCase().startsWith("--nick="))
{
nick = args[i].substring("--nick=".length(), args[i].length());
System.out.println("Using nick " + nick);
}
else if(args[i].toLowerCase().startsWith("--ident="))
{
nick = args[i].substring("--ident=".length(), args[i].length());
System.out.println("Using ident " + ident);
}
else if(args[i].startsWith("#"))
{
channels.add(args[i]);
}
}
System.out.println("Channel List");
for(int i = 0; i < channels.toArray().length; i++)
{
System.out.println("\t" + channels.get(i));
}
}
| public static void main(String[] args)
{
Boolean usenickserv = false;
String nickserv = "";
String server = "irc.esper.net";
int port = 6667;
List channels = new ArrayList();
String nick = "Danroth";
String ident = "Danroth";
for(int i = 0; i < args.length; i++)
{
if(args[i].toLowerCase().equalsIgnoreCase("--help"))
{
System.out.println("Help page here :P");
System.out.println("Arguments list:");
System.out.println("\t--help Shows this page");
System.out.println("\t--nickserv=[Password] Identifies the bot to nickserv upon connect using the specified password");
System.out.println("\t--server=[IRC Server Address] The address of the IRC server. Default Esper");
System.out.println("\t--port=[Port] The port to connect to the server using. Default 6667");
System.out.println("\t--nick=[Nick] The nickname for the bot to use");
System.out.println("\t--ident=[Ident] The ident/username for the bot to use");
System.out.println("");
System.exit(0);
return;
}
}
for(int i = 0; i < args.length; i++)
{
//System.out.println(args[i]);
if(args[i].toLowerCase().startsWith("--nickserv="))
{
usenickserv = true;
nickserv = args[i].substring("--nickserv=".length(), args[i].length());
System.out.println("Using NickServ authentication.");
}
else if(args[i].toLowerCase().startsWith("--server="))
{
server = args[i].toLowerCase().substring("--server=".length(), args[i].length());
System.out.println("Using " + server + " as the server.");
}
else if(args[i].toLowerCase().startsWith("--port="))
{
port = Integer.parseInt(args[i].substring("--port=".length(), args[i].length()));
System.out.println("Using port " + port);
}
else if(args[i].toLowerCase().startsWith("--nick="))
{
nick = args[i].substring("--nick=".length(), args[i].length());
System.out.println("Using nick " + nick);
}
else if(args[i].toLowerCase().startsWith("--ident="))
{
nick = args[i].substring("--ident=".length(), args[i].length());
System.out.println("Using ident " + ident);
}
else if(args[i].startsWith("#"))
{
channels.add(args[i]);
}
}
System.out.println("Channel List");
for(int i = 0; i < channels.toArray().length; i++)
{
System.out.println("\t" + channels.toArray()[i]);
}
}
|
diff --git a/src/net/ciderpunk/tanktris/graphics/Frame.java b/src/net/ciderpunk/tanktris/graphics/Frame.java
index a8abc12..4e39b2f 100644
--- a/src/net/ciderpunk/tanktris/graphics/Frame.java
+++ b/src/net/ciderpunk/tanktris/graphics/Frame.java
@@ -1,78 +1,78 @@
package net.ciderpunk.tanktris.graphics;
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.ImageIcon;
import net.ciderpunk.tanktris.Screen;
public class Frame {
protected Image oImage;
protected int iXOffs;
protected int iYOffs;
//constructors
//instantiate frame from image path
public Frame(String sPath){
this(sPath,0,0);
}
//instantiate frame from image with offset coordinates
public Frame(String sPath, int iXOffset, int iYOffset){
oImage = new ImageIcon(sPath).getImage();
iXOffs = iXOffset;
iYOffs = iYOffset;
}
public Frame(Frame oBaseFrame, int iX, int iY, int iW, int iH){
this(oBaseFrame, iX, iY, iW, iH, 0, 0);
}
public Frame(Frame oBaseFrame, int iX, int iY, int iW, int iH, int iXOffset, int iYOffset){
oImage = Screen.getInstance().createImage(iW, iH);
- Graphics oG = oBaseFrame.getImage().getGraphics();
+ Graphics oG = oImage.getGraphics();
oG.drawImage(oBaseFrame.getImage(), iX,iY,iX+iW,iY+iH,0,0,iW,iH, null);
iXOffs = iXOffset;
iYOffs = iYOffset;
}
//get underlying image
public Image getImage(){
return oImage;
}
//draw image
public void draw(Graphics oG, int x, int y){
oG.drawImage(oImage, x - iXOffs, y - iYOffs, null);
}
//draw image with some rotation
public void drawRotate(Graphics2D oG, int x, int y, int iRads){
AffineTransform oTransform = new AffineTransform();
oTransform.setToTranslation(x, y);
oTransform.rotate(iRads,iXOffs, iYOffs);
oG.drawImage(oImage, oTransform, null);
}
public int getXOffset(){
return iXOffs;
}
public int getYOffset(){
return iYOffs;
}
public int getWidth(){
return oImage.getWidth(null);
}
public int getHeight(){
return oImage.getHeight(null);
}
}
| true | true | public Frame(Frame oBaseFrame, int iX, int iY, int iW, int iH, int iXOffset, int iYOffset){
oImage = Screen.getInstance().createImage(iW, iH);
Graphics oG = oBaseFrame.getImage().getGraphics();
oG.drawImage(oBaseFrame.getImage(), iX,iY,iX+iW,iY+iH,0,0,iW,iH, null);
iXOffs = iXOffset;
iYOffs = iYOffset;
}
| public Frame(Frame oBaseFrame, int iX, int iY, int iW, int iH, int iXOffset, int iYOffset){
oImage = Screen.getInstance().createImage(iW, iH);
Graphics oG = oImage.getGraphics();
oG.drawImage(oBaseFrame.getImage(), iX,iY,iX+iW,iY+iH,0,0,iW,iH, null);
iXOffs = iXOffset;
iYOffs = iYOffset;
}
|
diff --git a/viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/FeatureSource.java b/viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/FeatureSource.java
index 9982992b3..d988bd9b4 100644
--- a/viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/FeatureSource.java
+++ b/viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/FeatureSource.java
@@ -1,238 +1,239 @@
/*
* Copyright (C) 2011-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.config.services;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.*;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.geotools.data.DataStore;
import org.geotools.data.Transaction;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.FeatureCollection;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.expression.Function;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@Entity
@DiscriminatorColumn(name="protocol")
public abstract class FeatureSource {
@Id
private Long id;
@Basic(optional=false)
private String name;
@Basic(optional=false)
private String url;
private String username;
private String password;
/**
* GeoService for which this FeatureSource was automatically created - to
* enable updating of both at the same time
*/
@ManyToOne
private GeoService linkedService;
@ManyToMany(cascade=CascadeType.ALL) // Actually @OneToMany, workaround for HHH-1268
@JoinTable(inverseJoinColumns=@JoinColumn(name="feature_type"))
@OrderColumn(name="list_index")
private List<SimpleFeatureType> featureTypes = new ArrayList<SimpleFeatureType>();
//<editor-fold defaultstate="collapsed" desc="getters en setters">
public List<SimpleFeatureType> getFeatureTypes() {
return featureTypes;
}
public void setFeatureTypes(List<SimpleFeatureType> featureTypes) {
this.featureTypes = featureTypes;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public GeoService getLinkedService() {
return linkedService;
}
public void setLinkedService(GeoService linkedService) {
this.linkedService = linkedService;
}
//</editor-fold>
public String getProtocol() {
return getClass().getAnnotation(DiscriminatorValue.class).value();
}
List<String> calculateUniqueValues(SimpleFeatureType sft, String attributeName, int maxFeatures) throws Exception{
org.geotools.data.FeatureSource fs = null;
try {
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
Function unique = ff.function("Collection_Unique", ff.property(attributeName));
Filter notNull = ff.not( ff.isNull( ff.property(attributeName) ));
org.geotools.data.Query q = new org.geotools.data.Query(sft.getTypeName(), notNull);
+ q.setMaxFeatures(maxFeatures);
fs = sft.openGeoToolsFeatureSource();
FeatureCollection fc = fs.getFeatures(q);
Object o = unique.evaluate( fc);
Set<String> uniqueValues = (Set<String>)o;
if(uniqueValues == null){
uniqueValues = new HashSet<String>();
}
List<String> l = new ArrayList<String>(uniqueValues);
Collections.sort(l);
return l;
} catch (Exception ex) {
throw ex;
}finally{
if(fs != null && fs.getDataStore() != null){
fs.getDataStore().dispose();
}
}
}
public Object getMaxValue(SimpleFeatureType sft, String attributeName, int maxFeatures) throws Exception {
org.geotools.data.FeatureSource fs = null;
try {
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
Function max = ff.function("Collection_Max", ff.property(attributeName));
fs = sft.openGeoToolsFeatureSource();
FeatureCollection fc = fs.getFeatures();
Object value = max.evaluate(fc);
return value;
} catch (Exception ex) {
throw ex;
} finally {
if (fs != null && fs.getDataStore() != null) {
fs.getDataStore().dispose();
}
}
}
public Object getMinValue(SimpleFeatureType sft, String attributeName, int maxFeatures) throws Exception {
org.geotools.data.FeatureSource fs = null;
try {
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
Function minFunction = ff.function("Collection_Min", ff.property(attributeName));
fs = sft.openGeoToolsFeatureSource();
FeatureCollection f = fs.getFeatures();
Object o = minFunction.evaluate(f);
return o;
} catch (Exception ex) {
throw ex;
} finally {
if (fs != null && fs.getDataStore() != null) {
fs.getDataStore().dispose();
}
}
}
/* package */ abstract org.geotools.data.FeatureSource openGeoToolsFeatureSource(SimpleFeatureType sft) throws Exception;
/* package */ abstract FeatureCollection getFeatures(SimpleFeatureType sft, Filter f, int maxFeatures) throws Exception;
/* package */ abstract org.geotools.data.FeatureSource openGeoToolsFeatureSource(SimpleFeatureType sft, int timeout) throws Exception;
public SimpleFeatureType getFeatureType(String typeName) {
for(SimpleFeatureType sft: getFeatureTypes()) {
if(sft.getTypeName().equals(typeName)) {
return sft;
}
}
return null;
}
public SimpleFeatureType addOrUpdateFeatureType(String typeName, SimpleFeatureType newType, MutableBoolean updated) {
SimpleFeatureType old = getFeatureType(typeName);
if(old != null) {
updated.setValue(old.update(newType));
return old;
}
newType.setFeatureSource(this);
getFeatureTypes().add(newType);
return newType;
}
public void removeFeatureType(SimpleFeatureType featureType) {
Stripersist.getEntityManager().remove(featureType);
getFeatureTypes().remove(featureType);
}
public JSONObject toJSONObject() throws JSONException {
JSONObject json = new JSONObject();
json.put("id", this.getId());
json.put("name",this.getName());
json.put("protocol",this.getProtocol());
json.put("url",this.getUrl());
return json;
}
}
| true | true | List<String> calculateUniqueValues(SimpleFeatureType sft, String attributeName, int maxFeatures) throws Exception{
org.geotools.data.FeatureSource fs = null;
try {
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
Function unique = ff.function("Collection_Unique", ff.property(attributeName));
Filter notNull = ff.not( ff.isNull( ff.property(attributeName) ));
org.geotools.data.Query q = new org.geotools.data.Query(sft.getTypeName(), notNull);
fs = sft.openGeoToolsFeatureSource();
FeatureCollection fc = fs.getFeatures(q);
Object o = unique.evaluate( fc);
Set<String> uniqueValues = (Set<String>)o;
if(uniqueValues == null){
uniqueValues = new HashSet<String>();
}
List<String> l = new ArrayList<String>(uniqueValues);
Collections.sort(l);
return l;
} catch (Exception ex) {
throw ex;
}finally{
if(fs != null && fs.getDataStore() != null){
fs.getDataStore().dispose();
}
}
}
| List<String> calculateUniqueValues(SimpleFeatureType sft, String attributeName, int maxFeatures) throws Exception{
org.geotools.data.FeatureSource fs = null;
try {
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
Function unique = ff.function("Collection_Unique", ff.property(attributeName));
Filter notNull = ff.not( ff.isNull( ff.property(attributeName) ));
org.geotools.data.Query q = new org.geotools.data.Query(sft.getTypeName(), notNull);
q.setMaxFeatures(maxFeatures);
fs = sft.openGeoToolsFeatureSource();
FeatureCollection fc = fs.getFeatures(q);
Object o = unique.evaluate( fc);
Set<String> uniqueValues = (Set<String>)o;
if(uniqueValues == null){
uniqueValues = new HashSet<String>();
}
List<String> l = new ArrayList<String>(uniqueValues);
Collections.sort(l);
return l;
} catch (Exception ex) {
throw ex;
}finally{
if(fs != null && fs.getDataStore() != null){
fs.getDataStore().dispose();
}
}
}
|
diff --git a/src/test/org/apache/hadoop/hbase/HBaseTestCase.java b/src/test/org/apache/hadoop/hbase/HBaseTestCase.java
index 16b828157..5baf70130 100644
--- a/src/test/org/apache/hadoop/hbase/HBaseTestCase.java
+++ b/src/test/org/apache/hadoop/hbase/HBaseTestCase.java
@@ -1,631 +1,632 @@
/**
* Copyright 2007 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.SortedMap;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.io.BatchUpdate;
import org.apache.hadoop.hbase.io.Cell;
import org.apache.hadoop.hbase.io.RowResult;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.InternalScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hdfs.MiniDFSCluster;
/**
* Abstract base class for test cases. Performs all static initialization
*/
public abstract class HBaseTestCase extends TestCase {
private static final Log LOG = LogFactory.getLog(HBaseTestCase.class);
/** configuration parameter name for test directory */
public static final String TEST_DIRECTORY_KEY = "test.build.data";
protected final static byte [] fam1 = Bytes.toBytes("colfamily1");
protected final static byte [] fam2 = Bytes.toBytes("colfamily2");
protected final static byte [] fam3 = Bytes.toBytes("colfamily3");
protected static final byte [][] COLUMNS = {fam1,
fam2, fam3};
private boolean localfs = false;
protected Path testDir = null;
protected FileSystem fs = null;
protected HRegion root = null;
protected HRegion meta = null;
protected static final char FIRST_CHAR = 'a';
protected static final char LAST_CHAR = 'z';
protected static final String PUNCTUATION = "~`@#$%^&*()-_+=:;',.<>/?[]{}|";
protected static final byte [] START_KEY_BYTES = {FIRST_CHAR, FIRST_CHAR, FIRST_CHAR};
protected String START_KEY;
protected static final int MAXVERSIONS = 3;
static {
initialize();
}
public volatile HBaseConfiguration conf;
/** constructor */
public HBaseTestCase() {
super();
init();
}
/**
* @param name
*/
public HBaseTestCase(String name) {
super(name);
init();
}
private void init() {
conf = new HBaseConfiguration();
try {
START_KEY = new String(START_KEY_BYTES, HConstants.UTF8_ENCODING);
} catch (UnsupportedEncodingException e) {
LOG.fatal("error during initialization", e);
fail();
}
}
/**
* Note that this method must be called after the mini hdfs cluster has
* started or we end up with a local file system.
*/
@Override
protected void setUp() throws Exception {
super.setUp();
localfs =
(conf.get("fs.default.name", "file:///").compareTo("file:///") == 0);
if (fs == null) {
this.fs = FileSystem.get(conf);
}
try {
if (localfs) {
this.testDir = getUnitTestdir(getName());
if (fs.exists(testDir)) {
fs.delete(testDir, true);
}
} else {
this.testDir =
this.fs.makeQualified(new Path(conf.get(HConstants.HBASE_DIR)));
}
} catch (Exception e) {
LOG.fatal("error during setup", e);
throw e;
}
}
@Override
protected void tearDown() throws Exception {
try {
if (localfs) {
if (this.fs.exists(testDir)) {
this.fs.delete(testDir, true);
}
}
} catch (Exception e) {
LOG.fatal("error during tear down", e);
}
super.tearDown();
}
protected Path getUnitTestdir(String testName) {
return new Path(
conf.get(TEST_DIRECTORY_KEY, "test/build/data"), testName);
}
protected HRegion createNewHRegion(HTableDescriptor desc, byte [] startKey,
byte [] endKey)
throws IOException {
FileSystem filesystem = FileSystem.get(conf);
Path rootdir = filesystem.makeQualified(
new Path(conf.get(HConstants.HBASE_DIR)));
filesystem.mkdirs(rootdir);
return HRegion.createHRegion(new HRegionInfo(desc, startKey, endKey),
rootdir, conf);
}
protected HRegion openClosedRegion(final HRegion closedRegion)
throws IOException {
HRegion r = new HRegion(closedRegion.getBaseDir(), closedRegion.getLog(),
closedRegion.getFilesystem(), closedRegion.getConf(),
closedRegion.getRegionInfo(), null);
r.initialize(null, null);
return r;
}
/**
* Create a table of name <code>name</code> with {@link COLUMNS} for
* families.
* @param name Name to give table.
* @return Column descriptor.
*/
protected HTableDescriptor createTableDescriptor(final String name) {
return createTableDescriptor(name, MAXVERSIONS);
}
/**
* Create a table of name <code>name</code> with {@link COLUMNS} for
* families.
* @param name Name to give table.
* @param versions How many versions to allow per column.
* @return Column descriptor.
*/
protected HTableDescriptor createTableDescriptor(final String name,
final int versions) {
HTableDescriptor htd = new HTableDescriptor(name);
htd.addFamily(new HColumnDescriptor(fam1, versions,
HColumnDescriptor.DEFAULT_COMPRESSION, false, false,
Integer.MAX_VALUE, HConstants.FOREVER, false));
htd.addFamily(new HColumnDescriptor(fam2, versions,
HColumnDescriptor.DEFAULT_COMPRESSION, false, false,
Integer.MAX_VALUE, HConstants.FOREVER, false));
htd.addFamily(new HColumnDescriptor(fam3, versions,
HColumnDescriptor.DEFAULT_COMPRESSION, false, false,
Integer.MAX_VALUE, HConstants.FOREVER, false));
return htd;
}
/**
* Add content to region <code>r</code> on the passed column
* <code>column</code>.
* Adds data of the from 'aaa', 'aab', etc where key and value are the same.
* @param r
* @param column
* @throws IOException
* @return count of what we added.
*/
protected static long addContent(final HRegion r, final byte [] column)
throws IOException {
byte [] startKey = r.getRegionInfo().getStartKey();
byte [] endKey = r.getRegionInfo().getEndKey();
byte [] startKeyBytes = startKey;
if (startKeyBytes == null || startKeyBytes.length == 0) {
startKeyBytes = START_KEY_BYTES;
}
return addContent(new HRegionIncommon(r), Bytes.toString(column),
startKeyBytes, endKey, -1);
}
/**
* Add content to region <code>r</code> on the passed column
* <code>column</code>.
* Adds data of the from 'aaa', 'aab', etc where key and value are the same.
* @param updater An instance of {@link Incommon}.
* @param column
* @throws IOException
* @return count of what we added.
*/
protected static long addContent(final Incommon updater, final String column)
throws IOException {
return addContent(updater, column, START_KEY_BYTES, null);
}
/**
* Add content to region <code>r</code> on the passed column
* <code>column</code>.
* Adds data of the from 'aaa', 'aab', etc where key and value are the same.
* @param updater An instance of {@link Incommon}.
* @param column
* @param startKeyBytes Where to start the rows inserted
* @param endKey Where to stop inserting rows.
* @return count of what we added.
* @throws IOException
*/
protected static long addContent(final Incommon updater, final String column,
final byte [] startKeyBytes, final byte [] endKey)
throws IOException {
return addContent(updater, column, startKeyBytes, endKey, -1);
}
/**
* Add content to region <code>r</code> on the passed column
* <code>column</code>.
* Adds data of the from 'aaa', 'aab', etc where key and value are the same.
* @param updater An instance of {@link Incommon}.
* @param column
* @param startKeyBytes Where to start the rows inserted
* @param endKey Where to stop inserting rows.
* @param ts Timestamp to write the content with.
* @return count of what we added.
* @throws IOException
*/
protected static long addContent(final Incommon updater, final String column,
final byte [] startKeyBytes, final byte [] endKey, final long ts)
throws IOException {
long count = 0;
// Add rows of three characters. The first character starts with the
// 'a' character and runs up to 'z'. Per first character, we run the
// second character over same range. And same for the third so rows
// (and values) look like this: 'aaa', 'aab', 'aac', etc.
char secondCharStart = (char)startKeyBytes[1];
char thirdCharStart = (char)startKeyBytes[2];
EXIT: for (char c = (char)startKeyBytes[0]; c <= LAST_CHAR; c++) {
for (char d = secondCharStart; d <= LAST_CHAR; d++) {
for (char e = thirdCharStart; e <= LAST_CHAR; e++) {
byte [] t = new byte [] {(byte)c, (byte)d, (byte)e};
if (endKey != null && endKey.length > 0
&& Bytes.compareTo(endKey, t) <= 0) {
break EXIT;
}
try {
Put put = new Put(t);
if(ts != -1) {
put.setTimeStamp(ts);
}
try {
- put.add(Bytes.toBytes(column), null, t);
+ byte[][] split = KeyValue.parseColumn(Bytes.toBytes(column));
+ put.add(split[0], split[1], t);
updater.put(put);
count++;
} catch (RuntimeException ex) {
ex.printStackTrace();
throw ex;
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
} catch (RuntimeException ex) {
ex.printStackTrace();
throw ex;
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
}
// Set start character back to FIRST_CHAR after we've done first loop.
thirdCharStart = FIRST_CHAR;
}
secondCharStart = FIRST_CHAR;
}
return count;
}
/**
* Implementors can flushcache.
*/
public static interface FlushCache {
/**
* @throws IOException
*/
public void flushcache() throws IOException;
}
/**
* Interface used by tests so can do common operations against an HTable
* or an HRegion.
*
* TOOD: Come up w/ a better name for this interface.
*/
public static interface Incommon {
/**
*
* @param delete
* @param lockid
* @param writeToWAL
* @throws IOException
*/
public void delete(Delete delete, Integer lockid, boolean writeToWAL)
throws IOException;
/**
* @param put
* @throws IOException
*/
public void put(Put put) throws IOException;
public Result get(Get get) throws IOException;
/**
* @param columns
* @param firstRow
* @param ts
* @return scanner for specified columns, first row and timestamp
* @throws IOException
*/
public ScannerIncommon getScanner(byte [] [] columns, byte [] firstRow,
long ts) throws IOException;
}
/**
* A class that makes a {@link Incommon} out of a {@link HRegion}
*/
public static class HRegionIncommon implements Incommon, FlushCache {
final HRegion region;
/**
* @param HRegion
*/
public HRegionIncommon(final HRegion HRegion) {
this.region = HRegion;
}
public void put(Put put) throws IOException {
region.put(put);
}
public void delete(Delete delete, Integer lockid, boolean writeToWAL)
throws IOException {
this.region.delete(delete, lockid, writeToWAL);
}
public Result get(Get get) throws IOException {
return region.get(get, null);
}
public ScannerIncommon getScanner(byte [][] columns, byte [] firstRow,
long ts)
throws IOException {
Scan scan = new Scan(firstRow);
scan.addColumns(columns);
scan.setTimeRange(0, ts);
return new
InternalScannerIncommon(region.getScanner(scan));
}
//New
public ScannerIncommon getScanner(byte [] family, byte [][] qualifiers,
byte [] firstRow, long ts)
throws IOException {
Scan scan = new Scan(firstRow);
for(int i=0; i<qualifiers.length; i++){
scan.addColumn(HConstants.CATALOG_FAMILY, qualifiers[i]);
}
scan.setTimeRange(0, ts);
return new
InternalScannerIncommon(region.getScanner(scan));
}
public Result get(Get get, Integer lockid) throws IOException{
return this.region.get(get, lockid);
}
public void flushcache() throws IOException {
this.region.flushcache();
}
}
/**
* A class that makes a {@link Incommon} out of a {@link HTable}
*/
public static class HTableIncommon implements Incommon {
final HTable table;
/**
* @param table
*/
public HTableIncommon(final HTable table) {
super();
this.table = table;
}
public void put(Put put) throws IOException {
table.put(put);
}
public void delete(Delete delete, Integer lockid, boolean writeToWAL)
throws IOException {
this.table.delete(delete);
}
public Result get(Get get) throws IOException {
return table.get(get);
}
public ScannerIncommon getScanner(byte [][] columns, byte [] firstRow, long ts)
throws IOException {
Scan scan = new Scan(firstRow);
scan.addColumns(columns);
scan.setTimeStamp(ts);
return new
ClientScannerIncommon(table.getScanner(scan));
}
}
public interface ScannerIncommon
extends Iterable<Map.Entry<HStoreKey, SortedMap<byte [], Cell>>> {
public boolean next(List<KeyValue> values)
throws IOException;
public void close() throws IOException;
}
public static class ClientScannerIncommon implements ScannerIncommon {
ResultScanner scanner;
public ClientScannerIncommon(ResultScanner scanner) {
this.scanner = scanner;
}
public boolean next(List<KeyValue> values)
throws IOException {
Result results = scanner.next();
if (results == null) {
return false;
}
values.clear();
values.addAll(results.list());
return true;
}
public void close() throws IOException {
scanner.close();
}
@SuppressWarnings("unchecked")
public Iterator iterator() {
return scanner.iterator();
}
}
public static class InternalScannerIncommon implements ScannerIncommon {
InternalScanner scanner;
public InternalScannerIncommon(InternalScanner scanner) {
this.scanner = scanner;
}
public boolean next(List<KeyValue> results)
throws IOException {
return scanner.next(results);
}
public void close() throws IOException {
scanner.close();
}
public Iterator<Map.Entry<HStoreKey, SortedMap<byte [], Cell>>> iterator() {
throw new UnsupportedOperationException();
}
}
// protected void assertCellEquals(final HRegion region, final byte [] row,
// final byte [] column, final long timestamp, final String value)
// throws IOException {
// Map<byte [], Cell> result = region.getFull(row, null, timestamp, 1, null);
// Cell cell_value = result.get(column);
// if (value == null) {
// assertEquals(Bytes.toString(column) + " at timestamp " + timestamp, null,
// cell_value);
// } else {
// if (cell_value == null) {
// fail(Bytes.toString(column) + " at timestamp " + timestamp +
// "\" was expected to be \"" + value + " but was null");
// }
// if (cell_value != null) {
// assertEquals(Bytes.toString(column) + " at timestamp "
// + timestamp, value, new String(cell_value.getValue()));
// }
// }
// }
protected void assertResultEquals(final HRegion region, final byte [] row,
final byte [] family, final byte [] qualifier, final long timestamp,
final byte [] value)
throws IOException {
Get get = new Get(row);
get.setTimeStamp(timestamp);
Result res = region.get(get, null);
NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> map =
res.getMap();
byte [] res_value = map.get(family).get(qualifier).get(timestamp);
if (value == null) {
assertEquals(Bytes.toString(family) + " " + Bytes.toString(qualifier) +
" at timestamp " + timestamp, null, res_value);
} else {
if (res_value == null) {
fail(Bytes.toString(family) + " " + Bytes.toString(qualifier) +
" at timestamp " + timestamp + "\" was expected to be \"" +
value + " but was null");
}
if (res_value != null) {
assertEquals(Bytes.toString(family) + " " + Bytes.toString(qualifier) +
" at timestamp " +
timestamp, value, new String(res_value));
}
}
}
/**
* Initializes parameters used in the test environment:
*
* Sets the configuration parameter TEST_DIRECTORY_KEY if not already set.
* Sets the boolean debugging if "DEBUGGING" is set in the environment.
* If debugging is enabled, reconfigures logging so that the root log level is
* set to WARN and the logging level for the package is set to DEBUG.
*/
public static void initialize() {
if (System.getProperty(TEST_DIRECTORY_KEY) == null) {
System.setProperty(TEST_DIRECTORY_KEY, new File(
"build/hbase/test").getAbsolutePath());
}
}
/**
* Common method to close down a MiniDFSCluster and the associated file system
*
* @param cluster
*/
public static void shutdownDfs(MiniDFSCluster cluster) {
if (cluster != null) {
try {
FileSystem fs = cluster.getFileSystem();
if (fs != null) {
LOG.info("Shutting down FileSystem");
fs.close();
}
} catch (IOException e) {
LOG.error("error closing file system", e);
}
LOG.info("Shutting down Mini DFS ");
try {
cluster.shutdown();
} catch (Exception e) {
/// Can get a java.lang.reflect.UndeclaredThrowableException thrown
// here because of an InterruptedException. Don't let exceptions in
// here be cause of test failure.
}
}
}
protected void createRootAndMetaRegions() throws IOException {
root = HRegion.createHRegion(HRegionInfo.ROOT_REGIONINFO, testDir, conf);
meta = HRegion.createHRegion(HRegionInfo.FIRST_META_REGIONINFO, testDir,
conf);
HRegion.addRegionToMETA(root, meta);
}
protected void closeRootAndMeta() throws IOException {
if (meta != null) {
meta.close();
meta.getLog().closeAndDelete();
}
if (root != null) {
root.close();
root.getLog().closeAndDelete();
}
}
}
| true | true | protected static long addContent(final Incommon updater, final String column,
final byte [] startKeyBytes, final byte [] endKey, final long ts)
throws IOException {
long count = 0;
// Add rows of three characters. The first character starts with the
// 'a' character and runs up to 'z'. Per first character, we run the
// second character over same range. And same for the third so rows
// (and values) look like this: 'aaa', 'aab', 'aac', etc.
char secondCharStart = (char)startKeyBytes[1];
char thirdCharStart = (char)startKeyBytes[2];
EXIT: for (char c = (char)startKeyBytes[0]; c <= LAST_CHAR; c++) {
for (char d = secondCharStart; d <= LAST_CHAR; d++) {
for (char e = thirdCharStart; e <= LAST_CHAR; e++) {
byte [] t = new byte [] {(byte)c, (byte)d, (byte)e};
if (endKey != null && endKey.length > 0
&& Bytes.compareTo(endKey, t) <= 0) {
break EXIT;
}
try {
Put put = new Put(t);
if(ts != -1) {
put.setTimeStamp(ts);
}
try {
put.add(Bytes.toBytes(column), null, t);
updater.put(put);
count++;
} catch (RuntimeException ex) {
ex.printStackTrace();
throw ex;
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
} catch (RuntimeException ex) {
ex.printStackTrace();
throw ex;
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
}
// Set start character back to FIRST_CHAR after we've done first loop.
thirdCharStart = FIRST_CHAR;
}
secondCharStart = FIRST_CHAR;
}
return count;
}
| protected static long addContent(final Incommon updater, final String column,
final byte [] startKeyBytes, final byte [] endKey, final long ts)
throws IOException {
long count = 0;
// Add rows of three characters. The first character starts with the
// 'a' character and runs up to 'z'. Per first character, we run the
// second character over same range. And same for the third so rows
// (and values) look like this: 'aaa', 'aab', 'aac', etc.
char secondCharStart = (char)startKeyBytes[1];
char thirdCharStart = (char)startKeyBytes[2];
EXIT: for (char c = (char)startKeyBytes[0]; c <= LAST_CHAR; c++) {
for (char d = secondCharStart; d <= LAST_CHAR; d++) {
for (char e = thirdCharStart; e <= LAST_CHAR; e++) {
byte [] t = new byte [] {(byte)c, (byte)d, (byte)e};
if (endKey != null && endKey.length > 0
&& Bytes.compareTo(endKey, t) <= 0) {
break EXIT;
}
try {
Put put = new Put(t);
if(ts != -1) {
put.setTimeStamp(ts);
}
try {
byte[][] split = KeyValue.parseColumn(Bytes.toBytes(column));
put.add(split[0], split[1], t);
updater.put(put);
count++;
} catch (RuntimeException ex) {
ex.printStackTrace();
throw ex;
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
} catch (RuntimeException ex) {
ex.printStackTrace();
throw ex;
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
}
// Set start character back to FIRST_CHAR after we've done first loop.
thirdCharStart = FIRST_CHAR;
}
secondCharStart = FIRST_CHAR;
}
return count;
}
|
diff --git a/src/enterpriseapp/mail/MailSender.java b/src/enterpriseapp/mail/MailSender.java
index 5a67c77..bfba1e3 100644
--- a/src/enterpriseapp/mail/MailSender.java
+++ b/src/enterpriseapp/mail/MailSender.java
@@ -1,107 +1,109 @@
package enterpriseapp.mail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import enterpriseapp.Utils;
import enterpriseapp.ui.Constants;
/**
* Helper class to send emails. Sending account is configured in your properties files (see defaultConfiguration.properties).
*
* @author Alejandro Duarte
*
*/
public class MailSender {
/**
* Sends an email message.
* @param recipient destination email.
* @param subject Subject of the message
* @param message Text of the message to send.
* @throws javax.mail.MessagingException
*/
public static void send(String recipient, String subject, String message) throws javax.mail.MessagingException {
List<String> recipients = new ArrayList<String>();
recipients.add(recipient);
send(recipients, subject, message);
}
/**
* Sends an email to multiple recipients.
* @param recipients Collection of destination emails.
* @param subject Subject of the message.
* @param message Text of the message to send.
* @throws javax.mail.MessagingException
*/
public static void send(Collection<String> recipients, String subject, String message) throws javax.mail.MessagingException {
send(recipients, subject, message, null, null);
}
/**
* Sends an email to multiple recipients.
* @param recipients Collection of destination emails.
* @param subject Subject of the message.
* @param message Text of the message to send.
* @param dataHandler DataHandler used to atthach a file.
* @param fileName Name of the file.
* @throws javax.mail.MessagingException
*/
public static void send(Collection<String> recipients, String subject, String message, DataHandler dataHandler, String fileName) throws javax.mail.MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", Constants.mailSmtpHost);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", Constants.mailSmtpPort);
props.put("mail.smtp.socketFactory.port", Constants.mailSmtpPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Constants.mailSmtpUsername, Constants.mailSmtpPassword());
}
}
);
session.setDebug(false);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(Constants.mailSmtpAddress);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.size()];
for (int i = 0; i < recipients.size(); i++) {
if(Constants.mailDeviateTo != null && !Constants.mailDeviateTo.isEmpty()) {
addressTo[i] = new InternetAddress(Constants.mailDeviateTo);
} else {
addressTo[i] = new InternetAddress((String) recipients.toArray()[i]);
}
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
msg.setSubject(subject);
msg.setContent(Utils.replaceHtmlSpecialCharacters(message), "text/html");
msg.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
- msg.setDataHandler(dataHandler);
- msg.setFileName(fileName);
+ if(dataHandler != null) {
+ msg.setDataHandler(dataHandler);
+ msg.setFileName(fileName);
+ }
Transport.send(msg);
}
}
| true | true | public static void send(Collection<String> recipients, String subject, String message, DataHandler dataHandler, String fileName) throws javax.mail.MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", Constants.mailSmtpHost);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", Constants.mailSmtpPort);
props.put("mail.smtp.socketFactory.port", Constants.mailSmtpPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Constants.mailSmtpUsername, Constants.mailSmtpPassword());
}
}
);
session.setDebug(false);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(Constants.mailSmtpAddress);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.size()];
for (int i = 0; i < recipients.size(); i++) {
if(Constants.mailDeviateTo != null && !Constants.mailDeviateTo.isEmpty()) {
addressTo[i] = new InternetAddress(Constants.mailDeviateTo);
} else {
addressTo[i] = new InternetAddress((String) recipients.toArray()[i]);
}
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
msg.setSubject(subject);
msg.setContent(Utils.replaceHtmlSpecialCharacters(message), "text/html");
msg.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
msg.setDataHandler(dataHandler);
msg.setFileName(fileName);
Transport.send(msg);
}
| public static void send(Collection<String> recipients, String subject, String message, DataHandler dataHandler, String fileName) throws javax.mail.MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", Constants.mailSmtpHost);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", Constants.mailSmtpPort);
props.put("mail.smtp.socketFactory.port", Constants.mailSmtpPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Constants.mailSmtpUsername, Constants.mailSmtpPassword());
}
}
);
session.setDebug(false);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(Constants.mailSmtpAddress);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.size()];
for (int i = 0; i < recipients.size(); i++) {
if(Constants.mailDeviateTo != null && !Constants.mailDeviateTo.isEmpty()) {
addressTo[i] = new InternetAddress(Constants.mailDeviateTo);
} else {
addressTo[i] = new InternetAddress((String) recipients.toArray()[i]);
}
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
msg.setSubject(subject);
msg.setContent(Utils.replaceHtmlSpecialCharacters(message), "text/html");
msg.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
if(dataHandler != null) {
msg.setDataHandler(dataHandler);
msg.setFileName(fileName);
}
Transport.send(msg);
}
|
diff --git a/src/SerialPort/Port.java b/src/SerialPort/Port.java
index fee9fed..19be41f 100644
--- a/src/SerialPort/Port.java
+++ b/src/SerialPort/Port.java
@@ -1,291 +1,291 @@
package SerialPort;
import gnu.io.*;
import java.util.*;
import Log.Logger;
import Game.Score;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
public class Port {
private SerialPort serialPort;
private String port;
private int baudrate;
private InputStream inputStream;
private OutputStream outputStream;
private Score score;
public static String[] listPorts() throws Exception {
CommPortIdentifier portId;
Enumeration portList;
String[] ports = new String[10];
portList = CommPortIdentifier.getPortIdentifiers();
int i = 0;
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
/* We willen alleen serieële poorten */
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
ports[i] = portId.getName();
i++;
}
}
if (i == 0) {
ports = null;
}
return ports;
}
public Port(String port) {
this.port = port;
}
public Port(String port, int baudrate) {
this.port = port;
this.baudrate = baudrate;
}
public void setScoreObject(Score score) {
this.score = score;
}
public void open() {
CommPortIdentifier portId = null;
/* We openen de poort */
try {
portId = CommPortIdentifier.getPortIdentifier(this.port);
this.serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000);
this.serialPort.setSerialPortParams(this.baudrate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
this.inputStream = serialPort.getInputStream();
this.outputStream = serialPort.getOutputStream();
this.serialPort.addEventListener(new ScoreReader(this.inputStream, this));
this.serialPort.notifyOnDataAvailable(true);
Logger.msg("Info", "Opened serial port: " + this.port + " with baudrate: " + this.baudrate);
} catch (Exception e) {
Logger.msg("Error", "Could not open " + this.port + " the message was: " + e.getMessage());
}
}
private void sendPacket(byte[] packetLoad) {
try {
this.outputStream.write(packetLoad);
this.outputStream.flush();
Logger.msg("Info", "Sending: " + this.hexToString(packetLoad));
} catch (Exception e) {
Logger.msg("Error", "Could not send packet, the message was: " + e.getMessage());
}
}
/* Stuur start commando naar alle vlaggen */
public void roundStart() {
Logger.msg("Info", "Sending start signal to all flags");
byte[] startGame = { (byte)238, (byte)255, (byte)255, 0, 0, 17, 1, 1, 0, (byte)238, (byte)204 };
/* Uit veiligheid sturen we een start en stop 3 keer */
for (int i = 0; i < 3; i++) {
this.sendPacket(startGame);
}
}
/* Stuur het stop commando naar alle vlaggen */
public void roundEnd() {
Logger.msg("Info", "Sending stop signal to all flags");
byte[] stopGame = { (byte)238, (byte)255, (byte)255, 0, 0, 17, 1, 2, 0, (byte)238, (byte)204 };
/* Uit veiligheid sturen we een start en stop 3 keer */
for (int i = 0; i < 3; i++) {
this.sendPacket(stopGame);
try {
Thread.sleep(100);
} catch (Exception e) {}
}
}
/* Reset de vlaggen, alles op 0 */
public void reset() {
Logger.msg("Info", "Resetting all flags");
byte[] resetGame = { (byte)238, (byte)255, (byte)255, 0, 0, 17, 1, 3, 0, (byte)238, (byte)204 };
this.sendPacket(resetGame);
}
public void reverseFlag(int destination) {
Logger.msg("Info", "Sending timereverse to flag: " + destination);
byte[] reverseFlag = { (byte)238, (byte)255, (byte)destination, 0, 0, 64, 1, 3, 0, (byte)238, (byte)204 };
this.sendPacket(reverseFlag);
}
public void freezeFlag(int destination) {
Logger.msg("Info", "Sending freeze to flag: " + destination);
byte[] freezeFlag = { (byte)238, (byte)255, (byte)destination, 0, 0, 64, 1, 0, 0, (byte)238, (byte)204 };
this.sendPacket(freezeFlag);
}
public void setGameSettings(int roundtime, int respawntime, int countdowntime) {
Logger.msg("Info", "Sending round data to all flags. Roundtime: " + roundtime + ", Respawntime: " + respawntime);
// De vlaggen verwachten hun data in 16 bits, daarom een cast naar een 16-bits short
short sRoundTime = new Integer(roundtime).shortValue();
short sRespawnTime = new Integer(respawntime).shortValue();
short sCountDownTime = new Integer(countdowntime).shortValue();
byte[] roundTimePacket = { (byte)238, (byte)255, (byte)255, 0, 2, 16, 4, 0, 1, (byte)(sRoundTime >> 8), (byte)sRoundTime, 0, (byte)238, (byte)204 };
byte[] respawnTimePacket = { (byte)238, (byte)255, (byte)255, 0, 2, 16, 4, 1, 1, (byte)(sRespawnTime >> 8), (byte)sRespawnTime, 0, (byte)238, (byte)204 };
byte[] countdownTimePacket = { (byte)238, (byte)255, (byte)255, 0, 2, 16, 4, 2, 0, (byte)(sCountDownTime >> 8), (byte)sCountDownTime, 0, (byte)238, (byte)204 };
this.sendPacket(roundTimePacket);
try {
Thread.sleep(300);
} catch (Exception e) {}
this.sendPacket(respawnTimePacket);
try {
Thread.sleep(300);
} catch (Exception e) {}
this.sendPacket(countdownTimePacket);
}
public void poll() {
byte[] pollPacket = { (byte)238, (byte)255, (byte)255, 0, 1, 32, 0, 0, (byte)238, (byte)204 };
this.sendPacket(pollPacket);
}
public void close() {
Logger.msg("Info", "Closing serial port.");
this.serialPort.close();
}
public void finalize() {
this.close();
}
protected synchronized void handleReceivedScores(byte[] packet) {
byte sender;
byte destination;
byte messagetype;
byte command;
byte length;
byte crc;
destination = packet[2];
sender = packet[3];
messagetype = packet[4];
command = packet[5];
length = packet[6];
/* Op dit moment wordt er GEEN gebruik gemaakt van enige vorm van CRC */
crc = packet[length + 7];
byte[] data = new byte[length];
for (int i = 0; i < length; i++) {
data[i] = packet[7 + i];
}
Logger.msg("Info", "Destination: " + destination + ", Sender: " + sender + ", Command: " + command);
if (destination == 0) {
switch (command) {
case 32:
switch (sender) {
case 1:
- this.score.setBlueBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
- break;
+ this.score.setBlueBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
+ break;
case 2:
- this.score.setRedBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
- break;
+ this.score.setRedBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
+ break;
case 3:
- this.score.setSwingBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
+ this.score.setSwingBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
break;
default:
Logger.msg("Warn", "Received a packet with wrong sender (" + sender + "), please check the dipswitches!");
break;
}
break;
default:
break;
}
}
Logger.msg("Info", "Finished processing packet");
}
public static class ScoreReader implements SerialPortEventListener {
private InputStream in;
private byte[] buffer = new byte[32];
private Port port;
public ScoreReader (InputStream in, Port port) {
this.in = in;
this.port = port;
}
public synchronized void serialEvent(SerialPortEvent arg0) {
int data;
try {
int len = 0;
boolean validPacket = true;
while ((data = in.read()) > -1) {
/* Als het eerste pakket geen 0xFF (255) bevat, dan is het geen volledig pakket */
if (len == 0 && data != 238) {
Logger.msg("Warn", "Corrupt packet received, did not start with 0xFF!");
validPacket = false;
} else {
buffer[len++] = (byte) data;
/* End of packet, verwerk het ingekomen pakket */
if (data == 204) {
break;
}
}
}
if (validPacket) {
Logger.msg("Info", "Received packet: " + port.hexToString(buffer));
port.handleReceivedScores(buffer);
}
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
protected String hexToString(byte[] packet) {
String hexString = "";
for (int i = 0; i < packet.length; i++) {
if (packet[i] == 204) {
break;
}
String hex = "0x";
hex += Integer.toHexString(packet[i]).toUpperCase();
hexString += hex + " ";
}
return hexString;
}
}
| false | true | protected synchronized void handleReceivedScores(byte[] packet) {
byte sender;
byte destination;
byte messagetype;
byte command;
byte length;
byte crc;
destination = packet[2];
sender = packet[3];
messagetype = packet[4];
command = packet[5];
length = packet[6];
/* Op dit moment wordt er GEEN gebruik gemaakt van enige vorm van CRC */
crc = packet[length + 7];
byte[] data = new byte[length];
for (int i = 0; i < length; i++) {
data[i] = packet[7 + i];
}
Logger.msg("Info", "Destination: " + destination + ", Sender: " + sender + ", Command: " + command);
if (destination == 0) {
switch (command) {
case 32:
switch (sender) {
case 1:
this.score.setBlueBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
break;
case 2:
this.score.setRedBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
break;
case 3:
this.score.setSwingBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
break;
default:
Logger.msg("Warn", "Received a packet with wrong sender (" + sender + "), please check the dipswitches!");
break;
}
break;
default:
break;
}
}
Logger.msg("Info", "Finished processing packet");
}
| protected synchronized void handleReceivedScores(byte[] packet) {
byte sender;
byte destination;
byte messagetype;
byte command;
byte length;
byte crc;
destination = packet[2];
sender = packet[3];
messagetype = packet[4];
command = packet[5];
length = packet[6];
/* Op dit moment wordt er GEEN gebruik gemaakt van enige vorm van CRC */
crc = packet[length + 7];
byte[] data = new byte[length];
for (int i = 0; i < length; i++) {
data[i] = packet[7 + i];
}
Logger.msg("Info", "Destination: " + destination + ", Sender: " + sender + ", Command: " + command);
if (destination == 0) {
switch (command) {
case 32:
switch (sender) {
case 1:
this.score.setBlueBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
break;
case 2:
this.score.setRedBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
break;
case 3:
this.score.setSwingBaseScore(data[6], (int)(data[2] << 8 | data[3] & 0xFF), (int)(data[4] << 8 | data[5] & 0xFF));
break;
default:
Logger.msg("Warn", "Received a packet with wrong sender (" + sender + "), please check the dipswitches!");
break;
}
break;
default:
break;
}
}
Logger.msg("Info", "Finished processing packet");
}
|
diff --git a/seminer/src/cvsanaly/CvsAnalyReleaseOverviewReader.java b/seminer/src/cvsanaly/CvsAnalyReleaseOverviewReader.java
index c8fa0e6..cd6a0de 100644
--- a/seminer/src/cvsanaly/CvsAnalyReleaseOverviewReader.java
+++ b/seminer/src/cvsanaly/CvsAnalyReleaseOverviewReader.java
@@ -1,52 +1,54 @@
package cvsanaly;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import seminer.ReleaseOverview;
import seminer.ReleaseOverviewReader;
public class CvsAnalyReleaseOverviewReader implements ReleaseOverviewReader {
Session s;
public CvsAnalyReleaseOverviewReader(Session s) {
this.s = s;
}
@Override
public List<ReleaseOverview> read(String project) {
List<ReleaseOverview> releases = new ArrayList<ReleaseOverview>();
List<Object[]> results = s.createSQLQuery("SELECT {tags.*}, {scmlog.*} FROM tags LEFT OUTER JOIN tag_revisions ON tags.id = tag_revisions.tag_id LEFT OUTER JOIN scmlog ON scmlog.id = tag_revisions.commit_id LEFT OUTER JOIN repositories ON repositories.id = scmlog.repository_id WHERE repositories.name = '" + project + "'").addEntity("tags", Tags.class).addEntity("scmlog", Scmlog.class).list();
for (Object[] result : results) {
Tags tag = (Tags)result[0];
Scmlog scmlog = (Scmlog)result[1];
String branchName = null;
List<Branches> branches = s.createSQLQuery("SELECT DISTINCT {branches.*} FROM actions LEFT OUTER JOIN branches ON actions.branch_id = branches.id WHERE actions.commit_id = " + scmlog.getId()).addEntity("branches", Branches.class).list();
- if(branches.size() != 1) {
+ if(branches.size() == 0) {
+ System.err.println(project + " tag " + tag.getName() + " not created from a branch");
+ } else if(branches.size() > 1) {
System.err.println(project + " tag " + tag.getName() + " created from multiple branches");
} else {
branchName = branches.get(0).getName();
}
ReleaseOverview release = new ReleaseOverview();
release.setProject_name(project);
release.setRelease_number(tag.getName());
release.setRelease_timestamp(scmlog.getDate());
release.setBranch_name(branchName);
//release.setLoc(loc);
//release.setNum_of_changerequest(num_of_changerequest);
//release.setNum_of_committers(num_of_committers);
//release.setNum_of_developers(num_of_developers);
//release.setNum_of_files(num_of_files)
//release.setRelease_location(release_location);
releases.add(release);
}
return releases;
}
}
| true | true | public List<ReleaseOverview> read(String project) {
List<ReleaseOverview> releases = new ArrayList<ReleaseOverview>();
List<Object[]> results = s.createSQLQuery("SELECT {tags.*}, {scmlog.*} FROM tags LEFT OUTER JOIN tag_revisions ON tags.id = tag_revisions.tag_id LEFT OUTER JOIN scmlog ON scmlog.id = tag_revisions.commit_id LEFT OUTER JOIN repositories ON repositories.id = scmlog.repository_id WHERE repositories.name = '" + project + "'").addEntity("tags", Tags.class).addEntity("scmlog", Scmlog.class).list();
for (Object[] result : results) {
Tags tag = (Tags)result[0];
Scmlog scmlog = (Scmlog)result[1];
String branchName = null;
List<Branches> branches = s.createSQLQuery("SELECT DISTINCT {branches.*} FROM actions LEFT OUTER JOIN branches ON actions.branch_id = branches.id WHERE actions.commit_id = " + scmlog.getId()).addEntity("branches", Branches.class).list();
if(branches.size() != 1) {
System.err.println(project + " tag " + tag.getName() + " created from multiple branches");
} else {
branchName = branches.get(0).getName();
}
ReleaseOverview release = new ReleaseOverview();
release.setProject_name(project);
release.setRelease_number(tag.getName());
release.setRelease_timestamp(scmlog.getDate());
release.setBranch_name(branchName);
//release.setLoc(loc);
//release.setNum_of_changerequest(num_of_changerequest);
//release.setNum_of_committers(num_of_committers);
//release.setNum_of_developers(num_of_developers);
//release.setNum_of_files(num_of_files)
//release.setRelease_location(release_location);
releases.add(release);
}
return releases;
}
| public List<ReleaseOverview> read(String project) {
List<ReleaseOverview> releases = new ArrayList<ReleaseOverview>();
List<Object[]> results = s.createSQLQuery("SELECT {tags.*}, {scmlog.*} FROM tags LEFT OUTER JOIN tag_revisions ON tags.id = tag_revisions.tag_id LEFT OUTER JOIN scmlog ON scmlog.id = tag_revisions.commit_id LEFT OUTER JOIN repositories ON repositories.id = scmlog.repository_id WHERE repositories.name = '" + project + "'").addEntity("tags", Tags.class).addEntity("scmlog", Scmlog.class).list();
for (Object[] result : results) {
Tags tag = (Tags)result[0];
Scmlog scmlog = (Scmlog)result[1];
String branchName = null;
List<Branches> branches = s.createSQLQuery("SELECT DISTINCT {branches.*} FROM actions LEFT OUTER JOIN branches ON actions.branch_id = branches.id WHERE actions.commit_id = " + scmlog.getId()).addEntity("branches", Branches.class).list();
if(branches.size() == 0) {
System.err.println(project + " tag " + tag.getName() + " not created from a branch");
} else if(branches.size() > 1) {
System.err.println(project + " tag " + tag.getName() + " created from multiple branches");
} else {
branchName = branches.get(0).getName();
}
ReleaseOverview release = new ReleaseOverview();
release.setProject_name(project);
release.setRelease_number(tag.getName());
release.setRelease_timestamp(scmlog.getDate());
release.setBranch_name(branchName);
//release.setLoc(loc);
//release.setNum_of_changerequest(num_of_changerequest);
//release.setNum_of_committers(num_of_committers);
//release.setNum_of_developers(num_of_developers);
//release.setNum_of_files(num_of_files)
//release.setRelease_location(release_location);
releases.add(release);
}
return releases;
}
|
diff --git a/unix-maven-plugin/src/main/java/org/codehaus/mojo/unix/maven/MojoHelper.java b/unix-maven-plugin/src/main/java/org/codehaus/mojo/unix/maven/MojoHelper.java
index 8883e4a..ad85dcf 100644
--- a/unix-maven-plugin/src/main/java/org/codehaus/mojo/unix/maven/MojoHelper.java
+++ b/unix-maven-plugin/src/main/java/org/codehaus/mojo/unix/maven/MojoHelper.java
@@ -1,519 +1,519 @@
package org.codehaus.mojo.unix.maven;
/*
* The MIT License
*
* Copyright 2009 The Codehaus.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import fj.*;
import static fj.Function.*;
import static fj.P.*;
import fj.data.List;
import static fj.data.List.join;
import static fj.data.List.*;
import static fj.data.List.single;
import fj.data.*;
import static fj.data.Option.*;
import fj.data.Set;
import static fj.data.Set.*;
import static fj.pre.Ord.*;
import org.apache.commons.logging.*;
import org.apache.commons.vfs.*;
import org.apache.maven.artifact.*;
import org.apache.maven.plugin.*;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.*;
import org.codehaus.mojo.unix.*;
import static org.codehaus.mojo.unix.PackageParameters.*;
import org.codehaus.mojo.unix.core.*;
import org.codehaus.mojo.unix.java.*;
import static org.codehaus.mojo.unix.java.StringF.*;
import org.codehaus.mojo.unix.maven.logging.*;
import org.codehaus.mojo.unix.maven.plugin.*;
import org.codehaus.mojo.unix.maven.plugin.Package;
import static org.codehaus.mojo.unix.util.FileModulator.*;
import org.codehaus.mojo.unix.util.*;
import org.codehaus.mojo.unix.util.line.*;
import java.io.*;
import static java.lang.String.*;
import java.text.*;
import java.util.*;
import java.util.TreeMap;
/**
* Utility class encapsulating how to create a package. Used by all packaging Mojos.
*
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @version $Id$
*/
public abstract class MojoHelper
{
public static final String ATTACHED_NO_ARTIFACTS_CONFIGURED = "When running in attached mode at least one package has to be configured.";
public static final String DUPLICATE_CLASSIFIER = "Duplicate package classifier: '%s'.";
public static final String DUPLICATE_UNCLASSIFIED = "There can only be one package without an classifier.";
static
{
System.setProperty( LogFactory.class.getName(), MavenCommonLoggingLogFactory.class.getName() );
}
public static Execution create( Map platforms,
String platformType,
Map formats,
String formatType,
MavenProjectWrapper project,
boolean debug,
boolean attachedMode,
F<UnixPackage, UnixPackage> validateMojoSettingsAndApplyFormatSpecificSettingsToPackage,
PackagingMojoParameters mojoParameters,
final Log log )
throws MojoFailureException, MojoExecutionException
{
MavenCommonLoggingLogFactory.setMavenLogger( log );
PackagingFormat format = (PackagingFormat) formats.get( formatType );
if ( format == null )
{
throw new MojoFailureException( "INTERNAL ERROR: could not find format: '" + formatType + "'." );
}
UnixPlatform platform = (UnixPlatform) platforms.get( platformType );
if ( platform == null )
{
throw new MojoFailureException( "INTERNAL ERROR: could not find platform: '" + platformType + "'." );
}
/*
// TODO: This is using a private Maven API that might change. Perhaps use some reflection magic here.
String timestamp = snapshotTransformation.getDeploymentTimestamp();
*/
// This chunk replaces the above getDeploymentTimestamp. However, it not ensure that all files get the
// same timestamp. Need to look into how this is done with Maven 3
DateFormat utcDateFormatter = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
utcDateFormatter.setTimeZone( TimeZone.getTimeZone( "UTC" ));
String timestamp = utcDateFormatter.format(new Date());
FileObject buildDirectory;
try
{
FileSystemManager fileSystemManager = VFS.getManager();
buildDirectory = fileSystemManager.resolveFile( project.buildDirectory.getAbsolutePath() );
}
catch ( FileSystemException e )
{
throw new MojoExecutionException( "Error while initializing Commons VFS", e);
}
PackageVersion version = PackageVersion.packageVersion( project.version, timestamp,
project.artifact.isSnapshot(), mojoParameters.revision );
List<P3<UnixPackage, Package, List<AssemblyOperation>>> packages = nil();
for ( Package pakke : validatePackages( mojoParameters.packages, attachedMode ) )
{
try
{
String name = "unix/root-" + formatType + pakke.classifier.map( dashString ).orSome( "" );
FileObject packageRoot = buildDirectory.resolveFile( name );
packageRoot.createFolder();
PackageParameters parameters = calculatePackageParameters( project,
version,
platform,
mojoParameters,
pakke );
UnixPackage unixPackage = format.start().
parameters( parameters ).
setVersion( version ). // TODO: This should go away
workingDirectory( packageRoot ).
debug( debug ).
basedir( project.basedir );
// -----------------------------------------------------------------------
// Let the implementation add its metadata
// -----------------------------------------------------------------------
unixPackage = validateMojoSettingsAndApplyFormatSpecificSettingsToPackage.f( unixPackage );
// TODO: here the logic should be different if many packages are to be created.
// Example: name should be taken from mojoParameters if there is only a single package, if not
// it should come from the Pakke object. This should also be validated, at least for
// name
List<AssemblyOperation> assemblyOperations = createAssemblyOperations( project,
parameters,
unixPackage,
project.basedir,
buildDirectory,
mojoParameters.assembly,
pakke.assembly );
// -----------------------------------------------------------------------
// Dump the execution
// -----------------------------------------------------------------------
if ( debug )
{
log.info( "=======================================================================" );
log.info( "Package parameters: " + parameters.id );
log.info( "Default file attributes: " );
log.info( " File : " + parameters.defaultFileAttributes );
log.info( " Directory : " + parameters.defaultDirectoryAttributes );
log.info( "Assembly operations: " );
for ( AssemblyOperation operation : assemblyOperations )
{
operation.streamTo( new AbstractLineStreamWriter()
{
protected void onLine( String line )
{
log.info( line );
}
} );
}
}
packages = packages.cons( p(unixPackage, pakke, assemblyOperations ) );
}
catch ( UnknownArtifactException e )
{
Map map = new TreeMap<String, Artifact>( e.artifactMap );
// TODO: Do not log here, throw a CouldNotFindArtifactException with the map as an argument
log.warn("Could not find artifact:" + e.artifact );
log.warn("Available artifacts:");
for ( Object o : map.keySet() )
{
log.warn( o.toString() );
}
throw new MojoFailureException( "Unable to find artifact: '" + e.artifact + "'. See log for available artifacts." );
}
catch ( MissingSettingException e )
{
String msg = "Missing required setting '" + e.getSetting() + "'";
if ( !pakke.classifier.isNone() )
{
msg += ", for '" + pakke.classifier.some() + "'";
}
msg += ", format '" + formatType + "'.";
throw new MojoFailureException( msg );
}
catch ( IOException e )
{
- throw new MojoExecutionException( "Error creating package '" + pakke.classifier + "', format '" + formatType + "'.", e );
+ throw new MojoExecutionException( "Error creating package " + (pakke.classifier.isSome() ? "classifier '" + pakke.classifier + "'" : "") + ", format '" + formatType + "'.", e );
}
}
return new Execution( packages, project, formatType, attachedMode );
}
public static class Execution
{
private final List<P3<UnixPackage, Package, List<AssemblyOperation>>> packages;
private final MavenProjectWrapper project;
private final String formatType;
private final boolean attachedMode;
public Execution( List<P3<UnixPackage, Package, List<AssemblyOperation>>> packages, MavenProjectWrapper project,
String formatType, boolean attachedMode )
{
this.packages = packages;
this.project = project;
this.formatType = formatType;
this.attachedMode = attachedMode;
}
public void execute( String artifactType, MavenProject mavenProject, MavenProjectHelper mavenProjectHelper, ScriptUtil.Strategy strategy )
throws MojoExecutionException, MojoFailureException
{
for ( P3<UnixPackage, Package, List<AssemblyOperation>> p : packages )
{
UnixPackage unixPackage = p._1();
Package pakke = p._2();
try
{
// -----------------------------------------------------------------------
// Assemble all the files
// -----------------------------------------------------------------------
for ( AssemblyOperation assemblyOperation : p._3() )
{
assemblyOperation.perform( unixPackage );
}
// -----------------------------------------------------------------------
// Package the stuff
// -----------------------------------------------------------------------
String name = project.artifactId +
pakke.classifier.map( dashString ).orSome( "" ) +
"-" + unixPackage.getVersion().getMavenVersion() +
"." + unixPackage.getPackageFileExtension();
File packageFile = new File( project.buildDirectory, name );
unixPackage.
packageToFile( packageFile, strategy );
attach( pakke.classifier, artifactType, packageFile, mavenProject, mavenProjectHelper,
attachedMode );
}
catch ( MojoExecutionException e )
{
throw e;
}
catch ( MojoFailureException e )
{
throw e;
}
catch ( Exception e )
{
throw new MojoExecutionException( "Unable to create package.", e );
}
}
}
private void attach( Option<String> classifier, String artifactType, File packageFile,
MavenProject project, MavenProjectHelper mavenProjectHelper, boolean attachedMode )
{
if ( attachedMode )
{
// In attached mode all the packages are required to have an classifier - this used to be correct - trygve
// For some reason it is allowed to have attached artifacts without classifier as long as the types differ
if ( classifier.isSome() )
{
mavenProjectHelper.attachArtifact( project, artifactType, classifier.some(), packageFile );
}
else
{
mavenProjectHelper.attachArtifact( project, artifactType, null, packageFile );
}
}
else
{
if ( classifier.isNone() )
{
project.getArtifact().setFile( packageFile );
}
else
{
mavenProjectHelper.attachArtifact( project, formatType, classifier.some(), packageFile );
}
}
}
}
public static PackageParameters calculatePackageParameters( final MavenProjectWrapper project,
PackageVersion version,
UnixPlatform platform,
PackagingMojoParameters mojoParameters,
final Package pakke )
{
String id = pakke.id.orSome( new P1<String>()
{
public String _1()
{
// This used to be ${groupId}-${artifactId}, but it was too long for pkg so this is a more sane default
return project.artifactId + pakke.classifier.map( dashString ).orSome( "" );
}
} );
P2<FileAttributes, FileAttributes> defaultFileAttributes =
calculateDefaultFileAttributes( platform,
mojoParameters.defaults,
pakke.defaults );
String name = pakke.name.orElse( mojoParameters.name ).orSome( project.name );
return packageParameters( project.groupId, project.artifactId, version, id, name, pakke.classifier, defaultFileAttributes._1(), defaultFileAttributes._2() ).
description( pakke.description.orElse( mojoParameters.description ).orElse( project.description ) ).
contact( mojoParameters.contact ).
contactEmail( mojoParameters.contactEmail ).
license( getLicense( project ) ).
architecture( mojoParameters.architecture );
}
public static P2<FileAttributes, FileAttributes> calculateDefaultFileAttributes( UnixPlatform platform,
Defaults mojo,
Defaults pakke )
{
return p(calculateFileAttributes( platform.getDefaultFileAttributes(),
mojo.fileAttributes.create(),
pakke.fileAttributes.create() ),
calculateFileAttributes( platform.getDefaultDirectoryAttributes(),
mojo.directoryAttributes.create(),
pakke.directoryAttributes.create() ) );
}
public static FileAttributes calculateFileAttributes( FileAttributes platform,
FileAttributes mojo,
FileAttributes pakke )
{
// Calculate default file and directory attributes.
// Priority order (last one wins): platform -> mojo defaults -> package defaults
return platform.
useAsDefaultsFor( mojo ).
useAsDefaultsFor( pakke );
}
public static List<AssemblyOperation> createAssemblyOperations( MavenProjectWrapper project,
PackageParameters parameters,
UnixPackage unixPackage,
File basedir,
FileObject buildDirectory,
List<AssemblyOp> mojoAssembly,
List<AssemblyOp> packageAssembly )
throws IOException, MojoFailureException, UnknownArtifactException
{
unixPackage.beforeAssembly( parameters.defaultDirectoryAttributes );
// Create the default set of assembly operations
String unix = new File( basedir, "src/main/unix/files" ).getAbsolutePath();
String classifierOrDefault = parameters.classifier.orSome( "default" );
List<AssemblyOp> defaultAssemblyOp = nil();
// It would be possible to use the AssemblyOperations here but this just make it easier to document
// as it has a one-to-one relationship with what the user would configure in a POM
for ( String s : modulatePath( classifierOrDefault, unixPackage.getPackageFileExtension(), unix ) )
{
File file = new File( s );
if ( !file.isDirectory() )
{
continue;
}
CopyDirectory op = new CopyDirectory();
op.setFrom( file );
defaultAssemblyOp = defaultAssemblyOp.cons( op );
}
// Create the complete list of assembly operations.
// Order: defaults -> mojo -> pakke
List<AssemblyOp> assemblyOps = join( list( defaultAssemblyOp.reverse(), mojoAssembly, packageAssembly ) );
List<AssemblyOperation> operations = nil();
for ( AssemblyOp assemblyOp : assemblyOps )
{
assemblyOp.setArtifactMap( project.artifactConflictIdMap );
AssemblyOperation operation = assemblyOp.createOperation( buildDirectory,
parameters.defaultFileAttributes,
parameters.defaultDirectoryAttributes );
operations = operations.cons( operation );
}
return operations.reverse();
}
public static List<Package> validatePackages( List<Package> packages, boolean attachedMode )
throws MojoFailureException
{
if ( packages.isEmpty() )
{
packages = single( new Package() );
}
Set<String> names = empty( stringOrd );
List<Package> outPackages = nil();
Option<Package> defaultPackage = none();
for ( Package pakke : packages )
{
if ( pakke.classifier.exists( curry( StringF.equals, "default" ) ) )
{
pakke.classifier = none();
}
if ( pakke.classifier.isNone() )
{
if ( defaultPackage.isSome() )
{
throw new MojoFailureException( DUPLICATE_UNCLASSIFIED );
}
defaultPackage = some( pakke );
}
else
{
if ( names.member( pakke.classifier.some() ) )
{
throw new MojoFailureException( format( DUPLICATE_CLASSIFIER, pakke.classifier ) );
}
names = names.insert( pakke.classifier.some() );
outPackages = outPackages.cons( pakke );
}
}
if ( attachedMode )
{
outPackages = defaultPackage.toList().append( outPackages );
if ( outPackages.isEmpty() )
{
throw new MojoFailureException( ATTACHED_NO_ARTIFACTS_CONFIGURED );
}
return outPackages;
}
if ( defaultPackage.isNone() )
{
throw new MojoFailureException( "When running in 'primary artifact mode' either one package has to have 'default' as classifier or there has to be one without any classifier." );
}
return defaultPackage.toList().append( outPackages );
}
private static Option<String> getLicense( MavenProjectWrapper project )
{
if ( project.licenses.size() == 0 )
{
return none();
}
return some( project.licenses.get( 0 ).getName() );
}
static F<String, String> dashString = curry( concat, "-" );
}
| true | true | public static Execution create( Map platforms,
String platformType,
Map formats,
String formatType,
MavenProjectWrapper project,
boolean debug,
boolean attachedMode,
F<UnixPackage, UnixPackage> validateMojoSettingsAndApplyFormatSpecificSettingsToPackage,
PackagingMojoParameters mojoParameters,
final Log log )
throws MojoFailureException, MojoExecutionException
{
MavenCommonLoggingLogFactory.setMavenLogger( log );
PackagingFormat format = (PackagingFormat) formats.get( formatType );
if ( format == null )
{
throw new MojoFailureException( "INTERNAL ERROR: could not find format: '" + formatType + "'." );
}
UnixPlatform platform = (UnixPlatform) platforms.get( platformType );
if ( platform == null )
{
throw new MojoFailureException( "INTERNAL ERROR: could not find platform: '" + platformType + "'." );
}
/*
// TODO: This is using a private Maven API that might change. Perhaps use some reflection magic here.
String timestamp = snapshotTransformation.getDeploymentTimestamp();
*/
// This chunk replaces the above getDeploymentTimestamp. However, it not ensure that all files get the
// same timestamp. Need to look into how this is done with Maven 3
DateFormat utcDateFormatter = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
utcDateFormatter.setTimeZone( TimeZone.getTimeZone( "UTC" ));
String timestamp = utcDateFormatter.format(new Date());
FileObject buildDirectory;
try
{
FileSystemManager fileSystemManager = VFS.getManager();
buildDirectory = fileSystemManager.resolveFile( project.buildDirectory.getAbsolutePath() );
}
catch ( FileSystemException e )
{
throw new MojoExecutionException( "Error while initializing Commons VFS", e);
}
PackageVersion version = PackageVersion.packageVersion( project.version, timestamp,
project.artifact.isSnapshot(), mojoParameters.revision );
List<P3<UnixPackage, Package, List<AssemblyOperation>>> packages = nil();
for ( Package pakke : validatePackages( mojoParameters.packages, attachedMode ) )
{
try
{
String name = "unix/root-" + formatType + pakke.classifier.map( dashString ).orSome( "" );
FileObject packageRoot = buildDirectory.resolveFile( name );
packageRoot.createFolder();
PackageParameters parameters = calculatePackageParameters( project,
version,
platform,
mojoParameters,
pakke );
UnixPackage unixPackage = format.start().
parameters( parameters ).
setVersion( version ). // TODO: This should go away
workingDirectory( packageRoot ).
debug( debug ).
basedir( project.basedir );
// -----------------------------------------------------------------------
// Let the implementation add its metadata
// -----------------------------------------------------------------------
unixPackage = validateMojoSettingsAndApplyFormatSpecificSettingsToPackage.f( unixPackage );
// TODO: here the logic should be different if many packages are to be created.
// Example: name should be taken from mojoParameters if there is only a single package, if not
// it should come from the Pakke object. This should also be validated, at least for
// name
List<AssemblyOperation> assemblyOperations = createAssemblyOperations( project,
parameters,
unixPackage,
project.basedir,
buildDirectory,
mojoParameters.assembly,
pakke.assembly );
// -----------------------------------------------------------------------
// Dump the execution
// -----------------------------------------------------------------------
if ( debug )
{
log.info( "=======================================================================" );
log.info( "Package parameters: " + parameters.id );
log.info( "Default file attributes: " );
log.info( " File : " + parameters.defaultFileAttributes );
log.info( " Directory : " + parameters.defaultDirectoryAttributes );
log.info( "Assembly operations: " );
for ( AssemblyOperation operation : assemblyOperations )
{
operation.streamTo( new AbstractLineStreamWriter()
{
protected void onLine( String line )
{
log.info( line );
}
} );
}
}
packages = packages.cons( p(unixPackage, pakke, assemblyOperations ) );
}
catch ( UnknownArtifactException e )
{
Map map = new TreeMap<String, Artifact>( e.artifactMap );
// TODO: Do not log here, throw a CouldNotFindArtifactException with the map as an argument
log.warn("Could not find artifact:" + e.artifact );
log.warn("Available artifacts:");
for ( Object o : map.keySet() )
{
log.warn( o.toString() );
}
throw new MojoFailureException( "Unable to find artifact: '" + e.artifact + "'. See log for available artifacts." );
}
catch ( MissingSettingException e )
{
String msg = "Missing required setting '" + e.getSetting() + "'";
if ( !pakke.classifier.isNone() )
{
msg += ", for '" + pakke.classifier.some() + "'";
}
msg += ", format '" + formatType + "'.";
throw new MojoFailureException( msg );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error creating package '" + pakke.classifier + "', format '" + formatType + "'.", e );
}
}
return new Execution( packages, project, formatType, attachedMode );
}
| public static Execution create( Map platforms,
String platformType,
Map formats,
String formatType,
MavenProjectWrapper project,
boolean debug,
boolean attachedMode,
F<UnixPackage, UnixPackage> validateMojoSettingsAndApplyFormatSpecificSettingsToPackage,
PackagingMojoParameters mojoParameters,
final Log log )
throws MojoFailureException, MojoExecutionException
{
MavenCommonLoggingLogFactory.setMavenLogger( log );
PackagingFormat format = (PackagingFormat) formats.get( formatType );
if ( format == null )
{
throw new MojoFailureException( "INTERNAL ERROR: could not find format: '" + formatType + "'." );
}
UnixPlatform platform = (UnixPlatform) platforms.get( platformType );
if ( platform == null )
{
throw new MojoFailureException( "INTERNAL ERROR: could not find platform: '" + platformType + "'." );
}
/*
// TODO: This is using a private Maven API that might change. Perhaps use some reflection magic here.
String timestamp = snapshotTransformation.getDeploymentTimestamp();
*/
// This chunk replaces the above getDeploymentTimestamp. However, it not ensure that all files get the
// same timestamp. Need to look into how this is done with Maven 3
DateFormat utcDateFormatter = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
utcDateFormatter.setTimeZone( TimeZone.getTimeZone( "UTC" ));
String timestamp = utcDateFormatter.format(new Date());
FileObject buildDirectory;
try
{
FileSystemManager fileSystemManager = VFS.getManager();
buildDirectory = fileSystemManager.resolveFile( project.buildDirectory.getAbsolutePath() );
}
catch ( FileSystemException e )
{
throw new MojoExecutionException( "Error while initializing Commons VFS", e);
}
PackageVersion version = PackageVersion.packageVersion( project.version, timestamp,
project.artifact.isSnapshot(), mojoParameters.revision );
List<P3<UnixPackage, Package, List<AssemblyOperation>>> packages = nil();
for ( Package pakke : validatePackages( mojoParameters.packages, attachedMode ) )
{
try
{
String name = "unix/root-" + formatType + pakke.classifier.map( dashString ).orSome( "" );
FileObject packageRoot = buildDirectory.resolveFile( name );
packageRoot.createFolder();
PackageParameters parameters = calculatePackageParameters( project,
version,
platform,
mojoParameters,
pakke );
UnixPackage unixPackage = format.start().
parameters( parameters ).
setVersion( version ). // TODO: This should go away
workingDirectory( packageRoot ).
debug( debug ).
basedir( project.basedir );
// -----------------------------------------------------------------------
// Let the implementation add its metadata
// -----------------------------------------------------------------------
unixPackage = validateMojoSettingsAndApplyFormatSpecificSettingsToPackage.f( unixPackage );
// TODO: here the logic should be different if many packages are to be created.
// Example: name should be taken from mojoParameters if there is only a single package, if not
// it should come from the Pakke object. This should also be validated, at least for
// name
List<AssemblyOperation> assemblyOperations = createAssemblyOperations( project,
parameters,
unixPackage,
project.basedir,
buildDirectory,
mojoParameters.assembly,
pakke.assembly );
// -----------------------------------------------------------------------
// Dump the execution
// -----------------------------------------------------------------------
if ( debug )
{
log.info( "=======================================================================" );
log.info( "Package parameters: " + parameters.id );
log.info( "Default file attributes: " );
log.info( " File : " + parameters.defaultFileAttributes );
log.info( " Directory : " + parameters.defaultDirectoryAttributes );
log.info( "Assembly operations: " );
for ( AssemblyOperation operation : assemblyOperations )
{
operation.streamTo( new AbstractLineStreamWriter()
{
protected void onLine( String line )
{
log.info( line );
}
} );
}
}
packages = packages.cons( p(unixPackage, pakke, assemblyOperations ) );
}
catch ( UnknownArtifactException e )
{
Map map = new TreeMap<String, Artifact>( e.artifactMap );
// TODO: Do not log here, throw a CouldNotFindArtifactException with the map as an argument
log.warn("Could not find artifact:" + e.artifact );
log.warn("Available artifacts:");
for ( Object o : map.keySet() )
{
log.warn( o.toString() );
}
throw new MojoFailureException( "Unable to find artifact: '" + e.artifact + "'. See log for available artifacts." );
}
catch ( MissingSettingException e )
{
String msg = "Missing required setting '" + e.getSetting() + "'";
if ( !pakke.classifier.isNone() )
{
msg += ", for '" + pakke.classifier.some() + "'";
}
msg += ", format '" + formatType + "'.";
throw new MojoFailureException( msg );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error creating package " + (pakke.classifier.isSome() ? "classifier '" + pakke.classifier + "'" : "") + ", format '" + formatType + "'.", e );
}
}
return new Execution( packages, project, formatType, attachedMode );
}
|
diff --git a/src/org/openjump/core/ui/plugin/layer/ChangeLayerableNamePlugIn.java b/src/org/openjump/core/ui/plugin/layer/ChangeLayerableNamePlugIn.java
index 9a74795e..20ab3f59 100644
--- a/src/org/openjump/core/ui/plugin/layer/ChangeLayerableNamePlugIn.java
+++ b/src/org/openjump/core/ui/plugin/layer/ChangeLayerableNamePlugIn.java
@@ -1,100 +1,102 @@
package org.openjump.core.ui.plugin.layer;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import com.vividsolutions.jump.I18N;
import com.vividsolutions.jump.workbench.WorkbenchContext;
import com.vividsolutions.jump.workbench.model.Layerable;
import com.vividsolutions.jump.workbench.model.UndoableCommand;
import com.vividsolutions.jump.workbench.plugin.AbstractPlugIn;
import com.vividsolutions.jump.workbench.plugin.EnableCheck;
import com.vividsolutions.jump.workbench.plugin.EnableCheckFactory;
import com.vividsolutions.jump.workbench.plugin.MultiEnableCheck;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
import com.vividsolutions.jump.workbench.ui.MenuNames;
import com.vividsolutions.jump.workbench.ui.plugin.FeatureInstaller;
/**
* <code>ChangeLayerableName</code> changes the name of a layer.
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author:$
*
* @version $Revision:$, $Date:$
*/
public class ChangeLayerableNamePlugIn extends AbstractPlugIn {
private MultiEnableCheck enableCheck;
@Override
public void initialize(PlugInContext context) throws Exception {
WorkbenchContext workbenchContext = context.getWorkbenchContext();
FeatureInstaller installer = new FeatureInstaller(workbenchContext);
installer.addMainMenuItemWithJava14Fix(this,
new String[] { MenuNames.LAYER }, getName() + "...", false,
null, enableCheck);
JPopupMenu popupMenu = workbenchContext.getWorkbench().getFrame()
.getLayerNamePopupMenu();
installer.addPopupMenuItem(popupMenu, this, getName() + "{pos:19}",
false, null, createEnableCheck(workbenchContext));
popupMenu = workbenchContext.getWorkbench().getFrame()
.getWMSLayerNamePopupMenu();
installer.addPopupMenuItem(popupMenu, this, getName() + "{pos:6}",
false, null, createEnableCheck(workbenchContext));
}
@Override
public String getName() {
return I18N
.get("org.openjump.core.ui.plugin.layer.ChangeLayerableName.Rename");
}
@Override
public boolean execute(PlugInContext context) throws Exception {
reportNothingToUndoYet(context);
final Layerable layer = (Layerable) context.getLayerNamePanel()
.selectedNodes(Layerable.class).iterator().next();
final String oldName = layer.getName();
final String newName = (String) JOptionPane
.showInputDialog(
context.getWorkbenchFrame(),
I18N
.get("org.openjump.core.ui.plugin.layer.ChangeLayerableName.Rename"),
getName(), JOptionPane.PLAIN_MESSAGE, null, null,
oldName);
- execute(new UndoableCommand(getName()) {
- @Override
- public void execute() {
- layer.setName(newName);
- }
+ if(newName != null) {
+ execute(new UndoableCommand(getName()) {
+ @Override
+ public void execute() {
+ layer.setName(newName);
+ }
- @Override
- public void unexecute() {
- layer.setName(oldName);
- }
- }, context);
+ @Override
+ public void unexecute() {
+ layer.setName(oldName);
+ }
+ }, context);
+ }
return true;
}
/**
* @param workbenchContext
* @return an enable check
*/
public EnableCheck createEnableCheck(WorkbenchContext workbenchContext) {
if (enableCheck != null)
return enableCheck;
EnableCheckFactory enableCheckFactory = new EnableCheckFactory(
workbenchContext);
enableCheck = new MultiEnableCheck();
enableCheck.add(enableCheckFactory
.createWindowWithLayerManagerMustBeActiveCheck());
enableCheck
.add(enableCheckFactory
.createExactlyNLayerablesMustBeSelectedCheck(1,
Layerable.class));
return enableCheck;
}
}
| false | true | public boolean execute(PlugInContext context) throws Exception {
reportNothingToUndoYet(context);
final Layerable layer = (Layerable) context.getLayerNamePanel()
.selectedNodes(Layerable.class).iterator().next();
final String oldName = layer.getName();
final String newName = (String) JOptionPane
.showInputDialog(
context.getWorkbenchFrame(),
I18N
.get("org.openjump.core.ui.plugin.layer.ChangeLayerableName.Rename"),
getName(), JOptionPane.PLAIN_MESSAGE, null, null,
oldName);
execute(new UndoableCommand(getName()) {
@Override
public void execute() {
layer.setName(newName);
}
@Override
public void unexecute() {
layer.setName(oldName);
}
}, context);
return true;
}
| public boolean execute(PlugInContext context) throws Exception {
reportNothingToUndoYet(context);
final Layerable layer = (Layerable) context.getLayerNamePanel()
.selectedNodes(Layerable.class).iterator().next();
final String oldName = layer.getName();
final String newName = (String) JOptionPane
.showInputDialog(
context.getWorkbenchFrame(),
I18N
.get("org.openjump.core.ui.plugin.layer.ChangeLayerableName.Rename"),
getName(), JOptionPane.PLAIN_MESSAGE, null, null,
oldName);
if(newName != null) {
execute(new UndoableCommand(getName()) {
@Override
public void execute() {
layer.setName(newName);
}
@Override
public void unexecute() {
layer.setName(oldName);
}
}, context);
}
return true;
}
|
diff --git a/SRGameBoard.java b/SRGameBoard.java
index d663324..62be1c3 100644
--- a/SRGameBoard.java
+++ b/SRGameBoard.java
@@ -1,863 +1,864 @@
/* GameBoard.java
* This class will handle all logic involving the actions, and movements involved with the
* game Sorry! as well as storing all other associated objects and various statistics about
* the game thus far. This class includes a representation of the track, deck, pawns, and
* records information about the game to be logged as statistics.
*/
import java.util.Date; //for gameplay length
import java.util.Random;
//import java.io.Console; //for debugging pauses
/**
* This class will handle all logic involving the actions, and movements
* involved with the game Sorry! as well as storing all other associated objects and
* various statistics about the game thus far. This class includes a representation of
* the track, deck, pawns, and records information about the game to be logged as
* statistics.
*
* @author Sam Brown, Taylor Krammen, and Yucan Zhang
*/
public class SRGameBoard {
//debug
private static boolean debug = false;
private static boolean pawnsStartHome = false;
private static boolean pawnsStartSafety = false;
//constants
public static final int trackLength = 56;
public static final int safetyLength = 6;
public static final int[] safetyZoneIndex = {56,62};
public static final int[] safetyZoneEntrance = {2, 29};
public static final int[] startIndex = {4,32};
public static final int slideLength = 3;
public static final int[] slideIndex = {1,9, 15, 23, 29, 37, 43, 51};
//gameplay
public SRSquare[] track = new SRSquare[68]; //squares that make up the regular track, safety zones, and home squares
public SRSquare[] startSquares = new SRSquare[2]; //indexes into the track representing where players may move their pawns into play
public SRDeck deck; //Deck object used in this game
public SRPawn[] pawns = new SRPawn[8]; //8 pawns used in the game
//statistics
public Date startTime;
public int elapsedTime; //elapsed time in seconds
public int numTurns; //turns taken
public int numBumps; //times player bumped another player
public int numStories; //successful uses of Sorry! cards
public String cpuStyle; //either nice or mean, how the computer was set to play
public int playerPawnsHome; //number of pawns player got home
public int playerDistanceTraveled; //total number of squares traveled by the human player
public int cpuDistanceTraveled; //"" "" "" "" computer
public SRGameBoard(){
//start the track
for (int i=0;i<track.length;i++){
//make 'em
track[i] = new SRSquare();
//check if this one is slippery
for (int j=0; j<SRGameBoard.slideIndex.length; j++){
//take appropriate action if it is
if (i == SRGameBoard.slideIndex[j]){
track[i].slideLength = SRGameBoard.slideLength;
}
}
}
//mark home squares
for (int i=0;i<SRGameBoard.safetyZoneIndex.length;i++){
this.track[SRGameBoard.safetyZoneIndex[i]+SRGameBoard.safetyLength-1].setIsHome(true);
}
//create startSquares
for (int i=0;i<this.startSquares.length; i++){
this.startSquares[i] = new SRSquare(4);
}
//shuffle the deck
this.deck = new SRDeck();
this.deck.shuffle();
//make some pawns
for (int i=0; i<this.pawns.length;i++){
if (i<4){
this.pawns[i] = new SRPawn(0);
this.pawns[i].setHomeIndex(SRGameBoard.safetyZoneIndex[0]+SRGameBoard.safetyLength-1);
}
else{
this.pawns[i] = new SRPawn(1);
this.pawns[i].setHomeIndex(SRGameBoard.safetyZoneIndex[1]+SRGameBoard.safetyLength-1);
}
this.pawns[i].setID(i%4);
}
this.cpuStyle = "easy";
this.startTime = new Date();
//testing:
printDebug("GameBoard initialized.");
for (int i=0;i<track.length;i++){
printDebug("Square "+i+"\tisHome: "+track[i].isHome+"\t\tslideLength: "+track[i].getSlideLength());
}
//start 3/4 of each players pawns on home in order to speed this up.
if (SRGameBoard.pawnsStartHome){
for (int i=0; i<this.pawns.length;i++){
if (i!=0 && i!=5){
movePawnTo(this.pawns[i], SRGameBoard.safetyZoneIndex[this.pawns[i].getPlayer()]+SRGameBoard.safetyLength-1);
}
}
}
//Start 2 pawns in the safety zone to test safety moves
if (SRGameBoard.pawnsStartSafety){
for (int i=0; i<this.pawns.length;i++){
movePawnTo(this.pawns[i], SRGameBoard.safetyZoneIndex[this.pawns[i].getPlayer()]+SRGameBoard.safetyLength-3);
}
}
}
//getters
//returns the pawn from a specific player with a specific ID
public SRPawn getPlayerPawn(int player, int number){
return this.pawns[(player*4+number)];
}
/**
* getSquareAt
*
* Returns square at track location "index"
*
* @param index
* @return
*/
public SRSquare getSquareAt(int index){
if (index >= 0 && index < this.track.length){
return this.track[index];
}
else{
throw new NullPointerException("There is no square at index "+index+".");
}
}
//card methods:
public SRCard drawCard(){
return deck.drawCard();
}
//movement methods:
/**
* This function uses the Pawn object is current location, as well as the Rules associated
* with the Card to determine where on the board the Pawn may move to. These
* locations on the board are returned as an array of integers, representing indices
* into the GameBoard.track object.
*
* @param pawn
* @param card
* @return
*/
public int[] findMoves(SRPawn pawn, SRCard card){
printDebug("\nEntered findMoves(card).");
int [] finalArray = new int [0];
int [] nextMoves;
for (int i=0;i<card.rules.length; i++){
nextMoves = findMoves(pawn, card.rules[i]);
finalArray = concatArrays(finalArray, nextMoves);
}
return finalArray;
}
/**
* findMoves (called by findMoves(SRPawn, SRCard)
*
* @param pawn
* @param rule
* @return int[]
*/
public int[] findMoves(SRPawn pawn, SRRule rule){
printDebug("\nEntered fineMoves(rule).");
int numMoves = rule.numMoves;//change when card truly has "rules"
int [] moveIndices;
boolean canSplit = rule.canSplit;
printDebug("Entered findMoves with rule. NumMoves is "+numMoves);
//figure out the direction of the pawn beforehand so we only need one loop (handles
//both - and + move directions.)
int step = getStep(numMoves);
//test for "special case" type moves
moveIndices = getSpecialMoves(pawn, rule);
if (moveIndices.length > 0){
return moveIndices;
}
int currIndex = pawn.getTrackIndex();
if (currIndex == -1 && !rule.canStart){
return moveIndices;
}
//make room for indices
int [] regIndices = new int [numMoves*step];
int regIndicesCount = 0;
int [] safetyIndices = new int [numMoves*step];
int safetyIndicesCount = 0;
//IF the pawn is on the regular track:
if (currIndex < SRGameBoard.trackLength){
regIndices = this.getNormalMoves(pawn.player, pawn.trackIndex, numMoves);
regIndicesCount = regIndices.length;
//if movement wasn't negative, maybe there was an opportunity to enter the safety zone!
if (step>0){
int numMovesLeft = 0; //number of moves left to make inside safety zone
boolean canEnterSafety = false;
for (int i=0; i<regIndices.length; i++){
- if (regIndices[i] == SRGameBoard.safetyZoneEntrance[pawn.player]){
+ if (regIndices[i] == SRGameBoard.safetyZoneEntrance[pawn.player] ||
+ currIndex == SRGameBoard.safetyZoneEntrance[pawn.player]){
canEnterSafety = true;
numMovesLeft = numMoves-(i+1);
}
}
if (canEnterSafety){
printDebug("P"+pawn.getPlayer()+" pawn "+pawn.getID()+" can enter safety!");
int firstSafetyIndex = SRGameBoard.safetyZoneIndex[pawn.player];
safetyIndices = this.getSafetyMoves(pawn.player, firstSafetyIndex, numMovesLeft);
safetyIndicesCount = safetyIndices.length;
//determine whether the safety moves were valid
//set the count of safetyIndices appropriately
if ((numMovesLeft != safetyIndices.length) && (!canSplit)){
safetyIndicesCount = 0;
}
}//end if(canEnterSafety)
}
}
//if the current pawn is in the safety zone
else{
safetyIndices = this.getSafetyMoves(pawn.player, pawn.trackIndex, numMoves);
safetyIndicesCount = safetyIndices.length;
//debugging
if (SRGameBoard.debug){
for (int i=0; i<safetyIndices.length; i++){
System.out.println("Safety indices: "+safetyIndices[i]);
}
}
if (step > 0 && safetyIndices.length < numMoves*step && !canSplit){
safetyIndicesCount = 0;
}
else if (step < 0){
int numMovesLeft = (numMoves*step - safetyIndices.length)*step;
regIndices = getNormalMoves(pawn.player, SRGameBoard.safetyZoneEntrance[pawn.player], numMovesLeft);
regIndicesCount = regIndices.length;
}
}
//handle either of these being empty
if (regIndicesCount== 0){
regIndices = new int [0];
}
if (safetyIndicesCount == 0){
safetyIndices = new int [0];
}
int [] finalArray = cleanUpMoveArrays(regIndices, safetyIndices, canSplit);
//handle 10
if (rule.shiftBackwards){
finalArray = concatArrays(findMoves(pawn, new SRCard(-1)), finalArray);
}
//check arrays to be sure they do not contain any of the player's pawns
int playerIndex = 4*pawn.getPlayer();
for (int i=playerIndex; i<(playerIndex+4); i++){
if (!pawns[i].isOnHome()){
finalArray = removeElementFrom(pawns[i].getTrackIndex(), finalArray);
}
}
if (SRGameBoard.debug){
System.out.println("FindMoves returning from end: ");
for (int i=0;i<finalArray.length;i++){
System.out.println("findMoves returns:\t"+finalArray[i]);
}
}
return finalArray;
}
/**
* getSpecialMoves()
* gets all "special" moves for cards (ie. sorry!, all non-generic movement)
* @param pawn
* @param rule
* @return int[] indices where pawn may move
*/
public int [] getSpecialMoves(SRPawn pawn, SRRule rule) {
printDebug("\nEntered getSpecialMoves().");
int[] moveIndices;
int indiceCount = 0;
int [] noMoves = new int[0];//just a dummy
int [] finalArray = new int [0];
//special cases:
//pawn is on start and card lets it start
//if pawn is on home
if (pawn.isOnHome()){
finalArray = noMoves;
}
else if (pawn.isOnStart() && rule.canStart){
moveIndices = new int [1];
moveIndices[0] = SRGameBoard.startIndex[pawn.getPlayer()];
finalArray = moveIndices;
}
//pawn moving from start and can bump another pawn
//or if pawn is not on start and may switch places with another pawn
else if ((pawn.isOnStart() && rule.isSorry) || (!pawn.isOnStart() && rule.canSwitch)){
SRPawn [] otherPawns = this.getOpponentPawns(pawn.getPlayer());
moveIndices = new int [4];
for (int i=0; i<4;i++){
SRPawn otherPawn = otherPawns[i];
if (otherPawn.isOnHome() && !otherPawn.isOnStart() && otherPawn.safetyIndex == -1 ){
moveIndices[indiceCount] = otherPawn.trackIndex;
}
}
finalArray = this.trimArray(moveIndices, indiceCount);
}
//pawn is on start and card doesn't let it start
else if (pawn.isOnStart() && !rule.canStart){
finalArray = noMoves;
}
//debugging output of each move
if (SRGameBoard.debug){
System.out.println("getSpecialMoves returning: ");
for (int i=0;i<finalArray.length;i++){
System.out.println("getSpecialMoves returns:\t"+finalArray[i]);
}
}
return finalArray;
}
/**
* getNormalMoves
* determines where the pawn can move on the regular track
* @param player
* @param currIndex
* @param numMoves
* @return
*/
public int [] getNormalMoves(int player, int currIndex, int numMoves){
printDebug("\nEntered getNormalMoves().");
int step = getStep(numMoves);
int [] regIndices = new int [numMoves*step];
int regIndicesCount = 0;
//assume forward motion
int max = numMoves;//currIndex + numMoves;
int min = 0;
//swap them if it isn't
if (max < min){
int temp = max;
max = min;
min = temp;
}
//otherwise adjust the range to be correct
else{
max++;
min++;
}
//first find all possible moves on the normal track
for (int i=min;i < max; i++){
regIndices[regIndicesCount] = (currIndex+(i))%SRGameBoard.trackLength;
//modulo of negative numbers doesn't work how we want, so do it by hand.
if (regIndices[regIndicesCount]<0){
regIndices[regIndicesCount] = SRGameBoard.trackLength+regIndices[regIndicesCount];
}
regIndicesCount += 1;
}
regIndices = this.trimArray(regIndices, regIndicesCount);//trim the array
//if the movement was negative, the array is backwards, so straighten it out
if (step<0){
regIndices = reverseArray(regIndices);
}
return trimArray(regIndices, regIndicesCount);
}
//figures out where the pawn can move in the safetyZone
public int [] getSafetyMoves(int player, int currIndex, int numMoves){
printDebug("\nEntered getSafetyMoves().");
int safetyStart = SRGameBoard.safetyZoneIndex[player];
int safetyEnd = safetyStart + SRGameBoard.safetyLength;
int min = 0;
int max = 0 + numMoves;
if (numMoves < 0){
printDebug("Switching direction for negative movement.");
int temp = min;
min = max;
max = temp;
}
int step = getStep(numMoves);
int [] safetyIndices = new int [SRGameBoard.safetyLength];
int [] allIndices = new int [numMoves*step];
int indiceCount = 0;
int nextIndex;
printDebug("Min is set to: "+min+" Max is set to: "+max);
//first get all theoretical places the pawn can go
printDebug("All potential indices are:");
for (int i=min;i < max; i++){
nextIndex = (currIndex+(i+1));
printDebug("NextIndex");
allIndices[indiceCount] = nextIndex;
indiceCount++;
//System.out.println("Next index: "+nextIndex);
}
indiceCount = 0;
//now trim the list down to only squares in the safety zone
for (int i=0; i<allIndices.length; i++){
//System.out.println("Checking index: "+allIndices[i]);
if (allIndices[i] < safetyEnd && allIndices[i] >= safetyStart){
//System.out.println("Passed!");
safetyIndices[indiceCount] = allIndices[i];
indiceCount++;
}
}
int [] finalArray = this.trimArray(safetyIndices, indiceCount);
if (step==-1){
finalArray = this.reverseArray(finalArray);
}
return finalArray;
}
//returns an array of SRPawns which belong to a given player
public SRPawn [] getPlayerPawns(int player){
SRPawn [] pawns = new SRPawn [4];
for (int i=4*player; i<(4*player)+4; i++){
pawns[i-(4*player)] = this.pawns[i];
}
return pawns;
}
//returns an array of SRPawns which belong to a given opponent
public SRPawn [] getOpponentPawns(int player){
switch (player){
case 0: return this.getPlayerPawns(1);
case 1: return this.getPlayerPawns(0);
}
return new SRPawn [0];
}
/**
* This function handles the actual movement of the pawn, and the resultant bumping
* and sliding that may occur. If a pawn is moved to a space with another pawn, the
* second pawn will be moved back to Start. If the pawn is moved to a space with a
* slide, the pawn will be moved a second time the distance of the slide.
*
* Return a boolean true if move successful or false otherwise.
*
* @param pawn
* @param card
* @return int
*/
public int movePawnTo(SRPawn pawn, int location){
printDebug("\nEntered movePawnTo().");
//System.out.print("movePawnTo breaking at ");
//int location = (pawn.getTrackIndex()+distance)%SRGameBoard.trackLength;
//check for starting pawns
int unalteredLocation = location;
if (location >= 0 && location < this.track.length){
location += this.track[location].getSlideLength();
}
//check for pawns going to start
else if (location < 0){
pawn.setOnStart(true);
//System.out.println("pawns going to start.");
printDebug("p"+pawn.player+" pawn "+pawn.getID()+" is moving to start.");
return 1;
}
//check for pawns going out of bounds
else if (location > SRGameBoard.trackLength+SRGameBoard.safetyLength*2){
//System.out.println("pawns out of bounds.");
printDebug("p"+pawn.player+" pawn "+pawn.getID()+" is trying to go out of bounds.");
return 0;
}
//check for pawns that are going home
if (this.track[location].isHome){
//System.out.println("(Player "+pawn.player+" pawn "+pawn.id+" is home!)");
pawn.setOnHome(true);
}
//check for pawns that are already home? do we need to? why not.
/*else if (pawn.isOnHome()){
//System.out.println("pawns already at home.");
printDebug("p"+pawn.player+" pawn "+pawn.getID()+" is home and will not be moved.");
return 0;
}*/
//bump (only bump the pawns of the opposing player)
for (int i=pawn.player;i<this.pawns.length; i++){
boolean sameSquare = pawns[i].getTrackIndex() == location;
//bump the opponent
if (sameSquare && pawn.player != pawns[i].player){
this.bumpPawn(pawns[i]);
printDebug("P"+pawn.getPlayer()+" pawn "+pawn.getID()+
" bumped opponent pawn "+pawns[i].getID());
}
//but don't move if you'll land on yourself
else if (sameSquare && !this.track[location].isHome){
//System.out.println("landing on yourself.");
printDebug("p"+pawn.player+" pawn "+pawn.getID()+" will land on another pawn and cannot move.");
return 0;
}
}
int currentIndex = pawn.getTrackIndex();
printDebug("Pawn current index is: \t" +currentIndex);
printDebug("Moved p"+pawn.player+" pawn "+pawn.getID()+" from "+pawn.trackIndex+" to "+location+".");
//move the pawn and slide too if we need it.
pawn.setTrackIndex(location);
int distance = getDistanceBetween(currentIndex, unalteredLocation);
printDebug("Number of spaces was: \t"+distance);
return distance;
}
/**
* Determines the location that the move will take the pawn to, and calls
* the movePawnTo function.
*
* @param pawn
* @param card
* @return
*
*/
public void movePawn(SRPawn pawn, int distance){
int location = pawn.getTrackIndex()+distance;
this.movePawnTo(pawn, location);// isSafety);
}
/**
* This function moves Pawn pawn back onto its start square.
*
* @param pawn
*/
public void bumpPawn(SRPawn pawn){
printDebug("\nEntered bumpPawn");
printDebug("Player "+pawn.player+" pawn "+pawn.id+" was bumped.\n");
pawn.bump();
}
/**
* This function moves Pawn pawn from its start square onto the square directly
* adjacent to the start square.
*
* @param pawn
*/
public void startPawn(SRPawn pawn){
this.movePawnTo(pawn, SRGameBoard.startIndex[pawn.player]);
}
/**
* This function checks to see whether a player has managed to place all 4 of his/her
* pawns on his/her start square and returns True if this is the case. Otherwise it
* returns False.
*
* @param player
* @return
*/
public boolean hasWon(int player){
int playerPawnIndex = player*4; //0 if player 0, 4 if player 1
//loop through pawns, if any not on home the player hasn't won.
for (int i=playerPawnIndex; i<playerPawnIndex+4; i++){
if (this.pawns[i].onHome == false){
return false;
}
}
printDebug("Player "+player+" has won the game!");
return true;
}
/**
* Performs after-game clean up and statistics prep.
*/
private void endGame(){
Date endTime = new Date();
//something like:
//elapsedTime = endTime - this.startTime
}
/**
* getDistanceBetween
*
* calculates the distance between two points on the
*
* @param index1
* @param index2
* @return
*/
private int getDistanceBetween(int index1, int index2){
if (index1 < index2){
int temp = index1;
index1 = index2;
index2 = temp;
}
int distance = 0;
int normalDist = 0;
//if they are only moving on the safety zone
if (index1 > SRGameBoard.trackLength && index2 > SRGameBoard.trackLength){
distance = index1 - index2;
}
//if they are only moving in the regular track
else if (0 <= index1 && index1 < SRGameBoard.trackLength &&
0 <= index2 && index2 < SRGameBoard.trackLength ){
distance = index1 - index2;
}
//now if index1 is the safetyZone entrance
else {
//assume player 0 safetyZone
int zone = 0;
//check if it is player 1
if (index1 > SRGameBoard.safetyZoneIndex[1]){
zone = 1;
}
distance =index1-SRGameBoard.safetyZoneIndex[zone];
normalDist = index2 - SRGameBoard.safetyZoneEntrance[zone];
}
if (distance < 0){
distance*=-1;
}
if (normalDist < 0){
normalDist*=-1;
}
return distance+normalDist;
}
/**
* cleanUpMoveArrays takes the array of safety moves and the array
* of regular board moves and
* @param regIndices
* @param safetyIndices
* @param canSplit
* @return
*/
private int[] cleanUpMoveArrays(int[] regIndices, int[] safetyIndices, boolean canSplit) {
printDebug("\nEntered cleanUpMoveArrays.");
int regIndicesCount;
int safetyIndicesCount;
int [] moveIndices;
safetyIndicesCount = safetyIndices.length;
regIndicesCount = regIndices.length;
//now set up array depending on if the pawn can split its moves or not
//can't split is only 2 long (could go safety, could not)
if (!canSplit){
moveIndices = new int [2]; //only 2 potential places to move if the card doesn't allow
//splitting
}
//if pawn can split its moves, we need way more space!
else{
moveIndices = new int [regIndices.length+safetyIndices.length]; //for now treat card number like number of moves
//Worst case for length of list is numMoves*2, so this is the maximum
//length of the array.
}
int indiceCount = 0; //So count how many locations we're allowed to enter, so we can trim later.
//clean up arrays at the end based on how we can split our moves
if (canSplit){
for (int i = 0; i < regIndicesCount+safetyIndicesCount; i++){
if (i<regIndicesCount){
moveIndices[i] = regIndices[i];
indiceCount++;
}
else{
moveIndices[i] = safetyIndices[i-regIndicesCount];
indiceCount++;
}
}
}
else{
if (regIndicesCount > 0){
moveIndices[0] = regIndices[regIndices.length-1];
indiceCount++;
}
if (safetyIndicesCount >0 && regIndicesCount > 0 && indiceCount>0){
moveIndices[1] = safetyIndices[safetyIndices.length-1];
indiceCount++;
}
else if (safetyIndicesCount > 0){
moveIndices[0] = safetyIndices[safetyIndices.length-1];
indiceCount++;
}
}
//output for debugging
if (SRGameBoard.debug){
for (int i=0; i<indiceCount; i++){
System.out.println("MoveIndices: " + moveIndices[i]);
}
}
return this.trimArray(moveIndices, indiceCount);
}
/**
* Calculate the direction of the move.
*
* @param numMoves
* @return
*/
private int getStep(int numMoves) {
int step = 1;
if (numMoves < 0){
step *= -1;
}
return step;
}
//trims an array down to a predetermined length
private int [] trimArray(int [] toTrim, int len){
int [] newArray = new int [len];
for (int i = 0; i<len; i++){
newArray[i]=toTrim[i];
}
return newArray;
}
//reverses an array
private int [] reverseArray(int [] toReverse){
int [] tempArray = new int [toReverse.length];
for (int i=0; i<toReverse.length; i++){
tempArray[tempArray.length-i-1] = toReverse[i];
}
return tempArray;
}
//removes element from array
private int[] removeElementFrom(int removeMe, int[] array) {
int arrayLen = array.length;
int [] newArray = array;
for (int i=0;i<arrayLen;i++){
if (array[i]==removeMe){
printDebug("Removing "+removeMe+"from array because there is a pawn there.");
newArray = new int [array.length-1];
System.arraycopy(array, 0, newArray, 0, i);
System.arraycopy(array, i+1, newArray, i, newArray.length-i);
}
}
return newArray;
}
//concatenates two arrays
private int [] concatArrays(int [] array1, int [] array2){
int [] finalArray = new int [array1.length + array2.length];
System.arraycopy(array1, 0, finalArray, 0, array1.length);
System.arraycopy(array2, 0, finalArray, array1.length, array2.length);
return finalArray;
}
/**
* printDebug
*
* Outputs a string only if debug is turned on.
*
* @param s
*/
private void printDebug(String s){
if (SRGameBoard.debug){
System.out.println(s);
}
}
public static void main(String [] args){
SRGameBoard gb = new SRGameBoard();
Random rand = new Random();
int [] moves;
int choice;
SRCard card;
SRPawn pawn;
int pawnIndex;
for (int i=0;i<gb.pawns.length;i++){
gb.movePawnTo(gb.pawns[i], i+49);
}
//
// gb.movePawnTo(gb.pawns[5], 8);
//
// gb.hasWon(0);
// gb.hasWon(1);
//play the game randomly until the victory condition is met
while (!gb.deck.isEmpty() && !gb.hasWon(0) && !gb.hasWon(1)){
//for (int turn = 0; turn<4;turn++){
do{
pawnIndex = rand.nextInt(8);
pawn = gb.pawns[pawnIndex];
}while(pawn.isOnHome());
gb.printDebug("\nMoving a pawn in main:");
gb.printDebug("Pawn "+pawnIndex+" selected at index "+pawn.getTrackIndex());
card = gb.deck.drawCard();
gb.printDebug("Trying to use card "+card.cardNum);
moves = gb.findMoves(pawn, card);
for (int i =0; i<moves.length;i++){
gb.printDebug("Move ["+i+"] is "+moves[i]);
}
if(moves.length>1){
choice = rand.nextInt(moves.length);
gb.movePawnTo(pawn, moves[choice]);
}
else if (moves.length == 1){
gb.movePawnTo(pawn, moves[0]);
}
else{
gb.printDebug("No moves.");
}
gb.printDebug("= = = = = = = = = = = = ");
for (int i=0; i<gb.pawns.length;i++){
gb.printDebug("Player "+gb.pawns[i].player+" pawn "+gb.pawns[i].id+" is at "+gb.pawns[i].trackIndex);
gb.printDebug(" || onHome = " + gb.pawns[i].onHome + ", trackIndex = " +gb.pawns[i].trackIndex+"\n");
}
gb.printDebug("\n\n========================");
if (gb.hasWon(0) || gb.hasWon(1)){
System.out.println("The game has been won!");
break;
}
}
}
}
| true | true | public int[] findMoves(SRPawn pawn, SRRule rule){
printDebug("\nEntered fineMoves(rule).");
int numMoves = rule.numMoves;//change when card truly has "rules"
int [] moveIndices;
boolean canSplit = rule.canSplit;
printDebug("Entered findMoves with rule. NumMoves is "+numMoves);
//figure out the direction of the pawn beforehand so we only need one loop (handles
//both - and + move directions.)
int step = getStep(numMoves);
//test for "special case" type moves
moveIndices = getSpecialMoves(pawn, rule);
if (moveIndices.length > 0){
return moveIndices;
}
int currIndex = pawn.getTrackIndex();
if (currIndex == -1 && !rule.canStart){
return moveIndices;
}
//make room for indices
int [] regIndices = new int [numMoves*step];
int regIndicesCount = 0;
int [] safetyIndices = new int [numMoves*step];
int safetyIndicesCount = 0;
//IF the pawn is on the regular track:
if (currIndex < SRGameBoard.trackLength){
regIndices = this.getNormalMoves(pawn.player, pawn.trackIndex, numMoves);
regIndicesCount = regIndices.length;
//if movement wasn't negative, maybe there was an opportunity to enter the safety zone!
if (step>0){
int numMovesLeft = 0; //number of moves left to make inside safety zone
boolean canEnterSafety = false;
for (int i=0; i<regIndices.length; i++){
if (regIndices[i] == SRGameBoard.safetyZoneEntrance[pawn.player]){
canEnterSafety = true;
numMovesLeft = numMoves-(i+1);
}
}
if (canEnterSafety){
printDebug("P"+pawn.getPlayer()+" pawn "+pawn.getID()+" can enter safety!");
int firstSafetyIndex = SRGameBoard.safetyZoneIndex[pawn.player];
safetyIndices = this.getSafetyMoves(pawn.player, firstSafetyIndex, numMovesLeft);
safetyIndicesCount = safetyIndices.length;
//determine whether the safety moves were valid
//set the count of safetyIndices appropriately
if ((numMovesLeft != safetyIndices.length) && (!canSplit)){
safetyIndicesCount = 0;
}
}//end if(canEnterSafety)
}
}
//if the current pawn is in the safety zone
else{
safetyIndices = this.getSafetyMoves(pawn.player, pawn.trackIndex, numMoves);
safetyIndicesCount = safetyIndices.length;
//debugging
if (SRGameBoard.debug){
for (int i=0; i<safetyIndices.length; i++){
System.out.println("Safety indices: "+safetyIndices[i]);
}
}
if (step > 0 && safetyIndices.length < numMoves*step && !canSplit){
safetyIndicesCount = 0;
}
else if (step < 0){
int numMovesLeft = (numMoves*step - safetyIndices.length)*step;
regIndices = getNormalMoves(pawn.player, SRGameBoard.safetyZoneEntrance[pawn.player], numMovesLeft);
regIndicesCount = regIndices.length;
}
}
//handle either of these being empty
if (regIndicesCount== 0){
regIndices = new int [0];
}
if (safetyIndicesCount == 0){
safetyIndices = new int [0];
}
int [] finalArray = cleanUpMoveArrays(regIndices, safetyIndices, canSplit);
//handle 10
if (rule.shiftBackwards){
finalArray = concatArrays(findMoves(pawn, new SRCard(-1)), finalArray);
}
//check arrays to be sure they do not contain any of the player's pawns
int playerIndex = 4*pawn.getPlayer();
for (int i=playerIndex; i<(playerIndex+4); i++){
if (!pawns[i].isOnHome()){
finalArray = removeElementFrom(pawns[i].getTrackIndex(), finalArray);
}
}
if (SRGameBoard.debug){
System.out.println("FindMoves returning from end: ");
for (int i=0;i<finalArray.length;i++){
System.out.println("findMoves returns:\t"+finalArray[i]);
}
}
return finalArray;
}
| public int[] findMoves(SRPawn pawn, SRRule rule){
printDebug("\nEntered fineMoves(rule).");
int numMoves = rule.numMoves;//change when card truly has "rules"
int [] moveIndices;
boolean canSplit = rule.canSplit;
printDebug("Entered findMoves with rule. NumMoves is "+numMoves);
//figure out the direction of the pawn beforehand so we only need one loop (handles
//both - and + move directions.)
int step = getStep(numMoves);
//test for "special case" type moves
moveIndices = getSpecialMoves(pawn, rule);
if (moveIndices.length > 0){
return moveIndices;
}
int currIndex = pawn.getTrackIndex();
if (currIndex == -1 && !rule.canStart){
return moveIndices;
}
//make room for indices
int [] regIndices = new int [numMoves*step];
int regIndicesCount = 0;
int [] safetyIndices = new int [numMoves*step];
int safetyIndicesCount = 0;
//IF the pawn is on the regular track:
if (currIndex < SRGameBoard.trackLength){
regIndices = this.getNormalMoves(pawn.player, pawn.trackIndex, numMoves);
regIndicesCount = regIndices.length;
//if movement wasn't negative, maybe there was an opportunity to enter the safety zone!
if (step>0){
int numMovesLeft = 0; //number of moves left to make inside safety zone
boolean canEnterSafety = false;
for (int i=0; i<regIndices.length; i++){
if (regIndices[i] == SRGameBoard.safetyZoneEntrance[pawn.player] ||
currIndex == SRGameBoard.safetyZoneEntrance[pawn.player]){
canEnterSafety = true;
numMovesLeft = numMoves-(i+1);
}
}
if (canEnterSafety){
printDebug("P"+pawn.getPlayer()+" pawn "+pawn.getID()+" can enter safety!");
int firstSafetyIndex = SRGameBoard.safetyZoneIndex[pawn.player];
safetyIndices = this.getSafetyMoves(pawn.player, firstSafetyIndex, numMovesLeft);
safetyIndicesCount = safetyIndices.length;
//determine whether the safety moves were valid
//set the count of safetyIndices appropriately
if ((numMovesLeft != safetyIndices.length) && (!canSplit)){
safetyIndicesCount = 0;
}
}//end if(canEnterSafety)
}
}
//if the current pawn is in the safety zone
else{
safetyIndices = this.getSafetyMoves(pawn.player, pawn.trackIndex, numMoves);
safetyIndicesCount = safetyIndices.length;
//debugging
if (SRGameBoard.debug){
for (int i=0; i<safetyIndices.length; i++){
System.out.println("Safety indices: "+safetyIndices[i]);
}
}
if (step > 0 && safetyIndices.length < numMoves*step && !canSplit){
safetyIndicesCount = 0;
}
else if (step < 0){
int numMovesLeft = (numMoves*step - safetyIndices.length)*step;
regIndices = getNormalMoves(pawn.player, SRGameBoard.safetyZoneEntrance[pawn.player], numMovesLeft);
regIndicesCount = regIndices.length;
}
}
//handle either of these being empty
if (regIndicesCount== 0){
regIndices = new int [0];
}
if (safetyIndicesCount == 0){
safetyIndices = new int [0];
}
int [] finalArray = cleanUpMoveArrays(regIndices, safetyIndices, canSplit);
//handle 10
if (rule.shiftBackwards){
finalArray = concatArrays(findMoves(pawn, new SRCard(-1)), finalArray);
}
//check arrays to be sure they do not contain any of the player's pawns
int playerIndex = 4*pawn.getPlayer();
for (int i=playerIndex; i<(playerIndex+4); i++){
if (!pawns[i].isOnHome()){
finalArray = removeElementFrom(pawns[i].getTrackIndex(), finalArray);
}
}
if (SRGameBoard.debug){
System.out.println("FindMoves returning from end: ");
for (int i=0;i<finalArray.length;i++){
System.out.println("findMoves returns:\t"+finalArray[i]);
}
}
return finalArray;
}
|
diff --git a/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/HideDivisionRenderer.java b/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/HideDivisionRenderer.java
index 1030f102..30362860 100644
--- a/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/HideDivisionRenderer.java
+++ b/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/HideDivisionRenderer.java
@@ -1,149 +1,149 @@
package org.sakaiproject.tool.messageforums.jsf;
import java.io.IOException;
import java.util.Iterator;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;
import java.util.List;
/**
* @author <a href="mailto:cwen.iupui.edu">Chen Wen</a>
* @version $Id$
*
*/
public class HideDivisionRenderer extends Renderer
{
private static final String BARSTYLE = "";
private static final String BARTAG = "h4";
private static final String RESOURCE_PATH;
private static final String FOLD_IMG_HIDE;
private static final String FOLD_IMG_SHOW;
private static final String CURSOR;
static {
RESOURCE_PATH = "/" + "sakai-messageforums-tool";
FOLD_IMG_HIDE = RESOURCE_PATH + "/images/right_arrow.gif";
FOLD_IMG_SHOW = RESOURCE_PATH + "/images/down_arrow.gif";
CURSOR = "cursor:pointer";
/*ConfigurationResource cr = new ConfigurationResource();
RESOURCE_PATH = "/" + cr.get("resources");
BARIMG = RESOURCE_PATH + "/" +cr.get("hideDivisionRight");
CURSOR = cr.get("picker_style");*/
}
public boolean supportsComponentType(UIComponent component)
{
return (component instanceof org.sakaiproject.tool.messageforums.jsf.HideDivisionComponent);
}
public void decode(FacesContext context, UIComponent component)
{
}
public void encodeChildren(FacesContext context, UIComponent component)
throws IOException
{
if (!component.isRendered())
{
return;
}
Iterator children = component.getChildren().iterator();
while (children.hasNext()) {
UIComponent child = (UIComponent) children.next();
if(!((child instanceof org.sakaiproject.tool.messageforums.jsf.BarLinkComponent)||
(child instanceof HtmlOutputText)))
{
child.encodeBegin(context);
child.encodeChildren(context);
child.encodeEnd(context);
}
}
}
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter writer = context.getResponseWriter();
String jsfId = (String) RendererUtil.getAttribute(context, component, "id");
String id = jsfId;
if (component.getId() != null &&
!component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
{
id = component.getClientId(context);
}
String title = (String) RendererUtil.getAttribute(context, component, "title");
Object tmpFoldStr = RendererUtil.getAttribute(context, component, "hideByDefault");
boolean foldDiv = tmpFoldStr != null && tmpFoldStr.equals("true");
String foldImage = foldDiv ? FOLD_IMG_HIDE : FOLD_IMG_SHOW;
writer.write("<" + BARTAG + " class=\"" + BARSTYLE + "\">");
writer.write("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
writer.write("<tr><td nowrap=\"nowrap\" align=\"left\">");
writer.write(" <img id=\"" + id + "__img_hide_division_" + "\" alt=\"" +
- title + "\"" + " onclick=\"javascript:showHideDiv('" + id +
+ title + "\"" + " onclick=\"javascript:showHideDivBlock('" + id +
"', '" + RESOURCE_PATH + "');\"");
- writer.write(" src=\"" + foldImage + "\" style=\"" + CURSOR + "\" />");
+ writer.write(" src=\"" + foldImage + "\" style=\"" + CURSOR + "\" >");
writer.write(" <b>" + title + "</b>");
writer.write("</td><td width=\"100%\"> </td>");
writer.write("<td nowrap=\"nowrap\" align=\"right\">");
List childrenList = component.getChildren();
for(int i=0; i<childrenList.size(); i++)
{
UIComponent thisComponent = (UIComponent)childrenList.get(i);
if(thisComponent instanceof org.sakaiproject.tool.messageforums.jsf.BarLinkComponent
||thisComponent instanceof HtmlOutputText)
{
thisComponent.encodeBegin(context);
thisComponent.encodeChildren(context);
thisComponent.encodeEnd(context);
}
}
writer.write("</td></tr></table>");
writer.write("</"+ BARTAG + ">");
if(foldDiv) {
writer.write("<div style=\"display:none\" " +
" id=\"" + id + "__hide_division_" + "\">");
} else {
writer.write("<div style=\"display:block\" " +
" id=\"" + id + "__hide_division_" + "\">");
}
}
public void encodeEnd(FacesContext context, UIComponent component) throws
IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter writer = context.getResponseWriter();
String jsfId = (String) RendererUtil.getAttribute(context, component, "id");
String id = jsfId;
if (component.getId() != null &&
!component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
{
id = component.getClientId(context);
}
writer.write("</div>");
// writer.write("<script type=\"text/javascript\">");
// writer.write(" showHideDiv('" + id +
// "', '" + RESOURCE_PATH + "');");
// writer.write("</script>");
}
}
| false | true | public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter writer = context.getResponseWriter();
String jsfId = (String) RendererUtil.getAttribute(context, component, "id");
String id = jsfId;
if (component.getId() != null &&
!component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
{
id = component.getClientId(context);
}
String title = (String) RendererUtil.getAttribute(context, component, "title");
Object tmpFoldStr = RendererUtil.getAttribute(context, component, "hideByDefault");
boolean foldDiv = tmpFoldStr != null && tmpFoldStr.equals("true");
String foldImage = foldDiv ? FOLD_IMG_HIDE : FOLD_IMG_SHOW;
writer.write("<" + BARTAG + " class=\"" + BARSTYLE + "\">");
writer.write("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
writer.write("<tr><td nowrap=\"nowrap\" align=\"left\">");
writer.write(" <img id=\"" + id + "__img_hide_division_" + "\" alt=\"" +
title + "\"" + " onclick=\"javascript:showHideDiv('" + id +
"', '" + RESOURCE_PATH + "');\"");
writer.write(" src=\"" + foldImage + "\" style=\"" + CURSOR + "\" />");
writer.write(" <b>" + title + "</b>");
writer.write("</td><td width=\"100%\"> </td>");
writer.write("<td nowrap=\"nowrap\" align=\"right\">");
List childrenList = component.getChildren();
for(int i=0; i<childrenList.size(); i++)
{
UIComponent thisComponent = (UIComponent)childrenList.get(i);
if(thisComponent instanceof org.sakaiproject.tool.messageforums.jsf.BarLinkComponent
||thisComponent instanceof HtmlOutputText)
{
thisComponent.encodeBegin(context);
thisComponent.encodeChildren(context);
thisComponent.encodeEnd(context);
}
}
writer.write("</td></tr></table>");
writer.write("</"+ BARTAG + ">");
if(foldDiv) {
writer.write("<div style=\"display:none\" " +
" id=\"" + id + "__hide_division_" + "\">");
} else {
writer.write("<div style=\"display:block\" " +
" id=\"" + id + "__hide_division_" + "\">");
}
}
| public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter writer = context.getResponseWriter();
String jsfId = (String) RendererUtil.getAttribute(context, component, "id");
String id = jsfId;
if (component.getId() != null &&
!component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
{
id = component.getClientId(context);
}
String title = (String) RendererUtil.getAttribute(context, component, "title");
Object tmpFoldStr = RendererUtil.getAttribute(context, component, "hideByDefault");
boolean foldDiv = tmpFoldStr != null && tmpFoldStr.equals("true");
String foldImage = foldDiv ? FOLD_IMG_HIDE : FOLD_IMG_SHOW;
writer.write("<" + BARTAG + " class=\"" + BARSTYLE + "\">");
writer.write("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
writer.write("<tr><td nowrap=\"nowrap\" align=\"left\">");
writer.write(" <img id=\"" + id + "__img_hide_division_" + "\" alt=\"" +
title + "\"" + " onclick=\"javascript:showHideDivBlock('" + id +
"', '" + RESOURCE_PATH + "');\"");
writer.write(" src=\"" + foldImage + "\" style=\"" + CURSOR + "\" >");
writer.write(" <b>" + title + "</b>");
writer.write("</td><td width=\"100%\"> </td>");
writer.write("<td nowrap=\"nowrap\" align=\"right\">");
List childrenList = component.getChildren();
for(int i=0; i<childrenList.size(); i++)
{
UIComponent thisComponent = (UIComponent)childrenList.get(i);
if(thisComponent instanceof org.sakaiproject.tool.messageforums.jsf.BarLinkComponent
||thisComponent instanceof HtmlOutputText)
{
thisComponent.encodeBegin(context);
thisComponent.encodeChildren(context);
thisComponent.encodeEnd(context);
}
}
writer.write("</td></tr></table>");
writer.write("</"+ BARTAG + ">");
if(foldDiv) {
writer.write("<div style=\"display:none\" " +
" id=\"" + id + "__hide_division_" + "\">");
} else {
writer.write("<div style=\"display:block\" " +
" id=\"" + id + "__hide_division_" + "\">");
}
}
|
diff --git a/jOOQ-test/src/org/jooq/test/_/testcases/MetaDataTests.java b/jOOQ-test/src/org/jooq/test/_/testcases/MetaDataTests.java
index 1c29ace7e..4173848fc 100644
--- a/jOOQ-test/src/org/jooq/test/_/testcases/MetaDataTests.java
+++ b/jOOQ-test/src/org/jooq/test/_/testcases/MetaDataTests.java
@@ -1,482 +1,482 @@
/**
* Copyright (c) 2009-2013, Lukas Eder, [email protected]
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.test._.testcases;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.jooq.SQLDialect.CUBRID;
import static org.jooq.SQLDialect.DB2;
import static org.jooq.SQLDialect.H2;
import static org.jooq.SQLDialect.ORACLE;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.jooq.Catalog;
import org.jooq.Field;
import org.jooq.Meta;
import org.jooq.Record1;
import org.jooq.Record2;
import org.jooq.Record3;
import org.jooq.Record6;
import org.jooq.SQLDialect;
import org.jooq.Schema;
import org.jooq.Sequence;
import org.jooq.Table;
import org.jooq.TableRecord;
import org.jooq.UDT;
import org.jooq.UpdatableRecord;
import org.jooq.UpdatableTable;
import org.jooq.impl.SQLDataType;
import org.jooq.test.BaseTest;
import org.jooq.test.jOOQAbstractTest;
import org.junit.Test;
public class MetaDataTests<
A extends UpdatableRecord<A> & Record6<Integer, String, String, Date, Integer, ?>,
AP,
B extends UpdatableRecord<B>,
S extends UpdatableRecord<S> & Record1<String>,
B2S extends UpdatableRecord<B2S> & Record3<String, Integer, Integer>,
BS extends UpdatableRecord<BS>,
L extends TableRecord<L> & Record2<String, String>,
X extends TableRecord<X>,
DATE extends UpdatableRecord<DATE>,
BOOL extends UpdatableRecord<BOOL>,
D extends UpdatableRecord<D>,
T extends UpdatableRecord<T>,
U extends TableRecord<U>,
UU extends UpdatableRecord<UU>,
I extends TableRecord<I>,
IPK extends UpdatableRecord<IPK>,
T725 extends UpdatableRecord<T725>,
T639 extends UpdatableRecord<T639>,
T785 extends TableRecord<T785>>
extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> {
public MetaDataTests(jOOQAbstractTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> delegate) {
super(delegate);
}
@Test
public void testMetaModel() throws Exception {
// Test correct source code generation for the meta model
Schema schema = TAuthor().getSchema();
if (schema != null) {
int sequences = 0;
if (cSequences() != null) {
sequences++;
// DB2 has an additional sequence for the T_TRIGGERS table
if (getDialect() == DB2 ||
getDialect() == H2) {
sequences++;
}
// CUBRID generates sequences for AUTO_INCREMENT columns
else if (getDialect() == CUBRID) {
sequences += 3;
}
// Oracle has additional sequences for [#961]
else if (getDialect() == ORACLE) {
sequences += 5;
}
}
assertEquals(sequences, schema.getSequences().size());
for (Table<?> table : schema.getTables()) {
assertEquals(table, schema.getTable(table.getName()));
}
for (UDT<?> udt : schema.getUDTs()) {
assertEquals(udt, schema.getUDT(udt.getName()));
}
for (Sequence<?> sequence : schema.getSequences()) {
assertEquals(sequence, schema.getSequence(sequence.getName()));
}
// Some selective tables
assertTrue(schema.getTables().contains(T639()));
assertTrue(schema.getTables().contains(TAuthor()));
assertTrue(schema.getTables().contains(TBook()));
assertTrue(schema.getTables().contains(TBookStore()));
assertTrue(schema.getTables().contains(TBookToBookStore()));
// The additional T_DIRECTORY table for recursive queries
if (TDirectory() != null) {
schema.getTables().contains(TDirectory());
}
// The additional T_TRIGGERS table for INSERT .. RETURNING
if (TTriggers() != null) {
schema.getTables().contains(TTriggers());
}
// The additional T_UNSIGNED table
if (TUnsigned() != null) {
schema.getTables().contains(TUnsigned());
}
// The additional T_IDENTITY table
if (TIdentity() != null) {
schema.getTables().contains(TIdentity());
}
// The additional T_IDENTITY_PK table
if (TIdentityPK() != null) {
schema.getTables().contains(TIdentityPK());
}
if (cUAddressType() == null) {
assertEquals(0, schema.getUDTs().size());
}
// [#643] The U_INVALID types are only available in Oracle
// [#799] The member procedure UDT's too
else if (getDialect() == ORACLE) {
assertEquals(7, schema.getUDTs().size());
}
else {
- assertEquals(2, schema.getUDTs().size());
+ assertEquals(3, schema.getUDTs().size());
}
}
// Test correct source code generation for identity columns
assertNull(TAuthor().getIdentity());
assertNull(TBook().getIdentity());
if (TIdentity() != null || TIdentityPK() != null) {
if (TIdentity() != null) {
assertEquals(TIdentity(), TIdentity().getIdentity().getTable());
assertEquals(TIdentity_ID(), TIdentity().getIdentity().getField());
}
if (TIdentityPK() != null) {
assertEquals(TIdentityPK(), TIdentityPK().getIdentity().getTable());
assertEquals(TIdentityPK_ID(), TIdentityPK().getIdentity().getField());
}
}
else {
log.info("SKIPPING", "Identity tests");
}
// Test correct source code generation for relations
assertNotNull(TAuthor().getPrimaryKey());
assertNotNull(TAuthor().getKeys());
assertTrue(TAuthor().getKeys().contains(TAuthor().getPrimaryKey()));
assertEquals(1, TAuthor().getKeys().size());
assertEquals(1, TAuthor().getPrimaryKey().getFields().size());
assertEquals(TAuthor_ID(), TAuthor().getPrimaryKey().getFields().get(0));
assertEquals(Record1.class, TAuthor().getRecordType().getMethod("key").getReturnType());
assertTrue(TAuthor().getRecordType().getMethod("key").toGenericString().contains("org.jooq.Record1<java.lang.Integer>"));
assertEquals(Record2.class, TBookToBookStore().getRecordType().getMethod("key").getReturnType());
assertTrue(TBookToBookStore().getRecordType().getMethod("key").toGenericString().contains("org.jooq.Record2<java.lang.String, java.lang.Integer>"));
if (supportsReferences()) {
// Without aliasing
assertEquals(0, TAuthor().getReferences().size());
assertEquals(2, TAuthor().getPrimaryKey().getReferences().size());
assertEquals(TBook(), TAuthor().getPrimaryKey().getReferences().get(0).getTable());
assertEquals(TBook(), TAuthor().getPrimaryKey().getReferences().get(1).getTable());
assertEquals(Arrays.asList(), TAuthor().getReferencesTo(TBook()));
assertTrue(TBook().getReferences().containsAll(TAuthor().getReferencesFrom(TBook())));
assertTrue(TBook().getReferences().containsAll(TBook().getReferencesFrom(TAuthor())));
assertEquals(TBook().getReferencesTo(TAuthor()), TAuthor().getReferencesFrom(TBook()));
// [#1460] With aliasing
Table<A> a = TAuthor().as("a");
Table<B> b = TBook().as("b");
assertEquals(0, a.getReferences().size());
assertEquals(Arrays.asList(), a.getReferencesTo(b));
// This should work with both types of meta-models (static, non-static)
assertEquals(TBook().getReferencesTo(TAuthor()), TBook().getReferencesTo(a));
assertEquals(TBook().getReferencesTo(TAuthor()), b.getReferencesTo(a));
assertEquals(TBook().getReferencesTo(TAuthor()), b.getReferencesTo(TAuthor()));
// Only with a non-static meta model
if (a instanceof UpdatableTable && b instanceof UpdatableTable) {
UpdatableTable<A> ua = (UpdatableTable<A>) a;
UpdatableTable<B> ub = (UpdatableTable<B>) b;
assertEquals(2, ua.getPrimaryKey().getReferences().size());
assertEquals(TBook(), ua.getPrimaryKey().getReferences().get(0).getTable());
assertEquals(TBook(), ua.getPrimaryKey().getReferences().get(1).getTable());
assertTrue(b.getReferences().containsAll(ua.getReferencesFrom(b)));
assertTrue(b.getReferences().containsAll(ub.getReferencesFrom(a)));
assertEquals(b.getReferencesTo(a), ua.getReferencesFrom(b));
assertEquals(TBook().getReferencesTo(a), ua.getReferencesFrom(b));
assertEquals(b.getReferencesTo(a), TAuthor().getReferencesFrom(b));
}
}
else {
log.info("SKIPPING", "References tests");
}
// Some string data type tests
// ---------------------------
assertEquals(0, TAuthor_LAST_NAME().getDataType().precision());
assertEquals(0, TAuthor_LAST_NAME().getDataType().scale());
assertEquals(50, TAuthor_LAST_NAME().getDataType().length());
// Some numeric data type tests
// ----------------------------
for (Field<?> field : T639().fields()) {
if ("BYTE".equalsIgnoreCase(field.getName())) {
assertEquals(Byte.class, field.getType());
assertEquals(SQLDataType.TINYINT, field.getDataType());
assertEquals(3, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("SHORT".equalsIgnoreCase(field.getName())) {
assertEquals(Short.class, field.getType());
assertEquals(SQLDataType.SMALLINT, field.getDataType());
assertEquals(5, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("INTEGER".equalsIgnoreCase(field.getName())) {
assertEquals(Integer.class, field.getType());
assertEquals(SQLDataType.INTEGER, field.getDataType());
assertEquals(10, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("LONG".equalsIgnoreCase(field.getName())) {
assertEquals(Long.class, field.getType());
assertEquals(SQLDataType.BIGINT, field.getDataType());
assertEquals(19, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BYTE_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Byte.class, field.getType());
assertEquals(SQLDataType.TINYINT, field.getDataType());
assertEquals(3, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("SHORT_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Short.class, field.getType());
assertEquals(SQLDataType.SMALLINT, field.getDataType());
assertEquals(5, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("INTEGER_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Integer.class, field.getType());
assertEquals(SQLDataType.INTEGER, field.getDataType());
assertEquals(10, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("LONG_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Long.class, field.getType());
assertEquals(SQLDataType.BIGINT, field.getDataType());
assertEquals(19, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BIG_INTEGER".equalsIgnoreCase(field.getName())) {
assertEquals(BigInteger.class, field.getType());
assertEquals(SQLDataType.DECIMAL_INTEGER.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
// [#745] TODO: Unify distinction between NUMERIC and DECIMAL
else if ("BIG_DECIMAL".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.ORACLE
&& getDialect() != SQLDialect.POSTGRES
&& getDialect() != SQLDialect.SQLITE
&& getDialect() != SQLDialect.SQLSERVER) {
assertEquals(BigDecimal.class, field.getType());
assertEquals(SQLDataType.DECIMAL.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(5, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BIG_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(BigDecimal.class, field.getType());
assertEquals(SQLDataType.NUMERIC.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(5, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
// [#746] TODO: Interestingly, HSQLDB and MySQL match REAL with DOUBLE.
// There is no matching type for java.lang.Float...
// [#456] TODO: Should floating point numbers have precision and scale?
else if ("FLOAT".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.HSQLDB
&& getDialect() != SQLDialect.MYSQL
&& getDialect() != SQLDialect.SYBASE) {
assertEquals(Float.class, field.getType());
assertEquals(SQLDataType.REAL, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("FLOAT".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.MYSQL
&& getDialect() != SQLDialect.SYBASE) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.DOUBLE, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("FLOAT".equalsIgnoreCase(field.getName())) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.FLOAT, field.getDataType());
assertEquals(0, field.getDataType().length());
}
// [#746] TODO: Fix this, too
else if ("DOUBLE".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.SQLSERVER
&& getDialect() != SQLDialect.ASE) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.DOUBLE, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("DOUBLE".equalsIgnoreCase(field.getName())) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.FLOAT, field.getDataType());
assertEquals(0, field.getDataType().length());
}
}
}
@Test
public void testMetaData() throws Exception {
Meta meta = create().meta();
if (schema() != null) {
// Catalog checks
List<Catalog> metaCatalogs = meta.getCatalogs();
List<Schema> metaSchemasFromCatalogs = new ArrayList<Schema>();
for (Catalog metaCatalog : metaCatalogs) {
metaSchemasFromCatalogs.addAll(metaCatalog.getSchemas());
}
assertTrue(metaSchemasFromCatalogs.contains(schema()));
// The schema returned from meta should be equal to the
// generated test schema
List<Schema> metaSchemas = meta.getSchemas();
assertTrue(metaSchemas.contains(schema()));
assertEquals(metaSchemasFromCatalogs, metaSchemas);
Schema metaSchema = metaSchemas.get(metaSchemas.indexOf(schema()));
assertEquals(schema(), metaSchema);
// The schema returned from meta should contain at least all the
// generated test tables
List<Table<?>> metaTables = metaSchema.getTables();
assertTrue(metaTables.containsAll(schema().getTables()));
assertTrue(metaTables.size() >= schema().getTables().size());
metaTableChecks(metaTables);
}
// Some sample checks about tables returned from meta
List<Table<?>> metaTables = meta.getTables();
assertTrue(metaTables.contains(TAuthor()));
assertTrue(metaTables.contains(TBook()));
assertTrue(metaTables.contains(TBookStore()));
assertTrue(metaTables.contains(TBookToBookStore()));
assertTrue(metaTables.contains(VAuthor()));
assertTrue(metaTables.contains(VBook()));
assertTrue(metaTables.contains(VLibrary()));
metaTableChecks(metaTables);
}
private void metaTableChecks(Collection<? extends Table<?>> metaTables) {
for (Table<?> metaTable : metaTables) {
// Check only the "TEST" schema, not "MULTI_SCHEMA" and others
if (schema().equals(metaTable.getSchema())) {
Table<?> generatedTable = schema().getTable(metaTable.getName());
// Every table returned from meta should have a corresponding
// table by name in the generated test tables
if (generatedTable != null) {
assertNotNull(generatedTable);
assertEquals(metaTable, generatedTable);
// Check if fields match, as well
List<Field<?>> metaFields = asList(metaTable.fields());
assertTrue(metaFields.containsAll(asList(generatedTable.fields())));
// Check if relations are correctly loaded (and typed) as well
// [#1977] Fix this, once the "main key" concept has been removed
if (generatedTable instanceof UpdatableTable && metaTable instanceof UpdatableTable) {
UpdatableTable<?> generatedUTable = (UpdatableTable<?>) generatedTable;
UpdatableTable<?> metaUTable = (UpdatableTable<?>) metaTable;
// [#1977] TODO: Add key checks
}
// Only truly updatable tables should be "Updatable"
else {
assertFalse(metaTable instanceof UpdatableTable);
}
}
}
}
}
}
| true | true | public void testMetaModel() throws Exception {
// Test correct source code generation for the meta model
Schema schema = TAuthor().getSchema();
if (schema != null) {
int sequences = 0;
if (cSequences() != null) {
sequences++;
// DB2 has an additional sequence for the T_TRIGGERS table
if (getDialect() == DB2 ||
getDialect() == H2) {
sequences++;
}
// CUBRID generates sequences for AUTO_INCREMENT columns
else if (getDialect() == CUBRID) {
sequences += 3;
}
// Oracle has additional sequences for [#961]
else if (getDialect() == ORACLE) {
sequences += 5;
}
}
assertEquals(sequences, schema.getSequences().size());
for (Table<?> table : schema.getTables()) {
assertEquals(table, schema.getTable(table.getName()));
}
for (UDT<?> udt : schema.getUDTs()) {
assertEquals(udt, schema.getUDT(udt.getName()));
}
for (Sequence<?> sequence : schema.getSequences()) {
assertEquals(sequence, schema.getSequence(sequence.getName()));
}
// Some selective tables
assertTrue(schema.getTables().contains(T639()));
assertTrue(schema.getTables().contains(TAuthor()));
assertTrue(schema.getTables().contains(TBook()));
assertTrue(schema.getTables().contains(TBookStore()));
assertTrue(schema.getTables().contains(TBookToBookStore()));
// The additional T_DIRECTORY table for recursive queries
if (TDirectory() != null) {
schema.getTables().contains(TDirectory());
}
// The additional T_TRIGGERS table for INSERT .. RETURNING
if (TTriggers() != null) {
schema.getTables().contains(TTriggers());
}
// The additional T_UNSIGNED table
if (TUnsigned() != null) {
schema.getTables().contains(TUnsigned());
}
// The additional T_IDENTITY table
if (TIdentity() != null) {
schema.getTables().contains(TIdentity());
}
// The additional T_IDENTITY_PK table
if (TIdentityPK() != null) {
schema.getTables().contains(TIdentityPK());
}
if (cUAddressType() == null) {
assertEquals(0, schema.getUDTs().size());
}
// [#643] The U_INVALID types are only available in Oracle
// [#799] The member procedure UDT's too
else if (getDialect() == ORACLE) {
assertEquals(7, schema.getUDTs().size());
}
else {
assertEquals(2, schema.getUDTs().size());
}
}
// Test correct source code generation for identity columns
assertNull(TAuthor().getIdentity());
assertNull(TBook().getIdentity());
if (TIdentity() != null || TIdentityPK() != null) {
if (TIdentity() != null) {
assertEquals(TIdentity(), TIdentity().getIdentity().getTable());
assertEquals(TIdentity_ID(), TIdentity().getIdentity().getField());
}
if (TIdentityPK() != null) {
assertEquals(TIdentityPK(), TIdentityPK().getIdentity().getTable());
assertEquals(TIdentityPK_ID(), TIdentityPK().getIdentity().getField());
}
}
else {
log.info("SKIPPING", "Identity tests");
}
// Test correct source code generation for relations
assertNotNull(TAuthor().getPrimaryKey());
assertNotNull(TAuthor().getKeys());
assertTrue(TAuthor().getKeys().contains(TAuthor().getPrimaryKey()));
assertEquals(1, TAuthor().getKeys().size());
assertEquals(1, TAuthor().getPrimaryKey().getFields().size());
assertEquals(TAuthor_ID(), TAuthor().getPrimaryKey().getFields().get(0));
assertEquals(Record1.class, TAuthor().getRecordType().getMethod("key").getReturnType());
assertTrue(TAuthor().getRecordType().getMethod("key").toGenericString().contains("org.jooq.Record1<java.lang.Integer>"));
assertEquals(Record2.class, TBookToBookStore().getRecordType().getMethod("key").getReturnType());
assertTrue(TBookToBookStore().getRecordType().getMethod("key").toGenericString().contains("org.jooq.Record2<java.lang.String, java.lang.Integer>"));
if (supportsReferences()) {
// Without aliasing
assertEquals(0, TAuthor().getReferences().size());
assertEquals(2, TAuthor().getPrimaryKey().getReferences().size());
assertEquals(TBook(), TAuthor().getPrimaryKey().getReferences().get(0).getTable());
assertEquals(TBook(), TAuthor().getPrimaryKey().getReferences().get(1).getTable());
assertEquals(Arrays.asList(), TAuthor().getReferencesTo(TBook()));
assertTrue(TBook().getReferences().containsAll(TAuthor().getReferencesFrom(TBook())));
assertTrue(TBook().getReferences().containsAll(TBook().getReferencesFrom(TAuthor())));
assertEquals(TBook().getReferencesTo(TAuthor()), TAuthor().getReferencesFrom(TBook()));
// [#1460] With aliasing
Table<A> a = TAuthor().as("a");
Table<B> b = TBook().as("b");
assertEquals(0, a.getReferences().size());
assertEquals(Arrays.asList(), a.getReferencesTo(b));
// This should work with both types of meta-models (static, non-static)
assertEquals(TBook().getReferencesTo(TAuthor()), TBook().getReferencesTo(a));
assertEquals(TBook().getReferencesTo(TAuthor()), b.getReferencesTo(a));
assertEquals(TBook().getReferencesTo(TAuthor()), b.getReferencesTo(TAuthor()));
// Only with a non-static meta model
if (a instanceof UpdatableTable && b instanceof UpdatableTable) {
UpdatableTable<A> ua = (UpdatableTable<A>) a;
UpdatableTable<B> ub = (UpdatableTable<B>) b;
assertEquals(2, ua.getPrimaryKey().getReferences().size());
assertEquals(TBook(), ua.getPrimaryKey().getReferences().get(0).getTable());
assertEquals(TBook(), ua.getPrimaryKey().getReferences().get(1).getTable());
assertTrue(b.getReferences().containsAll(ua.getReferencesFrom(b)));
assertTrue(b.getReferences().containsAll(ub.getReferencesFrom(a)));
assertEquals(b.getReferencesTo(a), ua.getReferencesFrom(b));
assertEquals(TBook().getReferencesTo(a), ua.getReferencesFrom(b));
assertEquals(b.getReferencesTo(a), TAuthor().getReferencesFrom(b));
}
}
else {
log.info("SKIPPING", "References tests");
}
// Some string data type tests
// ---------------------------
assertEquals(0, TAuthor_LAST_NAME().getDataType().precision());
assertEquals(0, TAuthor_LAST_NAME().getDataType().scale());
assertEquals(50, TAuthor_LAST_NAME().getDataType().length());
// Some numeric data type tests
// ----------------------------
for (Field<?> field : T639().fields()) {
if ("BYTE".equalsIgnoreCase(field.getName())) {
assertEquals(Byte.class, field.getType());
assertEquals(SQLDataType.TINYINT, field.getDataType());
assertEquals(3, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("SHORT".equalsIgnoreCase(field.getName())) {
assertEquals(Short.class, field.getType());
assertEquals(SQLDataType.SMALLINT, field.getDataType());
assertEquals(5, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("INTEGER".equalsIgnoreCase(field.getName())) {
assertEquals(Integer.class, field.getType());
assertEquals(SQLDataType.INTEGER, field.getDataType());
assertEquals(10, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("LONG".equalsIgnoreCase(field.getName())) {
assertEquals(Long.class, field.getType());
assertEquals(SQLDataType.BIGINT, field.getDataType());
assertEquals(19, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BYTE_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Byte.class, field.getType());
assertEquals(SQLDataType.TINYINT, field.getDataType());
assertEquals(3, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("SHORT_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Short.class, field.getType());
assertEquals(SQLDataType.SMALLINT, field.getDataType());
assertEquals(5, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("INTEGER_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Integer.class, field.getType());
assertEquals(SQLDataType.INTEGER, field.getDataType());
assertEquals(10, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("LONG_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Long.class, field.getType());
assertEquals(SQLDataType.BIGINT, field.getDataType());
assertEquals(19, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BIG_INTEGER".equalsIgnoreCase(field.getName())) {
assertEquals(BigInteger.class, field.getType());
assertEquals(SQLDataType.DECIMAL_INTEGER.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
// [#745] TODO: Unify distinction between NUMERIC and DECIMAL
else if ("BIG_DECIMAL".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.ORACLE
&& getDialect() != SQLDialect.POSTGRES
&& getDialect() != SQLDialect.SQLITE
&& getDialect() != SQLDialect.SQLSERVER) {
assertEquals(BigDecimal.class, field.getType());
assertEquals(SQLDataType.DECIMAL.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(5, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BIG_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(BigDecimal.class, field.getType());
assertEquals(SQLDataType.NUMERIC.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(5, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
// [#746] TODO: Interestingly, HSQLDB and MySQL match REAL with DOUBLE.
// There is no matching type for java.lang.Float...
// [#456] TODO: Should floating point numbers have precision and scale?
else if ("FLOAT".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.HSQLDB
&& getDialect() != SQLDialect.MYSQL
&& getDialect() != SQLDialect.SYBASE) {
assertEquals(Float.class, field.getType());
assertEquals(SQLDataType.REAL, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("FLOAT".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.MYSQL
&& getDialect() != SQLDialect.SYBASE) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.DOUBLE, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("FLOAT".equalsIgnoreCase(field.getName())) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.FLOAT, field.getDataType());
assertEquals(0, field.getDataType().length());
}
// [#746] TODO: Fix this, too
else if ("DOUBLE".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.SQLSERVER
&& getDialect() != SQLDialect.ASE) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.DOUBLE, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("DOUBLE".equalsIgnoreCase(field.getName())) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.FLOAT, field.getDataType());
assertEquals(0, field.getDataType().length());
}
}
}
| public void testMetaModel() throws Exception {
// Test correct source code generation for the meta model
Schema schema = TAuthor().getSchema();
if (schema != null) {
int sequences = 0;
if (cSequences() != null) {
sequences++;
// DB2 has an additional sequence for the T_TRIGGERS table
if (getDialect() == DB2 ||
getDialect() == H2) {
sequences++;
}
// CUBRID generates sequences for AUTO_INCREMENT columns
else if (getDialect() == CUBRID) {
sequences += 3;
}
// Oracle has additional sequences for [#961]
else if (getDialect() == ORACLE) {
sequences += 5;
}
}
assertEquals(sequences, schema.getSequences().size());
for (Table<?> table : schema.getTables()) {
assertEquals(table, schema.getTable(table.getName()));
}
for (UDT<?> udt : schema.getUDTs()) {
assertEquals(udt, schema.getUDT(udt.getName()));
}
for (Sequence<?> sequence : schema.getSequences()) {
assertEquals(sequence, schema.getSequence(sequence.getName()));
}
// Some selective tables
assertTrue(schema.getTables().contains(T639()));
assertTrue(schema.getTables().contains(TAuthor()));
assertTrue(schema.getTables().contains(TBook()));
assertTrue(schema.getTables().contains(TBookStore()));
assertTrue(schema.getTables().contains(TBookToBookStore()));
// The additional T_DIRECTORY table for recursive queries
if (TDirectory() != null) {
schema.getTables().contains(TDirectory());
}
// The additional T_TRIGGERS table for INSERT .. RETURNING
if (TTriggers() != null) {
schema.getTables().contains(TTriggers());
}
// The additional T_UNSIGNED table
if (TUnsigned() != null) {
schema.getTables().contains(TUnsigned());
}
// The additional T_IDENTITY table
if (TIdentity() != null) {
schema.getTables().contains(TIdentity());
}
// The additional T_IDENTITY_PK table
if (TIdentityPK() != null) {
schema.getTables().contains(TIdentityPK());
}
if (cUAddressType() == null) {
assertEquals(0, schema.getUDTs().size());
}
// [#643] The U_INVALID types are only available in Oracle
// [#799] The member procedure UDT's too
else if (getDialect() == ORACLE) {
assertEquals(7, schema.getUDTs().size());
}
else {
assertEquals(3, schema.getUDTs().size());
}
}
// Test correct source code generation for identity columns
assertNull(TAuthor().getIdentity());
assertNull(TBook().getIdentity());
if (TIdentity() != null || TIdentityPK() != null) {
if (TIdentity() != null) {
assertEquals(TIdentity(), TIdentity().getIdentity().getTable());
assertEquals(TIdentity_ID(), TIdentity().getIdentity().getField());
}
if (TIdentityPK() != null) {
assertEquals(TIdentityPK(), TIdentityPK().getIdentity().getTable());
assertEquals(TIdentityPK_ID(), TIdentityPK().getIdentity().getField());
}
}
else {
log.info("SKIPPING", "Identity tests");
}
// Test correct source code generation for relations
assertNotNull(TAuthor().getPrimaryKey());
assertNotNull(TAuthor().getKeys());
assertTrue(TAuthor().getKeys().contains(TAuthor().getPrimaryKey()));
assertEquals(1, TAuthor().getKeys().size());
assertEquals(1, TAuthor().getPrimaryKey().getFields().size());
assertEquals(TAuthor_ID(), TAuthor().getPrimaryKey().getFields().get(0));
assertEquals(Record1.class, TAuthor().getRecordType().getMethod("key").getReturnType());
assertTrue(TAuthor().getRecordType().getMethod("key").toGenericString().contains("org.jooq.Record1<java.lang.Integer>"));
assertEquals(Record2.class, TBookToBookStore().getRecordType().getMethod("key").getReturnType());
assertTrue(TBookToBookStore().getRecordType().getMethod("key").toGenericString().contains("org.jooq.Record2<java.lang.String, java.lang.Integer>"));
if (supportsReferences()) {
// Without aliasing
assertEquals(0, TAuthor().getReferences().size());
assertEquals(2, TAuthor().getPrimaryKey().getReferences().size());
assertEquals(TBook(), TAuthor().getPrimaryKey().getReferences().get(0).getTable());
assertEquals(TBook(), TAuthor().getPrimaryKey().getReferences().get(1).getTable());
assertEquals(Arrays.asList(), TAuthor().getReferencesTo(TBook()));
assertTrue(TBook().getReferences().containsAll(TAuthor().getReferencesFrom(TBook())));
assertTrue(TBook().getReferences().containsAll(TBook().getReferencesFrom(TAuthor())));
assertEquals(TBook().getReferencesTo(TAuthor()), TAuthor().getReferencesFrom(TBook()));
// [#1460] With aliasing
Table<A> a = TAuthor().as("a");
Table<B> b = TBook().as("b");
assertEquals(0, a.getReferences().size());
assertEquals(Arrays.asList(), a.getReferencesTo(b));
// This should work with both types of meta-models (static, non-static)
assertEquals(TBook().getReferencesTo(TAuthor()), TBook().getReferencesTo(a));
assertEquals(TBook().getReferencesTo(TAuthor()), b.getReferencesTo(a));
assertEquals(TBook().getReferencesTo(TAuthor()), b.getReferencesTo(TAuthor()));
// Only with a non-static meta model
if (a instanceof UpdatableTable && b instanceof UpdatableTable) {
UpdatableTable<A> ua = (UpdatableTable<A>) a;
UpdatableTable<B> ub = (UpdatableTable<B>) b;
assertEquals(2, ua.getPrimaryKey().getReferences().size());
assertEquals(TBook(), ua.getPrimaryKey().getReferences().get(0).getTable());
assertEquals(TBook(), ua.getPrimaryKey().getReferences().get(1).getTable());
assertTrue(b.getReferences().containsAll(ua.getReferencesFrom(b)));
assertTrue(b.getReferences().containsAll(ub.getReferencesFrom(a)));
assertEquals(b.getReferencesTo(a), ua.getReferencesFrom(b));
assertEquals(TBook().getReferencesTo(a), ua.getReferencesFrom(b));
assertEquals(b.getReferencesTo(a), TAuthor().getReferencesFrom(b));
}
}
else {
log.info("SKIPPING", "References tests");
}
// Some string data type tests
// ---------------------------
assertEquals(0, TAuthor_LAST_NAME().getDataType().precision());
assertEquals(0, TAuthor_LAST_NAME().getDataType().scale());
assertEquals(50, TAuthor_LAST_NAME().getDataType().length());
// Some numeric data type tests
// ----------------------------
for (Field<?> field : T639().fields()) {
if ("BYTE".equalsIgnoreCase(field.getName())) {
assertEquals(Byte.class, field.getType());
assertEquals(SQLDataType.TINYINT, field.getDataType());
assertEquals(3, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("SHORT".equalsIgnoreCase(field.getName())) {
assertEquals(Short.class, field.getType());
assertEquals(SQLDataType.SMALLINT, field.getDataType());
assertEquals(5, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("INTEGER".equalsIgnoreCase(field.getName())) {
assertEquals(Integer.class, field.getType());
assertEquals(SQLDataType.INTEGER, field.getDataType());
assertEquals(10, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("LONG".equalsIgnoreCase(field.getName())) {
assertEquals(Long.class, field.getType());
assertEquals(SQLDataType.BIGINT, field.getDataType());
assertEquals(19, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BYTE_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Byte.class, field.getType());
assertEquals(SQLDataType.TINYINT, field.getDataType());
assertEquals(3, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("SHORT_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Short.class, field.getType());
assertEquals(SQLDataType.SMALLINT, field.getDataType());
assertEquals(5, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("INTEGER_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Integer.class, field.getType());
assertEquals(SQLDataType.INTEGER, field.getDataType());
assertEquals(10, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("LONG_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(Long.class, field.getType());
assertEquals(SQLDataType.BIGINT, field.getDataType());
assertEquals(19, field.getDataType().precision());
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BIG_INTEGER".equalsIgnoreCase(field.getName())) {
assertEquals(BigInteger.class, field.getType());
assertEquals(SQLDataType.DECIMAL_INTEGER.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(0, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
// [#745] TODO: Unify distinction between NUMERIC and DECIMAL
else if ("BIG_DECIMAL".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.ORACLE
&& getDialect() != SQLDialect.POSTGRES
&& getDialect() != SQLDialect.SQLITE
&& getDialect() != SQLDialect.SQLSERVER) {
assertEquals(BigDecimal.class, field.getType());
assertEquals(SQLDataType.DECIMAL.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(5, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
else if ("BIG_DECIMAL".equalsIgnoreCase(field.getName())) {
assertEquals(BigDecimal.class, field.getType());
assertEquals(SQLDataType.NUMERIC.getType(), field.getDataType().getType());
assertTrue(field.getDataType().precision() > 0);
assertEquals(5, field.getDataType().scale());
assertEquals(0, field.getDataType().length());
}
// [#746] TODO: Interestingly, HSQLDB and MySQL match REAL with DOUBLE.
// There is no matching type for java.lang.Float...
// [#456] TODO: Should floating point numbers have precision and scale?
else if ("FLOAT".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.HSQLDB
&& getDialect() != SQLDialect.MYSQL
&& getDialect() != SQLDialect.SYBASE) {
assertEquals(Float.class, field.getType());
assertEquals(SQLDataType.REAL, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("FLOAT".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.MYSQL
&& getDialect() != SQLDialect.SYBASE) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.DOUBLE, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("FLOAT".equalsIgnoreCase(field.getName())) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.FLOAT, field.getDataType());
assertEquals(0, field.getDataType().length());
}
// [#746] TODO: Fix this, too
else if ("DOUBLE".equalsIgnoreCase(field.getName())
&& getDialect() != SQLDialect.SQLSERVER
&& getDialect() != SQLDialect.ASE) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.DOUBLE, field.getDataType());
assertEquals(0, field.getDataType().length());
}
else if ("DOUBLE".equalsIgnoreCase(field.getName())) {
assertEquals(Double.class, field.getType());
assertEquals(SQLDataType.FLOAT, field.getDataType());
assertEquals(0, field.getDataType().length());
}
}
}
|
diff --git a/src/client/Client.java b/src/client/Client.java
index a3dbc6e..f1c693d 100644
--- a/src/client/Client.java
+++ b/src/client/Client.java
@@ -1,263 +1,264 @@
package client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import server.packet.LoginAcknowledgementType;
import server.packet.ServerPacket;
import server.packet.impl.CurrentGameStatePacket;
import server.packet.impl.CurrentUsersListPacket;
import server.packet.impl.GameResultPacket;
import server.packet.impl.IllegalMovePacket;
import server.packet.impl.LoginAcknowledgementPacket;
import server.packet.impl.PlayRequestAcknowledgementPacket;
import server.packet.impl.PlayRequestPacket;
import common.Payload;
import common.User;
import exception.BadPacketException;
/**
* Tic Tac Toe client
*
* @author evan
*
*/
public class Client {
/**
* Creates a client and runs it.
*
* @param args
*/
public static void main(String[] args) {
//check arguments
if (args.length != 2) {
System.out.println("usage: client <server-ip> <server-port>");
return;
}
try {
(new Client(args[0], Integer.valueOf(args[1]))).run();
} catch (SocketException e) {
System.out.println("Could not connect to socket.");
}
}
private final DatagramSocket socket;
private final ExecutorService pool;
private User currentUser;
private final String receiverIP;
private final int receiverPort;
/**
* Creates client that sends packets to specified ip and port
*
* @param serverIp
* @param serverPort
* @throws SocketException
*/
public Client(String serverIp, int serverPort) throws SocketException {
this.receiverIP = serverIp;
this.receiverPort = serverPort;
socket = new DatagramSocket();
pool = Executors.newFixedThreadPool(2);
}
/**
* @return user that client is currently logged in as
*/
public User getCurrentUser() {
return currentUser;
}
/**
* @return local ip address of the client
*/
public String getIP() {
return socket.getLocalAddress().getHostAddress();
}
/**
* @return local port of client
*/
public int getPort() {
return socket.getLocalPort();
}
/**
* respond to server packet by figuring out that type of packet it is and calling the appropriate response method.
*
* @param packet
*/
private void handle(ServerPacket packet) {
switch (packet.getPacketType()) {
case ACK:
return;
case CURRENT_GAME_STATE:
handleCurrentGameState((CurrentGameStatePacket) packet);
return;
case CURRENT_USERS_LIST:
handleUserList((CurrentUsersListPacket) packet);
return;
case GAME_RESULT:
handleGameResult((GameResultPacket) packet);
return;
case ILLEGAL_MOVE:
handleIllegalMove((IllegalMovePacket) packet);
+ return;
case LOGIN_ACK:
handleLoginAck((LoginAcknowledgementPacket) packet);
return;
case PLAY_REQUEST_ACK:
handlePlayRequestAck((PlayRequestAcknowledgementPacket) packet);
return;
case PLAY_REQUEST:
handlePlayRequest((PlayRequestPacket) packet);
return;
default:
throw new BadPacketException("Unrecognized packet format");
}
}
private void handleIllegalMove(IllegalMovePacket packet) {
System.out.println(packet.toFormattedString());
}
/**
* respond to current game state packet by printing out the tic tac toe board
*
* @param packet
*/
private void handleCurrentGameState(CurrentGameStatePacket packet) {
System.out.println(packet.toFormattedString());
}
/**
* respond to game result packet by printing out a message to the console
*
* @param packet
*/
private void handleGameResult(GameResultPacket packet) {
String message = currentUser.getUsername();
switch (packet.getResult()) {
case DRAW:
message += " draw";
break;
case LOSS:
message += " lose";
break;
case WIN:
message += " win";
break;
default:
break;
}
System.out.println(message);
}
/**
* respond to a login acknowledgement packet
*
* @param packet
* @return
*/
private void handleLoginAck(LoginAcknowledgementPacket packet) {
//print login message to console
String message = "login ";
message += packet.getAcktype() == LoginAcknowledgementType.SUCCESS ? "success " : "failure ";
message += currentUser.getUsername();
System.out.println(message);
}
/**
* log out user and print message
*/
public void handleLogout() {
System.out.println(currentUser.getUsername() + " logout");
currentUser = null;
}
/**
* respond to a play request packet by printing out info to client
*
* @param packet
*/
private void handlePlayRequest(PlayRequestPacket packet) {
System.out.println(packet.toFormattedString());
}
/**
* respond to a play request ack packet by printing out info to client
*
* @param packet
*/
private void handlePlayRequestAck(PlayRequestAcknowledgementPacket packet) {
System.out.println(packet.toFormattedString());
}
/**
* respond to a current users list packet by printing the list to the console
*
* @param packet
* @return
*/
private void handleUserList(CurrentUsersListPacket packet) {
System.out.println(packet.getUsers().toFormattedString());
}
/**
* sets the current user variable
*
* @param username
* @param ip
* @param port
*/
public void login(String username, String ip, int port) {
currentUser = new User(username, ip, port);
}
/**
* runs a client UDPReceiver that receives packets from the server
*
* @throws SocketException
*/
public void recieve() throws SocketException {
pool.execute(new UDPReciever(socket, this));
}
/**
* respond to a datagram packet
*
* @param p
* @throws UnknownHostException
*/
public void respond(DatagramPacket p) throws UnknownHostException {
Payload payload = new Payload(new String(p.getData(), 0, p.getLength()));
ServerPacket sp = ServerPacket.fromPayload(payload);
handle(sp);
}
/**
* puts UDPSender and receiver in thread pool and runs them
*
* @throws SocketException
*/
private void run() throws SocketException {
send();
recieve();
}
/**
* runs a client UDPSender that takes console input and sends it, waiting for acks
*
* @throws SocketException
*/
public void send() throws SocketException {
pool.execute(new UDPSender(new DatagramSocket(), receiverIP, receiverPort, this));
}
}
| true | true | private void handle(ServerPacket packet) {
switch (packet.getPacketType()) {
case ACK:
return;
case CURRENT_GAME_STATE:
handleCurrentGameState((CurrentGameStatePacket) packet);
return;
case CURRENT_USERS_LIST:
handleUserList((CurrentUsersListPacket) packet);
return;
case GAME_RESULT:
handleGameResult((GameResultPacket) packet);
return;
case ILLEGAL_MOVE:
handleIllegalMove((IllegalMovePacket) packet);
case LOGIN_ACK:
handleLoginAck((LoginAcknowledgementPacket) packet);
return;
case PLAY_REQUEST_ACK:
handlePlayRequestAck((PlayRequestAcknowledgementPacket) packet);
return;
case PLAY_REQUEST:
handlePlayRequest((PlayRequestPacket) packet);
return;
default:
throw new BadPacketException("Unrecognized packet format");
}
}
| private void handle(ServerPacket packet) {
switch (packet.getPacketType()) {
case ACK:
return;
case CURRENT_GAME_STATE:
handleCurrentGameState((CurrentGameStatePacket) packet);
return;
case CURRENT_USERS_LIST:
handleUserList((CurrentUsersListPacket) packet);
return;
case GAME_RESULT:
handleGameResult((GameResultPacket) packet);
return;
case ILLEGAL_MOVE:
handleIllegalMove((IllegalMovePacket) packet);
return;
case LOGIN_ACK:
handleLoginAck((LoginAcknowledgementPacket) packet);
return;
case PLAY_REQUEST_ACK:
handlePlayRequestAck((PlayRequestAcknowledgementPacket) packet);
return;
case PLAY_REQUEST:
handlePlayRequest((PlayRequestPacket) packet);
return;
default:
throw new BadPacketException("Unrecognized packet format");
}
}
|
diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java
index d851688fc..3a50f8a36 100644
--- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java
+++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java
@@ -1,258 +1,262 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.tests.ccvs.core.subscriber;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.*;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.diff.IDiff;
import org.eclipse.team.core.diff.provider.Diff;
import org.eclipse.team.core.subscribers.Subscriber;
import org.eclipse.team.core.synchronize.SyncInfo;
import org.eclipse.team.internal.ccvs.core.*;
import org.eclipse.team.internal.ccvs.ui.subscriber.CVSSubscriberOperation;
import org.eclipse.team.internal.ccvs.ui.subscriber.ConfirmMergedOperation;
import org.eclipse.team.internal.core.mapping.SyncInfoToDiffConverter;
import org.eclipse.team.internal.ui.synchronize.SyncInfoModelElement;
import org.eclipse.team.tests.ccvs.core.CVSTestSetup;
/**
* This class acts as the source for the sync info used by the subscriber tests.
* The purpose is to allow the sync info to be obtained directly from the subscriber
* or through the sync set visible in the sync view.
*/
public class SyncInfoSource {
protected static IProgressMonitor DEFAULT_MONITOR = new NullProgressMonitor();
protected List mergeSubscribers = new ArrayList();
protected List compareSubscribers = new ArrayList();
public CVSMergeSubscriber createMergeSubscriber(IProject project, CVSTag root, CVSTag branch) {
CVSMergeSubscriber subscriber = new CVSMergeSubscriber(new IResource[] { project }, root, branch);
mergeSubscribers.add(subscriber);
return subscriber;
}
public CVSCompareSubscriber createCompareSubscriber(IResource resource, CVSTag tag) {
CVSCompareSubscriber subscriber = new CVSCompareSubscriber(new IResource[] { resource }, tag);
compareSubscribers.add(subscriber);
return subscriber;
}
public Subscriber createWorkspaceSubscriber() throws TeamException {
return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber();
}
/**
* Return the sync info for the given subscriber for the given resource.
*/
protected SyncInfo getSyncInfo(Subscriber subscriber, IResource resource) throws TeamException {
return subscriber.getSyncInfo(resource);
}
/**
* Return the diff for the given subscriber for the given resource.
*/
protected IDiff getDiff(Subscriber subscriber, IResource resource) throws CoreException {
return subscriber.getDiff(resource);
}
/**
* Refresh the subscriber for the given resource
*/
public void refresh(Subscriber subscriber, IResource resource) throws TeamException {
refresh(subscriber, new IResource[] { resource});
}
/**
* Refresh the subscriber for the given resources
*/
public void refresh(Subscriber subscriber, IResource[] resources) throws TeamException {
subscriber.refresh(resources, IResource.DEPTH_INFINITE, DEFAULT_MONITOR);
}
protected void assertProjectRemoved(Subscriber subscriber, IProject project) throws TeamException {
IResource[] roots = subscriber.roots();
for (int i = 0; i < roots.length; i++) {
IResource resource = roots[i];
if (resource.equals(project)) {
throw new AssertionFailedError();
}
}
}
public void tearDown() {
for (Iterator it = mergeSubscribers.iterator(); it.hasNext(); ) {
CVSMergeSubscriber s = (CVSMergeSubscriber) it.next();
s.cancel();
}
}
public void assertSyncEquals(String message, Subscriber subscriber, IResource resource, int syncKind) throws CoreException {
int conflictTypeMask = 0x0F; // ignore manual and auto merge sync types for now.
SyncInfo info = getSyncInfo(subscriber, resource);
int kind;
int kindOther = syncKind & conflictTypeMask;
if (info == null) {
kind = SyncInfo.IN_SYNC;
} else {
kind = info.getKind() & conflictTypeMask;
}
// Special handling for folders
if (kind != kindOther && resource.getType() == IResource.FOLDER) {
// The only two states for folders are outgoing addition and in-sync.
// Other additions will appear as in-sync
if (info.getKind() == SyncInfo.IN_SYNC
&& (syncKind & SyncInfo.ADDITION) != 0) {
return;
}
} else {
// Only test if kinds are equal
assertDiffKindEquals(message, subscriber, resource, SyncInfoToDiffConverter.asDiffFlags(syncKind));
}
junit.framework.Assert.assertTrue(message + ": improper sync state for " + resource + " expected " +
SyncInfo.kindToString(kindOther) + " but was " +
SyncInfo.kindToString(kind), kind == kindOther);
}
protected void assertDiffKindEquals(String message, Subscriber subscriber, IResource resource, int expectedFlags) throws CoreException {
int actualFlags = getActualDiffFlags(subscriber, resource);
boolean result = compareFlags(resource, actualFlags, expectedFlags);
int count = 0;
while (!result && count < 40) {
// The discrepancy may be due to a timing issue.
// Let's wait a few seconds and get the flags again.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
actualFlags = getActualDiffFlags(subscriber, resource);
result = compareFlags(resource, actualFlags, expectedFlags);
if (result) {
System.out.println("A timing issue has been detected in the CVS test");
new Exception().printStackTrace();
} else {
count++;
}
}
String errorString = message + ": improper diff for " + resource
+ " expected "
+ SyncInfoToDiffConverter.diffStatusToString(expectedFlags)
+ " but was "
+ SyncInfoToDiffConverter.diffStatusToString(actualFlags);
- if (CVSTestSetup.FAIL_ON_BAD_DIFF) {
+ if (CVSTestSetup.FAIL_ON_BAD_DIFF
+ || (expectedFlags != IDiff.NO_CHANGE && actualFlags == IDiff.NO_CHANGE)) {
+ // When running in the suites, we want to avoid intermittent failures.
+ // However, still fail if we expected a change but we get no change since that can
+ // cause work to be lost
junit.framework.Assert.assertTrue(errorString, result);
} else if (!result) {
System.out.println(errorString);
new Exception().printStackTrace();
}
}
private boolean compareFlags(IResource resource, int actualFlags, int expectedFlags) {
// Special handling for folders
if (actualFlags != expectedFlags && resource.getType() == IResource.FOLDER) {
// The only two states for folders are outgoing addition and in-sync.
// Other additions will appear as in-sync
int expectedKind = expectedFlags & Diff.KIND_MASK;
int actualKind = actualFlags & Diff.KIND_MASK;
if (actualKind == IDiff.NO_CHANGE
&& expectedKind == IDiff.ADD) {
return true;
}
}
return actualFlags == expectedFlags;
}
private int getActualDiffFlags(Subscriber subscriber, IResource resource)
throws CoreException {
IDiff node = getDiff(subscriber, resource);
int actualFlags;
if (node == null) {
actualFlags = IDiff.NO_CHANGE;
} else {
actualFlags = ((Diff)node).getStatus();
}
return actualFlags;
}
public void mergeResources(Subscriber subscriber, IResource[] resources, boolean allowOverwrite) throws TeamException, InvocationTargetException, InterruptedException {
SyncInfo[] infos = createSyncInfos(subscriber, resources);
mergeResources(subscriber, infos, allowOverwrite);
}
private void mergeResources(Subscriber subscriber, SyncInfo[] infos, boolean allowOverwrite) throws TeamException, InvocationTargetException, InterruptedException {
TestMergeUpdateOperation action = new TestMergeUpdateOperation(getElements(infos), allowOverwrite);
action.run(DEFAULT_MONITOR);
}
protected SyncInfo[] createSyncInfos(Subscriber subscriber, IResource[] resources) throws TeamException {
SyncInfo[] result = new SyncInfo[resources.length];
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
result[i] = getSyncInfo(subscriber, resource);
}
return result;
}
public void markAsMerged(Subscriber subscriber, IResource[] resources) throws InvocationTargetException, InterruptedException, TeamException {
SyncInfo[] infos = createSyncInfos(subscriber, resources);
new ConfirmMergedOperation(null, getElements(infos)).run(DEFAULT_MONITOR);
}
protected IDiffElement[] getElements(SyncInfo[] infos) {
SyncInfoModelElement[] elements = new SyncInfoModelElement[infos.length];
for (int i = 0; i < elements.length; i++) {
elements[i] = new SyncInfoModelElement(null, infos[i]);
}
return elements;
}
public void updateResources(Subscriber subscriber, IResource[] resources) throws CoreException {
runSubscriberOperation(new TestUpdateOperation(getElements(createSyncInfos(subscriber, resources))));
}
public void commitResources(Subscriber subscriber, IResource[] resources) throws CoreException {
runSubscriberOperation(new TestCommitOperation(getElements(createSyncInfos(subscriber, resources)), false /* override */));
}
public void overrideAndUpdateResources(Subscriber subscriber, boolean shouldPrompt, IResource[] resources) throws CoreException {
TestOverrideAndUpdateOperation action = new TestOverrideAndUpdateOperation(getElements(createSyncInfos(subscriber, resources)));
runSubscriberOperation(action);
Assert.assertTrue(shouldPrompt == action.isPrompted());
}
public void overrideAndCommitResources(Subscriber subscriber, IResource[] resources) throws CoreException {
TestCommitOperation action = new TestCommitOperation(getElements(createSyncInfos(subscriber, resources)), true /* override */);
runSubscriberOperation(action);
}
private void runSubscriberOperation(CVSSubscriberOperation op) throws CoreException {
try {
op.run();
} catch (InvocationTargetException e) {
throw CVSException.wrapException(e);
} catch (InterruptedException e) {
junit.framework.Assert.fail("Operation was interrupted");
}
}
}
| true | true | protected void assertDiffKindEquals(String message, Subscriber subscriber, IResource resource, int expectedFlags) throws CoreException {
int actualFlags = getActualDiffFlags(subscriber, resource);
boolean result = compareFlags(resource, actualFlags, expectedFlags);
int count = 0;
while (!result && count < 40) {
// The discrepancy may be due to a timing issue.
// Let's wait a few seconds and get the flags again.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
actualFlags = getActualDiffFlags(subscriber, resource);
result = compareFlags(resource, actualFlags, expectedFlags);
if (result) {
System.out.println("A timing issue has been detected in the CVS test");
new Exception().printStackTrace();
} else {
count++;
}
}
String errorString = message + ": improper diff for " + resource
+ " expected "
+ SyncInfoToDiffConverter.diffStatusToString(expectedFlags)
+ " but was "
+ SyncInfoToDiffConverter.diffStatusToString(actualFlags);
if (CVSTestSetup.FAIL_ON_BAD_DIFF) {
junit.framework.Assert.assertTrue(errorString, result);
} else if (!result) {
System.out.println(errorString);
new Exception().printStackTrace();
}
}
| protected void assertDiffKindEquals(String message, Subscriber subscriber, IResource resource, int expectedFlags) throws CoreException {
int actualFlags = getActualDiffFlags(subscriber, resource);
boolean result = compareFlags(resource, actualFlags, expectedFlags);
int count = 0;
while (!result && count < 40) {
// The discrepancy may be due to a timing issue.
// Let's wait a few seconds and get the flags again.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
actualFlags = getActualDiffFlags(subscriber, resource);
result = compareFlags(resource, actualFlags, expectedFlags);
if (result) {
System.out.println("A timing issue has been detected in the CVS test");
new Exception().printStackTrace();
} else {
count++;
}
}
String errorString = message + ": improper diff for " + resource
+ " expected "
+ SyncInfoToDiffConverter.diffStatusToString(expectedFlags)
+ " but was "
+ SyncInfoToDiffConverter.diffStatusToString(actualFlags);
if (CVSTestSetup.FAIL_ON_BAD_DIFF
|| (expectedFlags != IDiff.NO_CHANGE && actualFlags == IDiff.NO_CHANGE)) {
// When running in the suites, we want to avoid intermittent failures.
// However, still fail if we expected a change but we get no change since that can
// cause work to be lost
junit.framework.Assert.assertTrue(errorString, result);
} else if (!result) {
System.out.println(errorString);
new Exception().printStackTrace();
}
}
|
diff --git a/src/test/java/com/cjra/battleship_project/FleetDeploymentActivityTests.java b/src/test/java/com/cjra/battleship_project/FleetDeploymentActivityTests.java
index 4d7f131..e82e45d 100644
--- a/src/test/java/com/cjra/battleship_project/FleetDeploymentActivityTests.java
+++ b/src/test/java/com/cjra/battleship_project/FleetDeploymentActivityTests.java
@@ -1,25 +1,25 @@
package com.cjra.battleship_project;
import android.widget.TextView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.assertEquals;
@RunWith(RobolectricTestRunner.class)
public class FleetDeploymentActivityTests {
@Test
- public void RendersBattleshipGameWhenResumed(){
+ public void DisplaysCorrectNumberOfShipsTextForDeployment(){
FleetDeploymentActivity activity = new FleetDeploymentActivity();
activity.onCreate(null);
activity.setNumberOfAvailableShips(12);
TextView text = (TextView)activity.findViewById(R.id.ship_count);
assertEquals("You have 12 ships to place.\n" +
"Touch grid to place ships.", text.getText());
}
}
| true | true | public void RendersBattleshipGameWhenResumed(){
FleetDeploymentActivity activity = new FleetDeploymentActivity();
activity.onCreate(null);
activity.setNumberOfAvailableShips(12);
TextView text = (TextView)activity.findViewById(R.id.ship_count);
assertEquals("You have 12 ships to place.\n" +
"Touch grid to place ships.", text.getText());
}
| public void DisplaysCorrectNumberOfShipsTextForDeployment(){
FleetDeploymentActivity activity = new FleetDeploymentActivity();
activity.onCreate(null);
activity.setNumberOfAvailableShips(12);
TextView text = (TextView)activity.findViewById(R.id.ship_count);
assertEquals("You have 12 ships to place.\n" +
"Touch grid to place ships.", text.getText());
}
|
diff --git a/gltest/src/java/gltest/GLViewWindow.java b/gltest/src/java/gltest/GLViewWindow.java
index 7fa4730..beb8e92 100644
--- a/gltest/src/java/gltest/GLViewWindow.java
+++ b/gltest/src/java/gltest/GLViewWindow.java
@@ -1,172 +1,173 @@
package gltest;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import crossbase.abstracts.MenuConstructor;
import crossbase.ui.ViewWindowBase;
import crossbase.ui.ViewWindowsManager;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.opengl.CrossBaseGLCanvas;
import org.eclipse.swt.opengl.GLData;
import org.eclipse.wb.swt.SWTResourceManager;
public class GLViewWindow extends ViewWindowBase<GLDocument>
{
// Model constants
private static final int MODEL_CUBE = 0;
private static final int MODEL_MONKEY_SIMPLE = 1;
private static final int MODEL_MONKEY_SUBDIVIDED = 2;
private static native boolean globalInit();
private static native boolean createScene(int model, int width, int height);
private static native boolean destroyScene();
private static native boolean resizeView(int width, int height);
private static native boolean drawScene(double angle);
private double angle = 0;
public GLViewWindow(
String applicationTitle,
ViewWindowsManager<GLDocument, ? extends ViewWindowBase<GLDocument>> windowsManager,
MenuConstructor<GLDocument, ? extends ViewWindowBase<GLDocument>> menuConstructor)
{
super(applicationTitle, windowsManager, menuConstructor);
}
/**
* @wbp.parser.entryPoint
*/
protected Shell constructShell()
{
Shell shell = new Shell(SWT.CLOSE | SWT.MIN | SWT.TITLE | SWT.MAX | SWT.RESIZE);
Point size = shell.getSize();
Point clientSize = new Point(shell.getClientArea().width, shell.getClientArea().height);
shell.setSize(size.x - clientSize.x + 800, size.y - clientSize.y + 600);
if (SWT.getPlatform().equals("win32"))
{
shell.setImage(SWTResourceManager.getImage(GLViewWindow.class, "/gltest/gltest16.png"));
}
else
{
shell.setImage(SWTResourceManager.getImage(GLViewWindow.class, "/gltest/gltest64.png"));
}
shell.setLayout(new FillLayout());
Composite comp = new Composite(shell, SWT.NONE);
comp.setLayout(new FillLayout());
GLData data = new GLData ();
data.doubleBuffer = true;
+ data.depthSize = 1;
final CrossBaseGLCanvas canvas = new CrossBaseGLCanvas(comp, SWT.NO_BACKGROUND, data);
if (!canvas.isCurrent()) canvas.setCurrent();
globalInit();
Point csize = canvas.getSize();
createScene(MODEL_CUBE, csize.x, csize.y);
canvas.addKeyListener(new KeyListener() {
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0)
{
Point size = canvas.getSize();
if (arg0.character == '1')
{
destroyScene();
createScene(MODEL_CUBE, size.x, size.y);
}
else if (arg0.character == '2')
{
destroyScene();
createScene(MODEL_MONKEY_SIMPLE, size.x, size.y);
}
else if (arg0.character == '3')
{
destroyScene();
createScene(MODEL_MONKEY_SUBDIVIDED, size.x, size.y);
}
}
});
canvas.addControlListener(new ControlListener()
{
@Override
public void controlResized(ControlEvent arg0)
{
if (!canvas.isCurrent()) canvas.setCurrent();
Point size = canvas.getSize();
resizeView(size.x, size.y);
}
@Override
public void controlMoved(ControlEvent arg0)
{
// TODO Auto-generated method stub
}
});
canvas.addPaintListener(new PaintListener()
{
@Override
public void paintControl(PaintEvent arg0)
{
if (!canvas.isCurrent()) canvas.setCurrent();
drawScene(angle);
canvas.swapBuffers();
}
});
Runnable timerUpdateRunnable = new Runnable()
{
@Override
public void run()
{
if (canvas != null && !canvas.isDisposed())
{
canvas.redraw();
angle += 0.002;
Display.getCurrent().timerExec(10, this);
}
}
};
timerUpdateRunnable.run();
return shell;
}
@Override
public boolean supportsFullscreen()
{
return true;
}
@Override
public boolean supportsMaximizing()
{
return true;
}
}
| true | true | protected Shell constructShell()
{
Shell shell = new Shell(SWT.CLOSE | SWT.MIN | SWT.TITLE | SWT.MAX | SWT.RESIZE);
Point size = shell.getSize();
Point clientSize = new Point(shell.getClientArea().width, shell.getClientArea().height);
shell.setSize(size.x - clientSize.x + 800, size.y - clientSize.y + 600);
if (SWT.getPlatform().equals("win32"))
{
shell.setImage(SWTResourceManager.getImage(GLViewWindow.class, "/gltest/gltest16.png"));
}
else
{
shell.setImage(SWTResourceManager.getImage(GLViewWindow.class, "/gltest/gltest64.png"));
}
shell.setLayout(new FillLayout());
Composite comp = new Composite(shell, SWT.NONE);
comp.setLayout(new FillLayout());
GLData data = new GLData ();
data.doubleBuffer = true;
final CrossBaseGLCanvas canvas = new CrossBaseGLCanvas(comp, SWT.NO_BACKGROUND, data);
if (!canvas.isCurrent()) canvas.setCurrent();
globalInit();
Point csize = canvas.getSize();
createScene(MODEL_CUBE, csize.x, csize.y);
canvas.addKeyListener(new KeyListener() {
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0)
{
Point size = canvas.getSize();
if (arg0.character == '1')
{
destroyScene();
createScene(MODEL_CUBE, size.x, size.y);
}
else if (arg0.character == '2')
{
destroyScene();
createScene(MODEL_MONKEY_SIMPLE, size.x, size.y);
}
else if (arg0.character == '3')
{
destroyScene();
createScene(MODEL_MONKEY_SUBDIVIDED, size.x, size.y);
}
}
});
canvas.addControlListener(new ControlListener()
{
@Override
public void controlResized(ControlEvent arg0)
{
if (!canvas.isCurrent()) canvas.setCurrent();
Point size = canvas.getSize();
resizeView(size.x, size.y);
}
@Override
public void controlMoved(ControlEvent arg0)
{
// TODO Auto-generated method stub
}
});
canvas.addPaintListener(new PaintListener()
{
@Override
public void paintControl(PaintEvent arg0)
{
if (!canvas.isCurrent()) canvas.setCurrent();
drawScene(angle);
canvas.swapBuffers();
}
});
Runnable timerUpdateRunnable = new Runnable()
{
@Override
public void run()
{
if (canvas != null && !canvas.isDisposed())
{
canvas.redraw();
angle += 0.002;
Display.getCurrent().timerExec(10, this);
}
}
};
timerUpdateRunnable.run();
return shell;
}
| protected Shell constructShell()
{
Shell shell = new Shell(SWT.CLOSE | SWT.MIN | SWT.TITLE | SWT.MAX | SWT.RESIZE);
Point size = shell.getSize();
Point clientSize = new Point(shell.getClientArea().width, shell.getClientArea().height);
shell.setSize(size.x - clientSize.x + 800, size.y - clientSize.y + 600);
if (SWT.getPlatform().equals("win32"))
{
shell.setImage(SWTResourceManager.getImage(GLViewWindow.class, "/gltest/gltest16.png"));
}
else
{
shell.setImage(SWTResourceManager.getImage(GLViewWindow.class, "/gltest/gltest64.png"));
}
shell.setLayout(new FillLayout());
Composite comp = new Composite(shell, SWT.NONE);
comp.setLayout(new FillLayout());
GLData data = new GLData ();
data.doubleBuffer = true;
data.depthSize = 1;
final CrossBaseGLCanvas canvas = new CrossBaseGLCanvas(comp, SWT.NO_BACKGROUND, data);
if (!canvas.isCurrent()) canvas.setCurrent();
globalInit();
Point csize = canvas.getSize();
createScene(MODEL_CUBE, csize.x, csize.y);
canvas.addKeyListener(new KeyListener() {
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0)
{
Point size = canvas.getSize();
if (arg0.character == '1')
{
destroyScene();
createScene(MODEL_CUBE, size.x, size.y);
}
else if (arg0.character == '2')
{
destroyScene();
createScene(MODEL_MONKEY_SIMPLE, size.x, size.y);
}
else if (arg0.character == '3')
{
destroyScene();
createScene(MODEL_MONKEY_SUBDIVIDED, size.x, size.y);
}
}
});
canvas.addControlListener(new ControlListener()
{
@Override
public void controlResized(ControlEvent arg0)
{
if (!canvas.isCurrent()) canvas.setCurrent();
Point size = canvas.getSize();
resizeView(size.x, size.y);
}
@Override
public void controlMoved(ControlEvent arg0)
{
// TODO Auto-generated method stub
}
});
canvas.addPaintListener(new PaintListener()
{
@Override
public void paintControl(PaintEvent arg0)
{
if (!canvas.isCurrent()) canvas.setCurrent();
drawScene(angle);
canvas.swapBuffers();
}
});
Runnable timerUpdateRunnable = new Runnable()
{
@Override
public void run()
{
if (canvas != null && !canvas.isDisposed())
{
canvas.redraw();
angle += 0.002;
Display.getCurrent().timerExec(10, this);
}
}
};
timerUpdateRunnable.run();
return shell;
}
|
diff --git a/src/jpcsp/MainGUI.java b/src/jpcsp/MainGUI.java
index 3903ae99..076780b4 100644
--- a/src/jpcsp/MainGUI.java
+++ b/src/jpcsp/MainGUI.java
@@ -1,1573 +1,1583 @@
/*
This file is part of jpcsp.
Jpcsp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jpcsp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import jpcsp.Allegrex.compiler.Profiler;
import jpcsp.Allegrex.compiler.RuntimeContext;
import jpcsp.Debugger.ElfHeaderInfo;
import jpcsp.Debugger.InstructionCounter;
import jpcsp.Debugger.MemoryViewer;
import jpcsp.Debugger.StepLogger;
import jpcsp.Debugger.DisassemblerModule.DisassemblerFrame;
import jpcsp.Debugger.DisassemblerModule.VfpuFrame;
import jpcsp.GUI.MemStickBrowser;
import jpcsp.GUI.RecentElement;
import jpcsp.GUI.SettingsGUI;
import jpcsp.GUI.UmdBrowser;
import jpcsp.HLE.ThreadMan;
import jpcsp.HLE.pspdisplay;
import jpcsp.HLE.pspiofilemgr;
import jpcsp.HLE.kernel.types.SceModule;
import jpcsp.HLE.modules.sceMpeg;
import jpcsp.HLE.pspSysMem;
import jpcsp.filesystems.umdiso.UmdIsoFile;
import jpcsp.filesystems.umdiso.UmdIsoReader;
import jpcsp.format.PSF;
import jpcsp.graphics.VideoEngine;
import jpcsp.log.LogWindow;
import jpcsp.log.LoggingOutputStream;
import jpcsp.util.JpcspDialogManager;
import jpcsp.util.MetaInformation;
import jpcsp.util.Utilities;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
/**
*
* @author shadow
*/
public class MainGUI extends javax.swing.JFrame implements KeyListener, ComponentListener {
private static final long serialVersionUID = -3647025845406693230L;
public static final int MAX_RECENT = 10;
LogWindow consolewin;
ElfHeaderInfo elfheader;
SettingsGUI setgui;
MemStickBrowser memstick;
Emulator emulator;
UmdBrowser umdbrowser;
InstructionCounter instructioncounter;
File loadedFile;
boolean umdLoaded;
private Point mainwindowPos; // stores the last known window position
private boolean snapConsole = true;
private List<RecentElement> recentUMD = new LinkedList<RecentElement>();
private List<RecentElement> recentFile = new LinkedList<RecentElement>();
private Level rootLogLevel = null;
/** Creates new form MainGUI */
public MainGUI() {
DOMConfigurator.configure("LogSettings.xml");
System.setOut(new PrintStream(new LoggingOutputStream(Logger.getLogger("misc"), Level.INFO)));
consolewin = new LogWindow();
emulator = new Emulator(this);
Resource.add("jpcsp.languages." + Settings.getInstance().readLanguage());
/*next two lines are for overlay menus over joglcanvas*/
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
//end of
initComponents();
populateRecentMenu();
int pos[] = Settings.getInstance().readWindowPos("mainwindow");
setLocation(pos[0], pos[1]);
State.fileLogger.setLocation(pos[0] + 488, pos[1] + 18);
setTitle(MetaInformation.FULL_NAME);
/*add glcanvas to frame and pack frame to get the canvas size*/
getContentPane().add(pspdisplay.getInstance(), java.awt.BorderLayout.CENTER);
pspdisplay.getInstance().addKeyListener(this);
this.addComponentListener(this);
pack();
Insets insets = this.getInsets();
Dimension minSize = new Dimension(
480 + insets.left + insets.right,
272 + insets.top + insets.bottom);
this.setMinimumSize(minSize);
//logging console window stuff
snapConsole = Settings.getInstance().readBool("gui.snapLogwindow");
if (snapConsole) {
mainwindowPos = getLocation();
consolewin.setLocation(mainwindowPos.x, mainwindowPos.y + getHeight());
} else {
pos = Settings.getInstance().readWindowPos("logwindow");
consolewin.setLocation(pos[0], pos[1]);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
RunButton = new javax.swing.JToggleButton();
PauseButton = new javax.swing.JToggleButton();
ResetButton = new javax.swing.JButton();
MenuBar = new javax.swing.JMenuBar();
FileMenu = new javax.swing.JMenu();
openUmd = new javax.swing.JMenuItem();
OpenFile = new javax.swing.JMenuItem();
OpenMemStick = new javax.swing.JMenuItem();
RecentMenu = new javax.swing.JMenu();
ExitEmu = new javax.swing.JMenuItem();
EmulationMenu = new javax.swing.JMenu();
RunEmu = new javax.swing.JMenuItem();
PauseEmu = new javax.swing.JMenuItem();
ResetEmu = new javax.swing.JMenuItem();
OptionsMenu = new javax.swing.JMenu();
RotateItem = new javax.swing.JMenuItem();
SetttingsMenu = new javax.swing.JMenuItem();
ShotItem = new javax.swing.JMenuItem();
SaveSnap = new javax.swing.JMenuItem();
LoadSnap = new javax.swing.JMenuItem();
DebugMenu = new javax.swing.JMenu();
EnterDebugger = new javax.swing.JMenuItem();
EnterMemoryViewer = new javax.swing.JMenuItem();
VfpuRegisters = new javax.swing.JMenuItem();
ToggleConsole = new javax.swing.JMenuItem();
ElfHeaderViewer = new javax.swing.JMenuItem();
InstructionCounter = new javax.swing.JMenuItem();
FileLog = new javax.swing.JMenuItem();
ToggleDebugLog = new javax.swing.JMenuItem();
DumpIso = new javax.swing.JMenuItem();
ResetProfiler = new javax.swing.JMenuItem();
LanguageMenu = new javax.swing.JMenu();
English = new javax.swing.JMenuItem();
French = new javax.swing.JMenuItem();
German = new javax.swing.JMenuItem();
Lithuanian = new javax.swing.JMenuItem();
Spanish = new javax.swing.JMenuItem();
Catalan = new javax.swing.JMenuItem();
Portuguese = new javax.swing.JMenuItem();
Japanese = new javax.swing.JMenuItem();
HelpMenu = new javax.swing.JMenu();
About = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setForeground(java.awt.Color.white);
setMinimumSize(new java.awt.Dimension(480, 272));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
RunButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PlayIcon.png"))); // NOI18N
RunButton.setText(Resource.get("run"));
RunButton.setFocusable(false);
RunButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
RunButton.setIconTextGap(2);
RunButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
RunButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RunButtonActionPerformed(evt);
}
});
jToolBar1.add(RunButton);
PauseButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PauseIcon.png"))); // NOI18N
PauseButton.setText(Resource.get("pause"));
PauseButton.setFocusable(false);
PauseButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
PauseButton.setIconTextGap(2);
PauseButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
PauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PauseButtonActionPerformed(evt);
}
});
jToolBar1.add(PauseButton);
ResetButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/StopIcon.png"))); // NOI18N
ResetButton.setText(Resource.get("reset"));
ResetButton.setFocusable(false);
ResetButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
ResetButton.setIconTextGap(2);
ResetButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
ResetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetButtonActionPerformed(evt);
}
});
jToolBar1.add(ResetButton);
getContentPane().add(jToolBar1, java.awt.BorderLayout.NORTH);
MenuBar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
MenuBarMouseExited(evt);
}
});
FileMenu.setText(Resource.get("file"));
+ openUmd.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
openUmd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadUmdIcon.png"))); // NOI18N
openUmd.setText(Resource.get("loadumd"));
openUmd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openUmdActionPerformed(evt);
}
});
FileMenu.add(openUmd);
+ OpenFile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.ALT_MASK));
OpenFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadFileIcon.png"))); // NOI18N
OpenFile.setText(Resource.get("loadfile"));
OpenFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenFileActionPerformed(evt);
}
});
FileMenu.add(OpenFile);
+ OpenMemStick.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK));
OpenMemStick.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadMemoryStick.png"))); // NOI18N
OpenMemStick.setText(Resource.get("loadmemstick"));
OpenMemStick.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenMemStickActionPerformed(evt);
}
});
FileMenu.add(OpenMemStick);
RecentMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/RecentIcon.png"))); // NOI18N
RecentMenu.setText(Resource.get("loadrecent"));
FileMenu.add(RecentMenu);
+ ExitEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
ExitEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/CloseIcon.png"))); // NOI18N
ExitEmu.setText(Resource.get("exit"));
ExitEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitEmuActionPerformed(evt);
}
});
FileMenu.add(ExitEmu);
MenuBar.add(FileMenu);
EmulationMenu.setText(Resource.get("emulation"));
+ RunEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
RunEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PlayIcon.png"))); // NOI18N
RunEmu.setText(Resource.get("run"));
RunEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RunEmuActionPerformed(evt);
}
});
EmulationMenu.add(RunEmu);
+ PauseEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0));
PauseEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PauseIcon.png"))); // NOI18N
PauseEmu.setText(Resource.get("pause"));
PauseEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PauseEmuActionPerformed(evt);
}
});
EmulationMenu.add(PauseEmu);
+ ResetEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0));
ResetEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/StopIcon.png"))); // NOI18N
ResetEmu.setText(Resource.get("reset"));
ResetEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetEmuActionPerformed(evt);
}
});
EmulationMenu.add(ResetEmu);
MenuBar.add(EmulationMenu);
OptionsMenu.setText(Resource.get("options"));
+ RotateItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F11, 0));
RotateItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/RotateIcon.png"))); // NOI18N
RotateItem.setText(Resource.get("rotate"));
RotateItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RotateItemActionPerformed(evt);
}
});
OptionsMenu.add(RotateItem);
+ SetttingsMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F12, 0));
SetttingsMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/SettingsIcon.png"))); // NOI18N
SetttingsMenu.setText(Resource.get("settings"));
SetttingsMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SetttingsMenuActionPerformed(evt);
}
});
OptionsMenu.add(SetttingsMenu);
ShotItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
ShotItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/ScreenshotIcon.png"))); // NOI18N
ShotItem.setText(Resource.get("screenshot"));
ShotItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ShotItemActionPerformed(evt);
}
});
OptionsMenu.add(ShotItem);
SaveSnap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK));
SaveSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/SaveStateIcon.png"))); // NOI18N
SaveSnap.setText(Resource.get("savesnapshot"));
SaveSnap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveSnapActionPerformed(evt);
}
});
OptionsMenu.add(SaveSnap);
LoadSnap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.SHIFT_MASK));
LoadSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadStateIcon.png"))); // NOI18N
LoadSnap.setText(Resource.get("loadsnapshot"));
LoadSnap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadSnapActionPerformed(evt);
}
});
OptionsMenu.add(LoadSnap);
MenuBar.add(OptionsMenu);
DebugMenu.setText(Resource.get("debug"));
EnterDebugger.setText(Resource.get("enterdebugger"));
EnterDebugger.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterDebuggerActionPerformed(evt);
}
});
DebugMenu.add(EnterDebugger);
EnterMemoryViewer.setText(Resource.get("memoryviewer"));
EnterMemoryViewer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterMemoryViewerActionPerformed(evt);
}
});
DebugMenu.add(EnterMemoryViewer);
VfpuRegisters.setText(Resource.get("vfpuregisters"));
VfpuRegisters.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
VfpuRegistersActionPerformed(evt);
}
});
DebugMenu.add(VfpuRegisters);
ToggleConsole.setText(Resource.get("toggleconsole"));
ToggleConsole.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ToggleConsoleActionPerformed(evt);
}
});
DebugMenu.add(ToggleConsole);
ElfHeaderViewer.setText(Resource.get("elfheaderinfo"));
ElfHeaderViewer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ElfHeaderViewerActionPerformed(evt);
}
});
DebugMenu.add(ElfHeaderViewer);
InstructionCounter.setText(Resource.get("instructioncounter"));
InstructionCounter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InstructionCounterActionPerformed(evt);
}
});
DebugMenu.add(InstructionCounter);
FileLog.setText(Resource.get("filelog"));
FileLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FileLogActionPerformed(evt);
}
});
DebugMenu.add(FileLog);
ToggleDebugLog.setText(Resource.get("toggledebuglogging"));
ToggleDebugLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ToggleDebugLogActionPerformed(evt);
}
});
DebugMenu.add(ToggleDebugLog);
DumpIso.setText(Resource.get("dumpisotoisoindex"));
DumpIso.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DumpIsoActionPerformed(evt);
}
});
DebugMenu.add(DumpIso);
ResetProfiler.setText(Resource.get("resetprofilerinformation"));
ResetProfiler.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetProfilerActionPerformed(evt);
}
});
DebugMenu.add(ResetProfiler);
MenuBar.add(DebugMenu);
LanguageMenu.setText(Resource.get("language"));
English.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/en_EN.png"))); // NOI18N
English.setText(Resource.get("english"));
English.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnglishActionPerformed(evt);
}
});
LanguageMenu.add(English);
French.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/fr_FR.png"))); // NOI18N
French.setText(Resource.get("french"));
French.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FrenchActionPerformed(evt);
}
});
LanguageMenu.add(French);
German.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/de_DE.png"))); // NOI18N
German.setText(Resource.get("german"));
German.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GermanActionPerformed(evt);
}
});
LanguageMenu.add(German);
Lithuanian.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/lt_LT.png"))); // NOI18N
Lithuanian.setText(Resource.get("lithuanian"));
Lithuanian.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LithuanianActionPerformed(evt);
}
});
LanguageMenu.add(Lithuanian);
Spanish.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/es_ES.png"))); // NOI18N
Spanish.setText(Resource.get("spanish"));
Spanish.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SpanishActionPerformed(evt);
}
});
LanguageMenu.add(Spanish);
Catalan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/es_CA.png"))); // NOI18N
Catalan.setText(Resource.get("catalan"));
Catalan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CatalanActionPerformed(evt);
}
});
LanguageMenu.add(Catalan);
Portuguese.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/pt_PT.png"))); // NOI18N
Portuguese.setText(Resource.get("portuguese"));
Portuguese.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PortugueseActionPerformed(evt);
}
});
LanguageMenu.add(Portuguese);
Japanese.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/jp_JP.png"))); // NOI18N
Japanese.setText(Resource.get("japanese"));
Japanese.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JapaneseActionPerformed(evt);
}
});
LanguageMenu.add(Japanese);
MenuBar.add(LanguageMenu);
HelpMenu.setText(Resource.get("help"));
+ About.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
About.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/AboutIcon.png"))); // NOI18N
About.setText(Resource.get("about"));
About.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AboutActionPerformed(evt);
}
});
HelpMenu.add(About);
MenuBar.add(HelpMenu);
setJMenuBar(MenuBar);
pack();
}// </editor-fold>//GEN-END:initComponents
private void changeLanguage(String language) {
Resource.add("jpcsp.languages." + language);
Settings.getInstance().writeLanguage(language);
initComponents();
}
public LogWindow getConsoleWindow() {
return consolewin;
}
private void populateRecentMenu() {
RecentMenu.removeAll();
recentUMD.clear();
recentFile.clear();
Settings.getInstance().readRecent("umd", recentUMD);
Settings.getInstance().readRecent("file", recentFile);
for (RecentElement umd : recentUMD) {
JMenuItem item = new JMenuItem(umd.toString());
//item.setFont(Settings.getInstance().getFont()); // doesn't seem to work
item.addActionListener(new RecentElementActionListener(RecentElementActionListener.TYPE_UMD, umd.path));
RecentMenu.add(item);
}
if (recentUMD.size() > 0 && recentFile.size() > 0) {
RecentMenu.addSeparator();
}
for (RecentElement file : recentFile) {
JMenuItem item = new JMenuItem(file.toString());
item.addActionListener(new RecentElementActionListener(RecentElementActionListener.TYPE_FILE, file.path));
RecentMenu.add(item);
}
}
private void ToggleConsoleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ToggleConsoleActionPerformed
if (!consolewin.isVisible() && snapConsole) {
mainwindowPos = this.getLocation();
consolewin.setLocation(mainwindowPos.x, mainwindowPos.y + getHeight());
}
consolewin.setVisible(!consolewin.isVisible());
}//GEN-LAST:event_ToggleConsoleActionPerformed
private void EnterDebuggerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnterDebuggerActionPerformed
PauseEmu();
if (State.debugger == null)
{
State.debugger = new DisassemblerFrame(emulator);
int pos[] = Settings.getInstance().readWindowPos("disassembler");
State.debugger.setLocation(pos[0], pos[1]);
State.debugger.setVisible(true);
}
else
{
State.debugger.setVisible(true);
State.debugger.RefreshDebugger(false);
}
}//GEN-LAST:event_EnterDebuggerActionPerformed
private void RunButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RunButtonActionPerformed
RunEmu();
}//GEN-LAST:event_RunButtonActionPerformed
private JFileChooser makeJFileChooser() {
final JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Open Elf/Pbp File");
fc.setCurrentDirectory(new java.io.File("."));
return fc;
}
private void OpenFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenFileActionPerformed
PauseEmu();
final JFileChooser fc = makeJFileChooser();
int returnVal = fc.showOpenDialog(this);
if (userChooseSomething(returnVal)) {
File file = fc.getSelectedFile();
loadFile(file);
} else {
return; //user cancel the action
}
}//GEN-LAST:event_OpenFileActionPerformed
private String pspifyFilename(String pcfilename) {
// Files relative to ms0 directory
if (pcfilename.startsWith("ms0")) {
return "ms0:" + pcfilename.substring(3).replaceAll("\\\\", "/");
}
// Files with absolute path but also in ms0 directory
try {
String ms0path = new File("ms0").getCanonicalPath();
if (pcfilename.startsWith(ms0path)) {
// Strip off absolute prefix
return "ms0:" + pcfilename.substring(ms0path.length()).replaceAll("\\\\", "/");
}
} catch(Exception e) {
// Required by File.getCanonicalPath
e.printStackTrace();
}
// Files anywhere on user's hard drive, may not work
// use host0:/ ?
return pcfilename.replaceAll("\\\\", "/");
}
public void loadFile(File file) {
//This is where a real application would open the file.
try {
if (consolewin != null)
consolewin.clearScreenMessages();
Emulator.log.info(MetaInformation.FULL_CUSTOM_NAME);
umdLoaded = false;
loadedFile = file;
// Create a read-only memory-mapped file
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel roChannel = raf.getChannel();
ByteBuffer readbuffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());
SceModule module = emulator.load(pspifyFilename(file.getPath()), readbuffer);
roChannel.close(); // doesn't seem to work properly :(
raf.close(); // still doesn't work properly :/
PSF psf = module.psf;
String title;
String discId = State.DISCID_UNKNOWN_FILE;
boolean isHomebrew;
if (psf != null) {
title = psf.getPrintableString("TITLE");
discId = psf.getString("DISC_ID");
if (discId == null) {
discId = State.DISCID_UNKNOWN_FILE;
}
isHomebrew = psf.isLikelyHomebrew();
} else {
title = file.getParentFile().getName();
isHomebrew = true; // missing psf, assume homebrew
}
setTitle(MetaInformation.FULL_NAME + " - " + title);
addRecentFile(file, title);
// Strip off absolute file path if the file is inside our ms0 directory
String filepath = file.getParent();
String ms0path = new File("ms0").getCanonicalPath();
if (filepath.startsWith(ms0path)) {
filepath = filepath.substring(ms0path.length() - 3); // path must start with "ms0"
}
pspiofilemgr.getInstance().setfilepath(filepath);
pspiofilemgr.getInstance().setIsoReader(null);
jpcsp.HLE.Modules.sceUmdUserModule.setIsoReader(null);
RuntimeContext.setIsHomebrew(isHomebrew);
State.discId = discId;
State.title = title;
// use regular settings first
installCompatibilitySettings();
if (!isHomebrew && !discId.equals(State.DISCID_UNKNOWN_FILE)) {
// override with patch file (allows incomplete patch files)
installCompatibilityPatches(discId + ".patch");
}
if (instructioncounter != null)
instructioncounter.RefreshWindow();
StepLogger.clear();
StepLogger.setName(file.getPath());
} catch (GeneralJpcspException e) {
JpcspDialogManager.showError(this, Resource.get("generalError")+" : " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
JpcspDialogManager.showError(this, Resource.get("ioError")+" : " + e.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
if (ex.getMessage() != null) {
JpcspDialogManager.showError(this, Resource.get("criticalError")+" : " + ex.getMessage());
} else {
JpcspDialogManager.showError(this, Resource.get("criticalError")+" : Check console for details.");
}
}
}
private void addRecentFile(File file, String title) {
//try {
String s = file.getPath(); //file.getCanonicalPath();
for (int i = 0; i < recentFile.size(); ++i) {
if (recentFile.get(i).path.equals(s))
recentFile.remove(i--);
}
recentFile.add(0, new RecentElement(s, title));
while(recentFile.size() > MAX_RECENT)
recentFile.remove(MAX_RECENT);
Settings.getInstance().writeRecent("file", recentFile);
populateRecentMenu();
//} catch (IOException e) {
// e.printStackTrace();
//}
}
private void addRecentUMD(File file, String title) {
try {
String s = file.getCanonicalPath();
for (int i = 0; i < recentUMD.size(); ++i) {
if (recentUMD.get(i).path.equals(s))
recentUMD.remove(i--);
}
recentUMD.add(0, new RecentElement(s, title));
while(recentUMD.size() > MAX_RECENT)
recentUMD.remove(MAX_RECENT);
Settings.getInstance().writeRecent("umd", recentUMD);
populateRecentMenu();
} catch (IOException e) {
e.printStackTrace();
}
}
private void PauseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PauseButtonActionPerformed
TogglePauseEmu();
}//GEN-LAST:event_PauseButtonActionPerformed
private void ElfHeaderViewerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ElfHeaderViewerActionPerformed
if(elfheader==null)
{
elfheader = new ElfHeaderInfo();
int pos[] = Settings.getInstance().readWindowPos("elfheader");
elfheader.setLocation(pos[0], pos[1]);
elfheader.setVisible(true);
}
else
{
elfheader.RefreshWindow();
elfheader.setVisible(true);
}
}//GEN-LAST:event_ElfHeaderViewerActionPerformed
private void EnterMemoryViewerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnterMemoryViewerActionPerformed
PauseEmu();
if (State.memoryViewer == null)
{
State.memoryViewer = new MemoryViewer();
int pos[] = Settings.getInstance().readWindowPos("memoryview");
State.memoryViewer.setLocation(pos[0], pos[1]);
State.memoryViewer.setVisible(true);
}
else
{
State.memoryViewer.RefreshMemory();
State.memoryViewer.setVisible(true);
}
}//GEN-LAST:event_EnterMemoryViewerActionPerformed
private void ToggleDebugLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ToggleDebugLogActionPerformed
Logger rootLogger = Logger.getRootLogger();
if (rootLogLevel == null)
{
// Enable DEBUG logging
rootLogLevel = rootLogger.getLevel();
rootLogger.setLevel(Level.DEBUG);
}
else
{
// Reset logging level to previous level
rootLogger.setLevel(rootLogLevel);
rootLogLevel = null;
}
}//GEN-LAST:event_ToggleDebugLogActionPerformed
private void AboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AboutActionPerformed
StringBuilder message = new StringBuilder();
message.append("<html>").append("<h2>" + MetaInformation.FULL_NAME + "</h2>").append("<hr/>").append("Official site : <a href='" + MetaInformation.OFFICIAL_SITE + "'>" + MetaInformation.OFFICIAL_SITE + "</a><br/>").append("Official forum : <a href='" + MetaInformation.OFFICIAL_FORUM + "'>" + MetaInformation.OFFICIAL_FORUM + "</a><br/>").append("Official repository: <a href='" + MetaInformation.OFFICIAL_REPOSITORY + "'>" + MetaInformation.OFFICIAL_REPOSITORY + "</a><br/>").append("<hr/>").append("<i>Team:</i> <font color='gray'>" + MetaInformation.TEAM + "</font>").append("</html>");
JOptionPane.showMessageDialog(this, message.toString(), MetaInformation.FULL_NAME, JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_AboutActionPerformed
private void RunEmuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RunEmuActionPerformed
RunEmu();
}//GEN-LAST:event_RunEmuActionPerformed
private void PauseEmuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PauseEmuActionPerformed
PauseEmu();
}//GEN-LAST:event_PauseEmuActionPerformed
private void SetttingsMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SetttingsMenuActionPerformed
if(setgui==null)
{
setgui = new SettingsGUI();
Point mainwindow = this.getLocation();
setgui.setLocation(mainwindow.x+100, mainwindow.y+50);
setgui.setVisible(true);
/* add a direct link to the main window*/
setgui.setMainGUI(this);
}
else
{
setgui.RefreshWindow();
setgui.setVisible(true);
}
}//GEN-LAST:event_SetttingsMenuActionPerformed
private void ExitEmuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitEmuActionPerformed
exitEmu();
}//GEN-LAST:event_ExitEmuActionPerformed
private void OpenMemStickActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenMemStickActionPerformed
PauseEmu();
if(memstick==null)
{
memstick = new MemStickBrowser(this, new File("ms0/PSP/GAME"));
Point mainwindow = this.getLocation();
memstick.setLocation(mainwindow.x+100, mainwindow.y+50);
memstick.setVisible(true);
}
else
{
memstick.refreshFiles();
memstick.setVisible(true);
}
}//GEN-LAST:event_OpenMemStickActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
exitEmu();
}//GEN-LAST:event_formWindowClosing
private void openUmdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openUmdActionPerformed
PauseEmu();
if (Settings.getInstance().readBool("emu.umdbrowser"))
{
umdbrowser = new UmdBrowser(this, new File(Settings.getInstance().readString("emu.umdpath") + "/"));
Point mainwindow = this.getLocation();
umdbrowser.setLocation(mainwindow.x+100, mainwindow.y+50);
umdbrowser.setVisible(true);
}
else
{
final JFileChooser fc = makeJFileChooser();
fc.setDialogTitle(Resource.get("openumd"));
int returnVal = fc.showOpenDialog(this);
if (userChooseSomething(returnVal)) {
File file = fc.getSelectedFile();
loadUMD(file);
} else {
return; //user cancel the action
}
}
}//GEN-LAST:event_openUmdActionPerformed
/** Don't call this directly, see loadUMD(File file) */
private boolean loadUMD(UmdIsoReader iso, String bootPath) throws IOException {
boolean success = false;
try {
UmdIsoFile bootBin = iso.getFile(bootPath);
if (bootBin.length() != 0) {
byte[] bootfile = new byte[(int)bootBin.length()];
bootBin.read(bootfile);
ByteBuffer buf = ByteBuffer.wrap(bootfile);
emulator.load("disc0:/" + bootPath, buf);
success = true;
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (GeneralJpcspException e) {
//JpcspDialogManager.showError(this, "General Error : " + e.getMessage());
}
return success;
}
/** Don't call this directly, see loadUMD(File file) */
private boolean loadUnpackedUMD(String filename) throws IOException, GeneralJpcspException {
// Load unpacked BOOT.BIN as if it came from the umd
File file = new File(filename);
if (file.exists()) {
FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
ByteBuffer readbuffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());
emulator.load("disc0:/PSP_GAME/SYSDIR/EBOOT.BIN", readbuffer);
roChannel.close();
Emulator.log.info("Using unpacked UMD EBOOT.BIN image");
return true;
}
return false;
}
public void loadUMD(File file) {
try {
if (consolewin != null)
consolewin.clearScreenMessages();
Emulator.log.info(MetaInformation.FULL_CUSTOM_NAME);
umdLoaded = true;
loadedFile = file;
UmdIsoReader iso = new UmdIsoReader(file.getPath());
UmdIsoFile psfFile = iso.getFile("PSP_GAME/param.sfo");
//Emulator.log.debug("Loading param.sfo from UMD");
PSF psf = new PSF();
byte[] data = new byte[(int)psfFile.length()];
psfFile.read(data);
psf.read(ByteBuffer.wrap(data));
Emulator.log.info("UMD param.sfo :\n" + psf);
String title = psf.getPrintableString("TITLE");
String discId = psf.getString("DISC_ID");
if (discId == null) {
discId = State.DISCID_UNKNOWN_UMD;
}
setTitle(MetaInformation.FULL_NAME + " - " + title);
addRecentUMD(file, title);
emulator.setFirmwareVersion(psf.getString("PSP_SYSTEM_VER"));
RuntimeContext.setIsHomebrew(psf.isLikelyHomebrew());
if ((!discId.equals(State.DISCID_UNKNOWN_UMD) && loadUnpackedUMD(discId + ".BIN")) ||
loadUMD(iso, "PSP_GAME/SYSDIR/BOOT.BIN") ||
loadUMD(iso, "PSP_GAME/SYSDIR/EBOOT.BIN")) {
State.discId = discId;
State.title = title;
pspiofilemgr.getInstance().setfilepath("disc0/");
//pspiofilemgr.getInstance().setfilepath("disc0/PSP_GAME/SYSDIR");
pspiofilemgr.getInstance().setIsoReader(iso);
jpcsp.HLE.Modules.sceUmdUserModule.setIsoReader(iso);
// use regular settings first
installCompatibilitySettings();
// override with patch file (allows incomplete patch files)
installCompatibilityPatches(discId + ".patch");
if (instructioncounter != null)
instructioncounter.RefreshWindow();
StepLogger.clear();
StepLogger.setName(file.getPath());
} else {
throw new GeneralJpcspException(Resource.get("encryptedBoot"));
}
} catch (GeneralJpcspException e) {
JpcspDialogManager.showError(this, Resource.get("generalError")+" : " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
JpcspDialogManager.showError(this, Resource.get("ioError")+" : " + e.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
if (ex.getMessage() != null) {
JpcspDialogManager.showError(this, Resource.get("criticalError")+" : " + ex.getMessage());
} else {
JpcspDialogManager.showError(this, Resource.get("criticalError")+" : Check console for details.");
}
}
}
private void installCompatibilitySettings()
{
Emulator.log.info("Loading global compatibility settings");
boolean onlyGEGraphics = Settings.getInstance().readBool("emu.onlyGEGraphics");
pspdisplay.getInstance().setOnlyGEGraphics(onlyGEGraphics);
boolean useViewport = Settings.getInstance().readBool("emu.useViewport");
VideoEngine.getInstance().setUseViewport(useViewport);
boolean enableMpeg = Settings.getInstance().readBool("emu.enableMpeg");
sceMpeg.setEnableMpeg(enableMpeg);
boolean useVertexCache = Settings.getInstance().readBool("emu.useVertexCache");
VideoEngine.getInstance().setUseVertexCache(useVertexCache);
boolean disableAudio = Settings.getInstance().readBool("emu.disablesceAudio");
jpcsp.HLE.Modules.sceAudioModule.setChReserveEnabled(!disableAudio);
boolean audioMuted = Settings.getInstance().readBool("emu.mutesound");
jpcsp.HLE.Modules.sceAudioModule.setAudioMuted(audioMuted);
jpcsp.HLE.Modules.sceSasCoreModule.setAudioMuted(audioMuted);
boolean disableBlocking = Settings.getInstance().readBool("emu.disableblockingaudio");
jpcsp.HLE.Modules.sceAudioModule.setBlockingEnabled(!disableBlocking);
boolean ignoreAudioThreads = Settings.getInstance().readBool("emu.ignoreaudiothreads");
jpcsp.HLE.ThreadMan.getInstance().setThreadBanningEnabled(ignoreAudioThreads);
boolean ignoreInvalidMemoryAccess = Settings.getInstance().readBool("emu.ignoreInvalidMemoryAccess");
Memory.getInstance().setIgnoreInvalidMemoryAccess(ignoreInvalidMemoryAccess);
jpcsp.Allegrex.compiler.Compiler.setIgnoreInvalidMemory(ignoreInvalidMemoryAccess);
boolean disableReservedThreadMemory = Settings.getInstance().readBool("emu.disablereservedthreadmemory");
jpcsp.HLE.pspSysMem.getInstance().setDisableReservedThreadMemory(disableReservedThreadMemory);
boolean enableWaitThreadEndCB = Settings.getInstance().readBool("emu.enablewaitthreadendcb");
jpcsp.HLE.ThreadMan.getInstance().setEnableWaitThreadEndCB(enableWaitThreadEndCB);
boolean ignoreUnmappedImports = Settings.getInstance().readBool("emu.ignoreUnmappedImports");
jpcsp.HLE.SyscallHandler.setEnableIgnoreUnmappedImports(ignoreUnmappedImports);
}
/** @return true if a patch file was found */
public boolean installCompatibilityPatches(String filename)
{
File patchfile = new File("patches/" + filename);
if (!patchfile.exists())
{
Emulator.log.debug("No patch file found for this game");
return false;
}
Properties patchSettings= new Properties();
InputStream patchInputStream = null;
try {
Emulator.log.info("Overriding previous settings with patch file");
patchInputStream = new BufferedInputStream(new FileInputStream(patchfile));
patchSettings.load(patchInputStream);
String disableAudio = patchSettings.getProperty("emu.disablesceAudio");
if (disableAudio != null)
jpcsp.HLE.Modules.sceAudioModule.setChReserveEnabled(!(Integer.parseInt(disableAudio) != 0));
String disableBlocking = patchSettings.getProperty("emu.disableblockingaudio");
if (disableBlocking != null)
jpcsp.HLE.Modules.sceAudioModule.setBlockingEnabled(!(Integer.parseInt(disableBlocking) != 0));
String ignoreAudioThreads = patchSettings.getProperty("emu.ignoreaudiothreads");
if (ignoreAudioThreads != null)
jpcsp.HLE.ThreadMan.getInstance().setThreadBanningEnabled(Integer.parseInt(ignoreAudioThreads) != 0);
String ignoreInvalidMemoryAccess = patchSettings.getProperty("emu.ignoreInvalidMemoryAccess");
if (ignoreInvalidMemoryAccess != null)
Memory.getInstance().setIgnoreInvalidMemoryAccess(Integer.parseInt(ignoreInvalidMemoryAccess) != 0);
String onlyGEGraphics = patchSettings.getProperty("emu.onlyGEGraphics");
if (onlyGEGraphics != null)
pspdisplay.getInstance().setOnlyGEGraphics(Integer.parseInt(onlyGEGraphics) != 0);
String useViewport = patchSettings.getProperty("emu.useViewport");
if (useViewport != null)
VideoEngine.getInstance().setUseViewport(Integer.parseInt(useViewport) != 0);
String enableMpeg = patchSettings.getProperty("emu.enableMpeg");
if (enableMpeg != null)
sceMpeg.setEnableMpeg(Integer.parseInt(enableMpeg) != 0);
String useVertexCache = patchSettings.getProperty("emu.useVertexCache");
if (useVertexCache != null)
VideoEngine.getInstance().setUseVertexCache(Integer.parseInt(useVertexCache) != 0);
String disableReservedThreadMemory = patchSettings.getProperty("emu.disablereservedthreadmemory");
if (disableReservedThreadMemory != null)
pspSysMem.getInstance().setDisableReservedThreadMemory(Integer.parseInt(disableReservedThreadMemory) != 0);
} catch (IOException e) {
e.printStackTrace();
} finally{
Utilities.close(patchInputStream);
}
return true;
}
private void ResetEmuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetEmuActionPerformed
resetEmu();
}//GEN-LAST:event_ResetEmuActionPerformed
private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetButtonActionPerformed
resetEmu();
}//GEN-LAST:event_ResetButtonActionPerformed
private void resetEmu() {
if(loadedFile != null) {
PauseEmu();
if(umdLoaded)
loadUMD(loadedFile);
else
loadFile(loadedFile);
}
}
private void InstructionCounterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InstructionCounterActionPerformed
PauseEmu();
if (instructioncounter==null)
{
instructioncounter = new InstructionCounter();
emulator.setInstructionCounter(instructioncounter);
Point mainwindow = this.getLocation();
instructioncounter.setLocation(mainwindow.x+100, mainwindow.y+50);
instructioncounter.setVisible(true);
}
else
{
instructioncounter.RefreshWindow();
instructioncounter.setVisible(true);
}
}//GEN-LAST:event_InstructionCounterActionPerformed
private void FileLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FileLogActionPerformed
PauseEmu();
State.fileLogger.setVisible(true);
}//GEN-LAST:event_FileLogActionPerformed
private void VfpuRegistersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_VfpuRegistersActionPerformed
VfpuFrame.getInstance().setVisible(true);
}//GEN-LAST:event_VfpuRegistersActionPerformed
private void DumpIsoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DumpIsoActionPerformed
if (umdLoaded) {
UmdIsoReader iso = pspiofilemgr.getInstance().getIsoReader();
if (iso != null) {
try {
iso.dumpIndexFile("iso-index.txt");
} catch (IOException e) {
// Ignore Exception
}
}
}
}//GEN-LAST:event_DumpIsoActionPerformed
private void ResetProfilerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetProfilerActionPerformed
Profiler.reset();
}//GEN-LAST:event_ResetProfilerActionPerformed
private void MenuBarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MenuBarMouseExited
pspdisplay.getInstance().repaint();
}//GEN-LAST:event_MenuBarMouseExited
private void ShotItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShotItemActionPerformed
pspdisplay.getInstance().getscreen = true;
}//GEN-LAST:event_ShotItemActionPerformed
private void RotateItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateItemActionPerformed
pspdisplay screen = pspdisplay.getInstance();
Object[] options = {"90 CW","90 CCW","180","Mirror","Normal"};
int jop = JOptionPane.showOptionDialog(null, Resource.get("chooseRotation"), "Rotate", JOptionPane.UNDEFINED_CONDITION, JOptionPane.QUESTION_MESSAGE, null, options, options[4]);
if(jop != -1)
screen.rotate(jop);
else
return;
}//GEN-LAST:event_RotateItemActionPerformed
private byte safeRead8(int address)
{
byte value = 0;
if (Memory.getInstance().isAddressGood(address))
value = (byte)Memory.getInstance().read8(address);
return value;
}
private void safeWrite8(byte value, int address)
{
if (Memory.getInstance().isAddressGood(address))
Memory.getInstance().write8(address, value);
}
private void SaveSnapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveSnapActionPerformed
File f = new File("Snap_" + State.discId + ".bin");
BufferedOutputStream bOut = null;
ByteBuffer cpuBuf = ByteBuffer.allocate(1024);
Emulator.getProcessor().save(cpuBuf);
try
{
bOut = new BufferedOutputStream( new FileOutputStream(f) );
for(int i = 0x08000000; i<=0x09ffffff; i++)
{
bOut.write(safeRead8(i));
}
bOut.write(cpuBuf.array());
}
catch(IOException e)
{
}
finally
{
Utilities.close(bOut);
}
}//GEN-LAST:event_SaveSnapActionPerformed
private void LoadSnapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadSnapActionPerformed
File f = new File("Snap_" + State.discId + ".bin");
BufferedInputStream bIn = null;
ByteBuffer cpuBuf = ByteBuffer.allocate(1024);
try
{
bIn = new BufferedInputStream(new FileInputStream(f));
for(int i = 0x08000000; i<=0x09ffffff; i++ )
{
safeWrite8((byte)bIn.read(), i);
}
bIn.read(cpuBuf.array());
}
catch(IOException e)
{
}
finally
{
Utilities.close(bIn);
}
Emulator.getProcessor().load(cpuBuf);
}//GEN-LAST:event_LoadSnapActionPerformed
private void EnglishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnglishActionPerformed
changeLanguage("en_EN");
}//GEN-LAST:event_EnglishActionPerformed
private void FrenchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FrenchActionPerformed
changeLanguage("fr_FR");
}//GEN-LAST:event_FrenchActionPerformed
private void GermanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GermanActionPerformed
changeLanguage("de_DE");
}//GEN-LAST:event_GermanActionPerformed
private void LithuanianActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LithuanianActionPerformed
changeLanguage("lt_LT");
}//GEN-LAST:event_LithuanianActionPerformed
private void SpanishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SpanishActionPerformed
changeLanguage("es_ES");
}//GEN-LAST:event_SpanishActionPerformed
private void CatalanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CatalanActionPerformed
changeLanguage("es_CA");
}//GEN-LAST:event_CatalanActionPerformed
private void PortugueseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PortugueseActionPerformed
changeLanguage("pt_PT");
}//GEN-LAST:event_PortugueseActionPerformed
private void JapaneseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JapaneseActionPerformed
changeLanguage("jp_JP");
}//GEN-LAST:event_JapaneseActionPerformed
private void exitEmu() {
if (Settings.getInstance().readBool("gui.saveWindowPos"))
Settings.getInstance().writeWindowPos("mainwindow", getLocation());
ThreadMan.getInstance().exit();
pspdisplay.getInstance().exit();
VideoEngine.exit();
Emulator.exit();
System.exit(0);
}
public void snaptoMainwindow() {
snapConsole = true;
mainwindowPos = getLocation();
consolewin.setLocation(mainwindowPos.x, mainwindowPos.y + getHeight());
}
private void RunEmu()
{
emulator.RunEmu();
}
private void TogglePauseEmu()
{
// This is a toggle, so can pause and unpause
if (Emulator.run)
{
if (!Emulator.pause)
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_PAUSE);
else
RunEmu();
}
}
private void PauseEmu()
{
// This will only enter pause mode
if (Emulator.run && !Emulator.pause) {
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_PAUSE);
}
}
public void RefreshButtons()
{
RunButton.setSelected(Emulator.run && !Emulator.pause);
PauseButton.setSelected(Emulator.run && Emulator.pause);
}
/** set the FPS portion of the title */
public void setMainTitle(String message)
{
String oldtitle = getTitle();
int sub = oldtitle.indexOf("average");
if(sub!=-1)
{
String newtitle= oldtitle.substring(0, sub-1);
setTitle(newtitle + " " + message);
}
else
{
setTitle(oldtitle + " " + message);
}
}
private void printUsage() {
System.err.println("Usage: java -Xmx512m -jar jpcsp.jar [OPTIONS]");
System.err.println();
System.err.println(" -d, --debugger Open debugger at start.");
System.err.println(" -f, --loadfile FILE Load a file.");
System.err.println(" Example: ms0/PSP/GAME/pspsolitaire/EBOOT.PBP");
System.err.println(" -u, --loadumd FILE Load a UMD. Example: umdimages/cube.iso");
System.err.println(" -r, --run Run loaded file or umd. Use with -f or -u option.");
}
private void processArgs(String[] args) {
int i = 0;
while(i < args.length) {
if (args[i].equals("-d") || args[i].equals("--debugger")) {
i++;
// hack: reuse this function
EnterDebuggerActionPerformed(null);
} else if (args[i].equals("-f") || args[i].equals("--loadfile")) {
i++;
if (i < args.length) {
File file = new File(args[i]);
if(file.exists())
loadFile(file);
i++;
} else {
printUsage();
break;
}
} else if (args[i].equals("-u") || args[i].equals("--loadumd")) {
i++;
if (i < args.length) {
File file = new File(args[i]);
if(file.exists())
loadUMD(file);
i++;
} else {
printUsage();
break;
}
} else if (args[i].equals("-r") || args[i].equals("--run")) {
i++;
RunEmu();
} else {
printUsage();
break;
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// final copy of args for use in inner class
final String[] fargs = args;
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("GUI");
MainGUI maingui = new MainGUI();
maingui.setVisible(true);
if (Settings.getInstance().readBool("gui.openLogwindow"))
maingui.consolewin.setVisible(true);
maingui.processArgs(fargs);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem About;
private javax.swing.JMenuItem Catalan;
private javax.swing.JMenu DebugMenu;
private javax.swing.JMenuItem DumpIso;
private javax.swing.JMenuItem ElfHeaderViewer;
private javax.swing.JMenu EmulationMenu;
private javax.swing.JMenuItem English;
private javax.swing.JMenuItem EnterDebugger;
private javax.swing.JMenuItem EnterMemoryViewer;
private javax.swing.JMenuItem ExitEmu;
private javax.swing.JMenuItem FileLog;
private javax.swing.JMenu FileMenu;
private javax.swing.JMenuItem French;
private javax.swing.JMenuItem German;
private javax.swing.JMenu HelpMenu;
private javax.swing.JMenuItem InstructionCounter;
private javax.swing.JMenuItem Japanese;
private javax.swing.JMenu LanguageMenu;
private javax.swing.JMenuItem Lithuanian;
private javax.swing.JMenuItem LoadSnap;
private javax.swing.JMenuBar MenuBar;
private javax.swing.JMenuItem OpenFile;
private javax.swing.JMenuItem OpenMemStick;
private javax.swing.JMenu OptionsMenu;
private javax.swing.JToggleButton PauseButton;
private javax.swing.JMenuItem PauseEmu;
private javax.swing.JMenuItem Portuguese;
private javax.swing.JMenu RecentMenu;
private javax.swing.JButton ResetButton;
private javax.swing.JMenuItem ResetEmu;
private javax.swing.JMenuItem ResetProfiler;
private javax.swing.JMenuItem RotateItem;
private javax.swing.JToggleButton RunButton;
private javax.swing.JMenuItem RunEmu;
private javax.swing.JMenuItem SaveSnap;
private javax.swing.JMenuItem SetttingsMenu;
private javax.swing.JMenuItem ShotItem;
private javax.swing.JMenuItem Spanish;
private javax.swing.JMenuItem ToggleConsole;
private javax.swing.JMenuItem ToggleDebugLog;
private javax.swing.JMenuItem VfpuRegisters;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JMenuItem openUmd;
// End of variables declaration//GEN-END:variables
private boolean userChooseSomething(int returnVal) {
return returnVal == JFileChooser.APPROVE_OPTION;
}
@Override
public void keyTyped(KeyEvent arg0) { }
@Override
public void keyPressed(KeyEvent arg0) {
State.controller.keyPressed(arg0);
}
@Override
public void keyReleased(KeyEvent arg0) {
State.controller.keyReleased(arg0);
}
@Override
public void componentHidden(ComponentEvent e) { }
@Override
public void componentMoved(ComponentEvent e) {
if (snapConsole && consolewin.isVisible()) {
Point newPos = this.getLocation();
Point consolePos = consolewin.getLocation();
Dimension mainwindowSize = this.getSize();
if (consolePos.x == mainwindowPos.x &&
consolePos.y == mainwindowPos.y + mainwindowSize.height) {
consolewin.setLocation(newPos.x, newPos.y + mainwindowSize.height);
} else {
snapConsole = false;
}
mainwindowPos = newPos;
}
}
@Override
public void componentResized(ComponentEvent e) { }
@Override
public void componentShown(ComponentEvent e) { }
private class RecentElementActionListener implements ActionListener {
public static final int TYPE_UMD = 0;
public static final int TYPE_FILE = 1;
int type;
String path;
public RecentElementActionListener(int type, String path) {
this.path = path;
this.type = type;
}
@Override
public void actionPerformed(ActionEvent e) {
File file = new File(path);
if(file.exists()) {
if(type == TYPE_UMD)
loadUMD(file);
else
loadFile(file);
}
}
}
}
| false | true | private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
RunButton = new javax.swing.JToggleButton();
PauseButton = new javax.swing.JToggleButton();
ResetButton = new javax.swing.JButton();
MenuBar = new javax.swing.JMenuBar();
FileMenu = new javax.swing.JMenu();
openUmd = new javax.swing.JMenuItem();
OpenFile = new javax.swing.JMenuItem();
OpenMemStick = new javax.swing.JMenuItem();
RecentMenu = new javax.swing.JMenu();
ExitEmu = new javax.swing.JMenuItem();
EmulationMenu = new javax.swing.JMenu();
RunEmu = new javax.swing.JMenuItem();
PauseEmu = new javax.swing.JMenuItem();
ResetEmu = new javax.swing.JMenuItem();
OptionsMenu = new javax.swing.JMenu();
RotateItem = new javax.swing.JMenuItem();
SetttingsMenu = new javax.swing.JMenuItem();
ShotItem = new javax.swing.JMenuItem();
SaveSnap = new javax.swing.JMenuItem();
LoadSnap = new javax.swing.JMenuItem();
DebugMenu = new javax.swing.JMenu();
EnterDebugger = new javax.swing.JMenuItem();
EnterMemoryViewer = new javax.swing.JMenuItem();
VfpuRegisters = new javax.swing.JMenuItem();
ToggleConsole = new javax.swing.JMenuItem();
ElfHeaderViewer = new javax.swing.JMenuItem();
InstructionCounter = new javax.swing.JMenuItem();
FileLog = new javax.swing.JMenuItem();
ToggleDebugLog = new javax.swing.JMenuItem();
DumpIso = new javax.swing.JMenuItem();
ResetProfiler = new javax.swing.JMenuItem();
LanguageMenu = new javax.swing.JMenu();
English = new javax.swing.JMenuItem();
French = new javax.swing.JMenuItem();
German = new javax.swing.JMenuItem();
Lithuanian = new javax.swing.JMenuItem();
Spanish = new javax.swing.JMenuItem();
Catalan = new javax.swing.JMenuItem();
Portuguese = new javax.swing.JMenuItem();
Japanese = new javax.swing.JMenuItem();
HelpMenu = new javax.swing.JMenu();
About = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setForeground(java.awt.Color.white);
setMinimumSize(new java.awt.Dimension(480, 272));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
RunButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PlayIcon.png"))); // NOI18N
RunButton.setText(Resource.get("run"));
RunButton.setFocusable(false);
RunButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
RunButton.setIconTextGap(2);
RunButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
RunButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RunButtonActionPerformed(evt);
}
});
jToolBar1.add(RunButton);
PauseButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PauseIcon.png"))); // NOI18N
PauseButton.setText(Resource.get("pause"));
PauseButton.setFocusable(false);
PauseButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
PauseButton.setIconTextGap(2);
PauseButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
PauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PauseButtonActionPerformed(evt);
}
});
jToolBar1.add(PauseButton);
ResetButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/StopIcon.png"))); // NOI18N
ResetButton.setText(Resource.get("reset"));
ResetButton.setFocusable(false);
ResetButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
ResetButton.setIconTextGap(2);
ResetButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
ResetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetButtonActionPerformed(evt);
}
});
jToolBar1.add(ResetButton);
getContentPane().add(jToolBar1, java.awt.BorderLayout.NORTH);
MenuBar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
MenuBarMouseExited(evt);
}
});
FileMenu.setText(Resource.get("file"));
openUmd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadUmdIcon.png"))); // NOI18N
openUmd.setText(Resource.get("loadumd"));
openUmd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openUmdActionPerformed(evt);
}
});
FileMenu.add(openUmd);
OpenFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadFileIcon.png"))); // NOI18N
OpenFile.setText(Resource.get("loadfile"));
OpenFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenFileActionPerformed(evt);
}
});
FileMenu.add(OpenFile);
OpenMemStick.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadMemoryStick.png"))); // NOI18N
OpenMemStick.setText(Resource.get("loadmemstick"));
OpenMemStick.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenMemStickActionPerformed(evt);
}
});
FileMenu.add(OpenMemStick);
RecentMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/RecentIcon.png"))); // NOI18N
RecentMenu.setText(Resource.get("loadrecent"));
FileMenu.add(RecentMenu);
ExitEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/CloseIcon.png"))); // NOI18N
ExitEmu.setText(Resource.get("exit"));
ExitEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitEmuActionPerformed(evt);
}
});
FileMenu.add(ExitEmu);
MenuBar.add(FileMenu);
EmulationMenu.setText(Resource.get("emulation"));
RunEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PlayIcon.png"))); // NOI18N
RunEmu.setText(Resource.get("run"));
RunEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RunEmuActionPerformed(evt);
}
});
EmulationMenu.add(RunEmu);
PauseEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PauseIcon.png"))); // NOI18N
PauseEmu.setText(Resource.get("pause"));
PauseEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PauseEmuActionPerformed(evt);
}
});
EmulationMenu.add(PauseEmu);
ResetEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/StopIcon.png"))); // NOI18N
ResetEmu.setText(Resource.get("reset"));
ResetEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetEmuActionPerformed(evt);
}
});
EmulationMenu.add(ResetEmu);
MenuBar.add(EmulationMenu);
OptionsMenu.setText(Resource.get("options"));
RotateItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/RotateIcon.png"))); // NOI18N
RotateItem.setText(Resource.get("rotate"));
RotateItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RotateItemActionPerformed(evt);
}
});
OptionsMenu.add(RotateItem);
SetttingsMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/SettingsIcon.png"))); // NOI18N
SetttingsMenu.setText(Resource.get("settings"));
SetttingsMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SetttingsMenuActionPerformed(evt);
}
});
OptionsMenu.add(SetttingsMenu);
ShotItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
ShotItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/ScreenshotIcon.png"))); // NOI18N
ShotItem.setText(Resource.get("screenshot"));
ShotItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ShotItemActionPerformed(evt);
}
});
OptionsMenu.add(ShotItem);
SaveSnap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK));
SaveSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/SaveStateIcon.png"))); // NOI18N
SaveSnap.setText(Resource.get("savesnapshot"));
SaveSnap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveSnapActionPerformed(evt);
}
});
OptionsMenu.add(SaveSnap);
LoadSnap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.SHIFT_MASK));
LoadSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadStateIcon.png"))); // NOI18N
LoadSnap.setText(Resource.get("loadsnapshot"));
LoadSnap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadSnapActionPerformed(evt);
}
});
OptionsMenu.add(LoadSnap);
MenuBar.add(OptionsMenu);
DebugMenu.setText(Resource.get("debug"));
EnterDebugger.setText(Resource.get("enterdebugger"));
EnterDebugger.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterDebuggerActionPerformed(evt);
}
});
DebugMenu.add(EnterDebugger);
EnterMemoryViewer.setText(Resource.get("memoryviewer"));
EnterMemoryViewer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterMemoryViewerActionPerformed(evt);
}
});
DebugMenu.add(EnterMemoryViewer);
VfpuRegisters.setText(Resource.get("vfpuregisters"));
VfpuRegisters.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
VfpuRegistersActionPerformed(evt);
}
});
DebugMenu.add(VfpuRegisters);
ToggleConsole.setText(Resource.get("toggleconsole"));
ToggleConsole.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ToggleConsoleActionPerformed(evt);
}
});
DebugMenu.add(ToggleConsole);
ElfHeaderViewer.setText(Resource.get("elfheaderinfo"));
ElfHeaderViewer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ElfHeaderViewerActionPerformed(evt);
}
});
DebugMenu.add(ElfHeaderViewer);
InstructionCounter.setText(Resource.get("instructioncounter"));
InstructionCounter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InstructionCounterActionPerformed(evt);
}
});
DebugMenu.add(InstructionCounter);
FileLog.setText(Resource.get("filelog"));
FileLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FileLogActionPerformed(evt);
}
});
DebugMenu.add(FileLog);
ToggleDebugLog.setText(Resource.get("toggledebuglogging"));
ToggleDebugLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ToggleDebugLogActionPerformed(evt);
}
});
DebugMenu.add(ToggleDebugLog);
DumpIso.setText(Resource.get("dumpisotoisoindex"));
DumpIso.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DumpIsoActionPerformed(evt);
}
});
DebugMenu.add(DumpIso);
ResetProfiler.setText(Resource.get("resetprofilerinformation"));
ResetProfiler.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetProfilerActionPerformed(evt);
}
});
DebugMenu.add(ResetProfiler);
MenuBar.add(DebugMenu);
LanguageMenu.setText(Resource.get("language"));
English.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/en_EN.png"))); // NOI18N
English.setText(Resource.get("english"));
English.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnglishActionPerformed(evt);
}
});
LanguageMenu.add(English);
French.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/fr_FR.png"))); // NOI18N
French.setText(Resource.get("french"));
French.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FrenchActionPerformed(evt);
}
});
LanguageMenu.add(French);
German.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/de_DE.png"))); // NOI18N
German.setText(Resource.get("german"));
German.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GermanActionPerformed(evt);
}
});
LanguageMenu.add(German);
Lithuanian.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/lt_LT.png"))); // NOI18N
Lithuanian.setText(Resource.get("lithuanian"));
Lithuanian.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LithuanianActionPerformed(evt);
}
});
LanguageMenu.add(Lithuanian);
Spanish.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/es_ES.png"))); // NOI18N
Spanish.setText(Resource.get("spanish"));
Spanish.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SpanishActionPerformed(evt);
}
});
LanguageMenu.add(Spanish);
Catalan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/es_CA.png"))); // NOI18N
Catalan.setText(Resource.get("catalan"));
Catalan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CatalanActionPerformed(evt);
}
});
LanguageMenu.add(Catalan);
Portuguese.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/pt_PT.png"))); // NOI18N
Portuguese.setText(Resource.get("portuguese"));
Portuguese.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PortugueseActionPerformed(evt);
}
});
LanguageMenu.add(Portuguese);
Japanese.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/jp_JP.png"))); // NOI18N
Japanese.setText(Resource.get("japanese"));
Japanese.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JapaneseActionPerformed(evt);
}
});
LanguageMenu.add(Japanese);
MenuBar.add(LanguageMenu);
HelpMenu.setText(Resource.get("help"));
About.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/AboutIcon.png"))); // NOI18N
About.setText(Resource.get("about"));
About.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AboutActionPerformed(evt);
}
});
HelpMenu.add(About);
MenuBar.add(HelpMenu);
setJMenuBar(MenuBar);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
RunButton = new javax.swing.JToggleButton();
PauseButton = new javax.swing.JToggleButton();
ResetButton = new javax.swing.JButton();
MenuBar = new javax.swing.JMenuBar();
FileMenu = new javax.swing.JMenu();
openUmd = new javax.swing.JMenuItem();
OpenFile = new javax.swing.JMenuItem();
OpenMemStick = new javax.swing.JMenuItem();
RecentMenu = new javax.swing.JMenu();
ExitEmu = new javax.swing.JMenuItem();
EmulationMenu = new javax.swing.JMenu();
RunEmu = new javax.swing.JMenuItem();
PauseEmu = new javax.swing.JMenuItem();
ResetEmu = new javax.swing.JMenuItem();
OptionsMenu = new javax.swing.JMenu();
RotateItem = new javax.swing.JMenuItem();
SetttingsMenu = new javax.swing.JMenuItem();
ShotItem = new javax.swing.JMenuItem();
SaveSnap = new javax.swing.JMenuItem();
LoadSnap = new javax.swing.JMenuItem();
DebugMenu = new javax.swing.JMenu();
EnterDebugger = new javax.swing.JMenuItem();
EnterMemoryViewer = new javax.swing.JMenuItem();
VfpuRegisters = new javax.swing.JMenuItem();
ToggleConsole = new javax.swing.JMenuItem();
ElfHeaderViewer = new javax.swing.JMenuItem();
InstructionCounter = new javax.swing.JMenuItem();
FileLog = new javax.swing.JMenuItem();
ToggleDebugLog = new javax.swing.JMenuItem();
DumpIso = new javax.swing.JMenuItem();
ResetProfiler = new javax.swing.JMenuItem();
LanguageMenu = new javax.swing.JMenu();
English = new javax.swing.JMenuItem();
French = new javax.swing.JMenuItem();
German = new javax.swing.JMenuItem();
Lithuanian = new javax.swing.JMenuItem();
Spanish = new javax.swing.JMenuItem();
Catalan = new javax.swing.JMenuItem();
Portuguese = new javax.swing.JMenuItem();
Japanese = new javax.swing.JMenuItem();
HelpMenu = new javax.swing.JMenu();
About = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setForeground(java.awt.Color.white);
setMinimumSize(new java.awt.Dimension(480, 272));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
RunButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PlayIcon.png"))); // NOI18N
RunButton.setText(Resource.get("run"));
RunButton.setFocusable(false);
RunButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
RunButton.setIconTextGap(2);
RunButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
RunButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RunButtonActionPerformed(evt);
}
});
jToolBar1.add(RunButton);
PauseButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PauseIcon.png"))); // NOI18N
PauseButton.setText(Resource.get("pause"));
PauseButton.setFocusable(false);
PauseButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
PauseButton.setIconTextGap(2);
PauseButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
PauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PauseButtonActionPerformed(evt);
}
});
jToolBar1.add(PauseButton);
ResetButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/StopIcon.png"))); // NOI18N
ResetButton.setText(Resource.get("reset"));
ResetButton.setFocusable(false);
ResetButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
ResetButton.setIconTextGap(2);
ResetButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
ResetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetButtonActionPerformed(evt);
}
});
jToolBar1.add(ResetButton);
getContentPane().add(jToolBar1, java.awt.BorderLayout.NORTH);
MenuBar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
MenuBarMouseExited(evt);
}
});
FileMenu.setText(Resource.get("file"));
openUmd.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
openUmd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadUmdIcon.png"))); // NOI18N
openUmd.setText(Resource.get("loadumd"));
openUmd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openUmdActionPerformed(evt);
}
});
FileMenu.add(openUmd);
OpenFile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.ALT_MASK));
OpenFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadFileIcon.png"))); // NOI18N
OpenFile.setText(Resource.get("loadfile"));
OpenFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenFileActionPerformed(evt);
}
});
FileMenu.add(OpenFile);
OpenMemStick.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK));
OpenMemStick.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadMemoryStick.png"))); // NOI18N
OpenMemStick.setText(Resource.get("loadmemstick"));
OpenMemStick.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenMemStickActionPerformed(evt);
}
});
FileMenu.add(OpenMemStick);
RecentMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/RecentIcon.png"))); // NOI18N
RecentMenu.setText(Resource.get("loadrecent"));
FileMenu.add(RecentMenu);
ExitEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
ExitEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/CloseIcon.png"))); // NOI18N
ExitEmu.setText(Resource.get("exit"));
ExitEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitEmuActionPerformed(evt);
}
});
FileMenu.add(ExitEmu);
MenuBar.add(FileMenu);
EmulationMenu.setText(Resource.get("emulation"));
RunEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
RunEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PlayIcon.png"))); // NOI18N
RunEmu.setText(Resource.get("run"));
RunEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RunEmuActionPerformed(evt);
}
});
EmulationMenu.add(RunEmu);
PauseEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0));
PauseEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/PauseIcon.png"))); // NOI18N
PauseEmu.setText(Resource.get("pause"));
PauseEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PauseEmuActionPerformed(evt);
}
});
EmulationMenu.add(PauseEmu);
ResetEmu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0));
ResetEmu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/StopIcon.png"))); // NOI18N
ResetEmu.setText(Resource.get("reset"));
ResetEmu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetEmuActionPerformed(evt);
}
});
EmulationMenu.add(ResetEmu);
MenuBar.add(EmulationMenu);
OptionsMenu.setText(Resource.get("options"));
RotateItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F11, 0));
RotateItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/RotateIcon.png"))); // NOI18N
RotateItem.setText(Resource.get("rotate"));
RotateItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RotateItemActionPerformed(evt);
}
});
OptionsMenu.add(RotateItem);
SetttingsMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F12, 0));
SetttingsMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/SettingsIcon.png"))); // NOI18N
SetttingsMenu.setText(Resource.get("settings"));
SetttingsMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SetttingsMenuActionPerformed(evt);
}
});
OptionsMenu.add(SetttingsMenu);
ShotItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
ShotItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/ScreenshotIcon.png"))); // NOI18N
ShotItem.setText(Resource.get("screenshot"));
ShotItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ShotItemActionPerformed(evt);
}
});
OptionsMenu.add(ShotItem);
SaveSnap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK));
SaveSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/SaveStateIcon.png"))); // NOI18N
SaveSnap.setText(Resource.get("savesnapshot"));
SaveSnap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveSnapActionPerformed(evt);
}
});
OptionsMenu.add(SaveSnap);
LoadSnap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.SHIFT_MASK));
LoadSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/LoadStateIcon.png"))); // NOI18N
LoadSnap.setText(Resource.get("loadsnapshot"));
LoadSnap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadSnapActionPerformed(evt);
}
});
OptionsMenu.add(LoadSnap);
MenuBar.add(OptionsMenu);
DebugMenu.setText(Resource.get("debug"));
EnterDebugger.setText(Resource.get("enterdebugger"));
EnterDebugger.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterDebuggerActionPerformed(evt);
}
});
DebugMenu.add(EnterDebugger);
EnterMemoryViewer.setText(Resource.get("memoryviewer"));
EnterMemoryViewer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterMemoryViewerActionPerformed(evt);
}
});
DebugMenu.add(EnterMemoryViewer);
VfpuRegisters.setText(Resource.get("vfpuregisters"));
VfpuRegisters.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
VfpuRegistersActionPerformed(evt);
}
});
DebugMenu.add(VfpuRegisters);
ToggleConsole.setText(Resource.get("toggleconsole"));
ToggleConsole.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ToggleConsoleActionPerformed(evt);
}
});
DebugMenu.add(ToggleConsole);
ElfHeaderViewer.setText(Resource.get("elfheaderinfo"));
ElfHeaderViewer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ElfHeaderViewerActionPerformed(evt);
}
});
DebugMenu.add(ElfHeaderViewer);
InstructionCounter.setText(Resource.get("instructioncounter"));
InstructionCounter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InstructionCounterActionPerformed(evt);
}
});
DebugMenu.add(InstructionCounter);
FileLog.setText(Resource.get("filelog"));
FileLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FileLogActionPerformed(evt);
}
});
DebugMenu.add(FileLog);
ToggleDebugLog.setText(Resource.get("toggledebuglogging"));
ToggleDebugLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ToggleDebugLogActionPerformed(evt);
}
});
DebugMenu.add(ToggleDebugLog);
DumpIso.setText(Resource.get("dumpisotoisoindex"));
DumpIso.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DumpIsoActionPerformed(evt);
}
});
DebugMenu.add(DumpIso);
ResetProfiler.setText(Resource.get("resetprofilerinformation"));
ResetProfiler.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetProfilerActionPerformed(evt);
}
});
DebugMenu.add(ResetProfiler);
MenuBar.add(DebugMenu);
LanguageMenu.setText(Resource.get("language"));
English.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/en_EN.png"))); // NOI18N
English.setText(Resource.get("english"));
English.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnglishActionPerformed(evt);
}
});
LanguageMenu.add(English);
French.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/fr_FR.png"))); // NOI18N
French.setText(Resource.get("french"));
French.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FrenchActionPerformed(evt);
}
});
LanguageMenu.add(French);
German.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/de_DE.png"))); // NOI18N
German.setText(Resource.get("german"));
German.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GermanActionPerformed(evt);
}
});
LanguageMenu.add(German);
Lithuanian.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/lt_LT.png"))); // NOI18N
Lithuanian.setText(Resource.get("lithuanian"));
Lithuanian.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LithuanianActionPerformed(evt);
}
});
LanguageMenu.add(Lithuanian);
Spanish.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/es_ES.png"))); // NOI18N
Spanish.setText(Resource.get("spanish"));
Spanish.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SpanishActionPerformed(evt);
}
});
LanguageMenu.add(Spanish);
Catalan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/es_CA.png"))); // NOI18N
Catalan.setText(Resource.get("catalan"));
Catalan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CatalanActionPerformed(evt);
}
});
LanguageMenu.add(Catalan);
Portuguese.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/pt_PT.png"))); // NOI18N
Portuguese.setText(Resource.get("portuguese"));
Portuguese.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PortugueseActionPerformed(evt);
}
});
LanguageMenu.add(Portuguese);
Japanese.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/flags/jp_JP.png"))); // NOI18N
Japanese.setText(Resource.get("japanese"));
Japanese.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JapaneseActionPerformed(evt);
}
});
LanguageMenu.add(Japanese);
MenuBar.add(LanguageMenu);
HelpMenu.setText(Resource.get("help"));
About.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
About.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpcsp/icons/AboutIcon.png"))); // NOI18N
About.setText(Resource.get("about"));
About.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AboutActionPerformed(evt);
}
});
HelpMenu.add(About);
MenuBar.add(HelpMenu);
setJMenuBar(MenuBar);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/net/sf/cpsolver/coursett/heuristics/NeighbourSelectionWithSuggestions.java b/src/net/sf/cpsolver/coursett/heuristics/NeighbourSelectionWithSuggestions.java
index 7cebec8..153fe2e 100644
--- a/src/net/sf/cpsolver/coursett/heuristics/NeighbourSelectionWithSuggestions.java
+++ b/src/net/sf/cpsolver/coursett/heuristics/NeighbourSelectionWithSuggestions.java
@@ -1,256 +1,256 @@
package net.sf.cpsolver.coursett.heuristics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.sf.cpsolver.coursett.model.Lecture;
import net.sf.cpsolver.coursett.model.Placement;
import net.sf.cpsolver.coursett.model.TimetableModel;
import net.sf.cpsolver.ifs.heuristics.StandardNeighbourSelection;
import net.sf.cpsolver.ifs.model.Neighbour;
import net.sf.cpsolver.ifs.solution.Solution;
import net.sf.cpsolver.ifs.solver.Solver;
import net.sf.cpsolver.ifs.util.DataProperties;
import net.sf.cpsolver.ifs.util.JProf;
import net.sf.cpsolver.ifs.util.ToolBox;
/**
* Neighbour selection which does the standard time neighbour selection most of
* the time, however, the very best neighbour is selected time to time (using
* backtracking based search).
*
* @see StandardNeighbourSelection
* @version CourseTT 1.2 (University Course Timetabling)<br>
* Copyright (C) 2006 - 2010 Tomas Muller<br>
* <a href="mailto:[email protected]">[email protected]</a><br>
* <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
* <br>
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version. <br>
* <br>
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. <br>
* <br>
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not see <http://www.gnu.org/licenses/>.
*/
public class NeighbourSelectionWithSuggestions extends StandardNeighbourSelection<Lecture, Placement> {
private double iSuggestionProbability = 0.1;
private double iSuggestionProbabilityAllAssigned = 0.5;
private int iSuggestionTimeout = 500;
private int iSuggestionDepth = 4;
private Solution<Lecture, Placement> iSolution = null;
private SuggestionNeighbour iSuggestionNeighbour = null;
private TimetableComparator iCmp = null;
private double iValue = 0;
private int iNrAssigned = 0;
public NeighbourSelectionWithSuggestions(DataProperties properties) throws Exception {
super(properties);
iSuggestionProbability = properties
.getPropertyDouble("Neighbour.SuggestionProbability", iSuggestionProbability);
iSuggestionProbabilityAllAssigned = properties.getPropertyDouble("Neighbour.SuggestionProbabilityAllAssigned",
iSuggestionProbabilityAllAssigned);
iSuggestionTimeout = properties.getPropertyInt("Neighbour.SuggestionTimeout", iSuggestionTimeout);
iSuggestionDepth = properties.getPropertyInt("Neighbour.SuggestionDepth", iSuggestionDepth);
}
public NeighbourSelectionWithSuggestions(Solver<Lecture, Placement> solver) throws Exception {
this(solver.getProperties());
init(solver);
}
@Override
public void init(Solver<Lecture, Placement> solver) {
super.init(solver);
iCmp = (TimetableComparator) solver.getSolutionComparator();
}
@Override
public Neighbour<Lecture, Placement> selectNeighbour(Solution<Lecture, Placement> solution) {
Neighbour<Lecture, Placement> neighbour = null;
if (solution.getModel().unassignedVariables().isEmpty()) {
for (int d = iSuggestionDepth; d > 1; d--) {
if (ToolBox.random() < Math.pow(iSuggestionProbabilityAllAssigned, d - 1)) {
neighbour = selectNeighbourWithSuggestions(solution, selectVariable(solution), d);
break;
}
}
} else {
for (int d = iSuggestionDepth; d > 1; d--) {
if (ToolBox.random() < Math.pow(iSuggestionProbability, d - 1)) {
neighbour = selectNeighbourWithSuggestions(solution, selectVariable(solution), d);
break;
}
}
}
return (neighbour != null ? neighbour : super.selectNeighbour(solution));
}
public synchronized Neighbour<Lecture, Placement> selectNeighbourWithSuggestions(
Solution<Lecture, Placement> solution, Lecture lecture, int depth) {
if (lecture == null)
return null;
iSolution = solution;
iSuggestionNeighbour = null;
iValue = iCmp.currentValue(solution);
iNrAssigned = solution.getModel().assignedVariables().size();
synchronized (solution) {
// System.out.println("BEFORE BT ("+lecture.getName()+"): nrAssigned="+iSolution.getModel().assignedVariables().size()+", value="+iCmp.currentValue(iSolution));
List<Lecture> initialLectures = new ArrayList<Lecture>(1);
initialLectures.add(lecture);
backtrack(JProf.currentTimeMillis(), initialLectures, new ArrayList<Lecture>(),
new HashMap<Lecture, Placement>(), depth);
// System.out.println("AFTER BT ("+lecture.getName()+"): nrAssigned="+iSolution.getModel().assignedVariables().size()+", value="+iCmp.currentValue(iSolution));
}
return iSuggestionNeighbour;
}
private boolean containsCommited(Collection<Placement> values) {
if (((TimetableModel) iSolution.getModel()).hasConstantVariables()) {
for (Placement placement : values) {
Lecture lecture = placement.variable();
if (lecture.isCommitted())
return true;
}
}
return false;
}
private void backtrack(long startTime, List<Lecture> initialLectures, List<Lecture> resolvedLectures,
HashMap<Lecture, Placement> conflictsToResolve, int depth) {
int nrUnassigned = conflictsToResolve.size();
if ((initialLectures == null || initialLectures.isEmpty()) && nrUnassigned == 0) {
if (iSolution.getModel().assignedVariables().size() > iNrAssigned
|| (iSolution.getModel().assignedVariables().size() == iNrAssigned && iValue > iCmp
.currentValue(iSolution))) {
if (iSuggestionNeighbour == null || iSuggestionNeighbour.compareTo(iSolution) >= 0)
iSuggestionNeighbour = new SuggestionNeighbour(resolvedLectures);
}
return;
}
if (depth <= 0)
return;
if (iSuggestionTimeout > 0 && JProf.currentTimeMillis() - startTime > iSuggestionTimeout) {
return;
}
- for (Lecture lecture: (initialLectures != null && !initialLectures.isEmpty() ? initialLectures : conflictsToResolve.keySet())) {
+ for (Lecture lecture: initialLectures != null && !initialLectures.isEmpty() ? initialLectures : new ArrayList<Lecture>(conflictsToResolve.keySet())) {
if (resolvedLectures.contains(lecture))
continue;
resolvedLectures.add(lecture);
for (Placement placement : lecture.values()) {
if (placement.equals(lecture.getAssignment()))
continue;
if (placement.isHard())
continue;
Set<Placement> conflicts = iSolution.getModel().conflictValues(placement);
if (conflicts != null && (nrUnassigned + conflicts.size() > depth))
continue;
if (conflicts != null && conflicts.contains(placement))
continue;
if (containsCommited(conflicts))
continue;
boolean containException = false;
if (conflicts != null) {
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
if (resolvedLectures.contains((c.variable()).getClassId()))
containException = true;
}
}
if (containException)
continue;
Placement cur = lecture.getAssignment();
if (conflicts != null) {
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
c.variable().unassign(0);
}
}
if (cur != null)
cur.variable().unassign(0);
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
conflictsToResolve.put(c.variable(), c);
}
Placement resolvedConf = conflictsToResolve.remove(lecture);
backtrack(startTime, null, resolvedLectures, conflictsToResolve, depth - 1);
if (cur == null)
lecture.unassign(0);
else
lecture.assign(0, cur);
for (Iterator<Placement> i = conflicts.iterator(); i.hasNext();) {
Placement p = i.next();
p.variable().assign(0, p);
conflictsToResolve.remove(p.variable());
}
if (resolvedConf != null)
conflictsToResolve.put(lecture, resolvedConf);
}
resolvedLectures.remove(lecture);
}
}
public class SuggestionNeighbour extends Neighbour<Lecture, Placement> {
private double iValue = 0;
private List<Placement> iDifferentAssignments = null;
public SuggestionNeighbour(List<Lecture> resolvedLectures) {
iValue = iCmp.currentValue(iSolution);
iDifferentAssignments = new ArrayList<Placement>();
for (Lecture lecture : resolvedLectures) {
Placement p = lecture.getAssignment();
iDifferentAssignments.add(p);
}
}
@Override
public double value() {
return iValue;
}
@Override
public void assign(long iteration) {
// System.out.println("START ASSIGN: nrAssigned="+iSolution.getModel().assignedVariables().size()+", value="+iCmp.currentValue(iSolution));
// System.out.println(" "+this);
for (Placement p : iDifferentAssignments) {
if (p.variable().getAssignment() != null)
p.variable().unassign(iteration);
}
for (Placement p : iDifferentAssignments) {
p.variable().assign(iteration, p);
}
// System.out.println("END ASSIGN: nrAssigned="+iSolution.getModel().assignedVariables().size()+", value="+iCmp.currentValue(iSolution));
}
public int compareTo(Solution<Lecture, Placement> solution) {
return Double.compare(iValue, iCmp.currentValue(solution));
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer("Suggestion{value=" + (iValue - iCmp.currentValue(iSolution)) + ": ");
for (Iterator<Placement> e = iDifferentAssignments.iterator(); e.hasNext();) {
Placement p = e.next();
sb.append("\n " + p.variable().getName() + " " + p.getName() + (e.hasNext() ? "," : ""));
}
sb.append("}");
return sb.toString();
}
}
}
| true | true | private void backtrack(long startTime, List<Lecture> initialLectures, List<Lecture> resolvedLectures,
HashMap<Lecture, Placement> conflictsToResolve, int depth) {
int nrUnassigned = conflictsToResolve.size();
if ((initialLectures == null || initialLectures.isEmpty()) && nrUnassigned == 0) {
if (iSolution.getModel().assignedVariables().size() > iNrAssigned
|| (iSolution.getModel().assignedVariables().size() == iNrAssigned && iValue > iCmp
.currentValue(iSolution))) {
if (iSuggestionNeighbour == null || iSuggestionNeighbour.compareTo(iSolution) >= 0)
iSuggestionNeighbour = new SuggestionNeighbour(resolvedLectures);
}
return;
}
if (depth <= 0)
return;
if (iSuggestionTimeout > 0 && JProf.currentTimeMillis() - startTime > iSuggestionTimeout) {
return;
}
for (Lecture lecture: (initialLectures != null && !initialLectures.isEmpty() ? initialLectures : conflictsToResolve.keySet())) {
if (resolvedLectures.contains(lecture))
continue;
resolvedLectures.add(lecture);
for (Placement placement : lecture.values()) {
if (placement.equals(lecture.getAssignment()))
continue;
if (placement.isHard())
continue;
Set<Placement> conflicts = iSolution.getModel().conflictValues(placement);
if (conflicts != null && (nrUnassigned + conflicts.size() > depth))
continue;
if (conflicts != null && conflicts.contains(placement))
continue;
if (containsCommited(conflicts))
continue;
boolean containException = false;
if (conflicts != null) {
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
if (resolvedLectures.contains((c.variable()).getClassId()))
containException = true;
}
}
if (containException)
continue;
Placement cur = lecture.getAssignment();
if (conflicts != null) {
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
c.variable().unassign(0);
}
}
if (cur != null)
cur.variable().unassign(0);
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
conflictsToResolve.put(c.variable(), c);
}
Placement resolvedConf = conflictsToResolve.remove(lecture);
backtrack(startTime, null, resolvedLectures, conflictsToResolve, depth - 1);
if (cur == null)
lecture.unassign(0);
else
lecture.assign(0, cur);
for (Iterator<Placement> i = conflicts.iterator(); i.hasNext();) {
Placement p = i.next();
p.variable().assign(0, p);
conflictsToResolve.remove(p.variable());
}
if (resolvedConf != null)
conflictsToResolve.put(lecture, resolvedConf);
}
resolvedLectures.remove(lecture);
}
}
| private void backtrack(long startTime, List<Lecture> initialLectures, List<Lecture> resolvedLectures,
HashMap<Lecture, Placement> conflictsToResolve, int depth) {
int nrUnassigned = conflictsToResolve.size();
if ((initialLectures == null || initialLectures.isEmpty()) && nrUnassigned == 0) {
if (iSolution.getModel().assignedVariables().size() > iNrAssigned
|| (iSolution.getModel().assignedVariables().size() == iNrAssigned && iValue > iCmp
.currentValue(iSolution))) {
if (iSuggestionNeighbour == null || iSuggestionNeighbour.compareTo(iSolution) >= 0)
iSuggestionNeighbour = new SuggestionNeighbour(resolvedLectures);
}
return;
}
if (depth <= 0)
return;
if (iSuggestionTimeout > 0 && JProf.currentTimeMillis() - startTime > iSuggestionTimeout) {
return;
}
for (Lecture lecture: initialLectures != null && !initialLectures.isEmpty() ? initialLectures : new ArrayList<Lecture>(conflictsToResolve.keySet())) {
if (resolvedLectures.contains(lecture))
continue;
resolvedLectures.add(lecture);
for (Placement placement : lecture.values()) {
if (placement.equals(lecture.getAssignment()))
continue;
if (placement.isHard())
continue;
Set<Placement> conflicts = iSolution.getModel().conflictValues(placement);
if (conflicts != null && (nrUnassigned + conflicts.size() > depth))
continue;
if (conflicts != null && conflicts.contains(placement))
continue;
if (containsCommited(conflicts))
continue;
boolean containException = false;
if (conflicts != null) {
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
if (resolvedLectures.contains((c.variable()).getClassId()))
containException = true;
}
}
if (containException)
continue;
Placement cur = lecture.getAssignment();
if (conflicts != null) {
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
c.variable().unassign(0);
}
}
if (cur != null)
cur.variable().unassign(0);
for (Iterator<Placement> i = conflicts.iterator(); !containException && i.hasNext();) {
Placement c = i.next();
conflictsToResolve.put(c.variable(), c);
}
Placement resolvedConf = conflictsToResolve.remove(lecture);
backtrack(startTime, null, resolvedLectures, conflictsToResolve, depth - 1);
if (cur == null)
lecture.unassign(0);
else
lecture.assign(0, cur);
for (Iterator<Placement> i = conflicts.iterator(); i.hasNext();) {
Placement p = i.next();
p.variable().assign(0, p);
conflictsToResolve.remove(p.variable());
}
if (resolvedConf != null)
conflictsToResolve.put(lecture, resolvedConf);
}
resolvedLectures.remove(lecture);
}
}
|
diff --git a/EmailClient/src/Email/FilterRule.java b/EmailClient/src/Email/FilterRule.java
index aa06d0b..5a4c454 100644
--- a/EmailClient/src/Email/FilterRule.java
+++ b/EmailClient/src/Email/FilterRule.java
@@ -1,76 +1,76 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Email;
/**
*
* @author Bargavi
*/
public class FilterRule {
String ruleId;
String fromText;
String subjectText;
String contentText;
String moveToFolder;
public boolean matches(String messageid) {
MessageController controller = MessageController.getInstance();
- if (controller.getEmailHeader(messageid, "X-MeetingId") == "") {
+ if (controller.getEmailHeader(messageid, "X-MeetingId") != "") {
return false;
}
String from = controller.getEmailHeader(messageid, "From");
String subject = controller.getEmailHeader(messageid, "Subject");
String content = controller.getEmailContent(messageid);
if ((from.toLowerCase().contains(fromText.toLowerCase()))
&& (subject.toLowerCase().contains(subjectText.toLowerCase()))
&& (content.toLowerCase().contains(contentText.toLowerCase()))) {
return true;
}
return false;
}
public void setFromField(String fromText) {
this.fromText = fromText;
}
public void setsubjectField(String subjectText) {
this.subjectText = subjectText;
}
public void setcontentField(String contentText) {
this.contentText = contentText;
}
public void setmoveToField(String moveToFolder) {
this.moveToFolder = moveToFolder;
}
public String getFromField() {
return this.fromText;
}
public String getsubjectField() {
return this.subjectText;
}
public String getcontentField() {
return this.contentText;
}
public String getmoveToField() {
return this.moveToFolder;
}
public String getRuleId() {
return this.ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
}
| true | true | public boolean matches(String messageid) {
MessageController controller = MessageController.getInstance();
if (controller.getEmailHeader(messageid, "X-MeetingId") == "") {
return false;
}
String from = controller.getEmailHeader(messageid, "From");
String subject = controller.getEmailHeader(messageid, "Subject");
String content = controller.getEmailContent(messageid);
if ((from.toLowerCase().contains(fromText.toLowerCase()))
&& (subject.toLowerCase().contains(subjectText.toLowerCase()))
&& (content.toLowerCase().contains(contentText.toLowerCase()))) {
return true;
}
return false;
}
| public boolean matches(String messageid) {
MessageController controller = MessageController.getInstance();
if (controller.getEmailHeader(messageid, "X-MeetingId") != "") {
return false;
}
String from = controller.getEmailHeader(messageid, "From");
String subject = controller.getEmailHeader(messageid, "Subject");
String content = controller.getEmailContent(messageid);
if ((from.toLowerCase().contains(fromText.toLowerCase()))
&& (subject.toLowerCase().contains(subjectText.toLowerCase()))
&& (content.toLowerCase().contains(contentText.toLowerCase()))) {
return true;
}
return false;
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java
index d2f74095e..6537fabe6 100644
--- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java
+++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java
@@ -1,93 +1,101 @@
/*******************************************************************************
* Copyright (c) 2007, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.ui.viewers;
import org.eclipse.core.runtime.URIUtil;
import org.eclipse.equinox.internal.p2.ui.ProvUIMessages;
import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement;
import org.eclipse.equinox.internal.p2.ui.model.ProvElement;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.repository.IRepository;
import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages;
import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.osgi.util.TextProcessor;
import org.eclipse.swt.graphics.Image;
/**
* Label provider for repository elements. The column structure is
* assumed to be known by the caller who sets up the columns
*
* @since 3.5
*/
public class RepositoryDetailsLabelProvider extends LabelProvider implements ITableLabelProvider {
public static final int COL_NAME = 0;
public static final int COL_LOCATION = 1;
public static final int COL_ENABLEMENT = 2;
public Image getImage(Object obj) {
if (obj instanceof ProvElement) {
return ((ProvElement) obj).getImage(obj);
}
if (obj instanceof IArtifactRepository) {
return ProvUIImages.getImage(ProvUIImages.IMG_ARTIFACT_REPOSITORY);
}
if (obj instanceof IMetadataRepository) {
return ProvUIImages.getImage(ProvUIImages.IMG_METADATA_REPOSITORY);
}
return null;
}
public Image getColumnImage(Object element, int index) {
if (index == 0) {
return getImage(element);
}
return null;
}
public String getColumnText(Object element, int columnIndex) {
switch (columnIndex) {
case COL_NAME :
- String name = ((IRepositoryElement) element).getName();
- if (name != null) {
- return name;
+ if (element instanceof IRepositoryElement) {
+ String name = ((IRepositoryElement) element).getName();
+ if (name != null) {
+ return name;
+ }
+ }
+ if (element instanceof IRepository) {
+ String name = ((IRepository) element).getName();
+ if (name != null) {
+ return name;
+ }
}
return ""; //$NON-NLS-1$
case COL_LOCATION :
if (element instanceof IRepository) {
return TextProcessor.process(URIUtil.toUnencodedString(((IRepository) element).getLocation()));
}
if (element instanceof IRepositoryElement) {
return TextProcessor.process(URIUtil.toUnencodedString(((IRepositoryElement) element).getLocation()));
}
break;
case COL_ENABLEMENT :
if (element instanceof MetadataRepositoryElement)
return ((MetadataRepositoryElement) element).isEnabled() ? ProvUIMessages.RepositoryDetailsLabelProvider_Enabled : ProvUIMessages.RepositoryDetailsLabelProvider_Disabled;
}
return null;
}
public String getClipboardText(Object element, String columnDelimiter) {
StringBuffer result = new StringBuffer();
result.append(getColumnText(element, COL_NAME));
result.append(columnDelimiter);
result.append(getColumnText(element, COL_LOCATION));
result.append(columnDelimiter);
result.append(getColumnText(element, COL_ENABLEMENT));
return result.toString();
}
}
| true | true | public String getColumnText(Object element, int columnIndex) {
switch (columnIndex) {
case COL_NAME :
String name = ((IRepositoryElement) element).getName();
if (name != null) {
return name;
}
return ""; //$NON-NLS-1$
case COL_LOCATION :
if (element instanceof IRepository) {
return TextProcessor.process(URIUtil.toUnencodedString(((IRepository) element).getLocation()));
}
if (element instanceof IRepositoryElement) {
return TextProcessor.process(URIUtil.toUnencodedString(((IRepositoryElement) element).getLocation()));
}
break;
case COL_ENABLEMENT :
if (element instanceof MetadataRepositoryElement)
return ((MetadataRepositoryElement) element).isEnabled() ? ProvUIMessages.RepositoryDetailsLabelProvider_Enabled : ProvUIMessages.RepositoryDetailsLabelProvider_Disabled;
}
return null;
}
| public String getColumnText(Object element, int columnIndex) {
switch (columnIndex) {
case COL_NAME :
if (element instanceof IRepositoryElement) {
String name = ((IRepositoryElement) element).getName();
if (name != null) {
return name;
}
}
if (element instanceof IRepository) {
String name = ((IRepository) element).getName();
if (name != null) {
return name;
}
}
return ""; //$NON-NLS-1$
case COL_LOCATION :
if (element instanceof IRepository) {
return TextProcessor.process(URIUtil.toUnencodedString(((IRepository) element).getLocation()));
}
if (element instanceof IRepositoryElement) {
return TextProcessor.process(URIUtil.toUnencodedString(((IRepositoryElement) element).getLocation()));
}
break;
case COL_ENABLEMENT :
if (element instanceof MetadataRepositoryElement)
return ((MetadataRepositoryElement) element).isEnabled() ? ProvUIMessages.RepositoryDetailsLabelProvider_Enabled : ProvUIMessages.RepositoryDetailsLabelProvider_Disabled;
}
return null;
}
|
diff --git a/src/org/apache/xalan/xsltc/trax/DOM2SAX.java b/src/org/apache/xalan/xsltc/trax/DOM2SAX.java
index 8da79949..e25361ff 100644
--- a/src/org/apache/xalan/xsltc/trax/DOM2SAX.java
+++ b/src/org/apache/xalan/xsltc/trax/DOM2SAX.java
@@ -1,478 +1,485 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author G. Todd Miller
*
*/
package org.apache.xalan.xsltc.trax;
import java.util.Stack;
import java.util.Vector;
import java.util.Hashtable;
import org.xml.sax.XMLReader;
import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.Locator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.AttributeList;
import org.xml.sax.helpers.AttributeListImpl;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import java.io.IOException;
import org.w3c.dom.Entity;
import org.w3c.dom.Notation;
class DOM2SAX implements XMLReader, Locator {
private final static String EMPTYSTRING = "";
private static final String XMLNS_PREFIX = "xmlns";
private Node _dom = null;
private ContentHandler _sax = null;
private LexicalHandler _lex = null;
private Hashtable _nsPrefixes = new Hashtable();
public DOM2SAX(Node root) {
_dom = root;
}
public ContentHandler getContentHandler() {
return _sax;
}
public void setContentHandler(ContentHandler handler) throws
NullPointerException
{
_sax = handler;
if (handler instanceof LexicalHandler) {
_lex = (LexicalHandler) handler;
}
}
/**
* Begin the scope of namespace prefix. Forward the event to the
* SAX handler only if the prefix is unknown or it is mapped to a
* different URI.
*/
private boolean startPrefixMapping(String prefix, String uri)
throws SAXException
{
boolean pushed = true;
Stack uriStack = (Stack) _nsPrefixes.get(prefix);
if (uriStack != null) {
if (uriStack.isEmpty()) {
_sax.startPrefixMapping(prefix, uri);
uriStack.push(uri);
}
else {
final String lastUri = (String) uriStack.peek();
if (!lastUri.equals(uri)) {
_sax.startPrefixMapping(prefix, uri);
uriStack.push(uri);
}
else {
pushed = false;
}
}
}
else {
_sax.startPrefixMapping(prefix, uri);
_nsPrefixes.put(prefix, uriStack = new Stack());
uriStack.push(uri);
}
return pushed;
}
/*
* End the scope of a name prefix by popping it from the stack and
* passing the event to the SAX Handler.
*/
private void endPrefixMapping(String prefix)
throws SAXException
{
final Stack uriStack = (Stack) _nsPrefixes.get(prefix);
if (uriStack != null) {
_sax.endPrefixMapping(prefix);
uriStack.pop();
}
}
/**
* If the DOM was created using a DOM 1.0 API, the local name may be
* null. If so, get the local name from the qualified name before
* generating the SAX event.
*/
private static String getLocalName(Node node) {
final String localName = node.getLocalName();
if (localName == null) {
final String qname = node.getNodeName();
final int col = qname.lastIndexOf(':');
return (col > 0) ? qname.substring(col + 1) : qname;
}
return localName;
}
public void parse(InputSource unused) throws IOException, SAXException {
parse(_dom);
}
/**
* Traverse the DOM and generate SAX events for a handler. A
* startElement() event passes all attributes, including namespace
* declarations.
*/
private void parse(Node node) throws IOException, SAXException {
Node first = null;
if (node == null) return;
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
- case Node.CDATA_SECTION_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
case Node.DOCUMENT_TYPE_NODE :
case Node.ENTITY_NODE :
case Node.ENTITY_REFERENCE_NODE:
case Node.NOTATION_NODE :
// These node types are ignored!!!
break;
+ case Node.CDATA_SECTION_NODE:
+ if (_lex != null) {
+ final String data = node.getNodeValue();
+ _lex.startCDATA();
+ _sax.characters(data.toCharArray(), 0, data.length());
+ _lex.endCDATA();
+ }
+ break;
case Node.COMMENT_NODE: // should be handled!!!
if (_lex != null) {
final String value = node.getNodeValue();
_lex.comment(value.toCharArray(), 0, value.length());
}
break;
case Node.DOCUMENT_NODE:
_sax.setDocumentLocator(this);
_sax.startDocument();
Node next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
_sax.endDocument();
break;
case Node.ELEMENT_NODE:
String prefix;
Vector pushedPrefixes = new Vector();
final AttributesImpl attrs = new AttributesImpl();
final NamedNodeMap map = node.getAttributes();
final int length = map.getLength();
// Process all namespace declarations
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore everything but NS declarations here
if (qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNodeValue();
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.addElement(prefix);
}
}
}
// Process all other attributes
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore NS declarations here
if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNamespaceURI();
final String localNameAttr = getLocalName(attr);
// Uri may be implicitly declared
if (uriAttr != null) {
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.addElement(prefix);
}
}
// Add attribute to list
attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr),
qnameAttr, "CDATA", attr.getNodeValue());
}
}
// Now process the element itself
final String qname = node.getNodeName();
final String uri = node.getNamespaceURI();
final String localName = getLocalName(node);
// Uri may be implicitly declared
if (uri != null) {
final int colon = qname.lastIndexOf(':');
prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uri)) {
pushedPrefixes.addElement(prefix);
}
}
// Generate SAX event to start element
_sax.startElement(uri, localName, qname, attrs);
// Traverse all child nodes of the element (if any)
next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
// Generate SAX event to close element
_sax.endElement(uri, localName, qname);
// Generate endPrefixMapping() for all pushed prefixes
final int nPushedPrefixes = pushedPrefixes.size();
for (int i = 0; i < nPushedPrefixes; i++) {
endPrefixMapping((String) pushedPrefixes.elementAt(i));
}
break;
case Node.PROCESSING_INSTRUCTION_NODE:
_sax.processingInstruction(node.getNodeName(),
node.getNodeValue());
break;
case Node.TEXT_NODE:
final String data = node.getNodeValue();
_sax.characters(data.toCharArray(), 0, data.length());
break;
}
}
/**
* This class is only used internally so this method should never
* be called.
*/
public DTDHandler getDTDHandler() {
return null;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public ErrorHandler getErrorHandler() {
return null;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public boolean getFeature(String name) throws SAXNotRecognizedException,
SAXNotSupportedException
{
return false;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public void setFeature(String name, boolean value) throws
SAXNotRecognizedException, SAXNotSupportedException
{
}
/**
* This class is only used internally so this method should never
* be called.
*/
public void parse(String sysId) throws IOException, SAXException {
throw new IOException("This method is not yet implemented.");
}
/**
* This class is only used internally so this method should never
* be called.
*/
public void setDTDHandler(DTDHandler handler) throws NullPointerException {
}
/**
* This class is only used internally so this method should never
* be called.
*/
public void setEntityResolver(EntityResolver resolver) throws
NullPointerException
{
}
/**
* This class is only used internally so this method should never
* be called.
*/
public EntityResolver getEntityResolver() {
return null;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public void setErrorHandler(ErrorHandler handler) throws
NullPointerException
{
}
/**
* This class is only used internally so this method should never
* be called.
*/
public void setProperty(String name, Object value) throws
SAXNotRecognizedException, SAXNotSupportedException {
}
/**
* This class is only used internally so this method should never
* be called.
*/
public Object getProperty(String name) throws SAXNotRecognizedException,
SAXNotSupportedException
{
return null;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public int getColumnNumber() {
return 0;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public int getLineNumber() {
return 0;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public String getPublicId() {
return null;
}
/**
* This class is only used internally so this method should never
* be called.
*/
public String getSystemId() {
return null;
}
// Debugging
private String getNodeTypeFromCode(short code) {
String retval = null;
switch (code) {
case Node.ATTRIBUTE_NODE :
retval = "ATTRIBUTE_NODE"; break;
case Node.CDATA_SECTION_NODE :
retval = "CDATA_SECTION_NODE"; break;
case Node.COMMENT_NODE :
retval = "COMMENT_NODE"; break;
case Node.DOCUMENT_FRAGMENT_NODE :
retval = "DOCUMENT_FRAGMENT_NODE"; break;
case Node.DOCUMENT_NODE :
retval = "DOCUMENT_NODE"; break;
case Node.DOCUMENT_TYPE_NODE :
retval = "DOCUMENT_TYPE_NODE"; break;
case Node.ELEMENT_NODE :
retval = "ELEMENT_NODE"; break;
case Node.ENTITY_NODE :
retval = "ENTITY_NODE"; break;
case Node.ENTITY_REFERENCE_NODE :
retval = "ENTITY_REFERENCE_NODE"; break;
case Node.NOTATION_NODE :
retval = "NOTATION_NODE"; break;
case Node.PROCESSING_INSTRUCTION_NODE :
retval = "PROCESSING_INSTRUCTION_NODE"; break;
case Node.TEXT_NODE:
retval = "TEXT_NODE"; break;
}
return retval;
}
}
| false | true | private void parse(Node node) throws IOException, SAXException {
Node first = null;
if (node == null) return;
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
case Node.CDATA_SECTION_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
case Node.DOCUMENT_TYPE_NODE :
case Node.ENTITY_NODE :
case Node.ENTITY_REFERENCE_NODE:
case Node.NOTATION_NODE :
// These node types are ignored!!!
break;
case Node.COMMENT_NODE: // should be handled!!!
if (_lex != null) {
final String value = node.getNodeValue();
_lex.comment(value.toCharArray(), 0, value.length());
}
break;
case Node.DOCUMENT_NODE:
_sax.setDocumentLocator(this);
_sax.startDocument();
Node next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
_sax.endDocument();
break;
case Node.ELEMENT_NODE:
String prefix;
Vector pushedPrefixes = new Vector();
final AttributesImpl attrs = new AttributesImpl();
final NamedNodeMap map = node.getAttributes();
final int length = map.getLength();
// Process all namespace declarations
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore everything but NS declarations here
if (qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNodeValue();
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.addElement(prefix);
}
}
}
// Process all other attributes
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore NS declarations here
if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNamespaceURI();
final String localNameAttr = getLocalName(attr);
// Uri may be implicitly declared
if (uriAttr != null) {
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.addElement(prefix);
}
}
// Add attribute to list
attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr),
qnameAttr, "CDATA", attr.getNodeValue());
}
}
// Now process the element itself
final String qname = node.getNodeName();
final String uri = node.getNamespaceURI();
final String localName = getLocalName(node);
// Uri may be implicitly declared
if (uri != null) {
final int colon = qname.lastIndexOf(':');
prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uri)) {
pushedPrefixes.addElement(prefix);
}
}
// Generate SAX event to start element
_sax.startElement(uri, localName, qname, attrs);
// Traverse all child nodes of the element (if any)
next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
// Generate SAX event to close element
_sax.endElement(uri, localName, qname);
// Generate endPrefixMapping() for all pushed prefixes
final int nPushedPrefixes = pushedPrefixes.size();
for (int i = 0; i < nPushedPrefixes; i++) {
endPrefixMapping((String) pushedPrefixes.elementAt(i));
}
break;
case Node.PROCESSING_INSTRUCTION_NODE:
_sax.processingInstruction(node.getNodeName(),
node.getNodeValue());
break;
case Node.TEXT_NODE:
final String data = node.getNodeValue();
_sax.characters(data.toCharArray(), 0, data.length());
break;
}
}
| private void parse(Node node) throws IOException, SAXException {
Node first = null;
if (node == null) return;
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
case Node.DOCUMENT_FRAGMENT_NODE:
case Node.DOCUMENT_TYPE_NODE :
case Node.ENTITY_NODE :
case Node.ENTITY_REFERENCE_NODE:
case Node.NOTATION_NODE :
// These node types are ignored!!!
break;
case Node.CDATA_SECTION_NODE:
if (_lex != null) {
final String data = node.getNodeValue();
_lex.startCDATA();
_sax.characters(data.toCharArray(), 0, data.length());
_lex.endCDATA();
}
break;
case Node.COMMENT_NODE: // should be handled!!!
if (_lex != null) {
final String value = node.getNodeValue();
_lex.comment(value.toCharArray(), 0, value.length());
}
break;
case Node.DOCUMENT_NODE:
_sax.setDocumentLocator(this);
_sax.startDocument();
Node next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
_sax.endDocument();
break;
case Node.ELEMENT_NODE:
String prefix;
Vector pushedPrefixes = new Vector();
final AttributesImpl attrs = new AttributesImpl();
final NamedNodeMap map = node.getAttributes();
final int length = map.getLength();
// Process all namespace declarations
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore everything but NS declarations here
if (qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNodeValue();
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.addElement(prefix);
}
}
}
// Process all other attributes
for (int i = 0; i < length; i++) {
final Node attr = map.item(i);
final String qnameAttr = attr.getNodeName();
// Ignore NS declarations here
if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
final String uriAttr = attr.getNamespaceURI();
final String localNameAttr = getLocalName(attr);
// Uri may be implicitly declared
if (uriAttr != null) {
final int colon = qnameAttr.lastIndexOf(':');
prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uriAttr)) {
pushedPrefixes.addElement(prefix);
}
}
// Add attribute to list
attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr),
qnameAttr, "CDATA", attr.getNodeValue());
}
}
// Now process the element itself
final String qname = node.getNodeName();
final String uri = node.getNamespaceURI();
final String localName = getLocalName(node);
// Uri may be implicitly declared
if (uri != null) {
final int colon = qname.lastIndexOf(':');
prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
if (startPrefixMapping(prefix, uri)) {
pushedPrefixes.addElement(prefix);
}
}
// Generate SAX event to start element
_sax.startElement(uri, localName, qname, attrs);
// Traverse all child nodes of the element (if any)
next = node.getFirstChild();
while (next != null) {
parse(next);
next = next.getNextSibling();
}
// Generate SAX event to close element
_sax.endElement(uri, localName, qname);
// Generate endPrefixMapping() for all pushed prefixes
final int nPushedPrefixes = pushedPrefixes.size();
for (int i = 0; i < nPushedPrefixes; i++) {
endPrefixMapping((String) pushedPrefixes.elementAt(i));
}
break;
case Node.PROCESSING_INSTRUCTION_NODE:
_sax.processingInstruction(node.getNodeName(),
node.getNodeValue());
break;
case Node.TEXT_NODE:
final String data = node.getNodeValue();
_sax.characters(data.toCharArray(), 0, data.length());
break;
}
}
|
diff --git a/source/ch/cyberduck/core/AbstractLoginController.java b/source/ch/cyberduck/core/AbstractLoginController.java
index a842d36b0..e5e90cb76 100644
--- a/source/ch/cyberduck/core/AbstractLoginController.java
+++ b/source/ch/cyberduck/core/AbstractLoginController.java
@@ -1,157 +1,157 @@
package ch.cyberduck.core;
/*
* Copyright (c) 2008 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Bug fixes, suggestions and comments should be sent to:
* [email protected]
*/
import ch.cyberduck.core.i18n.Locale;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* @version $Id$
*/
public abstract class AbstractLoginController implements LoginController {
private static Logger log = Logger.getLogger(AbstractLoginController.class);
/**
* Show alert with a Continue and Disconnect option.
*
* @param title Title in alert window
* @param message Message in alert window
* @param preference Where to save preference if dismissed
* @throws LoginCanceledException
*/
public void warn(String title, String message, String preference) throws LoginCanceledException {
this.warn(title, message, Locale.localizedString("Continue", "Credentials"),
Locale.localizedString("Disconnect", "Credentials"), preference);
}
public abstract void warn(String title, String message, String continueButton, String disconnectButton, String preference)
throws LoginCanceledException;
/**
* @param host
* @param title The title for the login prompt
* @param message
* @throws LoginCanceledException
*/
public void check(final Host host, String title, String message)
throws LoginCanceledException {
this.check(host, title, message, Preferences.instance().getBoolean("connection.login.useKeychain"),
host.getProtocol().equals(Protocol.SFTP), host.getProtocol().isAnonymousConfigurable());
}
/**
* Check the credentials for validity and prompt the user for the password if not found
* in the login keychain
*
* @param host See Host#getCredentials
* @param message Additional message displayed in the password prompt
* @throws LoginCanceledException
*/
public void check(final Host host, String title, String message, boolean enableKeychain, boolean enablePublicKey, boolean enableAnonymous)
throws LoginCanceledException {
final Credentials credentials = host.getCredentials();
StringBuilder reason = new StringBuilder();
if(StringUtils.isNotBlank(message)) {
reason.append(message).append(". ");
}
- if(!credentials.validate(host.getProtocol())) {
+ if(!credentials.validate(host.getProtocol()) || credentials.isPublicKeyAuthentication()) {
+ // Lookup password if missing. Always lookup password for public key authentication. See #5754.
if(StringUtils.isNotBlank(credentials.getUsername())) {
if(Preferences.instance().getBoolean("connection.login.useKeychain")) {
String saved = KeychainFactory.instance().find(host);
if(StringUtils.isBlank(saved)) {
if(credentials.isPublicKeyAuthentication()) {
- ;
// We decide later if the key is encrypted and a password must be known to decrypt.
}
else {
reason.append(Locale.localizedString(
"No login credentials could be found in the Keychain", "Credentials")).append(".");
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
else {
credentials.setPassword(saved);
// No need to reinsert found password to the keychain.
credentials.setUseKeychain(false);
}
}
else {
reason.append(Locale.localizedString(
"The use of the Keychain is disabled in the Preferences", "Credentials")).append(".");
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
else {
reason.append(Locale.localizedString(
"No login credentials could be found in the Keychain", "Credentials")).append(".");
;
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
}
public void fail(Protocol protocol, Credentials credentials, String reason) throws LoginCanceledException {
this.prompt(protocol, credentials,
Locale.localizedString("Login failed", "Credentials"), reason);
}
public void success(Host host) {
Credentials credentials = host.getCredentials();
if(credentials.isAnonymousLogin()) {
log.info("Do not write anonymous credentials to Keychain");
return;
}
if(!credentials.isUseKeychain()) {
log.info("Do not write credentials to Keychain");
return;
}
KeychainFactory.instance().save(host);
}
/**
* Display login failure with a prompt to enter the username and password.
*
* @param protocol
* @param credentials
* @throws LoginCanceledException
*/
public void fail(Protocol protocol, Credentials credentials)
throws LoginCanceledException {
this.prompt(protocol, credentials,
Locale.localizedString("Login failed", "Credentials"),
Locale.localizedString("Login with username and password", "Credentials"));
}
public void prompt(final Protocol protocol, final Credentials credentials,
final String title, final String reason) throws LoginCanceledException {
this.prompt(protocol, credentials, title, reason, Preferences.instance().getBoolean("connection.login.useKeychain"),
protocol.equals(Protocol.SFTP), protocol.isAnonymousConfigurable());
}
public abstract void prompt(Protocol protocol, Credentials credentials,
String title, String reason,
boolean enableKeychain, boolean enablePublicKey, boolean enableAnonymous) throws LoginCanceledException;
}
| false | true | public void check(final Host host, String title, String message, boolean enableKeychain, boolean enablePublicKey, boolean enableAnonymous)
throws LoginCanceledException {
final Credentials credentials = host.getCredentials();
StringBuilder reason = new StringBuilder();
if(StringUtils.isNotBlank(message)) {
reason.append(message).append(". ");
}
if(!credentials.validate(host.getProtocol())) {
if(StringUtils.isNotBlank(credentials.getUsername())) {
if(Preferences.instance().getBoolean("connection.login.useKeychain")) {
String saved = KeychainFactory.instance().find(host);
if(StringUtils.isBlank(saved)) {
if(credentials.isPublicKeyAuthentication()) {
;
// We decide later if the key is encrypted and a password must be known to decrypt.
}
else {
reason.append(Locale.localizedString(
"No login credentials could be found in the Keychain", "Credentials")).append(".");
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
else {
credentials.setPassword(saved);
// No need to reinsert found password to the keychain.
credentials.setUseKeychain(false);
}
}
else {
reason.append(Locale.localizedString(
"The use of the Keychain is disabled in the Preferences", "Credentials")).append(".");
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
else {
reason.append(Locale.localizedString(
"No login credentials could be found in the Keychain", "Credentials")).append(".");
;
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
}
| public void check(final Host host, String title, String message, boolean enableKeychain, boolean enablePublicKey, boolean enableAnonymous)
throws LoginCanceledException {
final Credentials credentials = host.getCredentials();
StringBuilder reason = new StringBuilder();
if(StringUtils.isNotBlank(message)) {
reason.append(message).append(". ");
}
if(!credentials.validate(host.getProtocol()) || credentials.isPublicKeyAuthentication()) {
// Lookup password if missing. Always lookup password for public key authentication. See #5754.
if(StringUtils.isNotBlank(credentials.getUsername())) {
if(Preferences.instance().getBoolean("connection.login.useKeychain")) {
String saved = KeychainFactory.instance().find(host);
if(StringUtils.isBlank(saved)) {
if(credentials.isPublicKeyAuthentication()) {
// We decide later if the key is encrypted and a password must be known to decrypt.
}
else {
reason.append(Locale.localizedString(
"No login credentials could be found in the Keychain", "Credentials")).append(".");
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
else {
credentials.setPassword(saved);
// No need to reinsert found password to the keychain.
credentials.setUseKeychain(false);
}
}
else {
reason.append(Locale.localizedString(
"The use of the Keychain is disabled in the Preferences", "Credentials")).append(".");
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
else {
reason.append(Locale.localizedString(
"No login credentials could be found in the Keychain", "Credentials")).append(".");
;
this.prompt(host.getProtocol(), credentials, title, reason.toString(),
enableKeychain, enablePublicKey, enableAnonymous);
}
}
}
|
diff --git a/src/com/mel/wallpaper/starWars/entity/commands/BubbleCommand.java b/src/com/mel/wallpaper/starWars/entity/commands/BubbleCommand.java
index 5083731..2485e40 100644
--- a/src/com/mel/wallpaper/starWars/entity/commands/BubbleCommand.java
+++ b/src/com/mel/wallpaper/starWars/entity/commands/BubbleCommand.java
@@ -1,128 +1,128 @@
package com.mel.wallpaper.starWars.entity.commands;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.IModifier;
import org.andengine.util.modifier.ease.EaseLinear;
import org.andengine.util.modifier.ease.EaseQuartOut;
import com.mel.entityframework.Game;
import com.mel.util.MathUtil;
import com.mel.util.Point;
import com.mel.wallpaper.starWars.entity.Bubble;
import com.mel.wallpaper.starWars.entity.Bubble.BubbleType;
import com.mel.wallpaper.starWars.entity.LaserBeam;
import com.mel.wallpaper.starWars.entity.Map;
import com.mel.wallpaper.starWars.entity.Walker;
import com.mel.wallpaper.starWars.entity.Walker.Rol;
import com.mel.wallpaper.starWars.sound.SoundAssets;
import com.mel.wallpaper.starWars.sound.SoundAssets.Sample;
import com.mel.wallpaper.starWars.view.Position;
import com.mel.wallpaper.starWars.view.SpriteFactory;
public class BubbleCommand extends MoveCommand
{
public Bubble bubble;
private Game game;
public BubbleCommand(Walker walker, Game game) {
super(walker, 1.4f, EaseLinear.getInstance());
this.walker = walker;
this.game = game;
switch(walker.rol)
{
case JEDI:
- switch((int)Math.random()*10)
+ switch((int)(Math.random()*10))
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_OLA_K_ASE, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_HOLA_K_ASE, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBLE_SPACEPELOTAS, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_TINTINTIRIRIN, walker.position);
break;
default:
bubble = new Bubble(BubbleType.BUBBLE_NOTE_BLUE, walker.position);
}
break;
case STORM_TROOPER:
- switch((int)Math.random()*10)
+ switch((int)(Math.random()*10))
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_A_DUCADOS, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_A_EWOK, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBLE_A_NAPALM, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_EWOKS3, walker.position);
break;
case 4:
bubble = new Bubble(BubbleType.BUBBLE_PEINANDO, walker.position);
break;
default:
bubble = new Bubble(BubbleType.BUBBLE_NOTE_WHITE, walker.position);
}
break;
case DARTH_VADER:
- switch((int)Math.random()*4)
+ switch((int)(Math.random()*4))
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_A_OBI, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_A_OSCURO, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBBE_A_PADRE_2, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_VADER, walker.position);
break;
}
break;
case CHUWAKA:
bubble = new Bubble(BubbleType.getRandomBubble(), walker.position);
break;
default:
bubble = new Bubble(BubbleType.getRandomBubble(), walker.position);
}
movable = bubble;
this.game.addEntity(bubble);
}
@Override
public void execute(Map p) {
//increase destination
// this.destination = MathUtil.getPuntDesti(this.bubble.position.toPoint(), this.destination, 2000f);
destination = new Point(bubble.position.getX(), bubble.position.getY() + 50);
super.execute(p);
bubble.playSound();
walker.forceStopMovement();
//walker.animateTalking();
bubble.getSprite().registerEntityModifier(new AlphaModifier(2f, 1f, 0f, new IEntityModifierListener() {
public void onModifierStarted(IModifier<IEntity> arg0, IEntity sprite) {
}
public void onModifierFinished(IModifier<IEntity> arg0, IEntity sprite) {
bubble.isFinished = true;
}
}));
}
}
| false | true | public BubbleCommand(Walker walker, Game game) {
super(walker, 1.4f, EaseLinear.getInstance());
this.walker = walker;
this.game = game;
switch(walker.rol)
{
case JEDI:
switch((int)Math.random()*10)
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_OLA_K_ASE, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_HOLA_K_ASE, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBLE_SPACEPELOTAS, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_TINTINTIRIRIN, walker.position);
break;
default:
bubble = new Bubble(BubbleType.BUBBLE_NOTE_BLUE, walker.position);
}
break;
case STORM_TROOPER:
switch((int)Math.random()*10)
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_A_DUCADOS, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_A_EWOK, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBLE_A_NAPALM, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_EWOKS3, walker.position);
break;
case 4:
bubble = new Bubble(BubbleType.BUBBLE_PEINANDO, walker.position);
break;
default:
bubble = new Bubble(BubbleType.BUBBLE_NOTE_WHITE, walker.position);
}
break;
case DARTH_VADER:
switch((int)Math.random()*4)
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_A_OBI, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_A_OSCURO, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBBE_A_PADRE_2, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_VADER, walker.position);
break;
}
break;
case CHUWAKA:
bubble = new Bubble(BubbleType.getRandomBubble(), walker.position);
break;
default:
bubble = new Bubble(BubbleType.getRandomBubble(), walker.position);
}
movable = bubble;
this.game.addEntity(bubble);
}
| public BubbleCommand(Walker walker, Game game) {
super(walker, 1.4f, EaseLinear.getInstance());
this.walker = walker;
this.game = game;
switch(walker.rol)
{
case JEDI:
switch((int)(Math.random()*10))
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_OLA_K_ASE, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_HOLA_K_ASE, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBLE_SPACEPELOTAS, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_TINTINTIRIRIN, walker.position);
break;
default:
bubble = new Bubble(BubbleType.BUBBLE_NOTE_BLUE, walker.position);
}
break;
case STORM_TROOPER:
switch((int)(Math.random()*10))
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_A_DUCADOS, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_A_EWOK, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBLE_A_NAPALM, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_EWOKS3, walker.position);
break;
case 4:
bubble = new Bubble(BubbleType.BUBBLE_PEINANDO, walker.position);
break;
default:
bubble = new Bubble(BubbleType.BUBBLE_NOTE_WHITE, walker.position);
}
break;
case DARTH_VADER:
switch((int)(Math.random()*4))
{
case 0:
bubble = new Bubble(BubbleType.BUBBLE_A_OBI, walker.position);
break;
case 1:
bubble = new Bubble(BubbleType.BUBBLE_A_OSCURO, walker.position);
break;
case 2:
bubble = new Bubble(BubbleType.BUBBBE_A_PADRE_2, walker.position);
break;
case 3:
bubble = new Bubble(BubbleType.BUBBLE_VADER, walker.position);
break;
}
break;
case CHUWAKA:
bubble = new Bubble(BubbleType.getRandomBubble(), walker.position);
break;
default:
bubble = new Bubble(BubbleType.getRandomBubble(), walker.position);
}
movable = bubble;
this.game.addEntity(bubble);
}
|
diff --git a/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java b/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java
index 1ff3f482..68b2f0a2 100644
--- a/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java
+++ b/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java
@@ -1,100 +1,100 @@
package org.patientview.radar.test.service;
import org.apache.commons.collections.CollectionUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.patientview.model.Patient;
import org.patientview.model.generic.DiseaseGroup;
import org.patientview.radar.dao.DemographicsDao;
import org.patientview.radar.dao.UtilityDao;
import org.patientview.radar.model.PatientLink;
import org.patientview.radar.service.PatientLinkManager;
import org.patientview.radar.test.TestPvDbSchema;
import org.springframework.test.context.ContextConfiguration;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;
/**
* User: [email protected]
* Date: 15/11/13
* Time: 14:32
*/
@RunWith(org.springframework.test.context.junit4.SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class PatientLinkManagerTest extends TestPvDbSchema {
private final static String testDiseaseUnit = "Allports";
private final static String testRenalUnit = "RENALA";
@Inject
private PatientLinkManager patientLinkManager;
@Inject
private DemographicsDao demographicsDao;
@Inject
private UtilityDao utilityDao;
/**
* A unit admin is created by the superadmin in PV.
* <p/>
* Create a basic PV user structure - User - Role as unit admin etc
*/
@Before
public void setup() {
// Setup a Renal Unit and Disease Group
try {
utilityDao.createUnit(testRenalUnit);
utilityDao.createUnit(testDiseaseUnit);
} catch (Exception e) {
}
}
/**
* Test to create a link record and then query to find is that record is linked.
*
*/
@Test
- public void testLinkingPatientRecord() {
+ public void testLinkingPatientRecord() throws Exception {
Patient patient = new Patient();
patient.setUnitcode(testRenalUnit);
patient.setSurname("Test");
patient.setForename("Test");
patient.setDob(new Date());
patient.setNhsno("234235242");
DiseaseGroup diseaseGroup = new DiseaseGroup();
diseaseGroup.setId(testDiseaseUnit);
patient.setDiseaseGroup(diseaseGroup);
// Save the patient record before linking because the record should already exist
demographicsDao.saveDemographics(patient);
patientLinkManager.linkPatientRecord(patient);
List<PatientLink> patientLink = patientLinkManager.getPatientLink(patient.getNhsno(), testRenalUnit);
Assert.assertTrue("The list return should not be empty." , CollectionUtils.isNotEmpty(patientLink));
Assert.assertTrue("The should only be one link recreated", patientLink.size() == 1);
}
@After
public void tearDown(){
try {
this.clearData();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| true | true | public void testLinkingPatientRecord() {
Patient patient = new Patient();
patient.setUnitcode(testRenalUnit);
patient.setSurname("Test");
patient.setForename("Test");
patient.setDob(new Date());
patient.setNhsno("234235242");
DiseaseGroup diseaseGroup = new DiseaseGroup();
diseaseGroup.setId(testDiseaseUnit);
patient.setDiseaseGroup(diseaseGroup);
// Save the patient record before linking because the record should already exist
demographicsDao.saveDemographics(patient);
patientLinkManager.linkPatientRecord(patient);
List<PatientLink> patientLink = patientLinkManager.getPatientLink(patient.getNhsno(), testRenalUnit);
Assert.assertTrue("The list return should not be empty." , CollectionUtils.isNotEmpty(patientLink));
Assert.assertTrue("The should only be one link recreated", patientLink.size() == 1);
}
| public void testLinkingPatientRecord() throws Exception {
Patient patient = new Patient();
patient.setUnitcode(testRenalUnit);
patient.setSurname("Test");
patient.setForename("Test");
patient.setDob(new Date());
patient.setNhsno("234235242");
DiseaseGroup diseaseGroup = new DiseaseGroup();
diseaseGroup.setId(testDiseaseUnit);
patient.setDiseaseGroup(diseaseGroup);
// Save the patient record before linking because the record should already exist
demographicsDao.saveDemographics(patient);
patientLinkManager.linkPatientRecord(patient);
List<PatientLink> patientLink = patientLinkManager.getPatientLink(patient.getNhsno(), testRenalUnit);
Assert.assertTrue("The list return should not be empty." , CollectionUtils.isNotEmpty(patientLink));
Assert.assertTrue("The should only be one link recreated", patientLink.size() == 1);
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java b/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java
index 47cbc0f..e0fee28 100644
--- a/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java
+++ b/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java
@@ -1,674 +1,677 @@
/*
* This file is part of Technic Launcher.
*
* Copyright (c) 2013-2013, Technic <http://www.technicpack.net/>
* Technic Launcher is licensed under the Spout License Version 1.
*
* Technic Launcher is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the Spout License Version 1.
*
* Technic Launcher is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the Spout License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spoutcraft.launcher.skin;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.swing.*;
import net.minecraft.Launcher;
import org.spoutcraft.launcher.Settings;
import org.spoutcraft.launcher.skin.components.BackgroundImage;
import org.spoutcraft.launcher.skin.components.DynamicButton;
import org.spoutcraft.launcher.skin.components.ImageHyperlinkButton;
import org.spoutcraft.launcher.skin.components.LiteButton;
import org.spoutcraft.launcher.skin.components.LitePasswordBox;
import org.spoutcraft.launcher.skin.components.LiteProgressBar;
import org.spoutcraft.launcher.skin.components.LiteTextBox;
import org.spoutcraft.launcher.skin.components.LoginFrame;
import org.spoutcraft.launcher.technic.AddPack;
import org.spoutcraft.launcher.technic.PackInfo;
import org.spoutcraft.launcher.technic.RestInfo;
import org.spoutcraft.launcher.technic.skin.ImageButton;
import org.spoutcraft.launcher.technic.skin.LauncherOptions;
import org.spoutcraft.launcher.technic.skin.ModpackOptions;
import org.spoutcraft.launcher.technic.skin.ModpackSelector;
import org.spoutcraft.launcher.technic.skin.RoundedBox;
import org.spoutcraft.launcher.util.Download;
import org.spoutcraft.launcher.util.Download.Result;
import org.spoutcraft.launcher.util.DownloadUtils;
import org.spoutcraft.launcher.util.ImageUtils;
import org.spoutcraft.launcher.util.ResourceUtils;
import org.spoutcraft.launcher.util.Utils;
public class MetroLoginFrame extends LoginFrame implements ActionListener, KeyListener, MouseWheelListener {
private static final long serialVersionUID = 1L;
private static final int FRAME_WIDTH = 880;
private static final int FRAME_HEIGHT = 520;
private static final String OPTIONS_ACTION = "options";
private static final String PACK_OPTIONS_ACTION = "packoptions";
private static final String PACK_REMOVE_ACTION = "packremove";
private static final String EXIT_ACTION = "exit";
private static final String PACK_LEFT_ACTION = "packleft";
private static final String PACK_RIGHT_ACTION = "packright";
private static final String LOGIN_ACTION = "login";
private static final String IMAGE_LOGIN_ACTION = "image_login";
private static final String REMOVE_USER = "remove";
private static final Color TRANSPARENT = new Color(45, 45, 45, 160);
private static final Color DARK_GREY = new Color(45, 45, 45);
private final Map<JButton, DynamicButton> removeButtons = new HashMap<JButton, DynamicButton>();
private final Map<String, DynamicButton> userButtons = new HashMap<String, DynamicButton>();
private LiteTextBox name;
private LitePasswordBox pass;
private LiteButton login;
private JCheckBox remember;
private LiteProgressBar progressBar;
private LauncherOptions launcherOptions = null;
private ModpackOptions packOptions = null;
private ModpackSelector packSelector;
private BackgroundImage packBackground;
private ImageButton packOptionsBtn;
private ImageButton packRemoveBtn;
private ImageHyperlinkButton platform;
private JLabel packShadow;
private JLabel customName;
private long previous = 0L;
public MetroLoginFrame() {
initComponents();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((dim.width - FRAME_WIDTH) / 2, (dim.height - FRAME_HEIGHT) / 2, FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
packBackground = new BackgroundImage(this, FRAME_WIDTH, FRAME_HEIGHT);
this.addMouseListener(packBackground);
this.addMouseMotionListener(packBackground);
this.addMouseWheelListener(this);
getContentPane().add(packBackground);
this.setUndecorated(true);
}
private void initComponents() {
Font minecraft = getMinecraftFont(12);
// Login background box
RoundedBox loginArea = new RoundedBox(TRANSPARENT);
loginArea.setBounds(605, 377, 265, 83);
// Setup username box
name = new LiteTextBox(this, "Username...");
name.setBounds(loginArea.getX() + 15, loginArea.getY() + 15, 110, 24);
name.setFont(minecraft);
name.addKeyListener(this);
// Setup password box
pass = new LitePasswordBox(this, "Password...");
pass.setBounds(loginArea.getX() + 15, loginArea.getY() + name.getHeight() + 20, 110, 24);
pass.setFont(minecraft);
pass.addKeyListener(this);
// Setup login button
login = new LiteButton("Launch");
login.setBounds(loginArea.getX() + name.getWidth() + 30, loginArea.getY() + 15, 110, 24);
login.setFont(minecraft);
login.setActionCommand(LOGIN_ACTION);
login.addActionListener(this);
login.addKeyListener(this);
// Setup remember checkbox
remember = new JCheckBox("Remember");
remember.setBounds(loginArea.getX() + name.getWidth() + 30, loginArea.getY() + name.getHeight() + 20, 110, 24);
remember.setFont(minecraft);
remember.setOpaque(false);
remember.setBorderPainted(false);
remember.setFocusPainted(false);
remember.setContentAreaFilled(false);
remember.setBorder(null);
remember.setForeground(Color.WHITE);
remember.setHorizontalTextPosition(SwingConstants.RIGHT);
remember.setIconTextGap(10);
remember.addKeyListener(this);
// Technic logo
JLabel logo = new JLabel();
logo.setBounds(600, -10, 260, 109);
setIcon(logo, "techniclauncher.png", logo.getWidth(), logo.getHeight());
// Pack Selector Background
JLabel selectorBackground = new JLabel();
selectorBackground.setBounds(15, 0, 200, 520);
selectorBackground.setBackground(TRANSPARENT);
selectorBackground.setOpaque(true);
// Pack Select Up
ImageButton packUp = new ImageButton(getIcon("upButton.png", 65, 65));
packUp.setBounds(-7, 0, 65, 65);
packUp.setActionCommand(PACK_LEFT_ACTION);
packUp.addActionListener(this);
// Pack Select Down
ImageButton packDown = new ImageButton(getIcon("downButton.png", 65, 65));
packDown.setBounds(-7, FRAME_HEIGHT - 65, 65, 65);
packDown.setActionCommand(PACK_RIGHT_ACTION);
packDown.addActionListener(this);
// Progress Bar
progressBar = new LiteProgressBar();
progressBar.setBounds(605, 220, 265, 24);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
progressBar.setFont(minecraft);
// Link background box
RoundedBox linkArea = new RoundedBox(TRANSPARENT);
linkArea.setBounds(605, 250, 265, 120);
// Browse link
JButton browse = new ImageHyperlinkButton("http://beta.technicpack.net");
browse.setFont(minecraft);
browse.setForeground(Color.WHITE);
browse.setToolTipText("Browse More Modpacks");
browse.setText("Browse More Modpacks");
browse.setBounds(linkArea.getX() + 10, linkArea.getY() + 10, 245, 30);
browse.setHorizontalAlignment(SwingConstants.LEFT);
browse.setIcon(getIcon("platformLinkButton.png"));
browse.setBackground(DARK_GREY);
browse.setContentAreaFilled(true);
browse.setIconTextGap(10);
+ browse.setBorderPainted(false);
// Forums link
JButton forums = new ImageHyperlinkButton("http://forums.technicpack.net/");
forums.setFont(minecraft);
forums.setForeground(Color.WHITE);
forums.setToolTipText("Visit the forums");
forums.setText("Visit the Forums");
forums.setBounds(linkArea.getX() + 10, browse.getY() + browse.getHeight() + 5, 245, 30);
forums.setHorizontalAlignment(SwingConstants.LEFT);
forums.setIcon(getIcon("forumsLinkButton.png"));
forums.setBackground(DARK_GREY);
forums.setContentAreaFilled(true);
forums.setIconTextGap(10);
+ forums.setBorderPainted(false);
// Donate link
JButton donate = new ImageHyperlinkButton("http://www.technicpack.net/donate/");
donate.setFont(minecraft);
donate.setForeground(Color.WHITE);
donate.setToolTipText("Donate to the modders");
donate.setText("Donate to the Modders");
donate.setBounds(linkArea.getX() + 10, forums.getY() + forums.getHeight() + 5, 245, 30);
donate.setHorizontalAlignment(SwingConstants.LEFT);
donate.setIcon(getIcon("donateLinkButton.png"));
donate.setBackground(DARK_GREY);
donate.setContentAreaFilled(true);
donate.setIconTextGap(10);
+ donate.setBorderPainted(false);
// Options Button
ImageButton options = new ImageButton(getIcon("gear.png", 28 ,28), getIcon("gearInverted.png", 28, 28));
options.setBounds(FRAME_WIDTH - 34 * 2, 6, 28, 28);
options.setActionCommand(OPTIONS_ACTION);
options.addActionListener(this);
options.addKeyListener(this);
// Pack Options Button
packOptionsBtn = new ImageButton(getIcon("packOptions.png", 20, 21), getIcon("packOptionsInverted.png", 20, 21));
packOptionsBtn.setBounds(25, FRAME_HEIGHT / 2 + 56, 20, 21);
packOptionsBtn.setActionCommand(PACK_OPTIONS_ACTION);
packOptionsBtn.addActionListener(this);
// Platform website button
platform = new ImageHyperlinkButton("http://www.beta.technicpack.net/");
platform.setIcon(getIcon("openPlatformPage.png", 20, 20));
platform.setBounds(50, FRAME_HEIGHT / 2 + 56, 20, 20);
// Pack Remove Button
packRemoveBtn = new ImageButton(getIcon("packDelete.png", 20, 21), getIcon("packDeleteInverted.png", 20, 21));
packRemoveBtn.setBounds(185, FRAME_HEIGHT / 2 + 56, 20, 21);
packRemoveBtn.setActionCommand(PACK_REMOVE_ACTION);
packRemoveBtn.addActionListener(this);
// Exit Button
ImageButton exit = new ImageButton(getIcon("quit.png", 28, 28), getIcon("quitHover.png", 28, 28));
exit.setBounds(FRAME_WIDTH - 34, 6, 28, 28);
exit.setActionCommand(EXIT_ACTION);
exit.addActionListener(this);
// Steam button
JButton steam = new ImageHyperlinkButton("http://steamcommunity.com/groups/technic-pack");
steam.setRolloverIcon(getIcon("steamInverted.png", 28, 28));
steam.setToolTipText("Game with us on Steam");
steam.setBounds(215 + 6, 6, 28, 28);
setIcon(steam, "steam.png", 28);
// Twitter button
JButton twitter = new ImageHyperlinkButton("https://twitter.com/TechnicPack");
twitter.setRolloverIcon(getIcon("twitterInverted.png", 28, 28));
twitter.setToolTipText("Follow us on Twitter");
twitter.setBounds(215 + 6 + 34 * 3, 6, 28, 28);
setIcon(twitter, "twitter.png", 28);
// Facebook button
JButton facebook = new ImageHyperlinkButton("https://www.facebook.com/TechnicPack");
facebook.setRolloverIcon(getIcon("facebookInverted.png", 28, 28));
facebook.setToolTipText("Like us on Facebook");
facebook.setBounds(215 + 6 + 34 * 2, 6, 28, 28);
setIcon(facebook, "facebook.png", 28);
// YouTube button
JButton youtube = new ImageHyperlinkButton("http://www.youtube.com/user/kakermix");
youtube.setRolloverIcon(getIcon("youtubeInverted.png", 28, 28));
youtube.setToolTipText("Subscribe to our videos");
youtube.setBounds(215 + 6 + 34, 6, 28, 28);
setIcon(youtube, "youtube.png", 28);
Container contentPane = getContentPane();
contentPane.setLayout(null);
// Pack Selector
packSelector = new ModpackSelector(this);
packSelector.setBounds(15, 0, 200, 520);
// Custom Pack Name Label
customName = new JLabel("", JLabel.CENTER);
customName.setBounds(FRAME_WIDTH / 2 - (192 /2), FRAME_HEIGHT / 2 + (110 / 2) - 30, 192, 30);
customName.setFont(minecraft.deriveFont(14F));
customName.setVisible(false);
customName.setForeground(Color.white);
// User Faces
java.util.List<String> savedUsers = getSavedUsernames();
int users = Math.min(5, this.getSavedUsernames().size());
for (int i = 0; i < users; i++) {
String accountName = savedUsers.get(i);
String userName = this.getUsername(accountName);
ImageIcon image = getIcon("face.png");
File face = new File(Utils.getAssetsDirectory(), userName + ".png");
if (face.exists()) {
image = new ImageIcon(face.getAbsolutePath());
}
DynamicButton userButton = new DynamicButton(this, image, 1, accountName, userName);
userButton.setFont(minecraft.deriveFont(12F));
userButton.setBounds(FRAME_WIDTH - ((i + 1) * 70), FRAME_HEIGHT - 57, 45, 45);
contentPane.add(userButton);
userButton.setActionCommand(IMAGE_LOGIN_ACTION);
userButton.addActionListener(this);
setIcon(userButton.getRemoveIcon(), "remove.png", 16);
userButton.getRemoveIcon().addActionListener(this);
userButton.getRemoveIcon().setActionCommand(REMOVE_USER);
removeButtons.put(userButton.getRemoveIcon(), userButton);
userButtons.put(userName, userButton);
}
contentPane.add(progressBar);
contentPane.add(packUp);
contentPane.add(packDown);
contentPane.add(customName);
contentPane.add(packOptionsBtn);
contentPane.add(packRemoveBtn);
contentPane.add(platform);
contentPane.add(packSelector);
contentPane.add(selectorBackground);
contentPane.add(name);
contentPane.add(pass);
contentPane.add(remember);
contentPane.add(login);
contentPane.add(steam);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(youtube);
contentPane.add(browse);
contentPane.add(forums);
contentPane.add(donate);
contentPane.add(linkArea);
contentPane.add(logo);
contentPane.add(loginArea);
contentPane.add(options);
contentPane.add(exit);
setFocusTraversalPolicy(new LoginFocusTraversalPolicy());
}
public void setUser(String name) {
if (name != null) {
DynamicButton user = userButtons.get(this.getUsername(name));
if (user != null) {
user.doClick();
}
}
}
public ModpackSelector getSelector() {
return packSelector;
}
public BackgroundImage getBackgroundImage() {
return packBackground;
}
public static ImageIcon getIcon(String iconName) {
return new ImageIcon(Launcher.class.getResource("/org/spoutcraft/launcher/resources/" + iconName));
}
public static ImageIcon getIcon(String iconName, int w, int h) {
try {
return new ImageIcon(ImageUtils.scaleImage(ImageIO.read(ResourceUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/" + iconName)), w, h));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private void setIcon(JButton button, String iconName, int size) {
try {
button.setIcon(new ImageIcon(ImageUtils.scaleImage(ImageIO.read(ResourceUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/" + iconName)), size, size)));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setIcon(JLabel label, String iconName, int w, int h) {
try {
label.setIcon(new ImageIcon(ImageUtils.scaleImage(ImageIO.read(ResourceUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/" + iconName)), w, h)));
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateFaces() {
for (String user : userButtons.keySet()) {
BufferedImage image = getUserImage(user);
if (image != null) {
userButtons.get(user).updateIcon(new ImageIcon(image));
}
}
}
private BufferedImage getUserImage(String user) {
File file = new File(Utils.getAssetsDirectory(), user + ".png");
try {
Download download = DownloadUtils.downloadFile("http://skins.technicpack.net/helm/" + user + "/100", file.getAbsolutePath());
if (download.getResult().equals(Result.SUCCESS)) {
return ImageIO.read(download.getOutFile());
}
} catch (IOException e) {
if (Utils.getStartupParameters().isDebugMode()) {
org.spoutcraft.launcher.api.Launcher.getLogger().log(Level.INFO, "Error downloading user face image: " + user, e);
} else {
org.spoutcraft.launcher.api.Launcher.getLogger().log(Level.INFO, "Error downloading user face image: " + user);
}
}
return null;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JComponent) {
action(e.getActionCommand(), (JComponent)e.getSource());
}
}
private void action(String action, JComponent c) {
if (action.equals(OPTIONS_ACTION)) {
if (launcherOptions == null || !launcherOptions.isVisible()) {
launcherOptions = new LauncherOptions();
launcherOptions.setModal(true);
launcherOptions.setVisible(true);
}
} else if(action.equals(PACK_REMOVE_ACTION)) {
int result = JOptionPane.showConfirmDialog(this, "Are you sure you want to remove this pack?", "Remove Pack", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
getSelector().removePack();
}
} else if (action.equals(PACK_OPTIONS_ACTION)) {
if (packOptions == null || !packOptions.isVisible()) {
packOptions = new ModpackOptions(getSelector().getSelectedPack());
packOptions.setModal(true);
packOptions.setVisible(true);
}
} else if (action.equals(EXIT_ACTION)) {
System.exit(0);
} else if (action.equals(PACK_LEFT_ACTION)) {
getSelector().selectPreviousPack();
} else if (action.equals(PACK_RIGHT_ACTION)) {
getSelector().selectNextPack();
} else if (action.equals(LOGIN_ACTION)) {
PackInfo pack = getSelector().getSelectedPack();
if (pack instanceof AddPack) {
return;
}
// if (pack.getModpack() == null || pack.getModpack().getMinecraftVersion() == null) {
// JOptionPane.showMessageDialog(this, "Error retrieving information for selected pack: " + pack.getDisplayName(), "Error", JOptionPane.WARNING_MESSAGE);
// return;
// }
String pass = new String(this.pass.getPassword());
if (getSelectedUser().length() > 0 && pass.length() > 0) {
lockLoginButton(false);
this.doLogin(getSelectedUser(), pass);
if (remember.isSelected()) {
saveUsername(getSelectedUser(), pass);
Settings.setLastUser(getSelectedUser());
Settings.getYAML().save();
}
}
} else if (action.equals(IMAGE_LOGIN_ACTION)) {
DynamicButton userButton = (DynamicButton)c;
this.name.setText(userButton.getAccount());
this.pass.setText(this.getSavedPassword(userButton.getAccount()));
this.remember.setSelected(true);
pass.setLabelVisible(false);
name.setLabelVisible(false);
} else if (action.equals(REMOVE_USER)) {
DynamicButton userButton = removeButtons.get((JButton)c);
this.removeAccount(userButton.getAccount());
userButton.setVisible(false);
userButton.setEnabled(false);
getContentPane().remove(userButton);
c.setVisible(false);
c.setEnabled(false);
getContentPane().remove(c);
removeButtons.remove(c);
writeUsernameList();
}
}
@Override
public void stateChanged(final String status, final float progress) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int intProgress = Math.round(progress);
progressBar.setValue(intProgress);
String text = status;
if (text.length() > 60) {
text = text.substring(0, 60) + "...";
}
progressBar.setString(intProgress + "% " + text);
}
});
}
@Override
public JProgressBar getProgressBar() {
return progressBar;
}
@Override
public void disableForm() {
}
@Override
public void enableForm() {
}
@Override
public String getSelectedUser() {
return this.name.getText();
}
public ImageButton getPackOptionsBtn() {
return packOptionsBtn;
}
public ImageButton getPackRemoveBtn() {
return packRemoveBtn;
}
public JLabel getPackShadow() {
return packShadow;
}
public JLabel getCustomName() {
return customName;
}
public ImageHyperlinkButton getPlatform() {
return platform;
}
public void enableComponent(JComponent component, boolean enable) {
component.setVisible(enable);
component.setEnabled(enable);
}
public void setCustomName(String packName) {
customName.setText(packName);
}
public void lockLoginButton(boolean unlock) {
if (unlock) {
login.setText("Login");
} else {
login.setText("Launching...");
}
login.setEnabled(unlock);
packRemoveBtn.setEnabled(unlock);
packOptionsBtn.setEnabled(unlock);
}
public Image newBackgroundImage(RestInfo modpack) {
try {
Image image = modpack.getBackground().getScaledInstance(FRAME_WIDTH, FRAME_HEIGHT, Image.SCALE_SMOOTH);
return image;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// Emulates tab focus policy of name -> pass -> remember -> login
private class LoginFocusTraversalPolicy extends FocusTraversalPolicy{
@Override
public Component getComponentAfter(Container con, Component c) {
if (c == name) {
return pass;
} else if (c == pass) {
return remember;
} else if (c == remember) {
return login;
} else if (c == login) {
return name;
}
return getFirstComponent(con);
}
@Override
public Component getComponentBefore(Container con, Component c) {
if (c == name) {
return login;
} else if (c == pass) {
return name;
} else if (c == remember) {
return pass;
} else if (c == login) {
return remember;
}
return getFirstComponent(con);
}
@Override
public Component getFirstComponent(Container c) {
return name;
}
@Override
public Component getLastComponent(Container c) {
return login;
}
@Override
public Component getDefaultComponent(Container c) {
return name;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER){
// Allows the user to press enter and log in from the login box focus, username box focus, or password box focus
if (e.getComponent() == login || e.getComponent() == name || e.getComponent() == pass) {
action(LOGIN_ACTION, (JComponent) e.getComponent());
} else if (e.getComponent() == remember) {
remember.setSelected(!remember.isSelected());
}
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
action(PACK_LEFT_ACTION, null);
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
action(PACK_RIGHT_ACTION, null);
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getWhen() != previous) {
if (e.getUnitsToScroll() > 0) {
getSelector().selectNextPack();
} else if (e.getUnitsToScroll() < 0){
getSelector().selectPreviousPack();
}
this.previous = e.getWhen();
}
}
}
| false | true | private void initComponents() {
Font minecraft = getMinecraftFont(12);
// Login background box
RoundedBox loginArea = new RoundedBox(TRANSPARENT);
loginArea.setBounds(605, 377, 265, 83);
// Setup username box
name = new LiteTextBox(this, "Username...");
name.setBounds(loginArea.getX() + 15, loginArea.getY() + 15, 110, 24);
name.setFont(minecraft);
name.addKeyListener(this);
// Setup password box
pass = new LitePasswordBox(this, "Password...");
pass.setBounds(loginArea.getX() + 15, loginArea.getY() + name.getHeight() + 20, 110, 24);
pass.setFont(minecraft);
pass.addKeyListener(this);
// Setup login button
login = new LiteButton("Launch");
login.setBounds(loginArea.getX() + name.getWidth() + 30, loginArea.getY() + 15, 110, 24);
login.setFont(minecraft);
login.setActionCommand(LOGIN_ACTION);
login.addActionListener(this);
login.addKeyListener(this);
// Setup remember checkbox
remember = new JCheckBox("Remember");
remember.setBounds(loginArea.getX() + name.getWidth() + 30, loginArea.getY() + name.getHeight() + 20, 110, 24);
remember.setFont(minecraft);
remember.setOpaque(false);
remember.setBorderPainted(false);
remember.setFocusPainted(false);
remember.setContentAreaFilled(false);
remember.setBorder(null);
remember.setForeground(Color.WHITE);
remember.setHorizontalTextPosition(SwingConstants.RIGHT);
remember.setIconTextGap(10);
remember.addKeyListener(this);
// Technic logo
JLabel logo = new JLabel();
logo.setBounds(600, -10, 260, 109);
setIcon(logo, "techniclauncher.png", logo.getWidth(), logo.getHeight());
// Pack Selector Background
JLabel selectorBackground = new JLabel();
selectorBackground.setBounds(15, 0, 200, 520);
selectorBackground.setBackground(TRANSPARENT);
selectorBackground.setOpaque(true);
// Pack Select Up
ImageButton packUp = new ImageButton(getIcon("upButton.png", 65, 65));
packUp.setBounds(-7, 0, 65, 65);
packUp.setActionCommand(PACK_LEFT_ACTION);
packUp.addActionListener(this);
// Pack Select Down
ImageButton packDown = new ImageButton(getIcon("downButton.png", 65, 65));
packDown.setBounds(-7, FRAME_HEIGHT - 65, 65, 65);
packDown.setActionCommand(PACK_RIGHT_ACTION);
packDown.addActionListener(this);
// Progress Bar
progressBar = new LiteProgressBar();
progressBar.setBounds(605, 220, 265, 24);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
progressBar.setFont(minecraft);
// Link background box
RoundedBox linkArea = new RoundedBox(TRANSPARENT);
linkArea.setBounds(605, 250, 265, 120);
// Browse link
JButton browse = new ImageHyperlinkButton("http://beta.technicpack.net");
browse.setFont(minecraft);
browse.setForeground(Color.WHITE);
browse.setToolTipText("Browse More Modpacks");
browse.setText("Browse More Modpacks");
browse.setBounds(linkArea.getX() + 10, linkArea.getY() + 10, 245, 30);
browse.setHorizontalAlignment(SwingConstants.LEFT);
browse.setIcon(getIcon("platformLinkButton.png"));
browse.setBackground(DARK_GREY);
browse.setContentAreaFilled(true);
browse.setIconTextGap(10);
// Forums link
JButton forums = new ImageHyperlinkButton("http://forums.technicpack.net/");
forums.setFont(minecraft);
forums.setForeground(Color.WHITE);
forums.setToolTipText("Visit the forums");
forums.setText("Visit the Forums");
forums.setBounds(linkArea.getX() + 10, browse.getY() + browse.getHeight() + 5, 245, 30);
forums.setHorizontalAlignment(SwingConstants.LEFT);
forums.setIcon(getIcon("forumsLinkButton.png"));
forums.setBackground(DARK_GREY);
forums.setContentAreaFilled(true);
forums.setIconTextGap(10);
// Donate link
JButton donate = new ImageHyperlinkButton("http://www.technicpack.net/donate/");
donate.setFont(minecraft);
donate.setForeground(Color.WHITE);
donate.setToolTipText("Donate to the modders");
donate.setText("Donate to the Modders");
donate.setBounds(linkArea.getX() + 10, forums.getY() + forums.getHeight() + 5, 245, 30);
donate.setHorizontalAlignment(SwingConstants.LEFT);
donate.setIcon(getIcon("donateLinkButton.png"));
donate.setBackground(DARK_GREY);
donate.setContentAreaFilled(true);
donate.setIconTextGap(10);
// Options Button
ImageButton options = new ImageButton(getIcon("gear.png", 28 ,28), getIcon("gearInverted.png", 28, 28));
options.setBounds(FRAME_WIDTH - 34 * 2, 6, 28, 28);
options.setActionCommand(OPTIONS_ACTION);
options.addActionListener(this);
options.addKeyListener(this);
// Pack Options Button
packOptionsBtn = new ImageButton(getIcon("packOptions.png", 20, 21), getIcon("packOptionsInverted.png", 20, 21));
packOptionsBtn.setBounds(25, FRAME_HEIGHT / 2 + 56, 20, 21);
packOptionsBtn.setActionCommand(PACK_OPTIONS_ACTION);
packOptionsBtn.addActionListener(this);
// Platform website button
platform = new ImageHyperlinkButton("http://www.beta.technicpack.net/");
platform.setIcon(getIcon("openPlatformPage.png", 20, 20));
platform.setBounds(50, FRAME_HEIGHT / 2 + 56, 20, 20);
// Pack Remove Button
packRemoveBtn = new ImageButton(getIcon("packDelete.png", 20, 21), getIcon("packDeleteInverted.png", 20, 21));
packRemoveBtn.setBounds(185, FRAME_HEIGHT / 2 + 56, 20, 21);
packRemoveBtn.setActionCommand(PACK_REMOVE_ACTION);
packRemoveBtn.addActionListener(this);
// Exit Button
ImageButton exit = new ImageButton(getIcon("quit.png", 28, 28), getIcon("quitHover.png", 28, 28));
exit.setBounds(FRAME_WIDTH - 34, 6, 28, 28);
exit.setActionCommand(EXIT_ACTION);
exit.addActionListener(this);
// Steam button
JButton steam = new ImageHyperlinkButton("http://steamcommunity.com/groups/technic-pack");
steam.setRolloverIcon(getIcon("steamInverted.png", 28, 28));
steam.setToolTipText("Game with us on Steam");
steam.setBounds(215 + 6, 6, 28, 28);
setIcon(steam, "steam.png", 28);
// Twitter button
JButton twitter = new ImageHyperlinkButton("https://twitter.com/TechnicPack");
twitter.setRolloverIcon(getIcon("twitterInverted.png", 28, 28));
twitter.setToolTipText("Follow us on Twitter");
twitter.setBounds(215 + 6 + 34 * 3, 6, 28, 28);
setIcon(twitter, "twitter.png", 28);
// Facebook button
JButton facebook = new ImageHyperlinkButton("https://www.facebook.com/TechnicPack");
facebook.setRolloverIcon(getIcon("facebookInverted.png", 28, 28));
facebook.setToolTipText("Like us on Facebook");
facebook.setBounds(215 + 6 + 34 * 2, 6, 28, 28);
setIcon(facebook, "facebook.png", 28);
// YouTube button
JButton youtube = new ImageHyperlinkButton("http://www.youtube.com/user/kakermix");
youtube.setRolloverIcon(getIcon("youtubeInverted.png", 28, 28));
youtube.setToolTipText("Subscribe to our videos");
youtube.setBounds(215 + 6 + 34, 6, 28, 28);
setIcon(youtube, "youtube.png", 28);
Container contentPane = getContentPane();
contentPane.setLayout(null);
// Pack Selector
packSelector = new ModpackSelector(this);
packSelector.setBounds(15, 0, 200, 520);
// Custom Pack Name Label
customName = new JLabel("", JLabel.CENTER);
customName.setBounds(FRAME_WIDTH / 2 - (192 /2), FRAME_HEIGHT / 2 + (110 / 2) - 30, 192, 30);
customName.setFont(minecraft.deriveFont(14F));
customName.setVisible(false);
customName.setForeground(Color.white);
// User Faces
java.util.List<String> savedUsers = getSavedUsernames();
int users = Math.min(5, this.getSavedUsernames().size());
for (int i = 0; i < users; i++) {
String accountName = savedUsers.get(i);
String userName = this.getUsername(accountName);
ImageIcon image = getIcon("face.png");
File face = new File(Utils.getAssetsDirectory(), userName + ".png");
if (face.exists()) {
image = new ImageIcon(face.getAbsolutePath());
}
DynamicButton userButton = new DynamicButton(this, image, 1, accountName, userName);
userButton.setFont(minecraft.deriveFont(12F));
userButton.setBounds(FRAME_WIDTH - ((i + 1) * 70), FRAME_HEIGHT - 57, 45, 45);
contentPane.add(userButton);
userButton.setActionCommand(IMAGE_LOGIN_ACTION);
userButton.addActionListener(this);
setIcon(userButton.getRemoveIcon(), "remove.png", 16);
userButton.getRemoveIcon().addActionListener(this);
userButton.getRemoveIcon().setActionCommand(REMOVE_USER);
removeButtons.put(userButton.getRemoveIcon(), userButton);
userButtons.put(userName, userButton);
}
contentPane.add(progressBar);
contentPane.add(packUp);
contentPane.add(packDown);
contentPane.add(customName);
contentPane.add(packOptionsBtn);
contentPane.add(packRemoveBtn);
contentPane.add(platform);
contentPane.add(packSelector);
contentPane.add(selectorBackground);
contentPane.add(name);
contentPane.add(pass);
contentPane.add(remember);
contentPane.add(login);
contentPane.add(steam);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(youtube);
contentPane.add(browse);
contentPane.add(forums);
contentPane.add(donate);
contentPane.add(linkArea);
contentPane.add(logo);
contentPane.add(loginArea);
contentPane.add(options);
contentPane.add(exit);
setFocusTraversalPolicy(new LoginFocusTraversalPolicy());
}
| private void initComponents() {
Font minecraft = getMinecraftFont(12);
// Login background box
RoundedBox loginArea = new RoundedBox(TRANSPARENT);
loginArea.setBounds(605, 377, 265, 83);
// Setup username box
name = new LiteTextBox(this, "Username...");
name.setBounds(loginArea.getX() + 15, loginArea.getY() + 15, 110, 24);
name.setFont(minecraft);
name.addKeyListener(this);
// Setup password box
pass = new LitePasswordBox(this, "Password...");
pass.setBounds(loginArea.getX() + 15, loginArea.getY() + name.getHeight() + 20, 110, 24);
pass.setFont(minecraft);
pass.addKeyListener(this);
// Setup login button
login = new LiteButton("Launch");
login.setBounds(loginArea.getX() + name.getWidth() + 30, loginArea.getY() + 15, 110, 24);
login.setFont(minecraft);
login.setActionCommand(LOGIN_ACTION);
login.addActionListener(this);
login.addKeyListener(this);
// Setup remember checkbox
remember = new JCheckBox("Remember");
remember.setBounds(loginArea.getX() + name.getWidth() + 30, loginArea.getY() + name.getHeight() + 20, 110, 24);
remember.setFont(minecraft);
remember.setOpaque(false);
remember.setBorderPainted(false);
remember.setFocusPainted(false);
remember.setContentAreaFilled(false);
remember.setBorder(null);
remember.setForeground(Color.WHITE);
remember.setHorizontalTextPosition(SwingConstants.RIGHT);
remember.setIconTextGap(10);
remember.addKeyListener(this);
// Technic logo
JLabel logo = new JLabel();
logo.setBounds(600, -10, 260, 109);
setIcon(logo, "techniclauncher.png", logo.getWidth(), logo.getHeight());
// Pack Selector Background
JLabel selectorBackground = new JLabel();
selectorBackground.setBounds(15, 0, 200, 520);
selectorBackground.setBackground(TRANSPARENT);
selectorBackground.setOpaque(true);
// Pack Select Up
ImageButton packUp = new ImageButton(getIcon("upButton.png", 65, 65));
packUp.setBounds(-7, 0, 65, 65);
packUp.setActionCommand(PACK_LEFT_ACTION);
packUp.addActionListener(this);
// Pack Select Down
ImageButton packDown = new ImageButton(getIcon("downButton.png", 65, 65));
packDown.setBounds(-7, FRAME_HEIGHT - 65, 65, 65);
packDown.setActionCommand(PACK_RIGHT_ACTION);
packDown.addActionListener(this);
// Progress Bar
progressBar = new LiteProgressBar();
progressBar.setBounds(605, 220, 265, 24);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
progressBar.setFont(minecraft);
// Link background box
RoundedBox linkArea = new RoundedBox(TRANSPARENT);
linkArea.setBounds(605, 250, 265, 120);
// Browse link
JButton browse = new ImageHyperlinkButton("http://beta.technicpack.net");
browse.setFont(minecraft);
browse.setForeground(Color.WHITE);
browse.setToolTipText("Browse More Modpacks");
browse.setText("Browse More Modpacks");
browse.setBounds(linkArea.getX() + 10, linkArea.getY() + 10, 245, 30);
browse.setHorizontalAlignment(SwingConstants.LEFT);
browse.setIcon(getIcon("platformLinkButton.png"));
browse.setBackground(DARK_GREY);
browse.setContentAreaFilled(true);
browse.setIconTextGap(10);
browse.setBorderPainted(false);
// Forums link
JButton forums = new ImageHyperlinkButton("http://forums.technicpack.net/");
forums.setFont(minecraft);
forums.setForeground(Color.WHITE);
forums.setToolTipText("Visit the forums");
forums.setText("Visit the Forums");
forums.setBounds(linkArea.getX() + 10, browse.getY() + browse.getHeight() + 5, 245, 30);
forums.setHorizontalAlignment(SwingConstants.LEFT);
forums.setIcon(getIcon("forumsLinkButton.png"));
forums.setBackground(DARK_GREY);
forums.setContentAreaFilled(true);
forums.setIconTextGap(10);
forums.setBorderPainted(false);
// Donate link
JButton donate = new ImageHyperlinkButton("http://www.technicpack.net/donate/");
donate.setFont(minecraft);
donate.setForeground(Color.WHITE);
donate.setToolTipText("Donate to the modders");
donate.setText("Donate to the Modders");
donate.setBounds(linkArea.getX() + 10, forums.getY() + forums.getHeight() + 5, 245, 30);
donate.setHorizontalAlignment(SwingConstants.LEFT);
donate.setIcon(getIcon("donateLinkButton.png"));
donate.setBackground(DARK_GREY);
donate.setContentAreaFilled(true);
donate.setIconTextGap(10);
donate.setBorderPainted(false);
// Options Button
ImageButton options = new ImageButton(getIcon("gear.png", 28 ,28), getIcon("gearInverted.png", 28, 28));
options.setBounds(FRAME_WIDTH - 34 * 2, 6, 28, 28);
options.setActionCommand(OPTIONS_ACTION);
options.addActionListener(this);
options.addKeyListener(this);
// Pack Options Button
packOptionsBtn = new ImageButton(getIcon("packOptions.png", 20, 21), getIcon("packOptionsInverted.png", 20, 21));
packOptionsBtn.setBounds(25, FRAME_HEIGHT / 2 + 56, 20, 21);
packOptionsBtn.setActionCommand(PACK_OPTIONS_ACTION);
packOptionsBtn.addActionListener(this);
// Platform website button
platform = new ImageHyperlinkButton("http://www.beta.technicpack.net/");
platform.setIcon(getIcon("openPlatformPage.png", 20, 20));
platform.setBounds(50, FRAME_HEIGHT / 2 + 56, 20, 20);
// Pack Remove Button
packRemoveBtn = new ImageButton(getIcon("packDelete.png", 20, 21), getIcon("packDeleteInverted.png", 20, 21));
packRemoveBtn.setBounds(185, FRAME_HEIGHT / 2 + 56, 20, 21);
packRemoveBtn.setActionCommand(PACK_REMOVE_ACTION);
packRemoveBtn.addActionListener(this);
// Exit Button
ImageButton exit = new ImageButton(getIcon("quit.png", 28, 28), getIcon("quitHover.png", 28, 28));
exit.setBounds(FRAME_WIDTH - 34, 6, 28, 28);
exit.setActionCommand(EXIT_ACTION);
exit.addActionListener(this);
// Steam button
JButton steam = new ImageHyperlinkButton("http://steamcommunity.com/groups/technic-pack");
steam.setRolloverIcon(getIcon("steamInverted.png", 28, 28));
steam.setToolTipText("Game with us on Steam");
steam.setBounds(215 + 6, 6, 28, 28);
setIcon(steam, "steam.png", 28);
// Twitter button
JButton twitter = new ImageHyperlinkButton("https://twitter.com/TechnicPack");
twitter.setRolloverIcon(getIcon("twitterInverted.png", 28, 28));
twitter.setToolTipText("Follow us on Twitter");
twitter.setBounds(215 + 6 + 34 * 3, 6, 28, 28);
setIcon(twitter, "twitter.png", 28);
// Facebook button
JButton facebook = new ImageHyperlinkButton("https://www.facebook.com/TechnicPack");
facebook.setRolloverIcon(getIcon("facebookInverted.png", 28, 28));
facebook.setToolTipText("Like us on Facebook");
facebook.setBounds(215 + 6 + 34 * 2, 6, 28, 28);
setIcon(facebook, "facebook.png", 28);
// YouTube button
JButton youtube = new ImageHyperlinkButton("http://www.youtube.com/user/kakermix");
youtube.setRolloverIcon(getIcon("youtubeInverted.png", 28, 28));
youtube.setToolTipText("Subscribe to our videos");
youtube.setBounds(215 + 6 + 34, 6, 28, 28);
setIcon(youtube, "youtube.png", 28);
Container contentPane = getContentPane();
contentPane.setLayout(null);
// Pack Selector
packSelector = new ModpackSelector(this);
packSelector.setBounds(15, 0, 200, 520);
// Custom Pack Name Label
customName = new JLabel("", JLabel.CENTER);
customName.setBounds(FRAME_WIDTH / 2 - (192 /2), FRAME_HEIGHT / 2 + (110 / 2) - 30, 192, 30);
customName.setFont(minecraft.deriveFont(14F));
customName.setVisible(false);
customName.setForeground(Color.white);
// User Faces
java.util.List<String> savedUsers = getSavedUsernames();
int users = Math.min(5, this.getSavedUsernames().size());
for (int i = 0; i < users; i++) {
String accountName = savedUsers.get(i);
String userName = this.getUsername(accountName);
ImageIcon image = getIcon("face.png");
File face = new File(Utils.getAssetsDirectory(), userName + ".png");
if (face.exists()) {
image = new ImageIcon(face.getAbsolutePath());
}
DynamicButton userButton = new DynamicButton(this, image, 1, accountName, userName);
userButton.setFont(minecraft.deriveFont(12F));
userButton.setBounds(FRAME_WIDTH - ((i + 1) * 70), FRAME_HEIGHT - 57, 45, 45);
contentPane.add(userButton);
userButton.setActionCommand(IMAGE_LOGIN_ACTION);
userButton.addActionListener(this);
setIcon(userButton.getRemoveIcon(), "remove.png", 16);
userButton.getRemoveIcon().addActionListener(this);
userButton.getRemoveIcon().setActionCommand(REMOVE_USER);
removeButtons.put(userButton.getRemoveIcon(), userButton);
userButtons.put(userName, userButton);
}
contentPane.add(progressBar);
contentPane.add(packUp);
contentPane.add(packDown);
contentPane.add(customName);
contentPane.add(packOptionsBtn);
contentPane.add(packRemoveBtn);
contentPane.add(platform);
contentPane.add(packSelector);
contentPane.add(selectorBackground);
contentPane.add(name);
contentPane.add(pass);
contentPane.add(remember);
contentPane.add(login);
contentPane.add(steam);
contentPane.add(twitter);
contentPane.add(facebook);
contentPane.add(youtube);
contentPane.add(browse);
contentPane.add(forums);
contentPane.add(donate);
contentPane.add(linkArea);
contentPane.add(logo);
contentPane.add(loginArea);
contentPane.add(options);
contentPane.add(exit);
setFocusTraversalPolicy(new LoginFocusTraversalPolicy());
}
|
diff --git a/src/com/bbcnewsreader/ArticleActivity.java b/src/com/bbcnewsreader/ArticleActivity.java
index 6d17abd..384c446 100644
--- a/src/com/bbcnewsreader/ArticleActivity.java
+++ b/src/com/bbcnewsreader/ArticleActivity.java
@@ -1,14 +1,15 @@
package com.bbcnewsreader;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class ArticleActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
WebView webView = (WebView)findViewById(R.id.articleWebView);
+ webView.getUrl();
//webView.loadUrl("http://www.google.com");
}
}
| true | true | public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
WebView webView = (WebView)findViewById(R.id.articleWebView);
//webView.loadUrl("http://www.google.com");
}
| public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
WebView webView = (WebView)findViewById(R.id.articleWebView);
webView.getUrl();
//webView.loadUrl("http://www.google.com");
}
|
diff --git a/javasrc/src/org/ccnx/ccn/test/repo/RFSTest.java b/javasrc/src/org/ccnx/ccn/test/repo/RFSTest.java
index 323d829f3..d9b691d43 100644
--- a/javasrc/src/org/ccnx/ccn/test/repo/RFSTest.java
+++ b/javasrc/src/org/ccnx/ccn/test/repo/RFSTest.java
@@ -1,395 +1,397 @@
/**
* A CCNx library test.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package org.ccnx.ccn.test.repo;
import java.io.File;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import org.ccnx.ccn.impl.repo.LogStructRepoStore;
import org.ccnx.ccn.impl.repo.RepositoryException;
import org.ccnx.ccn.impl.repo.RepositoryStore;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.profiles.CommandMarkers;
import org.ccnx.ccn.profiles.SegmentationProfile;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.KeyLocator;
import org.ccnx.ccn.protocol.PublisherID;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test repository backend implementation(s) using filesystem (FS) as stable storage. In principle,
* there could be multiple FS-backed implementations exercised by these tests.
*
* Because it uses the default KeyManager, this test must be run
* with ccnd running.
*
*/
public class RFSTest extends RepoTestBase {
RepositoryStore repolog; // Instance of simple log-based repo implementation under test
private ContentName longName;
private byte[] longNameDigest;
private ContentName badCharName;
private ContentName badCharLongName;
private ContentName versionedName;
private ContentName segmentedName1;
private ContentName segmentedName223;
private ContentName versionedNameNormal;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
RepoTestBase.setUpBeforeClass();
_fileTest = new File(_fileTestDir);
DataUtils.deleteDirectory(_fileTest);
_fileTest.mkdirs();
}
@Before
public void setUp() throws Exception {
super.setUp();
initRepoLog();
}
public void initRepoLog() throws Exception {
repolog = new LogStructRepoStore();
repolog.initialize(_fileTestDir, null, _repoName, _globalPrefix, null, null);
}
@Test
public void testRepo() throws Exception {
System.out.println("testing repo (log-structured implementation)");
test(repolog);
initRepoLog();
// Having initialized a new instance on the same stable storage stage produced by the
// test() method, now run testReinitialization to check consistency.
testReinitialization(repolog);
}
public void test(RepositoryStore repo) throws Exception{
System.out.println("Repotest - Testing basic data");
ContentName name = ContentName.fromNative("/repoTest/data1");
ContentObject content = ContentObject.buildContentObject(name, "Here's my data!".getBytes());
repo.saveContent(content);
checkData(repo, name, "Here's my data!");
// TODO - Don't know how to check that multiple data doesn't result in multiple copies
// Do it just to make sure the mechanism doesn't break (but result is not tested).
repo.saveContent(content);
System.out.println("Repotest - Testing multiple digests for same data");
ContentObject digest2 = ContentObject.buildContentObject(name, "Testing2".getBytes());
repo.saveContent(digest2);
ContentName digestName = new ContentName(name, digest2.digest());
checkDataWithDigest(repo, digestName, "Testing2");
System.out.println("Repotest - Testing same digest for different data and/or publisher");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512); // go for fast
KeyPair pair1 = kpg.generateKeyPair();
PublisherPublicKeyDigest pubKey1 = new PublisherPublicKeyDigest(pair1.getPublic());
KeyLocator kl = new KeyLocator(new ContentName(keyprefix, pubKey1.digest()));
repo.saveContent(ContentObject.buildContentObject(kl.name().name(), pubKey1.digest()));
SignedInfo si = new SignedInfo(pubKey1, kl);
ContentObject digestSame1 = new ContentObject(name, si, "Testing2".getBytes(), pair1.getPrivate());
repo.saveContent(digestSame1);
KeyPair pair2 = kpg.generateKeyPair();
PublisherPublicKeyDigest pubKey2 = new PublisherPublicKeyDigest(pair2.getPublic());
kl = new KeyLocator(new ContentName(keyprefix, pubKey2.digest()));
repo.saveContent(ContentObject.buildContentObject(kl.name().name(), pubKey2.digest()));
si = new SignedInfo(pubKey2, kl);
ContentObject digestSame2 = new ContentObject(name, si, "Testing2".getBytes(), pair2.getPrivate());
repo.saveContent(digestSame2);
checkDataAndPublisher(repo, name, "Testing2", pubKey1);
checkDataAndPublisher(repo, name, "Testing2", pubKey2);
System.out.println("Repotest - Testing too long data");
String tooLongName = "0123456789";
for (int i = 0; i < 30; i++)
tooLongName += "0123456789";
longName = ContentName.fromNative("/repoTest/" + tooLongName);
ContentObject co = ContentObject.buildContentObject(longName, "Long name!".getBytes());
longNameDigest = co.digest();
repo.saveContent(co);
checkData(repo, longName, "Long name!");
digest2 = ContentObject.buildContentObject(longName, "Testing2".getBytes());
repo.saveContent(digest2);
digestName = new ContentName(longName, digest2.digest());
checkDataWithDigest(repo, digestName, "Testing2");
String wayTooLongName = tooLongName;
for (int i = 0; i < 30; i++)
wayTooLongName += "0123456789";
ContentName reallyLongName = ContentName.fromNative("/repoTest/" + wayTooLongName);
repo.saveContent(ContentObject.buildContentObject(reallyLongName, "Really Long name!".getBytes()));
checkData(repo, reallyLongName, "Really Long name!");
byte[][] longNonASCIIBytes = new byte[2][];
longNonASCIIBytes[0] = "repoTest".getBytes();
longNonASCIIBytes[1] = new byte[300];
for (int i = 0; i < 30; i++) {
rand.nextBytes(longNonASCIIBytes[1]);
ContentName lnab = new ContentName(longNonASCIIBytes);
repo.saveContent(ContentObject.buildContentObject(lnab, ("Long and Non ASCII " + i).getBytes()));
checkData(repo, lnab, "Long and Non ASCII " + i);
}
System.out.println("Repotest - Testing invalid characters in name");
badCharName = ContentName.fromNative("/repoTest/" + "*x?y<z>u");
repo.saveContent(ContentObject.buildContentObject(badCharName, "Funny characters!".getBytes()));
checkData(repo, badCharName, "Funny characters!");
badCharLongName = ContentName.fromNative("/repoTest/" + tooLongName + "*x?y<z>u");
repo.saveContent(ContentObject.buildContentObject(badCharLongName, "Long and funny".getBytes()));
checkData(repo, badCharLongName, "Long and funny");
System.out.println("Repotest - Testing different kinds of interests");
ContentName name1 = ContentName.fromNative("/repoTest/nextTest/aaa");
ContentObject content1 = ContentObject.buildContentObject(name1, "aaa".getBytes());
repo.saveContent(content1);
ContentName name2 = ContentName.fromNative("/repoTest/nextTest/bbb");
repo.saveContent(ContentObject.buildContentObject(name2, "bbb".getBytes()));
ContentName name3= ContentName.fromNative("/repoTest/nextTest/ccc");
repo.saveContent(ContentObject.buildContentObject(name3, "ccc".getBytes()));
ContentName name4= ContentName.fromNative("/repoTest/nextTest/ddd");
repo.saveContent(ContentObject.buildContentObject(name4, "ddd".getBytes()));
ContentName name5= ContentName.fromNative("/repoTest/nextTest/eee");
repo.saveContent(ContentObject.buildContentObject(name5, "eee".getBytes()));
checkData(repo, Interest.next(new ContentName(name1, content1.digest()), 2, null), "bbb");
checkData(repo, Interest.last(new ContentName(name1, content1.digest()), 2, null), "eee");
checkData(repo, Interest.next(new ContentName(name1, content1.digest()),
new Exclude(new byte [][] {"bbb".getBytes(), "ccc".getBytes()}), 2, null, null, null), "ddd");
System.out.println("Repotest - Testing different kinds of interests in a mixture of encoded/standard data");
ContentName nonLongName = ContentName.fromNative("/repoTestLong/nextTestLong/aaa");
ContentObject nonLongContent = ContentObject.buildContentObject(nonLongName, "aaa".getBytes());
repo.saveContent(nonLongContent);
ContentName longName2 = ContentName.fromNative("/repoTestLong/nextTestLong/bbb/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName2, "bbb".getBytes()));
ContentName nonLongName2 = ContentName.fromNative("/repoTestLong/nextTestLong/ccc");
repo.saveContent(ContentObject.buildContentObject(nonLongName2, "ccc".getBytes()));
ContentName longName3 = ContentName.fromNative("/repoTestLong/nextTestLong/ddd/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName3, "ddd".getBytes()));
ContentName longName4 = ContentName.fromNative("/repoTestLong/nextTestLong/eee/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName4, "eee".getBytes()));
checkData(repo, Interest.next(new ContentName(nonLongName, nonLongContent.digest()), 2, null), "bbb");
checkData(repo, Interest.last(new ContentName(nonLongName, nonLongContent.digest()), 2, null), "eee");
checkData(repo, Interest.next(new ContentName(nonLongName, nonLongContent.digest()),
new Exclude(new byte [][] {"bbb".getBytes(), "ccc".getBytes()}), 2, null, null, null), "ddd");
System.out.println("Repotest - testing version and segment files");
versionedName = ContentName.fromNative("/repoTest/testVersion");
versionedName = VersioningProfile.addVersion(versionedName);
repo.saveContent(ContentObject.buildContentObject(versionedName, "version".getBytes()));
checkData(repo, versionedName, "version");
segmentedName1 = SegmentationProfile.segmentName(versionedName, 1);
repo.saveContent(ContentObject.buildContentObject(segmentedName1, "segment1".getBytes()));
checkData(repo, segmentedName1, "segment1");
segmentedName223 = SegmentationProfile.segmentName(versionedName, 223);
repo.saveContent(ContentObject.buildContentObject(segmentedName223, "segment223".getBytes()));
checkData(repo, segmentedName223, "segment223");
System.out.println("Repotest - storing sequence of objects for versioned stream read testing");
versionedNameNormal = ContentName.fromNative("/testNameSpace/testVersionNormal");
versionedNameNormal = VersioningProfile.addVersion(versionedNameNormal);
repo.saveContent(ContentObject.buildContentObject(versionedNameNormal, "version-normal".getBytes()));
checkData(repo, versionedNameNormal, "version-normal");
byte[] finalBlockID = SegmentationProfile.getSegmentNumberNameComponent(4);
for (Long i=SegmentationProfile.baseSegment(); i<5; i++) {
ContentName segmented = SegmentationProfile.segmentName(versionedNameNormal, i);
String segmentContent = "segment"+ new Long(i).toString();
repo.saveContent(ContentObject.buildContentObject(segmented, segmentContent.getBytes(), null, null, finalBlockID));
checkData(repo, segmented, segmentContent);
}
System.out.println("Repotest - testing min and max in retrieval");
ContentName shortName = ContentName.fromNative("/repoTest/1/2");
ContentName longName = ContentName.fromNative("/repoTest/1/2/3/4/5/6");
ContentName middleName = ContentName.fromNative("/repoTest/1/2/3/4");
repo.saveContent(ContentObject.buildContentObject(shortName, "short".getBytes()));
repo.saveContent(ContentObject.buildContentObject(longName, "long".getBytes()));
repo.saveContent(ContentObject.buildContentObject(middleName, "middle".getBytes()));
Interest minInterest = new Interest(ContentName.fromNative("/repoTest/1"));
minInterest.minSuffixComponents(4);
checkData(repo, minInterest, "long");
Interest maxInterest = new Interest(ContentName.fromNative("/repoTest/1"));
maxInterest.maxSuffixComponents(3);
checkData(repo, maxInterest, "short");
Interest middleInterest = new Interest(ContentName.fromNative("/repoTest/1"));
middleInterest.maxSuffixComponents(4);
middleInterest.minSuffixComponents(3);
checkData(repo, middleInterest, "middle");
//adding in fast name enumeration response tests
System.out.println("Repotest - testing fast name enumeration response");
//building names for tests
ContentName nerpre = ContentName.fromNative("/testFastNameEnumeration");
ContentName ner = new ContentName(nerpre, "name1".getBytes());
ContentName nername1 = ContentName.fromNative("/name1");
ContentName ner2 = new ContentName(nerpre, "name2".getBytes());
ContentName nername2 = ContentName.fromNative("/name2");
ContentName ner3 = new ContentName(nerpre, "longer".getBytes());
ner3 = new ContentName(ner3, "name3".getBytes());
ContentName nername3 = ContentName.fromNative("/longer");
NameEnumerationResponse neresponse = null;
//send initial interest to make sure namespace is empty
//interest flag will not be set for a fast response since there isn't anything in the index yet
Interest interest = new Interest(new ContentName(nerpre, CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
ContentName responseName = new ContentName();
Log.info("RFSTEST: Name enumeration prefix:{0}", interest.name());
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse == null || neresponse.hasNames()==false);
//now saving the first piece of content in the repo. interest flag not set, so it should not get an object back
neresponse = repo.saveContent(ContentObject.buildContentObject(ner, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse==null || neresponse.hasNames()==false);
//now checking with the prefix that the first name is in
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
//now call get names with prefix again to set interest flag
//have to use the version from the last response (or at least a version after the last write
interest = Interest.last(VersioningProfile.addVersion(neresponse.getPrefix(), neresponse.getTimestamp()), null, null);
//the response should be null and the flag set
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse==null || neresponse.hasNames()==false);
//save content. if the flag was set, we should get an enumeration response
neresponse = repo.saveContent(ContentObject.buildContentObject(ner2, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getNames().contains(nername2));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
//need to reconstruct the interest again
interest = Interest.last(VersioningProfile.addVersion(neresponse.getPrefix(), neresponse.getTimestamp()), null, null);
//another interest to set interest flag, response should be null
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse == null || neresponse.hasNames()==false);
//interest flag should now be set, so when i add something - this is a longer name, i should be handed back an object
neresponse = repo.saveContent(ContentObject.buildContentObject(ner3, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getNames().contains(nername2));
Assert.assertTrue(neresponse.getNames().contains(nername3));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
repo.shutDown();
}
public void testReinitialization(RepositoryStore repo) throws Exception {
System.out.println("Repotest - Testing reinitialization of repo");
// Since we have 2 pieces of data with the name "longName" we need to compute the
// digest to make sure we get the right data.
longName = new ContentName(longName, longNameDigest);
checkDataWithDigest(repo, longName, "Long name!");
checkData(repo, badCharName, "Funny characters!");
checkData(repo, badCharLongName, "Long and funny");
Interest vnInterest = new Interest(versionedName);
vnInterest.maxSuffixComponents(1);
checkData(repo, vnInterest, "version");
checkData(repo, segmentedName1, "segment1");
checkData(repo, segmentedName223, "segment223");
vnInterest = new Interest(versionedNameNormal);
vnInterest.maxSuffixComponents(1);
checkData(repo, vnInterest, "version-normal");
for (Long i=SegmentationProfile.baseSegment(); i<5; i++) {
ContentName segmented = SegmentationProfile.segmentName(versionedNameNormal, i);
String segmentContent = "segment"+ new Long(i).toString();
checkData(repo, segmented, segmentContent);
}
}
@Test
public void testPolicy() throws Exception {
+ // Writes all this content signed with the repository's key
RepositoryStore repo = new LogStructRepoStore();
try { // Test no version
repo.initialize(_fileTestDir, new File(_topdir + "/org/ccnx/ccn/test/repo/badPolicyTest1.xml"), null, null, null, null);
Assert.fail("Bad policy file succeeded");
} catch (RepositoryException re) {}
try { // Test bad version
repo.initialize(_fileTestDir, new File(_topdir + "/org/ccnx/ccn/test/repo/badPolicyTest2.xml"), null, null, null, null);
Assert.fail("Bad policy file succeeded");
} catch (RepositoryException re) {}
+ // Make repository using repo's keystore, not user's
repo.initialize(_fileTestDir,
- new File(_topdir + "/org/ccnx/ccn/test/repo/policyTest.xml"), _repoName, _globalPrefix, null, putHandle);
+ new File(_topdir + "/org/ccnx/ccn/test/repo/policyTest.xml"), _repoName, _globalPrefix, null, null);
ContentName name = ContentName.fromNative("/testNameSpace/data1");
ContentObject content = ContentObject.buildContentObject(name, "Here's my data!".getBytes());
repo.saveContent(content);
checkData(repo, name, "Here's my data!");
ContentName outOfNameSpaceName = ContentName.fromNative("/anotherNameSpace/data1");
ContentObject oonsContent = ContentObject.buildContentObject(outOfNameSpaceName, "Shouldn't see this".getBytes());
repo.saveContent(oonsContent);
ContentObject testContent = repo.getContent(new Interest(outOfNameSpaceName));
Assert.assertTrue(testContent == null);
// Test reading policy file from the repo
repolog.initialize(_fileTestDir, null, _repoName, _globalPrefix, null, null);
repo.saveContent(oonsContent);
ContentObject testContentAgain = repo.getContent(new Interest(outOfNameSpaceName));
Assert.assertTrue(testContentAgain == null);
// Test setting prefix from the prefix parameter
repo.initialize(_fileTestDir, null, _repoName, _globalPrefix, "/", null);
repo.saveContent(oonsContent);
checkData(repo, outOfNameSpaceName, "Shouldn't see this");
}
private void checkData(RepositoryStore repo, ContentName name, String data) throws RepositoryException {
checkData(repo, new Interest(name), data);
}
private void checkDataWithDigest(RepositoryStore repo, ContentName name, String data) throws RepositoryException {
// When generating an Interest for the exact name with content digest, need to set maxSuffixComponents
// to 0, signifying that name ends with explicit digest
Interest interest = new Interest(name);
interest.maxSuffixComponents(0);
checkData(repo, interest, data);
}
private void checkData(RepositoryStore repo, Interest interest, String data) throws RepositoryException {
ContentObject testContent = repo.getContent(interest);
Assert.assertFalse(testContent == null);
Assert.assertEquals(data, new String(testContent.content()));
}
private void checkDataAndPublisher(RepositoryStore repo, ContentName name, String data, PublisherPublicKeyDigest publisher)
throws RepositoryException {
Interest interest = new Interest(name, new PublisherID(publisher));
ContentObject testContent = repo.getContent(interest);
Assert.assertFalse(testContent == null);
Assert.assertEquals(data, new String(testContent.content()));
Assert.assertTrue(testContent.signedInfo().getPublisherKeyID().equals(publisher));
}
}
| false | true | public void test(RepositoryStore repo) throws Exception{
System.out.println("Repotest - Testing basic data");
ContentName name = ContentName.fromNative("/repoTest/data1");
ContentObject content = ContentObject.buildContentObject(name, "Here's my data!".getBytes());
repo.saveContent(content);
checkData(repo, name, "Here's my data!");
// TODO - Don't know how to check that multiple data doesn't result in multiple copies
// Do it just to make sure the mechanism doesn't break (but result is not tested).
repo.saveContent(content);
System.out.println("Repotest - Testing multiple digests for same data");
ContentObject digest2 = ContentObject.buildContentObject(name, "Testing2".getBytes());
repo.saveContent(digest2);
ContentName digestName = new ContentName(name, digest2.digest());
checkDataWithDigest(repo, digestName, "Testing2");
System.out.println("Repotest - Testing same digest for different data and/or publisher");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512); // go for fast
KeyPair pair1 = kpg.generateKeyPair();
PublisherPublicKeyDigest pubKey1 = new PublisherPublicKeyDigest(pair1.getPublic());
KeyLocator kl = new KeyLocator(new ContentName(keyprefix, pubKey1.digest()));
repo.saveContent(ContentObject.buildContentObject(kl.name().name(), pubKey1.digest()));
SignedInfo si = new SignedInfo(pubKey1, kl);
ContentObject digestSame1 = new ContentObject(name, si, "Testing2".getBytes(), pair1.getPrivate());
repo.saveContent(digestSame1);
KeyPair pair2 = kpg.generateKeyPair();
PublisherPublicKeyDigest pubKey2 = new PublisherPublicKeyDigest(pair2.getPublic());
kl = new KeyLocator(new ContentName(keyprefix, pubKey2.digest()));
repo.saveContent(ContentObject.buildContentObject(kl.name().name(), pubKey2.digest()));
si = new SignedInfo(pubKey2, kl);
ContentObject digestSame2 = new ContentObject(name, si, "Testing2".getBytes(), pair2.getPrivate());
repo.saveContent(digestSame2);
checkDataAndPublisher(repo, name, "Testing2", pubKey1);
checkDataAndPublisher(repo, name, "Testing2", pubKey2);
System.out.println("Repotest - Testing too long data");
String tooLongName = "0123456789";
for (int i = 0; i < 30; i++)
tooLongName += "0123456789";
longName = ContentName.fromNative("/repoTest/" + tooLongName);
ContentObject co = ContentObject.buildContentObject(longName, "Long name!".getBytes());
longNameDigest = co.digest();
repo.saveContent(co);
checkData(repo, longName, "Long name!");
digest2 = ContentObject.buildContentObject(longName, "Testing2".getBytes());
repo.saveContent(digest2);
digestName = new ContentName(longName, digest2.digest());
checkDataWithDigest(repo, digestName, "Testing2");
String wayTooLongName = tooLongName;
for (int i = 0; i < 30; i++)
wayTooLongName += "0123456789";
ContentName reallyLongName = ContentName.fromNative("/repoTest/" + wayTooLongName);
repo.saveContent(ContentObject.buildContentObject(reallyLongName, "Really Long name!".getBytes()));
checkData(repo, reallyLongName, "Really Long name!");
byte[][] longNonASCIIBytes = new byte[2][];
longNonASCIIBytes[0] = "repoTest".getBytes();
longNonASCIIBytes[1] = new byte[300];
for (int i = 0; i < 30; i++) {
rand.nextBytes(longNonASCIIBytes[1]);
ContentName lnab = new ContentName(longNonASCIIBytes);
repo.saveContent(ContentObject.buildContentObject(lnab, ("Long and Non ASCII " + i).getBytes()));
checkData(repo, lnab, "Long and Non ASCII " + i);
}
System.out.println("Repotest - Testing invalid characters in name");
badCharName = ContentName.fromNative("/repoTest/" + "*x?y<z>u");
repo.saveContent(ContentObject.buildContentObject(badCharName, "Funny characters!".getBytes()));
checkData(repo, badCharName, "Funny characters!");
badCharLongName = ContentName.fromNative("/repoTest/" + tooLongName + "*x?y<z>u");
repo.saveContent(ContentObject.buildContentObject(badCharLongName, "Long and funny".getBytes()));
checkData(repo, badCharLongName, "Long and funny");
System.out.println("Repotest - Testing different kinds of interests");
ContentName name1 = ContentName.fromNative("/repoTest/nextTest/aaa");
ContentObject content1 = ContentObject.buildContentObject(name1, "aaa".getBytes());
repo.saveContent(content1);
ContentName name2 = ContentName.fromNative("/repoTest/nextTest/bbb");
repo.saveContent(ContentObject.buildContentObject(name2, "bbb".getBytes()));
ContentName name3= ContentName.fromNative("/repoTest/nextTest/ccc");
repo.saveContent(ContentObject.buildContentObject(name3, "ccc".getBytes()));
ContentName name4= ContentName.fromNative("/repoTest/nextTest/ddd");
repo.saveContent(ContentObject.buildContentObject(name4, "ddd".getBytes()));
ContentName name5= ContentName.fromNative("/repoTest/nextTest/eee");
repo.saveContent(ContentObject.buildContentObject(name5, "eee".getBytes()));
checkData(repo, Interest.next(new ContentName(name1, content1.digest()), 2, null), "bbb");
checkData(repo, Interest.last(new ContentName(name1, content1.digest()), 2, null), "eee");
checkData(repo, Interest.next(new ContentName(name1, content1.digest()),
new Exclude(new byte [][] {"bbb".getBytes(), "ccc".getBytes()}), 2, null, null, null), "ddd");
System.out.println("Repotest - Testing different kinds of interests in a mixture of encoded/standard data");
ContentName nonLongName = ContentName.fromNative("/repoTestLong/nextTestLong/aaa");
ContentObject nonLongContent = ContentObject.buildContentObject(nonLongName, "aaa".getBytes());
repo.saveContent(nonLongContent);
ContentName longName2 = ContentName.fromNative("/repoTestLong/nextTestLong/bbb/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName2, "bbb".getBytes()));
ContentName nonLongName2 = ContentName.fromNative("/repoTestLong/nextTestLong/ccc");
repo.saveContent(ContentObject.buildContentObject(nonLongName2, "ccc".getBytes()));
ContentName longName3 = ContentName.fromNative("/repoTestLong/nextTestLong/ddd/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName3, "ddd".getBytes()));
ContentName longName4 = ContentName.fromNative("/repoTestLong/nextTestLong/eee/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName4, "eee".getBytes()));
checkData(repo, Interest.next(new ContentName(nonLongName, nonLongContent.digest()), 2, null), "bbb");
checkData(repo, Interest.last(new ContentName(nonLongName, nonLongContent.digest()), 2, null), "eee");
checkData(repo, Interest.next(new ContentName(nonLongName, nonLongContent.digest()),
new Exclude(new byte [][] {"bbb".getBytes(), "ccc".getBytes()}), 2, null, null, null), "ddd");
System.out.println("Repotest - testing version and segment files");
versionedName = ContentName.fromNative("/repoTest/testVersion");
versionedName = VersioningProfile.addVersion(versionedName);
repo.saveContent(ContentObject.buildContentObject(versionedName, "version".getBytes()));
checkData(repo, versionedName, "version");
segmentedName1 = SegmentationProfile.segmentName(versionedName, 1);
repo.saveContent(ContentObject.buildContentObject(segmentedName1, "segment1".getBytes()));
checkData(repo, segmentedName1, "segment1");
segmentedName223 = SegmentationProfile.segmentName(versionedName, 223);
repo.saveContent(ContentObject.buildContentObject(segmentedName223, "segment223".getBytes()));
checkData(repo, segmentedName223, "segment223");
System.out.println("Repotest - storing sequence of objects for versioned stream read testing");
versionedNameNormal = ContentName.fromNative("/testNameSpace/testVersionNormal");
versionedNameNormal = VersioningProfile.addVersion(versionedNameNormal);
repo.saveContent(ContentObject.buildContentObject(versionedNameNormal, "version-normal".getBytes()));
checkData(repo, versionedNameNormal, "version-normal");
byte[] finalBlockID = SegmentationProfile.getSegmentNumberNameComponent(4);
for (Long i=SegmentationProfile.baseSegment(); i<5; i++) {
ContentName segmented = SegmentationProfile.segmentName(versionedNameNormal, i);
String segmentContent = "segment"+ new Long(i).toString();
repo.saveContent(ContentObject.buildContentObject(segmented, segmentContent.getBytes(), null, null, finalBlockID));
checkData(repo, segmented, segmentContent);
}
System.out.println("Repotest - testing min and max in retrieval");
ContentName shortName = ContentName.fromNative("/repoTest/1/2");
ContentName longName = ContentName.fromNative("/repoTest/1/2/3/4/5/6");
ContentName middleName = ContentName.fromNative("/repoTest/1/2/3/4");
repo.saveContent(ContentObject.buildContentObject(shortName, "short".getBytes()));
repo.saveContent(ContentObject.buildContentObject(longName, "long".getBytes()));
repo.saveContent(ContentObject.buildContentObject(middleName, "middle".getBytes()));
Interest minInterest = new Interest(ContentName.fromNative("/repoTest/1"));
minInterest.minSuffixComponents(4);
checkData(repo, minInterest, "long");
Interest maxInterest = new Interest(ContentName.fromNative("/repoTest/1"));
maxInterest.maxSuffixComponents(3);
checkData(repo, maxInterest, "short");
Interest middleInterest = new Interest(ContentName.fromNative("/repoTest/1"));
middleInterest.maxSuffixComponents(4);
middleInterest.minSuffixComponents(3);
checkData(repo, middleInterest, "middle");
//adding in fast name enumeration response tests
System.out.println("Repotest - testing fast name enumeration response");
//building names for tests
ContentName nerpre = ContentName.fromNative("/testFastNameEnumeration");
ContentName ner = new ContentName(nerpre, "name1".getBytes());
ContentName nername1 = ContentName.fromNative("/name1");
ContentName ner2 = new ContentName(nerpre, "name2".getBytes());
ContentName nername2 = ContentName.fromNative("/name2");
ContentName ner3 = new ContentName(nerpre, "longer".getBytes());
ner3 = new ContentName(ner3, "name3".getBytes());
ContentName nername3 = ContentName.fromNative("/longer");
NameEnumerationResponse neresponse = null;
//send initial interest to make sure namespace is empty
//interest flag will not be set for a fast response since there isn't anything in the index yet
Interest interest = new Interest(new ContentName(nerpre, CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
ContentName responseName = new ContentName();
Log.info("RFSTEST: Name enumeration prefix:{0}", interest.name());
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse == null || neresponse.hasNames()==false);
//now saving the first piece of content in the repo. interest flag not set, so it should not get an object back
neresponse = repo.saveContent(ContentObject.buildContentObject(ner, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse==null || neresponse.hasNames()==false);
//now checking with the prefix that the first name is in
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
//now call get names with prefix again to set interest flag
//have to use the version from the last response (or at least a version after the last write
interest = Interest.last(VersioningProfile.addVersion(neresponse.getPrefix(), neresponse.getTimestamp()), null, null);
//the response should be null and the flag set
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse==null || neresponse.hasNames()==false);
//save content. if the flag was set, we should get an enumeration response
neresponse = repo.saveContent(ContentObject.buildContentObject(ner2, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getNames().contains(nername2));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
//need to reconstruct the interest again
interest = Interest.last(VersioningProfile.addVersion(neresponse.getPrefix(), neresponse.getTimestamp()), null, null);
//another interest to set interest flag, response should be null
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse == null || neresponse.hasNames()==false);
//interest flag should now be set, so when i add something - this is a longer name, i should be handed back an object
neresponse = repo.saveContent(ContentObject.buildContentObject(ner3, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getNames().contains(nername2));
Assert.assertTrue(neresponse.getNames().contains(nername3));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
repo.shutDown();
}
public void testReinitialization(RepositoryStore repo) throws Exception {
System.out.println("Repotest - Testing reinitialization of repo");
// Since we have 2 pieces of data with the name "longName" we need to compute the
// digest to make sure we get the right data.
longName = new ContentName(longName, longNameDigest);
checkDataWithDigest(repo, longName, "Long name!");
checkData(repo, badCharName, "Funny characters!");
checkData(repo, badCharLongName, "Long and funny");
Interest vnInterest = new Interest(versionedName);
vnInterest.maxSuffixComponents(1);
checkData(repo, vnInterest, "version");
checkData(repo, segmentedName1, "segment1");
checkData(repo, segmentedName223, "segment223");
vnInterest = new Interest(versionedNameNormal);
vnInterest.maxSuffixComponents(1);
checkData(repo, vnInterest, "version-normal");
for (Long i=SegmentationProfile.baseSegment(); i<5; i++) {
ContentName segmented = SegmentationProfile.segmentName(versionedNameNormal, i);
String segmentContent = "segment"+ new Long(i).toString();
checkData(repo, segmented, segmentContent);
}
}
@Test
public void testPolicy() throws Exception {
RepositoryStore repo = new LogStructRepoStore();
try { // Test no version
repo.initialize(_fileTestDir, new File(_topdir + "/org/ccnx/ccn/test/repo/badPolicyTest1.xml"), null, null, null, null);
Assert.fail("Bad policy file succeeded");
} catch (RepositoryException re) {}
try { // Test bad version
repo.initialize(_fileTestDir, new File(_topdir + "/org/ccnx/ccn/test/repo/badPolicyTest2.xml"), null, null, null, null);
Assert.fail("Bad policy file succeeded");
} catch (RepositoryException re) {}
repo.initialize(_fileTestDir,
new File(_topdir + "/org/ccnx/ccn/test/repo/policyTest.xml"), _repoName, _globalPrefix, null, putHandle);
ContentName name = ContentName.fromNative("/testNameSpace/data1");
ContentObject content = ContentObject.buildContentObject(name, "Here's my data!".getBytes());
repo.saveContent(content);
checkData(repo, name, "Here's my data!");
ContentName outOfNameSpaceName = ContentName.fromNative("/anotherNameSpace/data1");
ContentObject oonsContent = ContentObject.buildContentObject(outOfNameSpaceName, "Shouldn't see this".getBytes());
repo.saveContent(oonsContent);
ContentObject testContent = repo.getContent(new Interest(outOfNameSpaceName));
Assert.assertTrue(testContent == null);
// Test reading policy file from the repo
repolog.initialize(_fileTestDir, null, _repoName, _globalPrefix, null, null);
repo.saveContent(oonsContent);
ContentObject testContentAgain = repo.getContent(new Interest(outOfNameSpaceName));
Assert.assertTrue(testContentAgain == null);
// Test setting prefix from the prefix parameter
repo.initialize(_fileTestDir, null, _repoName, _globalPrefix, "/", null);
repo.saveContent(oonsContent);
checkData(repo, outOfNameSpaceName, "Shouldn't see this");
}
private void checkData(RepositoryStore repo, ContentName name, String data) throws RepositoryException {
checkData(repo, new Interest(name), data);
}
private void checkDataWithDigest(RepositoryStore repo, ContentName name, String data) throws RepositoryException {
// When generating an Interest for the exact name with content digest, need to set maxSuffixComponents
// to 0, signifying that name ends with explicit digest
Interest interest = new Interest(name);
interest.maxSuffixComponents(0);
checkData(repo, interest, data);
}
private void checkData(RepositoryStore repo, Interest interest, String data) throws RepositoryException {
ContentObject testContent = repo.getContent(interest);
Assert.assertFalse(testContent == null);
Assert.assertEquals(data, new String(testContent.content()));
}
private void checkDataAndPublisher(RepositoryStore repo, ContentName name, String data, PublisherPublicKeyDigest publisher)
throws RepositoryException {
Interest interest = new Interest(name, new PublisherID(publisher));
ContentObject testContent = repo.getContent(interest);
Assert.assertFalse(testContent == null);
Assert.assertEquals(data, new String(testContent.content()));
Assert.assertTrue(testContent.signedInfo().getPublisherKeyID().equals(publisher));
}
}
| public void test(RepositoryStore repo) throws Exception{
System.out.println("Repotest - Testing basic data");
ContentName name = ContentName.fromNative("/repoTest/data1");
ContentObject content = ContentObject.buildContentObject(name, "Here's my data!".getBytes());
repo.saveContent(content);
checkData(repo, name, "Here's my data!");
// TODO - Don't know how to check that multiple data doesn't result in multiple copies
// Do it just to make sure the mechanism doesn't break (but result is not tested).
repo.saveContent(content);
System.out.println("Repotest - Testing multiple digests for same data");
ContentObject digest2 = ContentObject.buildContentObject(name, "Testing2".getBytes());
repo.saveContent(digest2);
ContentName digestName = new ContentName(name, digest2.digest());
checkDataWithDigest(repo, digestName, "Testing2");
System.out.println("Repotest - Testing same digest for different data and/or publisher");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512); // go for fast
KeyPair pair1 = kpg.generateKeyPair();
PublisherPublicKeyDigest pubKey1 = new PublisherPublicKeyDigest(pair1.getPublic());
KeyLocator kl = new KeyLocator(new ContentName(keyprefix, pubKey1.digest()));
repo.saveContent(ContentObject.buildContentObject(kl.name().name(), pubKey1.digest()));
SignedInfo si = new SignedInfo(pubKey1, kl);
ContentObject digestSame1 = new ContentObject(name, si, "Testing2".getBytes(), pair1.getPrivate());
repo.saveContent(digestSame1);
KeyPair pair2 = kpg.generateKeyPair();
PublisherPublicKeyDigest pubKey2 = new PublisherPublicKeyDigest(pair2.getPublic());
kl = new KeyLocator(new ContentName(keyprefix, pubKey2.digest()));
repo.saveContent(ContentObject.buildContentObject(kl.name().name(), pubKey2.digest()));
si = new SignedInfo(pubKey2, kl);
ContentObject digestSame2 = new ContentObject(name, si, "Testing2".getBytes(), pair2.getPrivate());
repo.saveContent(digestSame2);
checkDataAndPublisher(repo, name, "Testing2", pubKey1);
checkDataAndPublisher(repo, name, "Testing2", pubKey2);
System.out.println("Repotest - Testing too long data");
String tooLongName = "0123456789";
for (int i = 0; i < 30; i++)
tooLongName += "0123456789";
longName = ContentName.fromNative("/repoTest/" + tooLongName);
ContentObject co = ContentObject.buildContentObject(longName, "Long name!".getBytes());
longNameDigest = co.digest();
repo.saveContent(co);
checkData(repo, longName, "Long name!");
digest2 = ContentObject.buildContentObject(longName, "Testing2".getBytes());
repo.saveContent(digest2);
digestName = new ContentName(longName, digest2.digest());
checkDataWithDigest(repo, digestName, "Testing2");
String wayTooLongName = tooLongName;
for (int i = 0; i < 30; i++)
wayTooLongName += "0123456789";
ContentName reallyLongName = ContentName.fromNative("/repoTest/" + wayTooLongName);
repo.saveContent(ContentObject.buildContentObject(reallyLongName, "Really Long name!".getBytes()));
checkData(repo, reallyLongName, "Really Long name!");
byte[][] longNonASCIIBytes = new byte[2][];
longNonASCIIBytes[0] = "repoTest".getBytes();
longNonASCIIBytes[1] = new byte[300];
for (int i = 0; i < 30; i++) {
rand.nextBytes(longNonASCIIBytes[1]);
ContentName lnab = new ContentName(longNonASCIIBytes);
repo.saveContent(ContentObject.buildContentObject(lnab, ("Long and Non ASCII " + i).getBytes()));
checkData(repo, lnab, "Long and Non ASCII " + i);
}
System.out.println("Repotest - Testing invalid characters in name");
badCharName = ContentName.fromNative("/repoTest/" + "*x?y<z>u");
repo.saveContent(ContentObject.buildContentObject(badCharName, "Funny characters!".getBytes()));
checkData(repo, badCharName, "Funny characters!");
badCharLongName = ContentName.fromNative("/repoTest/" + tooLongName + "*x?y<z>u");
repo.saveContent(ContentObject.buildContentObject(badCharLongName, "Long and funny".getBytes()));
checkData(repo, badCharLongName, "Long and funny");
System.out.println("Repotest - Testing different kinds of interests");
ContentName name1 = ContentName.fromNative("/repoTest/nextTest/aaa");
ContentObject content1 = ContentObject.buildContentObject(name1, "aaa".getBytes());
repo.saveContent(content1);
ContentName name2 = ContentName.fromNative("/repoTest/nextTest/bbb");
repo.saveContent(ContentObject.buildContentObject(name2, "bbb".getBytes()));
ContentName name3= ContentName.fromNative("/repoTest/nextTest/ccc");
repo.saveContent(ContentObject.buildContentObject(name3, "ccc".getBytes()));
ContentName name4= ContentName.fromNative("/repoTest/nextTest/ddd");
repo.saveContent(ContentObject.buildContentObject(name4, "ddd".getBytes()));
ContentName name5= ContentName.fromNative("/repoTest/nextTest/eee");
repo.saveContent(ContentObject.buildContentObject(name5, "eee".getBytes()));
checkData(repo, Interest.next(new ContentName(name1, content1.digest()), 2, null), "bbb");
checkData(repo, Interest.last(new ContentName(name1, content1.digest()), 2, null), "eee");
checkData(repo, Interest.next(new ContentName(name1, content1.digest()),
new Exclude(new byte [][] {"bbb".getBytes(), "ccc".getBytes()}), 2, null, null, null), "ddd");
System.out.println("Repotest - Testing different kinds of interests in a mixture of encoded/standard data");
ContentName nonLongName = ContentName.fromNative("/repoTestLong/nextTestLong/aaa");
ContentObject nonLongContent = ContentObject.buildContentObject(nonLongName, "aaa".getBytes());
repo.saveContent(nonLongContent);
ContentName longName2 = ContentName.fromNative("/repoTestLong/nextTestLong/bbb/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName2, "bbb".getBytes()));
ContentName nonLongName2 = ContentName.fromNative("/repoTestLong/nextTestLong/ccc");
repo.saveContent(ContentObject.buildContentObject(nonLongName2, "ccc".getBytes()));
ContentName longName3 = ContentName.fromNative("/repoTestLong/nextTestLong/ddd/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName3, "ddd".getBytes()));
ContentName longName4 = ContentName.fromNative("/repoTestLong/nextTestLong/eee/" + tooLongName);
repo.saveContent(ContentObject.buildContentObject(longName4, "eee".getBytes()));
checkData(repo, Interest.next(new ContentName(nonLongName, nonLongContent.digest()), 2, null), "bbb");
checkData(repo, Interest.last(new ContentName(nonLongName, nonLongContent.digest()), 2, null), "eee");
checkData(repo, Interest.next(new ContentName(nonLongName, nonLongContent.digest()),
new Exclude(new byte [][] {"bbb".getBytes(), "ccc".getBytes()}), 2, null, null, null), "ddd");
System.out.println("Repotest - testing version and segment files");
versionedName = ContentName.fromNative("/repoTest/testVersion");
versionedName = VersioningProfile.addVersion(versionedName);
repo.saveContent(ContentObject.buildContentObject(versionedName, "version".getBytes()));
checkData(repo, versionedName, "version");
segmentedName1 = SegmentationProfile.segmentName(versionedName, 1);
repo.saveContent(ContentObject.buildContentObject(segmentedName1, "segment1".getBytes()));
checkData(repo, segmentedName1, "segment1");
segmentedName223 = SegmentationProfile.segmentName(versionedName, 223);
repo.saveContent(ContentObject.buildContentObject(segmentedName223, "segment223".getBytes()));
checkData(repo, segmentedName223, "segment223");
System.out.println("Repotest - storing sequence of objects for versioned stream read testing");
versionedNameNormal = ContentName.fromNative("/testNameSpace/testVersionNormal");
versionedNameNormal = VersioningProfile.addVersion(versionedNameNormal);
repo.saveContent(ContentObject.buildContentObject(versionedNameNormal, "version-normal".getBytes()));
checkData(repo, versionedNameNormal, "version-normal");
byte[] finalBlockID = SegmentationProfile.getSegmentNumberNameComponent(4);
for (Long i=SegmentationProfile.baseSegment(); i<5; i++) {
ContentName segmented = SegmentationProfile.segmentName(versionedNameNormal, i);
String segmentContent = "segment"+ new Long(i).toString();
repo.saveContent(ContentObject.buildContentObject(segmented, segmentContent.getBytes(), null, null, finalBlockID));
checkData(repo, segmented, segmentContent);
}
System.out.println("Repotest - testing min and max in retrieval");
ContentName shortName = ContentName.fromNative("/repoTest/1/2");
ContentName longName = ContentName.fromNative("/repoTest/1/2/3/4/5/6");
ContentName middleName = ContentName.fromNative("/repoTest/1/2/3/4");
repo.saveContent(ContentObject.buildContentObject(shortName, "short".getBytes()));
repo.saveContent(ContentObject.buildContentObject(longName, "long".getBytes()));
repo.saveContent(ContentObject.buildContentObject(middleName, "middle".getBytes()));
Interest minInterest = new Interest(ContentName.fromNative("/repoTest/1"));
minInterest.minSuffixComponents(4);
checkData(repo, minInterest, "long");
Interest maxInterest = new Interest(ContentName.fromNative("/repoTest/1"));
maxInterest.maxSuffixComponents(3);
checkData(repo, maxInterest, "short");
Interest middleInterest = new Interest(ContentName.fromNative("/repoTest/1"));
middleInterest.maxSuffixComponents(4);
middleInterest.minSuffixComponents(3);
checkData(repo, middleInterest, "middle");
//adding in fast name enumeration response tests
System.out.println("Repotest - testing fast name enumeration response");
//building names for tests
ContentName nerpre = ContentName.fromNative("/testFastNameEnumeration");
ContentName ner = new ContentName(nerpre, "name1".getBytes());
ContentName nername1 = ContentName.fromNative("/name1");
ContentName ner2 = new ContentName(nerpre, "name2".getBytes());
ContentName nername2 = ContentName.fromNative("/name2");
ContentName ner3 = new ContentName(nerpre, "longer".getBytes());
ner3 = new ContentName(ner3, "name3".getBytes());
ContentName nername3 = ContentName.fromNative("/longer");
NameEnumerationResponse neresponse = null;
//send initial interest to make sure namespace is empty
//interest flag will not be set for a fast response since there isn't anything in the index yet
Interest interest = new Interest(new ContentName(nerpre, CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
ContentName responseName = new ContentName();
Log.info("RFSTEST: Name enumeration prefix:{0}", interest.name());
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse == null || neresponse.hasNames()==false);
//now saving the first piece of content in the repo. interest flag not set, so it should not get an object back
neresponse = repo.saveContent(ContentObject.buildContentObject(ner, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse==null || neresponse.hasNames()==false);
//now checking with the prefix that the first name is in
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
//now call get names with prefix again to set interest flag
//have to use the version from the last response (or at least a version after the last write
interest = Interest.last(VersioningProfile.addVersion(neresponse.getPrefix(), neresponse.getTimestamp()), null, null);
//the response should be null and the flag set
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse==null || neresponse.hasNames()==false);
//save content. if the flag was set, we should get an enumeration response
neresponse = repo.saveContent(ContentObject.buildContentObject(ner2, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getNames().contains(nername2));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
//need to reconstruct the interest again
interest = Interest.last(VersioningProfile.addVersion(neresponse.getPrefix(), neresponse.getTimestamp()), null, null);
//another interest to set interest flag, response should be null
neresponse = repo.getNamesWithPrefix(interest, responseName);
Assert.assertTrue(neresponse == null || neresponse.hasNames()==false);
//interest flag should now be set, so when i add something - this is a longer name, i should be handed back an object
neresponse = repo.saveContent(ContentObject.buildContentObject(ner3, "FastNameRespTest".getBytes()));
Assert.assertTrue(neresponse.getNames().contains(nername1));
Assert.assertTrue(neresponse.getNames().contains(nername2));
Assert.assertTrue(neresponse.getNames().contains(nername3));
Assert.assertTrue(neresponse.getPrefix().contains(CommandMarkers.COMMAND_MARKER_BASIC_ENUMERATION));
Assert.assertTrue(neresponse.getTimestamp()!=null);
repo.shutDown();
}
public void testReinitialization(RepositoryStore repo) throws Exception {
System.out.println("Repotest - Testing reinitialization of repo");
// Since we have 2 pieces of data with the name "longName" we need to compute the
// digest to make sure we get the right data.
longName = new ContentName(longName, longNameDigest);
checkDataWithDigest(repo, longName, "Long name!");
checkData(repo, badCharName, "Funny characters!");
checkData(repo, badCharLongName, "Long and funny");
Interest vnInterest = new Interest(versionedName);
vnInterest.maxSuffixComponents(1);
checkData(repo, vnInterest, "version");
checkData(repo, segmentedName1, "segment1");
checkData(repo, segmentedName223, "segment223");
vnInterest = new Interest(versionedNameNormal);
vnInterest.maxSuffixComponents(1);
checkData(repo, vnInterest, "version-normal");
for (Long i=SegmentationProfile.baseSegment(); i<5; i++) {
ContentName segmented = SegmentationProfile.segmentName(versionedNameNormal, i);
String segmentContent = "segment"+ new Long(i).toString();
checkData(repo, segmented, segmentContent);
}
}
@Test
public void testPolicy() throws Exception {
// Writes all this content signed with the repository's key
RepositoryStore repo = new LogStructRepoStore();
try { // Test no version
repo.initialize(_fileTestDir, new File(_topdir + "/org/ccnx/ccn/test/repo/badPolicyTest1.xml"), null, null, null, null);
Assert.fail("Bad policy file succeeded");
} catch (RepositoryException re) {}
try { // Test bad version
repo.initialize(_fileTestDir, new File(_topdir + "/org/ccnx/ccn/test/repo/badPolicyTest2.xml"), null, null, null, null);
Assert.fail("Bad policy file succeeded");
} catch (RepositoryException re) {}
// Make repository using repo's keystore, not user's
repo.initialize(_fileTestDir,
new File(_topdir + "/org/ccnx/ccn/test/repo/policyTest.xml"), _repoName, _globalPrefix, null, null);
ContentName name = ContentName.fromNative("/testNameSpace/data1");
ContentObject content = ContentObject.buildContentObject(name, "Here's my data!".getBytes());
repo.saveContent(content);
checkData(repo, name, "Here's my data!");
ContentName outOfNameSpaceName = ContentName.fromNative("/anotherNameSpace/data1");
ContentObject oonsContent = ContentObject.buildContentObject(outOfNameSpaceName, "Shouldn't see this".getBytes());
repo.saveContent(oonsContent);
ContentObject testContent = repo.getContent(new Interest(outOfNameSpaceName));
Assert.assertTrue(testContent == null);
// Test reading policy file from the repo
repolog.initialize(_fileTestDir, null, _repoName, _globalPrefix, null, null);
repo.saveContent(oonsContent);
ContentObject testContentAgain = repo.getContent(new Interest(outOfNameSpaceName));
Assert.assertTrue(testContentAgain == null);
// Test setting prefix from the prefix parameter
repo.initialize(_fileTestDir, null, _repoName, _globalPrefix, "/", null);
repo.saveContent(oonsContent);
checkData(repo, outOfNameSpaceName, "Shouldn't see this");
}
private void checkData(RepositoryStore repo, ContentName name, String data) throws RepositoryException {
checkData(repo, new Interest(name), data);
}
private void checkDataWithDigest(RepositoryStore repo, ContentName name, String data) throws RepositoryException {
// When generating an Interest for the exact name with content digest, need to set maxSuffixComponents
// to 0, signifying that name ends with explicit digest
Interest interest = new Interest(name);
interest.maxSuffixComponents(0);
checkData(repo, interest, data);
}
private void checkData(RepositoryStore repo, Interest interest, String data) throws RepositoryException {
ContentObject testContent = repo.getContent(interest);
Assert.assertFalse(testContent == null);
Assert.assertEquals(data, new String(testContent.content()));
}
private void checkDataAndPublisher(RepositoryStore repo, ContentName name, String data, PublisherPublicKeyDigest publisher)
throws RepositoryException {
Interest interest = new Interest(name, new PublisherID(publisher));
ContentObject testContent = repo.getContent(interest);
Assert.assertFalse(testContent == null);
Assert.assertEquals(data, new String(testContent.content()));
Assert.assertTrue(testContent.signedInfo().getPublisherKeyID().equals(publisher));
}
}
|
diff --git a/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java b/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java
index 6c12c939c..46a93912d 100644
--- a/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java
+++ b/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java
@@ -1,121 +1,122 @@
/*
File: CytoscapeMenus.java
Copyright (c) 2006, 2010, The Cytoscape Consortium (www.cytoscape.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.internal.view;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import org.cytoscape.application.swing.CyAction;
public class CytoscapeMenus {
final private CytoscapeMenuBar menuBar;
final private CytoscapeToolBar toolBar;
public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) {
this.menuBar = menuBar;
this.toolBar = toolBar;
menuBar.addMenu("File", 0.0);
- menuBar.addMenu("File.New", 0.0);
+ menuBar.addMenu("File.Recent Session", 0.0);
+ menuBar.addMenu("File.New", 0.5);
menuBar.addMenu("File.New.Network", 0.0);
menuBar.addMenu("File.Import", 5.0);
menuBar.addMenu("File.Export", 5.1);
menuBar.addMenu("Edit", 0.0);
menuBar.addMenu("View", 0.0);
menuBar.addMenu("Select", 0.0);
menuBar.addMenu("Select.Nodes", 1.0);
menuBar.addMenu("Select.Edges", 1.1);
menuBar.addMenu("Layout", 0.0);
menuBar.addMenu("Plugins", 0.0);
menuBar.addMenu("Tools", 0.0);
menuBar.addMenu("Help", 0.0);
menuBar.addSeparator("File", 2.0);
menuBar.addSeparator("File", 4.0);
menuBar.addSeparator("File", 6.0);
menuBar.addSeparator("File", 8.0);
menuBar.addSeparator("Edit", 2.0);
menuBar.addSeparator("Edit", 4.0);
menuBar.addSeparator("Edit", 6.0);
menuBar.addMenu("Edit.Preferences", 10.0);
menuBar.addSeparator("View", 2.0);
menuBar.addSeparator("View", 6.0);
menuBar.addSeparator("Select", 2.0);
menuBar.addSeparator("Select", 4.0);
menuBar.addSeparator("Select", 6.0);
menuBar.addSeparator("Layout", 2.0);
menuBar.addSeparator("Layout", 4.0);
menuBar.addSeparator("Layout", 6.0);
menuBar.addSeparator("Plugins", 2.0);
menuBar.addSeparator("Help", 2.0);
toolBar.addSeparator(2.0f);
toolBar.addSeparator(4.0f);
toolBar.addSeparator(6.0f);
toolBar.addSeparator(8.0f);
}
public JMenu getJMenu(String s) {
return menuBar.getMenu(s);
}
public JMenuBar getJMenuBar() {
return menuBar;
}
public JToolBar getJToolBar() {
return toolBar;
}
public void removeAction(CyAction action) {
if (action.isInMenuBar())
menuBar.removeAction(action);
if (action.isInToolBar())
toolBar.removeAction(action);
}
public void addAction(CyAction action) {
if (action.isInMenuBar())
menuBar.addAction(action);
if (action.isInToolBar())
toolBar.addAction(action);
}
}
| true | true | public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) {
this.menuBar = menuBar;
this.toolBar = toolBar;
menuBar.addMenu("File", 0.0);
menuBar.addMenu("File.New", 0.0);
menuBar.addMenu("File.New.Network", 0.0);
menuBar.addMenu("File.Import", 5.0);
menuBar.addMenu("File.Export", 5.1);
menuBar.addMenu("Edit", 0.0);
menuBar.addMenu("View", 0.0);
menuBar.addMenu("Select", 0.0);
menuBar.addMenu("Select.Nodes", 1.0);
menuBar.addMenu("Select.Edges", 1.1);
menuBar.addMenu("Layout", 0.0);
menuBar.addMenu("Plugins", 0.0);
menuBar.addMenu("Tools", 0.0);
menuBar.addMenu("Help", 0.0);
menuBar.addSeparator("File", 2.0);
menuBar.addSeparator("File", 4.0);
menuBar.addSeparator("File", 6.0);
menuBar.addSeparator("File", 8.0);
menuBar.addSeparator("Edit", 2.0);
menuBar.addSeparator("Edit", 4.0);
menuBar.addSeparator("Edit", 6.0);
menuBar.addMenu("Edit.Preferences", 10.0);
menuBar.addSeparator("View", 2.0);
menuBar.addSeparator("View", 6.0);
menuBar.addSeparator("Select", 2.0);
menuBar.addSeparator("Select", 4.0);
menuBar.addSeparator("Select", 6.0);
menuBar.addSeparator("Layout", 2.0);
menuBar.addSeparator("Layout", 4.0);
menuBar.addSeparator("Layout", 6.0);
menuBar.addSeparator("Plugins", 2.0);
menuBar.addSeparator("Help", 2.0);
toolBar.addSeparator(2.0f);
toolBar.addSeparator(4.0f);
toolBar.addSeparator(6.0f);
toolBar.addSeparator(8.0f);
}
| public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) {
this.menuBar = menuBar;
this.toolBar = toolBar;
menuBar.addMenu("File", 0.0);
menuBar.addMenu("File.Recent Session", 0.0);
menuBar.addMenu("File.New", 0.5);
menuBar.addMenu("File.New.Network", 0.0);
menuBar.addMenu("File.Import", 5.0);
menuBar.addMenu("File.Export", 5.1);
menuBar.addMenu("Edit", 0.0);
menuBar.addMenu("View", 0.0);
menuBar.addMenu("Select", 0.0);
menuBar.addMenu("Select.Nodes", 1.0);
menuBar.addMenu("Select.Edges", 1.1);
menuBar.addMenu("Layout", 0.0);
menuBar.addMenu("Plugins", 0.0);
menuBar.addMenu("Tools", 0.0);
menuBar.addMenu("Help", 0.0);
menuBar.addSeparator("File", 2.0);
menuBar.addSeparator("File", 4.0);
menuBar.addSeparator("File", 6.0);
menuBar.addSeparator("File", 8.0);
menuBar.addSeparator("Edit", 2.0);
menuBar.addSeparator("Edit", 4.0);
menuBar.addSeparator("Edit", 6.0);
menuBar.addMenu("Edit.Preferences", 10.0);
menuBar.addSeparator("View", 2.0);
menuBar.addSeparator("View", 6.0);
menuBar.addSeparator("Select", 2.0);
menuBar.addSeparator("Select", 4.0);
menuBar.addSeparator("Select", 6.0);
menuBar.addSeparator("Layout", 2.0);
menuBar.addSeparator("Layout", 4.0);
menuBar.addSeparator("Layout", 6.0);
menuBar.addSeparator("Plugins", 2.0);
menuBar.addSeparator("Help", 2.0);
toolBar.addSeparator(2.0f);
toolBar.addSeparator(4.0f);
toolBar.addSeparator(6.0f);
toolBar.addSeparator(8.0f);
}
|
diff --git a/operator/kernelstats/src/main/java/org/jaitools/media/jai/kernelstats/KernelStatsOpImage.java b/operator/kernelstats/src/main/java/org/jaitools/media/jai/kernelstats/KernelStatsOpImage.java
index 239a9b43..80fb0298 100644
--- a/operator/kernelstats/src/main/java/org/jaitools/media/jai/kernelstats/KernelStatsOpImage.java
+++ b/operator/kernelstats/src/main/java/org/jaitools/media/jai/kernelstats/KernelStatsOpImage.java
@@ -1,733 +1,734 @@
/*
* Copyright (c) 2009-2011, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jaitools.media.jai.kernelstats;
import java.awt.Rectangle;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.util.Map;
import javax.media.jai.AreaOpImage;
import javax.media.jai.BorderExtender;
import javax.media.jai.ImageLayout;
import javax.media.jai.KernelJAI;
import javax.media.jai.ROI;
import javax.media.jai.RasterAccessor;
import javax.media.jai.RasterFormatTag;
import org.jaitools.numeric.SampleStats;
import org.jaitools.numeric.Statistic;
/**
* An operator to calculate neighbourhood statistics on a source image.
*
* @see KernelStatsDescriptor Description of the algorithm and example
*
* @author Michael Bedward
* @since 1.0
* @version $Id$
*/
public class KernelStatsOpImage extends AreaOpImage {
private int[] srcBandOffsets;
private int srcPixelStride;
private int srcScanlineStride;
/* Destination image variables */
private int destWidth;
private int destHeight;
private int destBands;
private int[] destBandOffsets;
private int destPixelStride;
private int destScanlineStride;
private int srcBand;
/* Kernel variables. */
private boolean[] inKernel;
private int kernelN;
private int kernelW;
private int kernelH;
private int kernelKeyX;
private int kernelKeyY;
/* Mask variables */
private ROI roi;
private boolean maskSrc;
private boolean maskDest;
private Statistic[] stats;
private Double[] sampleData;
private Calculator functionTable;
private Number nilValue;
/**
* Creates a new instance.
*
* @param source the source image
*
* @param extender an optional {@code BorderExtender} or {@code null}
*
* @param config configurable attributes of the image (see {@link AreaOpImage})
*
* @param layout an optional ImageLayout object; if the layout specifies a SampleModel
* and / or ColorModel that are invalid for the requested statistics (e.g. wrong
* number of bands) these will be overridden
*
* @param stats an array of Statistic constants
*
* @param kernel the convolution kernel
*
* @param band the source image band to process
*
* @param roi an optional {@code ROI} or {@code null}
*
* @param ignoreNaN if {@code true} NaN values are ignored; otherwise any NaN
* values in a pixels neighbourhood cause {@code nilValue} to be returned
*
* @param maskSrc if {@code true} only neighbourhood pixels within the {@code ROI}
* are used in calculations
*
* @param maskDest if {@code true}, {@code nilValue} is returned for any pixels
* outside the {@code ROI}
*
* @param nilValue value to return for pixels with no result
*
* @throws IllegalArgumentException if the ROI's bounds do not contain the entire
* source image
*
* @see KernelStatsDescriptor
* @see Statistic
*/
public KernelStatsOpImage(RenderedImage source,
BorderExtender extender,
Map config,
ImageLayout layout,
Statistic[] stats,
KernelJAI kernel,
int band,
ROI roi,
boolean maskSrc,
boolean maskDest,
boolean ignoreNaN,
Number nilValue) {
super(source,
layout,
config,
true,
extender,
kernel.getLeftPadding(),
kernel.getRightPadding(),
kernel.getTopPadding(),
kernel.getBottomPadding());
this.srcBand = band;
kernelW = kernel.getWidth();
kernelH = kernel.getHeight();
kernelKeyX = kernel.getXOrigin();
kernelKeyY = kernel.getYOrigin();
/*
* Convert the kernel data to boolean values such
* that all non-zero values -> true; all zero
* values -> false
*/
final float FTOL = 1.0e-8f;
inKernel = new boolean[kernelW * kernelH];
float[] data = kernel.getKernelData();
kernelN = 0;
for (int i = 0; i < inKernel.length; i++) {
if (Math.abs(data[i]) > FTOL) {
inKernel[i] = true;
kernelN++ ;
} else {
inKernel[i] = false;
}
}
- this.stats = stats;
+ this.stats = new Statistic[stats.length];
+ System.arraycopy(stats, 0, this.stats, 0, stats.length);
this.roi = roi;
if (roi == null) {
this.maskSrc = this.maskDest = false;
} else {
// check that the ROI contains the source image bounds
Rectangle sourceBounds = new Rectangle(
source.getMinX(), source.getMinY(), source.getWidth(), source.getHeight());
if (!roi.getBounds().contains(sourceBounds)) {
throw new IllegalArgumentException("The bounds of the ROI must contain the source image");
}
this.maskSrc = maskSrc;
this.maskDest = maskDest;
}
this.functionTable = new Calculator(ignoreNaN);
this.nilValue = nilValue;
this.sampleData = new Double[kernelN];
}
/**
* Calculates neighbourhood statistics for a specified rectangle
*
* @param sources source rasters (only sources[0] is used here)
* @param dest a WritableRaster tile containing the area to be computed.
* @param destRect the rectangle within dest to be processed.
*/
@Override
protected void computeRect(Raster[] sources,
WritableRaster dest,
Rectangle destRect) {
RasterFormatTag[] formatTags = getFormatTags();
Raster source = sources[0];
Rectangle srcRect = mapDestRect(destRect, 0);
RasterAccessor srcAcc =
new RasterAccessor(source, srcRect,
formatTags[0], getSourceImage(0).getColorModel());
RasterAccessor destAcc =
new RasterAccessor(dest, destRect,
formatTags[1], getColorModel());
destWidth = destAcc.getWidth();
destHeight = destAcc.getHeight();
destBands = destAcc.getNumBands();
destBandOffsets = destAcc.getBandOffsets();
destPixelStride = destAcc.getPixelStride();
destScanlineStride = destAcc.getScanlineStride();
srcBandOffsets = srcAcc.getBandOffsets();
srcPixelStride = srcAcc.getPixelStride();
srcScanlineStride = srcAcc.getScanlineStride();
switch (destAcc.getDataType()) {
case DataBuffer.TYPE_BYTE:
calcByteData(srcAcc, destAcc);
break;
case DataBuffer.TYPE_SHORT:
calcShortData(srcAcc, destAcc);
break;
case DataBuffer.TYPE_USHORT:
calcUShortData(srcAcc, destAcc);
break;
case DataBuffer.TYPE_INT:
calcIntData(srcAcc, destAcc);
break;
case DataBuffer.TYPE_FLOAT:
calcFloatData(srcAcc, destAcc);
break;
case DataBuffer.TYPE_DOUBLE:
calcDoubleData(srcAcc, destAcc);
break;
}
if (destAcc.isDataCopy()) {
destAcc.clampDataArrays();
destAcc.copyDataToRaster();
}
}
private void calcByteData(RasterAccessor srcAcc, RasterAccessor destAcc) {
byte srcData[][] = srcAcc.getByteDataArrays();
byte destData[][] = destAcc.getByteDataArrays();
int destY = destAcc.getY();
int destX = destAcc.getX();
byte srcBandData[] = srcData[srcBand];
int srcScanlineOffset = srcBandOffsets[srcBand];
int destLineDelta = 0;
for (int j = 0; j < destHeight; j++, destY++) {
int srcPixelOffset = srcScanlineOffset;
int destPixelDelta = 0;
for (int i = 0; i < destWidth; i++, destX++) {
int numSamples = 0;
if (!maskDest || roi.contains(destX, destY)) {
int srcY = destY - kernelKeyY;
int kernelVerticalOffset = 0;
int imageVerticalOffset = srcPixelOffset;
for (int u = 0; u < kernelH; u++, srcY++) {
int srcX = destX - kernelKeyX;
int imageOffset = imageVerticalOffset;
for (int v = 0; v < kernelW; v++, srcX++) {
if (!maskSrc || roi.contains(srcX, srcY)) {
if (inKernel[kernelVerticalOffset + v]) {
sampleData[numSamples++] = (double) (srcBandData[imageOffset] & 0xff);
}
}
imageOffset += srcPixelStride;
}
kernelVerticalOffset += kernelW;
imageVerticalOffset += srcScanlineStride;
}
}
for (int band = 0; band < destBands; band++) {
byte destBandData[] = destData[band];
int dstPixelOffset = destBandOffsets[band] + destPixelDelta + destLineDelta;
int val = nilValue.byteValue();
if (numSamples > 0) {
double statValue = functionTable.call(stats[band], sampleData, numSamples);
if (!Double.isNaN(statValue)) {
val = (int) (statValue + 0.5);
if (val < 0) {
val = 0;
} else if (val > 255) {
val = 255;
}
}
}
destBandData[dstPixelOffset] = (byte) val;
}
srcPixelOffset += srcPixelStride;
destPixelDelta += destPixelStride;
}
srcScanlineOffset += srcScanlineStride;
destLineDelta += destScanlineStride;
}
}
private void calcShortData(RasterAccessor srcAcc, RasterAccessor destAcc) {
short destData[][] = destAcc.getShortDataArrays();
short srcData[][] = srcAcc.getShortDataArrays();
int destY = destAcc.getY();
int destX = destAcc.getX();
short srcBandData[] = srcData[srcBand];
int srcScanlineOffset = srcBandOffsets[srcBand];
int destLineDelta = 0;
for (int j = 0; j < destHeight; j++, destY++) {
int srcPixelOffset = srcScanlineOffset;
int destPixelDelta = 0;
for (int i = 0; i < destWidth; i++, destX++) {
int numSamples = 0;
if (!maskDest || roi.contains(destX, destY)) {
int srcY = destY - kernelKeyY;
int kernelVerticalOffset = 0;
int imageVerticalOffset = srcPixelOffset;
for (int u = 0; u < kernelH; u++, srcY++) {
int srcX = destX - kernelKeyX;
int imageOffset = imageVerticalOffset;
for (int v = 0; v < kernelW; v++, srcX++) {
if (!maskSrc || roi.contains(srcX, srcY)) {
if (inKernel[kernelVerticalOffset + v]) {
sampleData[numSamples++] = (double) srcBandData[imageOffset];
}
}
imageOffset += srcPixelStride;
}
kernelVerticalOffset += kernelW;
imageVerticalOffset += srcScanlineStride;
}
}
for (int band = 0; band < destBands; band++) {
short destBandData[] = destData[band];
int dstPixelOffset = destBandOffsets[band] + destPixelDelta + destLineDelta;
int val = nilValue.shortValue();
if (numSamples > 0) {
double statValue = functionTable.call(stats[band], sampleData, numSamples);
if (!Double.isNaN(statValue)) {
val = (int) (statValue + 0.5);
if (val < Short.MIN_VALUE) {
val = Short.MIN_VALUE;
} else if (val > Short.MAX_VALUE) {
val = Short.MAX_VALUE;
}
}
}
destBandData[dstPixelOffset] = (short) val;
}
srcPixelOffset += srcPixelStride;
destPixelDelta += destPixelStride;
}
srcScanlineOffset += srcScanlineStride;
destLineDelta += destScanlineStride;
}
}
private void calcUShortData(RasterAccessor srcAcc, RasterAccessor destAcc) {
short destData[][] = destAcc.getShortDataArrays();
short srcData[][] = srcAcc.getShortDataArrays();
int destY = destAcc.getY();
int destX = destAcc.getX();
short srcBandData[] = srcData[srcBand];
int srcScanlineOffset = srcBandOffsets[srcBand];
int destLineDelta = 0;
for (int j = 0; j < destHeight; j++, destY++) {
int srcPixelOffset = srcScanlineOffset;
int destPixelDelta = 0;
for (int i = 0; i < destWidth; i++, destX++) {
int numSamples = 0;
if (!maskDest || roi.contains(destX, destY)) {
int srcY = destY - kernelKeyY;
int kernelVerticalOffset = 0;
int imageVerticalOffset = srcPixelOffset;
for (int u = 0; u < kernelH; u++, srcY++) {
int srcX = destX - kernelKeyX;
int imageOffset = imageVerticalOffset;
for (int v = 0; v < kernelW; v++, srcX++) {
if (!maskSrc || roi.contains(srcX, srcY)) {
if (inKernel[kernelVerticalOffset + v]) {
sampleData[numSamples++] = (double) (srcBandData[imageOffset] & 0xffff);
}
}
imageOffset += srcPixelStride;
}
kernelVerticalOffset += kernelW;
imageVerticalOffset += srcScanlineStride;
}
}
for (int band = 0; band < destBands; band++) {
short destBandData[] = destData[band];
int dstPixelOffset = destBandOffsets[band] + destPixelDelta + destLineDelta;
int val = nilValue.shortValue();
if (numSamples > 0) {
double statValue = functionTable.call(stats[band], sampleData, numSamples);
if (!Double.isNaN(statValue)) {
val = (int) (statValue + 0.5);
if (val < 0) {
val = 0;
} else if (val > 0xffff) {
val = 0xffff;
}
}
}
destBandData[dstPixelOffset] = (short) val;
}
srcPixelOffset += srcPixelStride;
destPixelDelta += destPixelStride;
}
srcScanlineOffset += srcScanlineStride;
destLineDelta += destScanlineStride;
}
}
private void calcIntData(RasterAccessor srcAcc, RasterAccessor destAcc) {
int destData[][] = destAcc.getIntDataArrays();
int srcData[][] = srcAcc.getIntDataArrays();
int destY = destAcc.getY();
int destX = destAcc.getX();
int srcBandData[] = srcData[srcBand];
int srcScanlineOffset = srcBandOffsets[srcBand];
int destLineDelta = 0;
for (int j = 0; j < destHeight; j++, destY++) {
int srcPixelOffset = srcScanlineOffset;
int destPixelDelta = 0;
for (int i = 0; i < destWidth; i++, destX++) {
int numSamples = 0;
if (!maskDest || roi.contains(destX, destY)) {
int srcY = destY - kernelKeyY;
int kernelVerticalOffset = 0;
int imageVerticalOffset = srcPixelOffset;
for (int u = 0; u < kernelH; u++, srcY++) {
int srcX = destX - kernelKeyX;
int imageOffset = imageVerticalOffset;
for (int v = 0; v < kernelW; v++, srcX++) {
if (!maskSrc || roi.contains(srcX, srcY)) {
if (inKernel[kernelVerticalOffset + v]) {
sampleData[numSamples++] = (double) srcBandData[imageOffset];
}
}
imageOffset += srcPixelStride;
}
kernelVerticalOffset += kernelW;
imageVerticalOffset += srcScanlineStride;
}
}
for (int band = 0; band < destBands; band++) {
int destBandData[] = destData[band];
int dstPixelOffset = destBandOffsets[band] + destPixelDelta + destLineDelta;
int val = nilValue.intValue();
if (numSamples > 0) {
double statValue = functionTable.call(stats[band], sampleData, numSamples);
if (!Double.isNaN(statValue)) {
val = (int) (statValue + 0.5);
}
}
destBandData[dstPixelOffset] = val;
}
srcPixelOffset += srcPixelStride;
destPixelDelta += destPixelStride;
}
srcScanlineOffset += srcScanlineStride;
destLineDelta += destScanlineStride;
}
}
private void calcFloatData(RasterAccessor srcAcc, RasterAccessor destAcc) {
float destData[][] = destAcc.getFloatDataArrays();
float srcData[][] = srcAcc.getFloatDataArrays();
int destY = destAcc.getY();
int destX = destAcc.getX();
float srcBandData[] = srcData[srcBand];
int srcScanlineOffset = srcBandOffsets[srcBand];
int destLineDelta = 0;
for (int j = 0; j < destHeight; j++, destY++) {
int srcPixelOffset = srcScanlineOffset;
int destPixelDelta = 0;
for (int i = 0; i < destWidth; i++, destX++) {
int numSamples = 0;
if (!maskDest || roi.contains(destX, destY)) {
int srcY = destY - kernelKeyY;
int kernelVerticalOffset = 0;
int imageVerticalOffset = srcPixelOffset;
for (int u = 0; u < kernelH; u++, srcY++) {
int srcX = destX - kernelKeyX;
int imageOffset = imageVerticalOffset;
for (int v = 0; v < kernelW; v++, srcX++) {
if (!maskSrc || roi.contains(srcX, srcY)) {
if (inKernel[kernelVerticalOffset + v]) {
sampleData[numSamples++] = (double) srcBandData[imageOffset];
}
}
imageOffset += srcPixelStride;
}
kernelVerticalOffset += kernelW;
imageVerticalOffset += srcScanlineStride;
}
}
for (int band = 0; band < destBands; band++) {
float destBandData[] = destData[band];
int dstPixelOffset = destBandOffsets[band] + destPixelDelta + destLineDelta;
float val = nilValue.floatValue();
if (numSamples > 0) {
double statValue = functionTable.call(stats[band], sampleData, numSamples);
if (!Double.isNaN(statValue)) {
val = (float) statValue;
}
}
destBandData[dstPixelOffset] = val;
}
srcPixelOffset += srcPixelStride;
destPixelDelta += destPixelStride;
}
srcScanlineOffset += srcScanlineStride;
destLineDelta += destScanlineStride;
}
}
private void calcDoubleData(RasterAccessor srcAcc, RasterAccessor destAcc) {
double destData[][] = destAcc.getDoubleDataArrays();
double srcData[][] = srcAcc.getDoubleDataArrays();
int destY = destAcc.getY();
int destX = destAcc.getX();
double srcBandData[] = srcData[srcBand];
int srcScanlineOffset = srcBandOffsets[srcBand];
int destLineDelta = 0;
for (int j = 0; j < destHeight; j++, destY++) {
int srcPixelOffset = srcScanlineOffset;
int destPixelDelta = 0;
for (int i = 0; i < destWidth; i++, destX++) {
int numSamples = 0;
if (!maskDest || roi.contains(destX, destY)) {
int srcY = destY - kernelKeyY;
int kernelVerticalOffset = 0;
int imageVerticalOffset = srcPixelOffset;
for (int u = 0; u < kernelH; u++, srcY++) {
int srcX = destX - kernelKeyX;
int imageOffset = imageVerticalOffset;
for (int v = 0; v < kernelW; v++, srcX++) {
if (!maskSrc || roi.contains(srcX, srcY)) {
if (inKernel[kernelVerticalOffset + v]) {
sampleData[numSamples++] = srcBandData[imageOffset];
}
}
imageOffset += srcPixelStride;
}
kernelVerticalOffset += kernelW;
imageVerticalOffset += srcScanlineStride;
}
}
for (int band = 0; band < destBands; band++) {
double destBandData[] = destData[band];
int dstPixelOffset = destBandOffsets[band] + destPixelDelta + destLineDelta;
double val = nilValue.doubleValue();
if (numSamples > 0) {
double statValue = functionTable.call(stats[band], sampleData, numSamples);
if (!Double.isNaN(statValue)) {
val = statValue;
}
}
destBandData[dstPixelOffset] = val;
}
srcPixelOffset += srcPixelStride;
destPixelDelta += destPixelStride;
}
srcScanlineOffset += srcScanlineStride;
destLineDelta += destScanlineStride;
}
}
/**
* This class handles preparation of sample data, passing calculation tasks
* to {@linkplain jaitools.utils.SampleStats} methods, and returning results
*/
private static class Calculator {
private boolean ignoreNaN;
/**
* Constructor
* @param ignoreNaN specifies how to respond to NaN values
*/
Calculator(boolean ignoreNaN) {
this.ignoreNaN = ignoreNaN;
}
/**
* Calculate the specified statistic on sample data
* @param stat the {@linkplain Statistic} constant for the desired statistic
* @param data the sample data
* @param n number of elements to use from the sample data array
* @return value of the statistic as a double (may be NaN)
*/
public double call(Statistic stat, Double[] data, int n) {
Double[] values = null;
if (data.length == n) {
values = data;
} else {
values = new Double[n];
System.arraycopy(data, 0, values, 0, n);
}
switch (stat) {
case MAX:
return SampleStats.max(values, ignoreNaN);
case MEAN:
return SampleStats.mean(values, ignoreNaN);
case MEDIAN:
return SampleStats.median(values, ignoreNaN);
case MIN:
return SampleStats.min(values, ignoreNaN);
case RANGE:
return SampleStats.range(values, ignoreNaN);
case SDEV:
return SampleStats.sdev(values, ignoreNaN);
case VARIANCE:
return SampleStats.variance(values, ignoreNaN);
case SUM:
return SampleStats.sum(values, ignoreNaN);
default:
throw new IllegalArgumentException("Unrecognized KernelStatstic arg");
}
}
}
}
| true | true | public KernelStatsOpImage(RenderedImage source,
BorderExtender extender,
Map config,
ImageLayout layout,
Statistic[] stats,
KernelJAI kernel,
int band,
ROI roi,
boolean maskSrc,
boolean maskDest,
boolean ignoreNaN,
Number nilValue) {
super(source,
layout,
config,
true,
extender,
kernel.getLeftPadding(),
kernel.getRightPadding(),
kernel.getTopPadding(),
kernel.getBottomPadding());
this.srcBand = band;
kernelW = kernel.getWidth();
kernelH = kernel.getHeight();
kernelKeyX = kernel.getXOrigin();
kernelKeyY = kernel.getYOrigin();
/*
* Convert the kernel data to boolean values such
* that all non-zero values -> true; all zero
* values -> false
*/
final float FTOL = 1.0e-8f;
inKernel = new boolean[kernelW * kernelH];
float[] data = kernel.getKernelData();
kernelN = 0;
for (int i = 0; i < inKernel.length; i++) {
if (Math.abs(data[i]) > FTOL) {
inKernel[i] = true;
kernelN++ ;
} else {
inKernel[i] = false;
}
}
this.stats = stats;
this.roi = roi;
if (roi == null) {
this.maskSrc = this.maskDest = false;
} else {
// check that the ROI contains the source image bounds
Rectangle sourceBounds = new Rectangle(
source.getMinX(), source.getMinY(), source.getWidth(), source.getHeight());
if (!roi.getBounds().contains(sourceBounds)) {
throw new IllegalArgumentException("The bounds of the ROI must contain the source image");
}
this.maskSrc = maskSrc;
this.maskDest = maskDest;
}
this.functionTable = new Calculator(ignoreNaN);
this.nilValue = nilValue;
this.sampleData = new Double[kernelN];
}
| public KernelStatsOpImage(RenderedImage source,
BorderExtender extender,
Map config,
ImageLayout layout,
Statistic[] stats,
KernelJAI kernel,
int band,
ROI roi,
boolean maskSrc,
boolean maskDest,
boolean ignoreNaN,
Number nilValue) {
super(source,
layout,
config,
true,
extender,
kernel.getLeftPadding(),
kernel.getRightPadding(),
kernel.getTopPadding(),
kernel.getBottomPadding());
this.srcBand = band;
kernelW = kernel.getWidth();
kernelH = kernel.getHeight();
kernelKeyX = kernel.getXOrigin();
kernelKeyY = kernel.getYOrigin();
/*
* Convert the kernel data to boolean values such
* that all non-zero values -> true; all zero
* values -> false
*/
final float FTOL = 1.0e-8f;
inKernel = new boolean[kernelW * kernelH];
float[] data = kernel.getKernelData();
kernelN = 0;
for (int i = 0; i < inKernel.length; i++) {
if (Math.abs(data[i]) > FTOL) {
inKernel[i] = true;
kernelN++ ;
} else {
inKernel[i] = false;
}
}
this.stats = new Statistic[stats.length];
System.arraycopy(stats, 0, this.stats, 0, stats.length);
this.roi = roi;
if (roi == null) {
this.maskSrc = this.maskDest = false;
} else {
// check that the ROI contains the source image bounds
Rectangle sourceBounds = new Rectangle(
source.getMinX(), source.getMinY(), source.getWidth(), source.getHeight());
if (!roi.getBounds().contains(sourceBounds)) {
throw new IllegalArgumentException("The bounds of the ROI must contain the source image");
}
this.maskSrc = maskSrc;
this.maskDest = maskDest;
}
this.functionTable = new Calculator(ignoreNaN);
this.nilValue = nilValue;
this.sampleData = new Double[kernelN];
}
|
diff --git a/src/test/java/mikera/vectorz/util/TestMatrixBuilder.java b/src/test/java/mikera/vectorz/util/TestMatrixBuilder.java
index 33428e4d..9cc64e3e 100644
--- a/src/test/java/mikera/vectorz/util/TestMatrixBuilder.java
+++ b/src/test/java/mikera/vectorz/util/TestMatrixBuilder.java
@@ -1,26 +1,25 @@
package mikera.vectorz.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import mikera.matrixx.AMatrix;
import mikera.vectorz.Vector;
import mikera.vectorz.Vector3;
import org.junit.Test;
public class TestMatrixBuilder {
@Test public void testBuild() {
- MatrixBuilder vb=new MatrixBuilder();
- assertEquals(0,vb.toMatrix().toVector().length());
+ MatrixBuilder mb=new MatrixBuilder();
- vb.append(Vector3.of(1,0,0));
- vb.append(new double[] {0,1,0});
- vb.append(Vector.of(0,0).join(Vector.of(1)));
+ mb.append(Vector3.of(1,0,0));
+ mb.append(new double[] {0,1,0});
+ mb.append(Vector.of(0,0).join(Vector.of(1)));
- AMatrix m= vb.toMatrix();
+ AMatrix m= mb.toMatrix();
assertEquals(3,m.outputDimensions());
assertTrue(m.isIdentity());
}
}
| false | true | @Test public void testBuild() {
MatrixBuilder vb=new MatrixBuilder();
assertEquals(0,vb.toMatrix().toVector().length());
vb.append(Vector3.of(1,0,0));
vb.append(new double[] {0,1,0});
vb.append(Vector.of(0,0).join(Vector.of(1)));
AMatrix m= vb.toMatrix();
assertEquals(3,m.outputDimensions());
assertTrue(m.isIdentity());
}
| @Test public void testBuild() {
MatrixBuilder mb=new MatrixBuilder();
mb.append(Vector3.of(1,0,0));
mb.append(new double[] {0,1,0});
mb.append(Vector.of(0,0).join(Vector.of(1)));
AMatrix m= mb.toMatrix();
assertEquals(3,m.outputDimensions());
assertTrue(m.isIdentity());
}
|
diff --git a/src/main/java/org/jenkinsci/plugins/envinject/service/PropertiesLoader.java b/src/main/java/org/jenkinsci/plugins/envinject/service/PropertiesLoader.java
index 7b8e2d9..036a1d4 100644
--- a/src/main/java/org/jenkinsci/plugins/envinject/service/PropertiesLoader.java
+++ b/src/main/java/org/jenkinsci/plugins/envinject/service/PropertiesLoader.java
@@ -1,109 +1,109 @@
package org.jenkinsci.plugins.envinject.service;
import hudson.Util;
import org.jenkinsci.lib.envinject.EnvInjectException;
import org.jenkinsci.plugins.envinject.util.SortedProperties;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author Gregory Boissinot
*/
public class PropertiesLoader implements Serializable {
/**
* Get environment variables from a properties file path
*
* @param propertiesFile the properties file
* @param currentEnvVars the current environment variables to resolve against
* @return the environment variables
* @throws EnvInjectException
*/
public Map<String, String> getVarsFromPropertiesFile(File propertiesFile, Map<String, String> currentEnvVars) throws EnvInjectException {
if (propertiesFile == null) {
throw new NullPointerException("The properties file object must be set.");
}
if (!propertiesFile.exists()) {
throw new IllegalArgumentException("The properties file object must be exist.");
}
Map<String, String> result = new LinkedHashMap<String, String>();
SortedProperties properties = new SortedProperties();
try {
String fileContent = Util.loadFile(propertiesFile);
String fileContentResolved = Util.replaceMacro(fileContent, currentEnvVars);
fileContentResolved = processPath(fileContentResolved);
properties.load(new StringReader(fileContentResolved));
} catch (IOException ioe) {
throw new EnvInjectException("Problem occurs on loading content", ioe);
}
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
result.put(processElement(entry.getKey()), processElement(entry.getValue()));
}
return result;
}
/**
* Get a map environment variables from the content
*
* @param content the properties content to parse
* @param currentEnvVars the current environment variables to resolve against
* @return the environment variables
* @throws EnvInjectException
*/
public Map<String, String> getVarsFromPropertiesContent(String content, Map<String, String> currentEnvVars) throws EnvInjectException {
if (content == null) {
throw new NullPointerException("A properties content must be set.");
}
if (content.trim().length() == 0) {
throw new IllegalArgumentException("A properties content must be not empty.");
}
- content = processPath(content);
String contentResolved = Util.replaceMacro(content, currentEnvVars);
+ contentResolved = processPath(contentResolved);
Map<String, String> result = new LinkedHashMap<String, String>();
StringReader stringReader = new StringReader(contentResolved);
SortedProperties properties = new SortedProperties();
try {
properties.load(stringReader);
} catch (IOException ioe) {
throw new EnvInjectException("Problem occurs on loading content", ioe);
} finally {
stringReader.close();
}
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
result.put(processElement(entry.getKey()), processElement(entry.getValue()));
}
return result;
}
private String processElement(Object prop) {
if (prop == null) {
return null;
}
return String.valueOf(prop).trim();
}
private String processPath(String content) {
if (content == null) {
return null;
}
content = content.replace("\\", "\\\\");
return content.replace("\\\\\n", "\\\n");
}
}
| false | true | public Map<String, String> getVarsFromPropertiesContent(String content, Map<String, String> currentEnvVars) throws EnvInjectException {
if (content == null) {
throw new NullPointerException("A properties content must be set.");
}
if (content.trim().length() == 0) {
throw new IllegalArgumentException("A properties content must be not empty.");
}
content = processPath(content);
String contentResolved = Util.replaceMacro(content, currentEnvVars);
Map<String, String> result = new LinkedHashMap<String, String>();
StringReader stringReader = new StringReader(contentResolved);
SortedProperties properties = new SortedProperties();
try {
properties.load(stringReader);
} catch (IOException ioe) {
throw new EnvInjectException("Problem occurs on loading content", ioe);
} finally {
stringReader.close();
}
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
result.put(processElement(entry.getKey()), processElement(entry.getValue()));
}
return result;
}
| public Map<String, String> getVarsFromPropertiesContent(String content, Map<String, String> currentEnvVars) throws EnvInjectException {
if (content == null) {
throw new NullPointerException("A properties content must be set.");
}
if (content.trim().length() == 0) {
throw new IllegalArgumentException("A properties content must be not empty.");
}
String contentResolved = Util.replaceMacro(content, currentEnvVars);
contentResolved = processPath(contentResolved);
Map<String, String> result = new LinkedHashMap<String, String>();
StringReader stringReader = new StringReader(contentResolved);
SortedProperties properties = new SortedProperties();
try {
properties.load(stringReader);
} catch (IOException ioe) {
throw new EnvInjectException("Problem occurs on loading content", ioe);
} finally {
stringReader.close();
}
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
result.put(processElement(entry.getKey()), processElement(entry.getValue()));
}
return result;
}
|
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/HelpActivity.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/HelpActivity.java
index 32350cc2..dc195940 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/HelpActivity.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/HelpActivity.java
@@ -1,64 +1,64 @@
/*
* Copyright (C) 2011 asksven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asksven.betterbatterystats;
import com.asksven.betterbatterystats.R;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class HelpActivity extends Activity
{
/**
* @see android.app.Activity#onCreate(Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.helpwebview);
WebView browser = (WebView)findViewById(R.id.webview);
WebSettings settings = browser.getSettings();
settings.setJavaScriptEnabled(true);
// retrieve any passed data (filename)
String strFilename = getIntent().getStringExtra("filename");
String strURL = getIntent().getStringExtra("url");
// if a URL is passed open it
// if not open a local file
- if (strURL.equals(""))
+ if ( (strURL == null) || (strURL.equals("")) )
{
if (strFilename.equals(""))
{
browser.loadUrl("file:///android_asset/help.html");
}
else
{
browser.loadUrl("file:///android_asset/" + strFilename);
}
}
else
{
browser.loadUrl(strURL);
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.helpwebview);
WebView browser = (WebView)findViewById(R.id.webview);
WebSettings settings = browser.getSettings();
settings.setJavaScriptEnabled(true);
// retrieve any passed data (filename)
String strFilename = getIntent().getStringExtra("filename");
String strURL = getIntent().getStringExtra("url");
// if a URL is passed open it
// if not open a local file
if (strURL.equals(""))
{
if (strFilename.equals(""))
{
browser.loadUrl("file:///android_asset/help.html");
}
else
{
browser.loadUrl("file:///android_asset/" + strFilename);
}
}
else
{
browser.loadUrl(strURL);
}
}
| protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.helpwebview);
WebView browser = (WebView)findViewById(R.id.webview);
WebSettings settings = browser.getSettings();
settings.setJavaScriptEnabled(true);
// retrieve any passed data (filename)
String strFilename = getIntent().getStringExtra("filename");
String strURL = getIntent().getStringExtra("url");
// if a URL is passed open it
// if not open a local file
if ( (strURL == null) || (strURL.equals("")) )
{
if (strFilename.equals(""))
{
browser.loadUrl("file:///android_asset/help.html");
}
else
{
browser.loadUrl("file:///android_asset/" + strFilename);
}
}
else
{
browser.loadUrl(strURL);
}
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
index 03c12ddeb..e8723177f 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
@@ -1,365 +1,378 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.core.dispatchers;
import gov.nist.javax.sip.header.extensions.JoinHeader;
import gov.nist.javax.sip.header.extensions.ReplacesHeader;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.sip.ProxyBranch;
import javax.servlet.sip.SipServletResponse;
import javax.sip.Dialog;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.header.CSeqHeader;
import javax.sip.header.Parameters;
import javax.sip.header.RouteHeader;
import javax.sip.header.SubscriptionStateHeader;
import javax.sip.header.ToHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode;
import org.mobicents.servlet.sip.core.ApplicationRoutingHeaderComposer;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.core.session.SessionManagerUtil;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.core.session.SipManager;
import org.mobicents.servlet.sip.core.session.SipSessionKey;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletMessageImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.proxy.ProxyBranchImpl;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.startup.SipContext;
/**
* This class is responsible for routing and dispatching subsequent request to applications according to JSR 289 Section
* 15.6 Responses, Subsequent Requests and Application Path
*
* It uses route header parameters for proxy apps or to tag parameter for UAS/B2BUA apps
* that were previously set by the container on
* record route headers or to tag to know which app has to be called
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class SubsequentRequestDispatcher extends RequestDispatcher {
private static transient Logger logger = Logger.getLogger(SubsequentRequestDispatcher.class);
public SubsequentRequestDispatcher() {}
// public SubsequentRequestDispatcher(
// SipApplicationDispatcher sipApplicationDispatcher) {
// super(sipApplicationDispatcher);
// }
/**
* {@inheritDoc}
*/
public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
final String method = request.getMethod();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
// Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
try {
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
} catch(IllegalArgumentException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, e);
}
if(applicationId == null && applicationName == null) {
javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI();
final String host = sipRequestUri.getHost();
final int port = sipRequestUri.getPort();
final String transport = JainSipUtils.findTransport(request);
final boolean isAnotherDomain = sipApplicationDispatcher.isExternal(host, port, transport);
//Issue 823 (http://code.google.com/p/mobicents/issues/detail?id=823) :
// Container should proxy statelessly subsequent requests not targeted at itself
if(isAnotherDomain) {
// Some UA are misbehaving and don't follow the non record proxy so they sent subsequent requests to the container (due to oubound proxy set probably) instead of directly to the UA
// so we proxy statelessly those requests
if(logger.isDebugEnabled()) {
logger.debug("No application found to handle this request " + request + " with the following popped route header " + poppedRouteHeader + " so forwarding statelessly to the outside since it is not targeted at the container");
}
try {
sipProvider.sendRequest(request);
} catch (SipException e) {
throw new DispatcherException("cannot proxy statelessly outside of the container the following request " + request, e);
}
return;
} else {
if(Request.ACK.equals(method)) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
} else {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
- "in this popped routed header " + poppedRouteHeader + ", it may already have been invalidated or timed out");
+ "in this popped routed header " + poppedRouteHeader);
} else {
- throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
- ", it may already have been invalidated or timed out");
+ throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
}
}
}
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
- throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
+ if(poppedRouteHeader != null) {
+ throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
+ } else {
+ throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
+ }
}
final SipManager sipManager = (SipManager)sipContext.getManager();
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
}
if(sipApplicationSession == null) {
- throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
- " with the following popped route header " + sipServletRequest.getPoppedRoute());
+ if(poppedRouteHeader != null) {
+ throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
+ " with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
+ } else {
+ throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
+ ", it may already have been invalidated or timed out");
+ }
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
- throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
- " with the following popped route header " + sipServletRequest.getPoppedRoute());
+ if(poppedRouteHeader != null) {
+ throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session to this subsequent request " + request +
+ " with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
+ } else {
+ throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session to this subsequent request " + request +
+ ", it may already have been invalidated or timed out");
+ }
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSessionKey(key);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
final boolean isAck = Request.ACK.equalsIgnoreCase(method);
final boolean isAckRetranmission = sipSession.isAckReceived() && isAck;
if(isAck) {
sipSession.setAckReceived(true);
}
//CSeq validation should only be done for non proxy applications
if(sipSession.getProxy() == null) {
final long localCseq = sipSession.getCseq();
final long remoteCseq = ((CSeqHeader) request.getHeader(CSeqHeader.NAME)).getSeqNumber();
if(isAckRetranmission) {
// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
if(!isAck) {
final SipServletResponse response = sipServletRequest.createResponse(Response.SERVER_INTERNAL_ERROR, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
}
if(Request.INVITE.equalsIgnoreCase(method)){
//if it's a reinvite, we reset the ACK retransmission flag
sipSession.setAckReceived(false);
if(logger.isDebugEnabled()) {
logger.debug("resetting the ack retransmission flag on the sip session " + sipSession.getKey() + " because following reINVITE has been received " + request);
}
}
sipSession.setCseq(remoteCseq);
}
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
final SubsequentDispatchTask dispatchTask = new SubsequentDispatchTask(sipServletRequest, sipProvider);
// if the flag is set we bypass the executor
if(sipApplicationDispatcher.isBypassRequestExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
}
public static class SubsequentDispatchTask extends DispatchTask {
SubsequentDispatchTask(SipServletRequestImpl sipServletRequest, SipProvider sipProvider) {
super(sipServletRequest, sipProvider);
}
public void dispatch() throws DispatcherException {
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl)sipServletMessage;
final MobicentsSipSession sipSession = sipServletRequest.getSipSession();
final MobicentsSipApplicationSession appSession = sipSession.getSipApplicationSession();
final SipContext sipContext = appSession.getSipContext();
final SipManager sipManager = (SipManager)sipContext.getManager();
final Request request = (Request) sipServletRequest.getMessage();
sipContext.enterSipApp(sipServletRequest, null, sipManager, true, true);
final String requestMethod = sipServletRequest.getMethod();
try {
sipSession.setSessionCreatingTransaction(sipServletRequest.getTransaction());
// JSR 289 Section 6.2.1 :
// any state transition caused by the reception of a SIP message,
// the state change must be accomplished by the container before calling
// the service() method of any SipServlet to handle the incoming message.
sipSession.updateStateOnSubsequentRequest(sipServletRequest, true);
try {
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if(Request.NOTIFY.equals(requestMethod)) {
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
if (subscriptionStateHeader != null &&
(SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.addSubscription(sipServletRequest);
}
}
// See if the subsequent request should go directly to the proxy
final ProxyImpl proxy = sipSession.getProxy();
if(proxy != null) {
final ProxyBranchImpl finalBranch = proxy.getFinalBranchForSubsequentRequests();
if(finalBranch != null) {
proxy.setAckReceived(requestMethod.equalsIgnoreCase(Request.ACK));
proxy.setOriginalRequest(sipServletRequest);
// if(!isAckRetranmission) { // We should pass the ack retrans (implied by 10.2.4.1 Handling 2xx Responses to INVITE)
callServlet(sipServletRequest);
finalBranch.proxySubsequentRequest(sipServletRequest);
} else if(requestMethod.equals(Request.PRACK)) {
callServlet(sipServletRequest);
List<ProxyBranch> branches = proxy.getProxyBranches();
for(ProxyBranch pb : branches) {
ProxyBranchImpl proxyBranch = (ProxyBranchImpl) pb;
if(proxyBranch.isWaitingForPrack()) {
proxyBranch.proxyDialogStateless(sipServletRequest);
proxyBranch.setWaitingForPrack(false);
}
}
}
}
// If it's not for a proxy then it's just an AR, so go to the next application
else {
callServlet(sipServletRequest);
}
} catch (ServletException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (IOException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
}
} finally {
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if(Request.NOTIFY.equals(requestMethod)) {
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
if (subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState())) {
sipSession.removeSubscription(sipServletRequest);
}
}
sipContext.exitSipApp(sipServletRequest, null);
}
//nothing more needs to be done, either the app acted as UA, PROXY or B2BUA. in any case we stop routing
}
}
}
| false | true | public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
final String method = request.getMethod();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
// Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
try {
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
} catch(IllegalArgumentException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, e);
}
if(applicationId == null && applicationName == null) {
javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI();
final String host = sipRequestUri.getHost();
final int port = sipRequestUri.getPort();
final String transport = JainSipUtils.findTransport(request);
final boolean isAnotherDomain = sipApplicationDispatcher.isExternal(host, port, transport);
//Issue 823 (http://code.google.com/p/mobicents/issues/detail?id=823) :
// Container should proxy statelessly subsequent requests not targeted at itself
if(isAnotherDomain) {
// Some UA are misbehaving and don't follow the non record proxy so they sent subsequent requests to the container (due to oubound proxy set probably) instead of directly to the UA
// so we proxy statelessly those requests
if(logger.isDebugEnabled()) {
logger.debug("No application found to handle this request " + request + " with the following popped route header " + poppedRouteHeader + " so forwarding statelessly to the outside since it is not targeted at the container");
}
try {
sipProvider.sendRequest(request);
} catch (SipException e) {
throw new DispatcherException("cannot proxy statelessly outside of the container the following request " + request, e);
}
return;
} else {
if(Request.ACK.equals(method)) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
} else {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader + ", it may already have been invalidated or timed out");
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
", it may already have been invalidated or timed out");
}
}
}
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
}
final SipManager sipManager = (SipManager)sipContext.getManager();
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
}
if(sipApplicationSession == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSessionKey(key);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
final boolean isAck = Request.ACK.equalsIgnoreCase(method);
final boolean isAckRetranmission = sipSession.isAckReceived() && isAck;
if(isAck) {
sipSession.setAckReceived(true);
}
//CSeq validation should only be done for non proxy applications
if(sipSession.getProxy() == null) {
final long localCseq = sipSession.getCseq();
final long remoteCseq = ((CSeqHeader) request.getHeader(CSeqHeader.NAME)).getSeqNumber();
if(isAckRetranmission) {
// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
if(!isAck) {
final SipServletResponse response = sipServletRequest.createResponse(Response.SERVER_INTERNAL_ERROR, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
}
if(Request.INVITE.equalsIgnoreCase(method)){
//if it's a reinvite, we reset the ACK retransmission flag
sipSession.setAckReceived(false);
if(logger.isDebugEnabled()) {
logger.debug("resetting the ack retransmission flag on the sip session " + sipSession.getKey() + " because following reINVITE has been received " + request);
}
}
sipSession.setCseq(remoteCseq);
}
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
final SubsequentDispatchTask dispatchTask = new SubsequentDispatchTask(sipServletRequest, sipProvider);
// if the flag is set we bypass the executor
if(sipApplicationDispatcher.isBypassRequestExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
}
| public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
final String method = request.getMethod();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
// Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
try {
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
} catch(IllegalArgumentException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, e);
}
if(applicationId == null && applicationName == null) {
javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI();
final String host = sipRequestUri.getHost();
final int port = sipRequestUri.getPort();
final String transport = JainSipUtils.findTransport(request);
final boolean isAnotherDomain = sipApplicationDispatcher.isExternal(host, port, transport);
//Issue 823 (http://code.google.com/p/mobicents/issues/detail?id=823) :
// Container should proxy statelessly subsequent requests not targeted at itself
if(isAnotherDomain) {
// Some UA are misbehaving and don't follow the non record proxy so they sent subsequent requests to the container (due to oubound proxy set probably) instead of directly to the UA
// so we proxy statelessly those requests
if(logger.isDebugEnabled()) {
logger.debug("No application found to handle this request " + request + " with the following popped route header " + poppedRouteHeader + " so forwarding statelessly to the outside since it is not targeted at the container");
}
try {
sipProvider.sendRequest(request);
} catch (SipException e) {
throw new DispatcherException("cannot proxy statelessly outside of the container the following request " + request, e);
}
return;
} else {
if(Request.ACK.equals(method)) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
} else {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
}
}
}
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request);
}
}
final SipManager sipManager = (SipManager)sipContext.getManager();
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
}
if(sipApplicationSession == null) {
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
", it may already have been invalidated or timed out");
}
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
if(poppedRouteHeader != null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ", it may already have been invalidated or timed out");
} else {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session to this subsequent request " + request +
", it may already have been invalidated or timed out");
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSessionKey(key);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
final boolean isAck = Request.ACK.equalsIgnoreCase(method);
final boolean isAckRetranmission = sipSession.isAckReceived() && isAck;
if(isAck) {
sipSession.setAckReceived(true);
}
//CSeq validation should only be done for non proxy applications
if(sipSession.getProxy() == null) {
final long localCseq = sipSession.getCseq();
final long remoteCseq = ((CSeqHeader) request.getHeader(CSeqHeader.NAME)).getSeqNumber();
if(isAckRetranmission) {
// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
if(!isAck) {
final SipServletResponse response = sipServletRequest.createResponse(Response.SERVER_INTERNAL_ERROR, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
}
if(Request.INVITE.equalsIgnoreCase(method)){
//if it's a reinvite, we reset the ACK retransmission flag
sipSession.setAckReceived(false);
if(logger.isDebugEnabled()) {
logger.debug("resetting the ack retransmission flag on the sip session " + sipSession.getKey() + " because following reINVITE has been received " + request);
}
}
sipSession.setCseq(remoteCseq);
}
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
final SubsequentDispatchTask dispatchTask = new SubsequentDispatchTask(sipServletRequest, sipProvider);
// if the flag is set we bypass the executor
if(sipApplicationDispatcher.isBypassRequestExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
}
|
diff --git a/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionStart.java b/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionStart.java
index fe69eb7..f6afe25 100644
--- a/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionStart.java
+++ b/src/net/invisioncraft/plugins/salesmania/commands/auction/AuctionStart.java
@@ -1,131 +1,131 @@
/*
Copyright 2012 Byte 2 O Software LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.invisioncraft.plugins.salesmania.commands.auction;
import net.invisioncraft.plugins.salesmania.Auction;
import net.invisioncraft.plugins.salesmania.CommandHandler;
import net.invisioncraft.plugins.salesmania.Salesmania;
import net.invisioncraft.plugins.salesmania.configuration.AuctionSettings;
import net.invisioncraft.plugins.salesmania.configuration.Locale;
import net.invisioncraft.plugins.salesmania.util.ItemManager;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class AuctionStart extends CommandHandler {
AuctionSettings auctionSettings;
public AuctionStart(Salesmania plugin) {
super(plugin);
auctionSettings = plugin.getSettings().getAuctionSettings();
}
@Override
public boolean execute(CommandSender sender, Command command, String label, String[] args) {
Locale locale = plugin.getLocaleHandler().getLocale(sender);
// Console check
if(!(sender instanceof Player)) {
sender.sendMessage(locale.getMessage("Console.cantStartAuction"));
return false;
}
Player player = (Player) sender;
ItemStack itemStack = player.getItemInHand().clone();
// Disable check
if(!auctionSettings.getEnabled()) {
sender.sendMessage(locale.getMessage("Auction.disabled"));
return false;
}
// Creative check
if(!auctionSettings.getAllowCreative() && player.getGameMode() == GameMode.CREATIVE) {
sender.sendMessage(locale.getMessage("Auction.noCreative"));
return false;
}
// Syntax check
if(args.length < 2) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
float startingBid;
int quantity;
try {
startingBid = Float.valueOf(args[1]);
quantity = Integer.valueOf(args[2]);
} catch (NumberFormatException ex) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
// Permission check
- if(!sender.hasPermission("salesmania.auction.queue")) {
+ if(!sender.hasPermission("salesmania.auction.start")) {
sender.sendMessage(String.format(
locale.getMessage("Permission.noPermission"),
- locale.getMessage("Permisson.Auction.queue")));
+ locale.getMessage("Permisson.Auction.start")));
return false;
}
// Blacklist check
if(auctionSettings.isBlacklisted(itemStack)) {
player.sendMessage(String.format(
locale.getMessage("Auction.itemBlacklisted"), ItemManager.getName(itemStack)));
return false;
}
// Quantity check
if(quantity > ItemManager.getQuantity(player, itemStack)) {
player.sendMessage(locale.getMessage("Auction.notEnough"));
return false;
}
if(quantity < 1) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
else itemStack.setAmount(quantity);
Auction auction = new Auction(plugin);
switch(auction.queue(player, itemStack, startingBid)) {
case QUEUE_FULL:
player.sendMessage(locale.getMessage("Auction.queueFull"));
return false;
case PLAYER_QUEUE_FULL:
player.sendMessage(locale.getMessage("Auction.playerQueueFull"));
return false;
case UNDER_MIN:
player.sendMessage(String.format(locale.getMessage("Auction.startUnderMin"),
auctionSettings.getMinStart()));
return false;
case OVER_MAX:
player.sendMessage(String.format(locale.getMessage("Auction.startOverMax"),
auctionSettings.getMaxStart()));
return false;
case CANT_AFFORD_TAX:
player.sendMessage(String.format(locale.getMessage("Auction.cantAffordTax"),
auction.getStartTax()));
case QUEUE_SUCCESS:
player.sendMessage(locale.getMessage("Auction.queued"));
case SUCCESS:
return true;
}
return false;
}
}
| false | true | public boolean execute(CommandSender sender, Command command, String label, String[] args) {
Locale locale = plugin.getLocaleHandler().getLocale(sender);
// Console check
if(!(sender instanceof Player)) {
sender.sendMessage(locale.getMessage("Console.cantStartAuction"));
return false;
}
Player player = (Player) sender;
ItemStack itemStack = player.getItemInHand().clone();
// Disable check
if(!auctionSettings.getEnabled()) {
sender.sendMessage(locale.getMessage("Auction.disabled"));
return false;
}
// Creative check
if(!auctionSettings.getAllowCreative() && player.getGameMode() == GameMode.CREATIVE) {
sender.sendMessage(locale.getMessage("Auction.noCreative"));
return false;
}
// Syntax check
if(args.length < 2) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
float startingBid;
int quantity;
try {
startingBid = Float.valueOf(args[1]);
quantity = Integer.valueOf(args[2]);
} catch (NumberFormatException ex) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
// Permission check
if(!sender.hasPermission("salesmania.auction.queue")) {
sender.sendMessage(String.format(
locale.getMessage("Permission.noPermission"),
locale.getMessage("Permisson.Auction.queue")));
return false;
}
// Blacklist check
if(auctionSettings.isBlacklisted(itemStack)) {
player.sendMessage(String.format(
locale.getMessage("Auction.itemBlacklisted"), ItemManager.getName(itemStack)));
return false;
}
// Quantity check
if(quantity > ItemManager.getQuantity(player, itemStack)) {
player.sendMessage(locale.getMessage("Auction.notEnough"));
return false;
}
if(quantity < 1) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
else itemStack.setAmount(quantity);
Auction auction = new Auction(plugin);
switch(auction.queue(player, itemStack, startingBid)) {
case QUEUE_FULL:
player.sendMessage(locale.getMessage("Auction.queueFull"));
return false;
case PLAYER_QUEUE_FULL:
player.sendMessage(locale.getMessage("Auction.playerQueueFull"));
return false;
case UNDER_MIN:
player.sendMessage(String.format(locale.getMessage("Auction.startUnderMin"),
auctionSettings.getMinStart()));
return false;
case OVER_MAX:
player.sendMessage(String.format(locale.getMessage("Auction.startOverMax"),
auctionSettings.getMaxStart()));
return false;
case CANT_AFFORD_TAX:
player.sendMessage(String.format(locale.getMessage("Auction.cantAffordTax"),
auction.getStartTax()));
case QUEUE_SUCCESS:
player.sendMessage(locale.getMessage("Auction.queued"));
case SUCCESS:
return true;
}
return false;
}
| public boolean execute(CommandSender sender, Command command, String label, String[] args) {
Locale locale = plugin.getLocaleHandler().getLocale(sender);
// Console check
if(!(sender instanceof Player)) {
sender.sendMessage(locale.getMessage("Console.cantStartAuction"));
return false;
}
Player player = (Player) sender;
ItemStack itemStack = player.getItemInHand().clone();
// Disable check
if(!auctionSettings.getEnabled()) {
sender.sendMessage(locale.getMessage("Auction.disabled"));
return false;
}
// Creative check
if(!auctionSettings.getAllowCreative() && player.getGameMode() == GameMode.CREATIVE) {
sender.sendMessage(locale.getMessage("Auction.noCreative"));
return false;
}
// Syntax check
if(args.length < 2) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
float startingBid;
int quantity;
try {
startingBid = Float.valueOf(args[1]);
quantity = Integer.valueOf(args[2]);
} catch (NumberFormatException ex) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
// Permission check
if(!sender.hasPermission("salesmania.auction.start")) {
sender.sendMessage(String.format(
locale.getMessage("Permission.noPermission"),
locale.getMessage("Permisson.Auction.start")));
return false;
}
// Blacklist check
if(auctionSettings.isBlacklisted(itemStack)) {
player.sendMessage(String.format(
locale.getMessage("Auction.itemBlacklisted"), ItemManager.getName(itemStack)));
return false;
}
// Quantity check
if(quantity > ItemManager.getQuantity(player, itemStack)) {
player.sendMessage(locale.getMessage("Auction.notEnough"));
return false;
}
if(quantity < 1) {
sender.sendMessage(locale.getMessage("Syntax.Auction.auctionStart"));
return false;
}
else itemStack.setAmount(quantity);
Auction auction = new Auction(plugin);
switch(auction.queue(player, itemStack, startingBid)) {
case QUEUE_FULL:
player.sendMessage(locale.getMessage("Auction.queueFull"));
return false;
case PLAYER_QUEUE_FULL:
player.sendMessage(locale.getMessage("Auction.playerQueueFull"));
return false;
case UNDER_MIN:
player.sendMessage(String.format(locale.getMessage("Auction.startUnderMin"),
auctionSettings.getMinStart()));
return false;
case OVER_MAX:
player.sendMessage(String.format(locale.getMessage("Auction.startOverMax"),
auctionSettings.getMaxStart()));
return false;
case CANT_AFFORD_TAX:
player.sendMessage(String.format(locale.getMessage("Auction.cantAffordTax"),
auction.getStartTax()));
case QUEUE_SUCCESS:
player.sendMessage(locale.getMessage("Auction.queued"));
case SUCCESS:
return true;
}
return false;
}
|
diff --git a/src/me/libraryaddict/Hungergames/Commands/BuyKit.java b/src/me/libraryaddict/Hungergames/Commands/BuyKit.java
index 9f93fcd..8edab5c 100644
--- a/src/me/libraryaddict/Hungergames/Commands/BuyKit.java
+++ b/src/me/libraryaddict/Hungergames/Commands/BuyKit.java
@@ -1,55 +1,55 @@
package me.libraryaddict.Hungergames.Commands;
import me.libraryaddict.Hungergames.Configs.TranslationConfig;
import me.libraryaddict.Hungergames.Managers.KitManager;
import me.libraryaddict.Hungergames.Managers.PlayerManager;
import me.libraryaddict.Hungergames.Types.HungergamesApi;
import me.libraryaddict.Hungergames.Types.Gamer;
import me.libraryaddict.Hungergames.Types.GiveKitThread;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class BuyKit implements CommandExecutor {
private TranslationConfig cm = HungergamesApi.getConfigManager().getTranslationsConfig();
public String description = "When mysql is enabled you can use this command to buy kits";
private KitManager kits = HungergamesApi.getKitManager();
private PlayerManager pm = HungergamesApi.getPlayerManager();
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Gamer gamer = pm.getGamer(sender.getName());
if (args.length > 0) {
me.libraryaddict.Hungergames.Types.Kit kit = kits.getKitByName(StringUtils.join(args, " "));
if (kit != null) {
if (gamer.getBalance() < kit.getPrice()) {
sender.sendMessage(cm.getCommandBuyKitCantAfford());
return true;
}
- if (kit.getPrice() == -1 || kit.isFree()) {
+ if (kit.getPrice() < 0 || kit.isFree()) {
sender.sendMessage(cm.getCommandBuyKitCantBuyKit());
return true;
}
if (kits.ownsKit(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitAlreadyOwn());
return true;
}
if (!HungergamesApi.getConfigManager().getMainConfig().isMysqlEnabled()) {
sender.sendMessage(cm.getCommandBuyKitMysqlNotEnabled());
return true;
}
if (!kits.addKitToPlayer(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitKitsNotLoaded());
} else {
gamer.addBalance(-kit.getPrice());
new GiveKitThread(gamer.getName(), kit.getName()).start();
sender.sendMessage(String.format(cm.getCommandBuyKitPurchasedKit(), kit.getName()));
}
return true;
}
}
sender.sendMessage(cm.getCommandBuyKitNoArgs());
return true;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Gamer gamer = pm.getGamer(sender.getName());
if (args.length > 0) {
me.libraryaddict.Hungergames.Types.Kit kit = kits.getKitByName(StringUtils.join(args, " "));
if (kit != null) {
if (gamer.getBalance() < kit.getPrice()) {
sender.sendMessage(cm.getCommandBuyKitCantAfford());
return true;
}
if (kit.getPrice() == -1 || kit.isFree()) {
sender.sendMessage(cm.getCommandBuyKitCantBuyKit());
return true;
}
if (kits.ownsKit(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitAlreadyOwn());
return true;
}
if (!HungergamesApi.getConfigManager().getMainConfig().isMysqlEnabled()) {
sender.sendMessage(cm.getCommandBuyKitMysqlNotEnabled());
return true;
}
if (!kits.addKitToPlayer(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitKitsNotLoaded());
} else {
gamer.addBalance(-kit.getPrice());
new GiveKitThread(gamer.getName(), kit.getName()).start();
sender.sendMessage(String.format(cm.getCommandBuyKitPurchasedKit(), kit.getName()));
}
return true;
}
}
sender.sendMessage(cm.getCommandBuyKitNoArgs());
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Gamer gamer = pm.getGamer(sender.getName());
if (args.length > 0) {
me.libraryaddict.Hungergames.Types.Kit kit = kits.getKitByName(StringUtils.join(args, " "));
if (kit != null) {
if (gamer.getBalance() < kit.getPrice()) {
sender.sendMessage(cm.getCommandBuyKitCantAfford());
return true;
}
if (kit.getPrice() < 0 || kit.isFree()) {
sender.sendMessage(cm.getCommandBuyKitCantBuyKit());
return true;
}
if (kits.ownsKit(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitAlreadyOwn());
return true;
}
if (!HungergamesApi.getConfigManager().getMainConfig().isMysqlEnabled()) {
sender.sendMessage(cm.getCommandBuyKitMysqlNotEnabled());
return true;
}
if (!kits.addKitToPlayer(gamer.getPlayer(), kit)) {
sender.sendMessage(cm.getCommandBuyKitKitsNotLoaded());
} else {
gamer.addBalance(-kit.getPrice());
new GiveKitThread(gamer.getName(), kit.getName()).start();
sender.sendMessage(String.format(cm.getCommandBuyKitPurchasedKit(), kit.getName()));
}
return true;
}
}
sender.sendMessage(cm.getCommandBuyKitNoArgs());
return true;
}
|
diff --git a/RedditInPictures-Free/src/com/antew/redditinpictures/ui/ImageGridFragmentFree.java b/RedditInPictures-Free/src/com/antew/redditinpictures/ui/ImageGridFragmentFree.java
index bbb5433..076df64 100644
--- a/RedditInPictures-Free/src/com/antew/redditinpictures/ui/ImageGridFragmentFree.java
+++ b/RedditInPictures-Free/src/com/antew/redditinpictures/ui/ImageGridFragmentFree.java
@@ -1,119 +1,118 @@
package com.antew.redditinpictures.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.GridView;
import android.widget.RelativeLayout;
import com.antew.redditinpictures.R;
import com.antew.redditinpictures.library.logging.Log;
import com.antew.redditinpictures.library.ui.ImageDetailActivity;
import com.antew.redditinpictures.preferences.SharedPreferencesHelperFree;
import com.antew.redditinpictures.util.AdUtil;
import com.antew.redditinpictures.util.ConstsFree;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class ImageGridFragmentFree extends com.antew.redditinpictures.library.ui.ImageGridFragment {
public static final String TAG = ImageGridFragmentFree.class.getSimpleName();
private AdView mAdView;
private GridView mGridView;
private BroadcastReceiver mHideAds = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (mAdView != null) {
mAdView.setVisibility(View.GONE);
mAdView.destroy();
}
// Remove the margin from the GridView
if (mGridView != null) {
RelativeLayout.LayoutParams gridViewParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
gridViewParams.setMargins(0, 0, 0, 0);
mGridView.setLayoutParams(gridViewParams);
}
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout v = (RelativeLayout) super.onCreateView(inflater, container, savedInstanceState);
mGridView = (GridView) v.findViewById(R.id.gridView);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mHideAds , new IntentFilter(ConstsFree.REMOVE_ADS));
/**
* If ads are disabled we don't need to load any
*/
if (!SharedPreferencesHelperFree.getDisableAds(getActivity())) {
mAdView = new AdView(getActivity(), AdSize.SMART_BANNER, ConstsFree.ADMOB_ID);
/**
* The AdView should be attached to the bottom of the screen, with the GridView position above it
*/
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
v.addView(mAdView, adParams);
/**
* We use the onGlobalLayoutListener here in order to adjust the bottom margin of the GridView
* so that when the user scrolls to the bottom of the GridView the last images are not obscured
* by the AdView
*/
mAdView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (mAdView != null && mGridView != null) {
int height = mAdView.getHeight();
if (height > 0) {
RelativeLayout.LayoutParams gridViewParams = (RelativeLayout.LayoutParams) mGridView.getLayoutParams();
gridViewParams.setMargins(0, 0, 0, height);
mGridView.setLayoutParams(gridViewParams);
mAdView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
- Log.i("onGlobalLayout", mAdView.getHeight() + "");
}
});
mAdView.loadAd(AdUtil.getAdRequest());
}
return v;
}
/**
* Unregister our BroadcastReceiver
*/
@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mHideAds);
if (mAdView != null) {
mAdView.destroy();
mAdView = null;
}
super.onDestroy();
}
@Override
public Class<? extends ImageDetailActivity> getImageDetailActivityClass() {
return ImageDetailActivityFree.class;
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout v = (RelativeLayout) super.onCreateView(inflater, container, savedInstanceState);
mGridView = (GridView) v.findViewById(R.id.gridView);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mHideAds , new IntentFilter(ConstsFree.REMOVE_ADS));
/**
* If ads are disabled we don't need to load any
*/
if (!SharedPreferencesHelperFree.getDisableAds(getActivity())) {
mAdView = new AdView(getActivity(), AdSize.SMART_BANNER, ConstsFree.ADMOB_ID);
/**
* The AdView should be attached to the bottom of the screen, with the GridView position above it
*/
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
v.addView(mAdView, adParams);
/**
* We use the onGlobalLayoutListener here in order to adjust the bottom margin of the GridView
* so that when the user scrolls to the bottom of the GridView the last images are not obscured
* by the AdView
*/
mAdView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (mAdView != null && mGridView != null) {
int height = mAdView.getHeight();
if (height > 0) {
RelativeLayout.LayoutParams gridViewParams = (RelativeLayout.LayoutParams) mGridView.getLayoutParams();
gridViewParams.setMargins(0, 0, 0, height);
mGridView.setLayoutParams(gridViewParams);
mAdView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
Log.i("onGlobalLayout", mAdView.getHeight() + "");
}
});
mAdView.loadAd(AdUtil.getAdRequest());
}
return v;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout v = (RelativeLayout) super.onCreateView(inflater, container, savedInstanceState);
mGridView = (GridView) v.findViewById(R.id.gridView);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mHideAds , new IntentFilter(ConstsFree.REMOVE_ADS));
/**
* If ads are disabled we don't need to load any
*/
if (!SharedPreferencesHelperFree.getDisableAds(getActivity())) {
mAdView = new AdView(getActivity(), AdSize.SMART_BANNER, ConstsFree.ADMOB_ID);
/**
* The AdView should be attached to the bottom of the screen, with the GridView position above it
*/
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
v.addView(mAdView, adParams);
/**
* We use the onGlobalLayoutListener here in order to adjust the bottom margin of the GridView
* so that when the user scrolls to the bottom of the GridView the last images are not obscured
* by the AdView
*/
mAdView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (mAdView != null && mGridView != null) {
int height = mAdView.getHeight();
if (height > 0) {
RelativeLayout.LayoutParams gridViewParams = (RelativeLayout.LayoutParams) mGridView.getLayoutParams();
gridViewParams.setMargins(0, 0, 0, height);
mGridView.setLayoutParams(gridViewParams);
mAdView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
}
});
mAdView.loadAd(AdUtil.getAdRequest());
}
return v;
}
|
diff --git a/util/src/main/java/com/psddev/dari/util/CodeDebugServlet.java b/util/src/main/java/com/psddev/dari/util/CodeDebugServlet.java
index ae1b5150..c71a6c54 100644
--- a/util/src/main/java/com/psddev/dari/util/CodeDebugServlet.java
+++ b/util/src/main/java/com/psddev/dari/util/CodeDebugServlet.java
@@ -1,630 +1,631 @@
package com.psddev.dari.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
@DebugFilter.Path("code")
public class CodeDebugServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String INPUTS_ATTRIBUTE = CodeDebugServlet.class.getName() + ".inputs";
public static final String INCLUDE_IMPORTS_SETTING = "dari/code/includeImports";
public static final String EXCLUDE_IMPORTS_SETTING = "dari/code/excludeImports";
private static final String WEB_INF_CLASSES_PATH = "/WEB-INF/classes/";
private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<Map<String, Object>>() { };
@Override
protected void service(
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
WebPageContext page = new WebPageContext(this, request, response);
String action = page.param(String.class, "action");
if ("run".equals(action)) {
if (page.param(String.class, "isSave") != null) {
doSave(page);
} else {
page.paramOrDefault(Type.class, "type", Type.JAVA).run(page);
}
} else {
doEdit(page);
}
}
private static File getFile(WebPageContext page) throws IOException {
String file = page.param(String.class, "file");
if (file == null) {
String servletPath = page.param(String.class, "servletPath");
if (servletPath != null) {
file = page.getServletContext().getRealPath(servletPath);
}
}
if (file == null) {
return null;
}
File fileInstance = new File(file);
if (!fileInstance.exists()) {
IoUtils.createParentDirectories(fileInstance);
}
return fileInstance;
}
private void doSave(WebPageContext page) throws IOException, ServletException {
if (!page.isFormPost()) {
throw new IllegalArgumentException("Must post!");
}
new DebugFilter.PageWriter(page) {{
File file = getFile(page);
ErrorUtils.errorIfNull(file, "file");
String code = page.paramOrDefault(String.class, "code", "");
try {
CLASS_FOUND:
if (file.isDirectory()) {
Object result = CodeUtils.evaluateJava(code);
if (result instanceof Collection) {
for (Object item : (Collection<?>) result) {
if (item instanceof Class) {
file = new File(file, ((Class<?>) item).getName().replace('.', File.separatorChar) + ".java");
IoUtils.createParentDirectories(file);
break CLASS_FOUND;
}
}
}
throw new IllegalArgumentException("Syntax error!");
}
IoUtils.createFile(file);
FileOutputStream fileOutput = new FileOutputStream(file);
try {
fileOutput.write(code.replaceAll("(?:\r\n|[\r\n])", "\n").getBytes("UTF-8"));
writeStart("p", "class", "alert alert-success");
writeHtml("Saved Successfully! (");
writeObject(new Date());
writeHtml(")");
writeEnd();
} finally {
fileOutput.close();
}
} catch (Exception ex) {
writeStart("pre", "class", "alert alert-error");
writeObject(ex);
writeEnd();
}
}};
}
private void doEdit(WebPageContext page) throws IOException, ServletException {
final Type type = page.paramOrDefault(Type.class, "type", Type.JAVA);
final File file = getFile(page);
final StringBuilder codeBuilder = new StringBuilder();
if (file != null) {
if (file.exists()) {
if (file.isDirectory()) {
} else {
codeBuilder.append(IoUtils.toString(file, StringUtils.UTF_8));
}
} else {
String filePath = file.getPath();
if (filePath.endsWith(".java")) {
filePath = filePath.substring(0, filePath.length() - 5);
for (File sourceDirectory : CodeUtils.getSourceDirectories()) { String sourceDirectoryPath = sourceDirectory.getPath();
if (filePath.startsWith(sourceDirectoryPath)) {
String classPath = filePath.substring(sourceDirectoryPath.length());
if (classPath.startsWith(File.separator)) {
classPath = classPath.substring(1);
}
int lastSepAt = classPath.lastIndexOf(File.separatorChar);
if (lastSepAt < 0) {
codeBuilder.append("public class ");
codeBuilder.append(classPath);
} else {
codeBuilder.append("package ");
codeBuilder.append(classPath.substring(0, lastSepAt).replace(File.separatorChar, '.'));
codeBuilder.append(";\n\npublic class ");
codeBuilder.append(classPath.substring(lastSepAt + 1));
}
codeBuilder.append(" {\n}");
break;
}
}
}
}
} else {
Set<String> imports = findImports();
imports.add("com.psddev.dari.db.*");
imports.add("com.psddev.dari.util.*");
imports.add("java.util.*");
String includes = Settings.get(String.class, INCLUDE_IMPORTS_SETTING);
if (!ObjectUtils.isBlank(includes)) {
Collections.addAll(imports, includes.trim().split("\\s*,?\\s+"));
}
String excludes = Settings.get(String.class, EXCLUDE_IMPORTS_SETTING);
if (!ObjectUtils.isBlank(excludes)) {
for (String exclude : excludes.trim().split("\\s*,?\\s+")) {
imports.remove(exclude);
}
}
for (String i : imports) {
codeBuilder.append("import ");
codeBuilder.append(i);
codeBuilder.append(";\n");
}
codeBuilder.append('\n');
codeBuilder.append("public class Code {\n");
codeBuilder.append(" public static Object main() throws Throwable {\n");
String query = page.param(String.class, "query");
String objectClass = page.paramOrDefault(String.class, "objectClass", "Object");
if (query == null) {
codeBuilder.append(" return null;\n");
} else {
codeBuilder.append(" Query<").append(objectClass).append("> query = ").append(query).append(";\n");
codeBuilder.append(" PaginatedResult<").append(objectClass).append("> result = query.select(0L, 10);\n");
codeBuilder.append(" return result;\n");
}
codeBuilder.append(" }\n");
codeBuilder.append("}\n");
}
new DebugFilter.PageWriter(page) {{
List<Object> inputs = CodeDebugServlet.Static.getInputs(getServletContext());
Object input = inputs == null || inputs.isEmpty() ? null : inputs.get(0);
String name;
if (file == null) {
name = null;
} else {
name = file.toString();
int slashAt = name.lastIndexOf('/');
if (slashAt > -1) {
name = name.substring(slashAt + 1);
}
}
startPage("Code Editor", name);
writeStart("div", "class", "row-fluid");
if (input != null) {
writeStart("div", "class", "codeInput", "style", "bottom: 65px; position: fixed; top: 55px; width: 18%; z-index: 1000;");
writeStart("h2").writeHtml("Input").writeEnd();
writeStart("div", "style", "bottom: 0; overflow: auto; position: absolute; top: 38px; width: 100%;");
writeObject(input);
writeEnd();
writeEnd();
writeStart("style", "type", "text/css");
write(".codeInput pre { white-space: pre; word-break: normal; word-wrap: normal; }");
writeEnd();
writeStart("script", "type", "text/javascript");
write("$('.codeInput').hover(function() {");
write("$(this).css('width', '50%');");
write("}, function() {");
write("$(this).css('width', '18%');");
write("});");
writeEnd();
}
writeStart("div",
"class", input != null ? "span9" : "span12",
"style", input != null ? "margin-left: 20%" : null);
writeStart("form",
"action", page.url(null),
"class", "code",
"method", "post",
"style", "margin-bottom: 70px;",
"target", "result");
writeTag("input", "name", "action", "type", "hidden", "value", "run");
writeTag("input", "name", "type", "type", "hidden", "value", type);
writeTag("input", "name", "file", "type", "hidden", "value", file);
writeTag("input", "name", "jspPreviewUrl", "type", "hidden", "value", page.param(String.class, "jspPreviewUrl"));
writeStart("textarea", "name", "code");
writeHtml(codeBuilder);
writeEnd();
writeStart("div",
"class", "form-actions",
"style", "bottom: 0; left: 0; margin: 0; padding: 10px 20px; position:fixed; right: 0; z-index: 1000;");
writeTag("input", "class", "btn btn-primary", "type", "submit", "value", "Run");
writeStart("label", "class", "checkbox", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;");
writeTag("input", "name", "isLiveResult", "type", "checkbox");
writeHtml("Live Result");
writeEnd();
writeStart("label", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;", "title", "Shortcut: ?_vim=true");
boolean vimMode = page.param(boolean.class, "_vim");
writeStart("label", "class", "checkbox", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;");
writeTag("input", "name", "_vim", "type", "checkbox", "value", "true", vimMode ? "checked" : "_unchecked", "true");
writeHtml("Vim Mode");
writeEnd();
writeEnd();
writeTag("input",
"class", "btn btn-success pull-right",
"name", "isSave",
"type", "submit",
"value", "Save");
writeEnd();
writeEnd();
writeStart("div",
"class", "resultContainer",
"style",
"background: rgba(255, 255, 255, 0.8);" +
"border-color: rgba(0, 0, 0, 0.2);" +
"border-style: solid;" +
"border-width: 0 0 0 1px;" +
"max-height: 45%;" +
"top: 55px;" +
"overflow: auto;" +
"padding: 0px 20px 5px 10px;" +
"position: fixed;" +
+ "z-index: 3;" +
"right: 0px;" +
"width: 35%;");
writeStart("h2").writeHtml("Result").writeEnd();
writeStart("div", "class", "frame", "name", "result");
writeEnd();
writeEnd();
writeStart("script", "type", "text/javascript");
write("$('body').frame();");
write("var $codeForm = $('form.code');");
write("setTimeout(function() { $codeForm.submit(); }, 0);");
write("var lineMarkers = [ ];");
write("var columnMarkers = [ ];");
write("var codeMirror = CodeMirror.fromTextArea($('textarea')[0], {");
write("'indentUnit': 4,");
write("'lineNumbers': true,");
write("'lineWrapping': true,");
write("'matchBrackets': true,");
write("'mode': 'text/x-java',");
write("'onChange': $.throttle(1000, function() {");
write("if ($codeForm.find(':checkbox[name=isLiveResult]').is(':checked')) {");
write("$codeForm.submit();");
write("}");
write("})");
write("});");
write("$('input[name=_vim]').change(function() {");
write("codeMirror.setOption('vimMode', $(this).is(':checked'));");
write("});");
write("$('input[name=_vim]').change();");
int line = page.param(int.class, "line");
if (line > 0) {
write("var line = ");
write(String.valueOf(line));
write(" - 1;");
write("codeMirror.setCursor(line);");
write("codeMirror.setLineClass(line, 'selected', 'selected');");
write("$(window).scrollTop(codeMirror.cursorCoords().y - $(window).height() / 2);");
}
write("var $resultContainer = $('.resultContainer');");
write("$resultContainer.find('.frame').bind('load', function() {");
write("$.each(lineMarkers, function() { codeMirror.clearMarker(this); codeMirror.setLineClass(this, null, null); });");
write("$.each(columnMarkers, function() { this.clear(); });");
write("var $frame = $(this).find('.syntaxErrors li').each(function() {");
write("var $error = $(this);");
write("var line = parseInt($error.attr('data-line')) - 1;");
write("var column = parseInt($error.attr('data-column')) - 1;");
write("if (line > -1 && column > -1) {");
write("lineMarkers.push(codeMirror.setMarker(line, '!'));");
write("codeMirror.setLineClass(line, 'errorLine', 'errorLine');");
write("columnMarkers.push(codeMirror.markText({ 'line': line, 'ch': column }, { 'line': line, 'ch': column + 1 }, 'errorColumn'));");
write("}");
write("});");
write("});");
writeEnd();
writeEnd();
writeEnd();
endPage();
}
@Override
public void startBody(String... titles) throws IOException {
writeStart("body");
writeStart("div", "class", "navbar navbar-fixed-top");
writeStart("div", "class", "navbar-inner");
writeStart("div", "class", "container-fluid");
writeStart("span", "class", "brand");
writeStart("a", "href", DebugFilter.Static.getServletPath(page.getRequest(), ""));
writeHtml("Dari");
writeEnd();
writeHtml("Code Editor \u2192 ");
writeEnd();
writeStart("form",
"action", page.url(null),
"method", "get",
"style", "float: left; height: 40px; line-height: 40px; margin: 0; padding-left: 10px;");
writeStart("select",
"class", "span6",
"name", "file",
"onchange", "$(this).closest('form').submit();");
writeStart("option", "value", "");
writeHtml("PLAYGROUND");
writeEnd();
for (File sourceDirectory : CodeUtils.getSourceDirectories()) {
writeStart("optgroup", "label", sourceDirectory);
writeStart("option",
"selected", sourceDirectory.equals(file) ? "selected" : null,
"value", sourceDirectory);
writeHtml("NEW CLASS IN ").writeHtml(sourceDirectory);
writeEnd();
writeFileOption(file, sourceDirectory, sourceDirectory);
writeEnd();
}
writeEnd();
writeEnd();
includeStylesheet("/_resource/chosen/chosen.css");
includeScript("/_resource/chosen/chosen.jquery.min.js");
writeStart("script", "type", "text/javascript");
write("(function() {");
write("$('select[name=file]').chosen({ 'search_contains': true });");
write("})();");
writeEnd();
writeEnd();
writeEnd();
writeEnd();
writeStart("div", "class", "container-fluid", "style", "padding-top: 54px;");
}
private void writeFileOption(File file, File sourceDirectory, File source) throws IOException {
if (source.isDirectory()) {
for (File child : source.listFiles()) {
writeFileOption(file, sourceDirectory, child);
}
} else {
writeStart("option",
"selected", source.equals(file) ? "selected" : null,
"value", source);
writeHtml(source.toString().substring(sourceDirectory.toString().length()));
writeEnd();
}
}
};
}
private Set<String> findImports() {
Set<String> imports = new TreeSet<String>();
addImports(imports, WEB_INF_CLASSES_PATH.length(), WEB_INF_CLASSES_PATH);
return imports;
}
@SuppressWarnings("unchecked")
private void addImports(Set<String> imports, int prefixLength, String path) {
for (String subPath : (Set<String>) getServletContext().getResourcePaths(path)) {
if (subPath.endsWith("/")) {
addImports(imports, prefixLength, subPath);
} else if (subPath.endsWith(".class")) {
imports.add(path.substring(prefixLength).replace('/', '.') + "*");
}
}
}
private enum Type {
JAVA("Java") {
@Override
public void run(WebPageContext page) throws IOException, ServletException {
new DebugFilter.PageWriter(page) {{
try {
Object result = CodeUtils.evaluateJava(page.paramOrDefault(String.class, "code", ""));
if (result instanceof DiagnosticCollector) {
writeStart("pre", "class", "alert alert-error");
writeHtml("Syntax error!\n\n");
writeStart("ol", "class", "syntaxErrors");
for (Diagnostic<?> diagnostic : ((DiagnosticCollector<?>) result).getDiagnostics()) {
if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
writeStart("li", "data-line", diagnostic.getLineNumber(), "data-column", diagnostic.getColumnNumber());
writeHtml(diagnostic.getMessage(null));
writeEnd();
}
}
writeEnd();
writeEnd();
} else if (result instanceof Collection) {
for (Object item : (Collection<?>) result) {
if (item instanceof Class) {
List<Object> inputs = CodeDebugServlet.Static.getInputs(page.getServletContext());
Object input = inputs == null || inputs.isEmpty() ? null : inputs.get(0);
if (input != null) {
Class<?> inputClass = input.getClass();
Class<?> itemClass = (Class<?>) item;
for (Method method : ((Class<?>) item).getDeclaredMethods()) {
Class<?>[] parameterClasses = method.getParameterTypes();
if (parameterClasses.length == 1 &&
parameterClasses[0].isAssignableFrom(inputClass) &&
method.getReturnType().isAssignableFrom(inputClass)) {
Map<String, Object> inputMap = ObjectUtils.to(MAP_TYPE, input);
Map<String, Object> processedMap = ObjectUtils.to(MAP_TYPE, method.invoke(itemClass.newInstance(), input));
Set<String> keys = new HashSet<String>(inputMap.keySet());
keys.addAll(processedMap.keySet());
for (String key : keys) {
Object inputValue = inputMap.get(key);
Object processedValue = processedMap.get(key);
if (ObjectUtils.equals(inputValue, processedValue)) {
processedMap.remove(key);
}
}
result = processedMap;
break;
}
}
}
}
}
writeObject(result);
} else {
writeObject(result);
}
} catch (Exception ex) {
writeStart("pre", "class", "alert alert-error");
writeObject(ex);
writeEnd();
}
}};
}
},
JSP("JSP") {
private final Map<String, Integer> draftIndexes = new HashMap<String, Integer>();
@Override
public void run(WebPageContext page) throws IOException, ServletException {
new DebugFilter.PageWriter(page) {{
ServletContext context = page.getServletContext();
File file = getFile(page);
if (file == null) {
throw new IllegalArgumentException();
}
String servletPath = file.toString().substring(context.getRealPath("/").length() - 1).replace(File.separatorChar, '/');
String draft = "/WEB-INF/_draft" + servletPath;
int dotAt = draft.indexOf('.');
String extension;
if (dotAt < 0) {
extension = "";
} else {
extension = draft.substring(dotAt);
draft = draft.substring(0, dotAt);
}
synchronized (draftIndexes) {
Integer draftIndex = draftIndexes.get(draft);
if (draftIndex == null) {
draftIndex = 0;
draftIndexes.put(draft, draftIndex);
}
IoUtils.delete(new File(context.getRealPath(draft + draftIndex + extension)));
++ draftIndex;
draftIndexes.put(draft, draftIndex);
draft = draft + draftIndex + extension;
}
String realDraft = context.getRealPath(draft);
File realDraftFile = new File(realDraft);
IoUtils.createParentDirectories(realDraftFile);
FileOutputStream realDraftOutput = new FileOutputStream(realDraftFile);
try {
realDraftOutput.write(page.paramOrDefault(String.class, "code", "").getBytes("UTF-8"));
} finally {
realDraftOutput.close();
}
page.getResponse().sendRedirect(
StringUtils.addQueryParameters(
page.param(String.class, "jspPreviewUrl"),
"_jsp", servletPath,
"_draft", draft));
}};
}
};
private final String displayName;
private Type(String displayName) {
this.displayName = displayName;
}
public abstract void run(WebPageContext page) throws IOException, ServletException;
// --- Object support ---
@Override
public String toString() {
return displayName;
}
}
/** {@link CodeDebugServlet} utility methods. */
public static final class Static {
@SuppressWarnings("unchecked")
public static List<Object> getInputs(ServletContext context) {
return (List<Object>) context.getAttribute(INPUTS_ATTRIBUTE);
}
public static void setInputs(ServletContext context, List<Object> inputs) {
context.setAttribute(INPUTS_ATTRIBUTE, inputs);
}
}
}
| true | true | private void doEdit(WebPageContext page) throws IOException, ServletException {
final Type type = page.paramOrDefault(Type.class, "type", Type.JAVA);
final File file = getFile(page);
final StringBuilder codeBuilder = new StringBuilder();
if (file != null) {
if (file.exists()) {
if (file.isDirectory()) {
} else {
codeBuilder.append(IoUtils.toString(file, StringUtils.UTF_8));
}
} else {
String filePath = file.getPath();
if (filePath.endsWith(".java")) {
filePath = filePath.substring(0, filePath.length() - 5);
for (File sourceDirectory : CodeUtils.getSourceDirectories()) { String sourceDirectoryPath = sourceDirectory.getPath();
if (filePath.startsWith(sourceDirectoryPath)) {
String classPath = filePath.substring(sourceDirectoryPath.length());
if (classPath.startsWith(File.separator)) {
classPath = classPath.substring(1);
}
int lastSepAt = classPath.lastIndexOf(File.separatorChar);
if (lastSepAt < 0) {
codeBuilder.append("public class ");
codeBuilder.append(classPath);
} else {
codeBuilder.append("package ");
codeBuilder.append(classPath.substring(0, lastSepAt).replace(File.separatorChar, '.'));
codeBuilder.append(";\n\npublic class ");
codeBuilder.append(classPath.substring(lastSepAt + 1));
}
codeBuilder.append(" {\n}");
break;
}
}
}
}
} else {
Set<String> imports = findImports();
imports.add("com.psddev.dari.db.*");
imports.add("com.psddev.dari.util.*");
imports.add("java.util.*");
String includes = Settings.get(String.class, INCLUDE_IMPORTS_SETTING);
if (!ObjectUtils.isBlank(includes)) {
Collections.addAll(imports, includes.trim().split("\\s*,?\\s+"));
}
String excludes = Settings.get(String.class, EXCLUDE_IMPORTS_SETTING);
if (!ObjectUtils.isBlank(excludes)) {
for (String exclude : excludes.trim().split("\\s*,?\\s+")) {
imports.remove(exclude);
}
}
for (String i : imports) {
codeBuilder.append("import ");
codeBuilder.append(i);
codeBuilder.append(";\n");
}
codeBuilder.append('\n');
codeBuilder.append("public class Code {\n");
codeBuilder.append(" public static Object main() throws Throwable {\n");
String query = page.param(String.class, "query");
String objectClass = page.paramOrDefault(String.class, "objectClass", "Object");
if (query == null) {
codeBuilder.append(" return null;\n");
} else {
codeBuilder.append(" Query<").append(objectClass).append("> query = ").append(query).append(";\n");
codeBuilder.append(" PaginatedResult<").append(objectClass).append("> result = query.select(0L, 10);\n");
codeBuilder.append(" return result;\n");
}
codeBuilder.append(" }\n");
codeBuilder.append("}\n");
}
new DebugFilter.PageWriter(page) {{
List<Object> inputs = CodeDebugServlet.Static.getInputs(getServletContext());
Object input = inputs == null || inputs.isEmpty() ? null : inputs.get(0);
String name;
if (file == null) {
name = null;
} else {
name = file.toString();
int slashAt = name.lastIndexOf('/');
if (slashAt > -1) {
name = name.substring(slashAt + 1);
}
}
startPage("Code Editor", name);
writeStart("div", "class", "row-fluid");
if (input != null) {
writeStart("div", "class", "codeInput", "style", "bottom: 65px; position: fixed; top: 55px; width: 18%; z-index: 1000;");
writeStart("h2").writeHtml("Input").writeEnd();
writeStart("div", "style", "bottom: 0; overflow: auto; position: absolute; top: 38px; width: 100%;");
writeObject(input);
writeEnd();
writeEnd();
writeStart("style", "type", "text/css");
write(".codeInput pre { white-space: pre; word-break: normal; word-wrap: normal; }");
writeEnd();
writeStart("script", "type", "text/javascript");
write("$('.codeInput').hover(function() {");
write("$(this).css('width', '50%');");
write("}, function() {");
write("$(this).css('width', '18%');");
write("});");
writeEnd();
}
writeStart("div",
"class", input != null ? "span9" : "span12",
"style", input != null ? "margin-left: 20%" : null);
writeStart("form",
"action", page.url(null),
"class", "code",
"method", "post",
"style", "margin-bottom: 70px;",
"target", "result");
writeTag("input", "name", "action", "type", "hidden", "value", "run");
writeTag("input", "name", "type", "type", "hidden", "value", type);
writeTag("input", "name", "file", "type", "hidden", "value", file);
writeTag("input", "name", "jspPreviewUrl", "type", "hidden", "value", page.param(String.class, "jspPreviewUrl"));
writeStart("textarea", "name", "code");
writeHtml(codeBuilder);
writeEnd();
writeStart("div",
"class", "form-actions",
"style", "bottom: 0; left: 0; margin: 0; padding: 10px 20px; position:fixed; right: 0; z-index: 1000;");
writeTag("input", "class", "btn btn-primary", "type", "submit", "value", "Run");
writeStart("label", "class", "checkbox", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;");
writeTag("input", "name", "isLiveResult", "type", "checkbox");
writeHtml("Live Result");
writeEnd();
writeStart("label", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;", "title", "Shortcut: ?_vim=true");
boolean vimMode = page.param(boolean.class, "_vim");
writeStart("label", "class", "checkbox", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;");
writeTag("input", "name", "_vim", "type", "checkbox", "value", "true", vimMode ? "checked" : "_unchecked", "true");
writeHtml("Vim Mode");
writeEnd();
writeEnd();
writeTag("input",
"class", "btn btn-success pull-right",
"name", "isSave",
"type", "submit",
"value", "Save");
writeEnd();
writeEnd();
writeStart("div",
"class", "resultContainer",
"style",
"background: rgba(255, 255, 255, 0.8);" +
"border-color: rgba(0, 0, 0, 0.2);" +
"border-style: solid;" +
"border-width: 0 0 0 1px;" +
"max-height: 45%;" +
"top: 55px;" +
"overflow: auto;" +
"padding: 0px 20px 5px 10px;" +
"position: fixed;" +
"right: 0px;" +
"width: 35%;");
writeStart("h2").writeHtml("Result").writeEnd();
writeStart("div", "class", "frame", "name", "result");
writeEnd();
writeEnd();
writeStart("script", "type", "text/javascript");
write("$('body').frame();");
write("var $codeForm = $('form.code');");
write("setTimeout(function() { $codeForm.submit(); }, 0);");
write("var lineMarkers = [ ];");
write("var columnMarkers = [ ];");
write("var codeMirror = CodeMirror.fromTextArea($('textarea')[0], {");
write("'indentUnit': 4,");
write("'lineNumbers': true,");
write("'lineWrapping': true,");
write("'matchBrackets': true,");
write("'mode': 'text/x-java',");
write("'onChange': $.throttle(1000, function() {");
write("if ($codeForm.find(':checkbox[name=isLiveResult]').is(':checked')) {");
write("$codeForm.submit();");
write("}");
write("})");
write("});");
write("$('input[name=_vim]').change(function() {");
write("codeMirror.setOption('vimMode', $(this).is(':checked'));");
write("});");
write("$('input[name=_vim]').change();");
int line = page.param(int.class, "line");
if (line > 0) {
write("var line = ");
write(String.valueOf(line));
write(" - 1;");
write("codeMirror.setCursor(line);");
write("codeMirror.setLineClass(line, 'selected', 'selected');");
write("$(window).scrollTop(codeMirror.cursorCoords().y - $(window).height() / 2);");
}
write("var $resultContainer = $('.resultContainer');");
write("$resultContainer.find('.frame').bind('load', function() {");
write("$.each(lineMarkers, function() { codeMirror.clearMarker(this); codeMirror.setLineClass(this, null, null); });");
write("$.each(columnMarkers, function() { this.clear(); });");
write("var $frame = $(this).find('.syntaxErrors li').each(function() {");
write("var $error = $(this);");
write("var line = parseInt($error.attr('data-line')) - 1;");
write("var column = parseInt($error.attr('data-column')) - 1;");
write("if (line > -1 && column > -1) {");
write("lineMarkers.push(codeMirror.setMarker(line, '!'));");
write("codeMirror.setLineClass(line, 'errorLine', 'errorLine');");
write("columnMarkers.push(codeMirror.markText({ 'line': line, 'ch': column }, { 'line': line, 'ch': column + 1 }, 'errorColumn'));");
write("}");
write("});");
write("});");
writeEnd();
writeEnd();
writeEnd();
endPage();
}
@Override
public void startBody(String... titles) throws IOException {
writeStart("body");
writeStart("div", "class", "navbar navbar-fixed-top");
writeStart("div", "class", "navbar-inner");
writeStart("div", "class", "container-fluid");
writeStart("span", "class", "brand");
writeStart("a", "href", DebugFilter.Static.getServletPath(page.getRequest(), ""));
writeHtml("Dari");
writeEnd();
writeHtml("Code Editor \u2192 ");
writeEnd();
writeStart("form",
"action", page.url(null),
"method", "get",
"style", "float: left; height: 40px; line-height: 40px; margin: 0; padding-left: 10px;");
writeStart("select",
"class", "span6",
"name", "file",
"onchange", "$(this).closest('form').submit();");
writeStart("option", "value", "");
writeHtml("PLAYGROUND");
writeEnd();
for (File sourceDirectory : CodeUtils.getSourceDirectories()) {
writeStart("optgroup", "label", sourceDirectory);
writeStart("option",
"selected", sourceDirectory.equals(file) ? "selected" : null,
"value", sourceDirectory);
writeHtml("NEW CLASS IN ").writeHtml(sourceDirectory);
writeEnd();
writeFileOption(file, sourceDirectory, sourceDirectory);
writeEnd();
}
writeEnd();
writeEnd();
includeStylesheet("/_resource/chosen/chosen.css");
includeScript("/_resource/chosen/chosen.jquery.min.js");
writeStart("script", "type", "text/javascript");
write("(function() {");
write("$('select[name=file]').chosen({ 'search_contains': true });");
write("})();");
writeEnd();
writeEnd();
writeEnd();
writeEnd();
writeStart("div", "class", "container-fluid", "style", "padding-top: 54px;");
}
private void writeFileOption(File file, File sourceDirectory, File source) throws IOException {
if (source.isDirectory()) {
for (File child : source.listFiles()) {
writeFileOption(file, sourceDirectory, child);
}
} else {
writeStart("option",
"selected", source.equals(file) ? "selected" : null,
"value", source);
writeHtml(source.toString().substring(sourceDirectory.toString().length()));
writeEnd();
}
}
};
}
| private void doEdit(WebPageContext page) throws IOException, ServletException {
final Type type = page.paramOrDefault(Type.class, "type", Type.JAVA);
final File file = getFile(page);
final StringBuilder codeBuilder = new StringBuilder();
if (file != null) {
if (file.exists()) {
if (file.isDirectory()) {
} else {
codeBuilder.append(IoUtils.toString(file, StringUtils.UTF_8));
}
} else {
String filePath = file.getPath();
if (filePath.endsWith(".java")) {
filePath = filePath.substring(0, filePath.length() - 5);
for (File sourceDirectory : CodeUtils.getSourceDirectories()) { String sourceDirectoryPath = sourceDirectory.getPath();
if (filePath.startsWith(sourceDirectoryPath)) {
String classPath = filePath.substring(sourceDirectoryPath.length());
if (classPath.startsWith(File.separator)) {
classPath = classPath.substring(1);
}
int lastSepAt = classPath.lastIndexOf(File.separatorChar);
if (lastSepAt < 0) {
codeBuilder.append("public class ");
codeBuilder.append(classPath);
} else {
codeBuilder.append("package ");
codeBuilder.append(classPath.substring(0, lastSepAt).replace(File.separatorChar, '.'));
codeBuilder.append(";\n\npublic class ");
codeBuilder.append(classPath.substring(lastSepAt + 1));
}
codeBuilder.append(" {\n}");
break;
}
}
}
}
} else {
Set<String> imports = findImports();
imports.add("com.psddev.dari.db.*");
imports.add("com.psddev.dari.util.*");
imports.add("java.util.*");
String includes = Settings.get(String.class, INCLUDE_IMPORTS_SETTING);
if (!ObjectUtils.isBlank(includes)) {
Collections.addAll(imports, includes.trim().split("\\s*,?\\s+"));
}
String excludes = Settings.get(String.class, EXCLUDE_IMPORTS_SETTING);
if (!ObjectUtils.isBlank(excludes)) {
for (String exclude : excludes.trim().split("\\s*,?\\s+")) {
imports.remove(exclude);
}
}
for (String i : imports) {
codeBuilder.append("import ");
codeBuilder.append(i);
codeBuilder.append(";\n");
}
codeBuilder.append('\n');
codeBuilder.append("public class Code {\n");
codeBuilder.append(" public static Object main() throws Throwable {\n");
String query = page.param(String.class, "query");
String objectClass = page.paramOrDefault(String.class, "objectClass", "Object");
if (query == null) {
codeBuilder.append(" return null;\n");
} else {
codeBuilder.append(" Query<").append(objectClass).append("> query = ").append(query).append(";\n");
codeBuilder.append(" PaginatedResult<").append(objectClass).append("> result = query.select(0L, 10);\n");
codeBuilder.append(" return result;\n");
}
codeBuilder.append(" }\n");
codeBuilder.append("}\n");
}
new DebugFilter.PageWriter(page) {{
List<Object> inputs = CodeDebugServlet.Static.getInputs(getServletContext());
Object input = inputs == null || inputs.isEmpty() ? null : inputs.get(0);
String name;
if (file == null) {
name = null;
} else {
name = file.toString();
int slashAt = name.lastIndexOf('/');
if (slashAt > -1) {
name = name.substring(slashAt + 1);
}
}
startPage("Code Editor", name);
writeStart("div", "class", "row-fluid");
if (input != null) {
writeStart("div", "class", "codeInput", "style", "bottom: 65px; position: fixed; top: 55px; width: 18%; z-index: 1000;");
writeStart("h2").writeHtml("Input").writeEnd();
writeStart("div", "style", "bottom: 0; overflow: auto; position: absolute; top: 38px; width: 100%;");
writeObject(input);
writeEnd();
writeEnd();
writeStart("style", "type", "text/css");
write(".codeInput pre { white-space: pre; word-break: normal; word-wrap: normal; }");
writeEnd();
writeStart("script", "type", "text/javascript");
write("$('.codeInput').hover(function() {");
write("$(this).css('width', '50%');");
write("}, function() {");
write("$(this).css('width', '18%');");
write("});");
writeEnd();
}
writeStart("div",
"class", input != null ? "span9" : "span12",
"style", input != null ? "margin-left: 20%" : null);
writeStart("form",
"action", page.url(null),
"class", "code",
"method", "post",
"style", "margin-bottom: 70px;",
"target", "result");
writeTag("input", "name", "action", "type", "hidden", "value", "run");
writeTag("input", "name", "type", "type", "hidden", "value", type);
writeTag("input", "name", "file", "type", "hidden", "value", file);
writeTag("input", "name", "jspPreviewUrl", "type", "hidden", "value", page.param(String.class, "jspPreviewUrl"));
writeStart("textarea", "name", "code");
writeHtml(codeBuilder);
writeEnd();
writeStart("div",
"class", "form-actions",
"style", "bottom: 0; left: 0; margin: 0; padding: 10px 20px; position:fixed; right: 0; z-index: 1000;");
writeTag("input", "class", "btn btn-primary", "type", "submit", "value", "Run");
writeStart("label", "class", "checkbox", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;");
writeTag("input", "name", "isLiveResult", "type", "checkbox");
writeHtml("Live Result");
writeEnd();
writeStart("label", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;", "title", "Shortcut: ?_vim=true");
boolean vimMode = page.param(boolean.class, "_vim");
writeStart("label", "class", "checkbox", "style", "display: inline-block; margin-left: 10px; white-space: nowrap;");
writeTag("input", "name", "_vim", "type", "checkbox", "value", "true", vimMode ? "checked" : "_unchecked", "true");
writeHtml("Vim Mode");
writeEnd();
writeEnd();
writeTag("input",
"class", "btn btn-success pull-right",
"name", "isSave",
"type", "submit",
"value", "Save");
writeEnd();
writeEnd();
writeStart("div",
"class", "resultContainer",
"style",
"background: rgba(255, 255, 255, 0.8);" +
"border-color: rgba(0, 0, 0, 0.2);" +
"border-style: solid;" +
"border-width: 0 0 0 1px;" +
"max-height: 45%;" +
"top: 55px;" +
"overflow: auto;" +
"padding: 0px 20px 5px 10px;" +
"position: fixed;" +
"z-index: 3;" +
"right: 0px;" +
"width: 35%;");
writeStart("h2").writeHtml("Result").writeEnd();
writeStart("div", "class", "frame", "name", "result");
writeEnd();
writeEnd();
writeStart("script", "type", "text/javascript");
write("$('body').frame();");
write("var $codeForm = $('form.code');");
write("setTimeout(function() { $codeForm.submit(); }, 0);");
write("var lineMarkers = [ ];");
write("var columnMarkers = [ ];");
write("var codeMirror = CodeMirror.fromTextArea($('textarea')[0], {");
write("'indentUnit': 4,");
write("'lineNumbers': true,");
write("'lineWrapping': true,");
write("'matchBrackets': true,");
write("'mode': 'text/x-java',");
write("'onChange': $.throttle(1000, function() {");
write("if ($codeForm.find(':checkbox[name=isLiveResult]').is(':checked')) {");
write("$codeForm.submit();");
write("}");
write("})");
write("});");
write("$('input[name=_vim]').change(function() {");
write("codeMirror.setOption('vimMode', $(this).is(':checked'));");
write("});");
write("$('input[name=_vim]').change();");
int line = page.param(int.class, "line");
if (line > 0) {
write("var line = ");
write(String.valueOf(line));
write(" - 1;");
write("codeMirror.setCursor(line);");
write("codeMirror.setLineClass(line, 'selected', 'selected');");
write("$(window).scrollTop(codeMirror.cursorCoords().y - $(window).height() / 2);");
}
write("var $resultContainer = $('.resultContainer');");
write("$resultContainer.find('.frame').bind('load', function() {");
write("$.each(lineMarkers, function() { codeMirror.clearMarker(this); codeMirror.setLineClass(this, null, null); });");
write("$.each(columnMarkers, function() { this.clear(); });");
write("var $frame = $(this).find('.syntaxErrors li').each(function() {");
write("var $error = $(this);");
write("var line = parseInt($error.attr('data-line')) - 1;");
write("var column = parseInt($error.attr('data-column')) - 1;");
write("if (line > -1 && column > -1) {");
write("lineMarkers.push(codeMirror.setMarker(line, '!'));");
write("codeMirror.setLineClass(line, 'errorLine', 'errorLine');");
write("columnMarkers.push(codeMirror.markText({ 'line': line, 'ch': column }, { 'line': line, 'ch': column + 1 }, 'errorColumn'));");
write("}");
write("});");
write("});");
writeEnd();
writeEnd();
writeEnd();
endPage();
}
@Override
public void startBody(String... titles) throws IOException {
writeStart("body");
writeStart("div", "class", "navbar navbar-fixed-top");
writeStart("div", "class", "navbar-inner");
writeStart("div", "class", "container-fluid");
writeStart("span", "class", "brand");
writeStart("a", "href", DebugFilter.Static.getServletPath(page.getRequest(), ""));
writeHtml("Dari");
writeEnd();
writeHtml("Code Editor \u2192 ");
writeEnd();
writeStart("form",
"action", page.url(null),
"method", "get",
"style", "float: left; height: 40px; line-height: 40px; margin: 0; padding-left: 10px;");
writeStart("select",
"class", "span6",
"name", "file",
"onchange", "$(this).closest('form').submit();");
writeStart("option", "value", "");
writeHtml("PLAYGROUND");
writeEnd();
for (File sourceDirectory : CodeUtils.getSourceDirectories()) {
writeStart("optgroup", "label", sourceDirectory);
writeStart("option",
"selected", sourceDirectory.equals(file) ? "selected" : null,
"value", sourceDirectory);
writeHtml("NEW CLASS IN ").writeHtml(sourceDirectory);
writeEnd();
writeFileOption(file, sourceDirectory, sourceDirectory);
writeEnd();
}
writeEnd();
writeEnd();
includeStylesheet("/_resource/chosen/chosen.css");
includeScript("/_resource/chosen/chosen.jquery.min.js");
writeStart("script", "type", "text/javascript");
write("(function() {");
write("$('select[name=file]').chosen({ 'search_contains': true });");
write("})();");
writeEnd();
writeEnd();
writeEnd();
writeEnd();
writeStart("div", "class", "container-fluid", "style", "padding-top: 54px;");
}
private void writeFileOption(File file, File sourceDirectory, File source) throws IOException {
if (source.isDirectory()) {
for (File child : source.listFiles()) {
writeFileOption(file, sourceDirectory, child);
}
} else {
writeStart("option",
"selected", source.equals(file) ? "selected" : null,
"value", source);
writeHtml(source.toString().substring(sourceDirectory.toString().length()));
writeEnd();
}
}
};
}
|
diff --git a/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java b/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java
index a1d104726..cd421c38d 100644
--- a/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java
+++ b/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java
@@ -1,198 +1,198 @@
package spim.progacq;
import java.io.File;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import org.micromanager.utils.ReportingUtils;
import loci.common.DataTools;
import loci.common.services.ServiceFactory;
import loci.formats.IFormatWriter;
import loci.formats.ImageWriter;
import loci.formats.MetadataTools;
import loci.formats.meta.IMetadata;
import loci.formats.services.OMEXMLService;
import mmcorej.CMMCore;
import ome.xml.model.enums.DimensionOrder;
import ome.xml.model.enums.PixelType;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
public class OMETIFFHandler implements AcqOutputHandler {
private File outputDirectory;
private IMetadata meta;
private int imageCounter, sliceCounter;
private IFormatWriter writer;
private CMMCore core;
private int stacks, timesteps;
private AcqRow[] acqRows;
private double deltat;
public OMETIFFHandler(CMMCore iCore, File outDir, String xyDev,
String cDev, String zDev, String tDev, AcqRow[] acqRows,
int iTimeSteps, double iDeltaT) {
if(outDir == null || !outDir.exists() || !outDir.isDirectory())
throw new IllegalArgumentException("Null path specified: " + outDir.toString());
imageCounter = -1;
sliceCounter = 0;
stacks = acqRows.length;
core = iCore;
timesteps = iTimeSteps;
deltat = iDeltaT;
outputDirectory = outDir;
this.acqRows = acqRows;
try {
meta = new ServiceFactory().getInstance(OMEXMLService.class).createOMEXMLMetadata();
meta.createRoot();
meta.setDatasetID(MetadataTools.createLSID("Dataset", 0), 0);
for (int image = 0; image < stacks; ++image) {
meta.setImageID(MetadataTools.createLSID("Image", image), image);
AcqRow row = acqRows[image];
int depth = row.getDepth();
meta.setPixelsID(MetadataTools.createLSID("Pixels", 0), image);
meta.setPixelsDimensionOrder(DimensionOrder.XYCZT, image);
meta.setPixelsBinDataBigEndian(Boolean.FALSE, image, 0);
meta.setPixelsType(core.getImageBitDepth() == 8 ? PixelType.UINT8 : PixelType.UINT16, image);
meta.setChannelID(MetadataTools.createLSID("Channel", 0), image, 0);
meta.setChannelSamplesPerPixel(new PositiveInteger(1), image, 0);
for (int t = 0; t < timesteps; ++t) {
String fileName = makeFilename(image, t);
for(int z = 0; z < depth; ++z) {
int td = depth*t + z;
meta.setUUIDFileName(fileName, image, td);
// meta.setUUIDValue("urn:uuid:" + (String)UUID.nameUUIDFromBytes(fileName.getBytes()).toString(), image, td);
meta.setTiffDataPlaneCount(new NonNegativeInteger(1), image, td);
meta.setTiffDataFirstT(new NonNegativeInteger(t), image, td);
meta.setTiffDataFirstC(new NonNegativeInteger(0), image, td);
meta.setTiffDataFirstZ(new NonNegativeInteger(z), image, td);
};
};
meta.setPixelsSizeX(new PositiveInteger((int)core.getImageWidth()), image);
meta.setPixelsSizeY(new PositiveInteger((int)core.getImageHeight()), image);
meta.setPixelsSizeZ(new PositiveInteger(depth), image);
meta.setPixelsSizeC(new PositiveInteger(1), image);
meta.setPixelsSizeT(new PositiveInteger(timesteps), image);
- meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()), image);
- meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()), image);
- meta.setPixelsPhysicalSizeZ(new PositiveFloat(row.getZStepSize()*1.5D), image); // TODO: This is hardcoded. Change the DAL.
+ meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()*1.5D), image);
+ meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()*1.5D), image);
+ meta.setPixelsPhysicalSizeZ(new PositiveFloat(Math.max(row.getZStepSize(), 1.0D)*1.5D), image); // TODO: These are hardcoded. Change the DAL.
meta.setPixelsTimeIncrement(new Double(deltat), image);
}
writer = new ImageWriter().getWriter(makeFilename(0, 0));
writer.setWriteSequentially(true);
writer.setMetadataRetrieve(meta);
writer.setInterleaved(false);
writer.setValidBitsPerPixel((int) core.getImageBitDepth());
writer.setCompression("Uncompressed");
} catch(Throwable t) {
t.printStackTrace();
throw new IllegalArgumentException(t);
}
}
private static String makeFilename(int angleIndex, int timepoint) {
return String.format("spim_TL%02d_Angle%01d.ome.tiff", (timepoint + 1), angleIndex);
}
private void openWriter(int angleIndex, int timepoint) throws Exception {
writer.changeOutputFile(new File(outputDirectory, meta.getUUIDFileName(angleIndex, acqRows[angleIndex].getDepth()*timepoint)).getAbsolutePath());
writer.setSeries(angleIndex);
meta.setUUID(meta.getUUIDValue(angleIndex, acqRows[angleIndex].getDepth()*timepoint));
sliceCounter = 0;
}
@Override
public ImagePlus getImagePlus() throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public void beginStack(int axis) throws Exception {
ReportingUtils.logMessage("Beginning stack along dimension " + axis);
if(++imageCounter < stacks * timesteps)
openWriter(imageCounter % stacks, imageCounter / stacks);
}
private int doubleAnnotations = 0;
private int storeDouble(int image, int plane, int n, String name, double val) {
String key = String.format("%d/%d/%d: %s", image, plane, n, name);
meta.setDoubleAnnotationID(key, doubleAnnotations);
meta.setDoubleAnnotationValue(val, doubleAnnotations);
meta.setPlaneAnnotationRef(key, image, plane, n);
return doubleAnnotations++;
}
@Override
public void processSlice(ImageProcessor ip, double X, double Y, double Z, double theta, double deltaT)
throws Exception {
long bitDepth = core.getImageBitDepth();
byte[] data = bitDepth == 8 ?
(byte[])ip.getPixels() :
DataTools.shortsToBytes((short[])ip.getPixels(), true);
int image = imageCounter % stacks;
int timePoint = imageCounter / stacks;
int plane = timePoint*acqRows[image].getDepth() + sliceCounter;
meta.setPlanePositionX(X, image, plane);
meta.setPlanePositionY(Y, image, plane);
meta.setPlanePositionZ(Z, image, plane);
meta.setPlaneTheZ(new NonNegativeInteger(sliceCounter), image, plane);
meta.setPlaneTheT(new NonNegativeInteger(timePoint), image, plane);
meta.setPlaneDeltaT(deltaT, image, plane);
storeDouble(image, plane, 0, "Theta", theta);
try {
writer.saveBytes(plane, data);
} catch(java.io.IOException ioe) {
finalizeStack(0);
if(writer != null)
writer.close();
throw new Exception("Error writing OME-TIFF.", ioe);
}
++sliceCounter;
}
@Override
public void finalizeStack(int depth) throws Exception {
ReportingUtils.logMessage("Finished stack along dimension " + depth);
}
@Override
public void finalizeAcquisition() throws Exception {
if(writer != null)
writer.close();
imageCounter = 0;
writer = null;
}
}
| true | true | public OMETIFFHandler(CMMCore iCore, File outDir, String xyDev,
String cDev, String zDev, String tDev, AcqRow[] acqRows,
int iTimeSteps, double iDeltaT) {
if(outDir == null || !outDir.exists() || !outDir.isDirectory())
throw new IllegalArgumentException("Null path specified: " + outDir.toString());
imageCounter = -1;
sliceCounter = 0;
stacks = acqRows.length;
core = iCore;
timesteps = iTimeSteps;
deltat = iDeltaT;
outputDirectory = outDir;
this.acqRows = acqRows;
try {
meta = new ServiceFactory().getInstance(OMEXMLService.class).createOMEXMLMetadata();
meta.createRoot();
meta.setDatasetID(MetadataTools.createLSID("Dataset", 0), 0);
for (int image = 0; image < stacks; ++image) {
meta.setImageID(MetadataTools.createLSID("Image", image), image);
AcqRow row = acqRows[image];
int depth = row.getDepth();
meta.setPixelsID(MetadataTools.createLSID("Pixels", 0), image);
meta.setPixelsDimensionOrder(DimensionOrder.XYCZT, image);
meta.setPixelsBinDataBigEndian(Boolean.FALSE, image, 0);
meta.setPixelsType(core.getImageBitDepth() == 8 ? PixelType.UINT8 : PixelType.UINT16, image);
meta.setChannelID(MetadataTools.createLSID("Channel", 0), image, 0);
meta.setChannelSamplesPerPixel(new PositiveInteger(1), image, 0);
for (int t = 0; t < timesteps; ++t) {
String fileName = makeFilename(image, t);
for(int z = 0; z < depth; ++z) {
int td = depth*t + z;
meta.setUUIDFileName(fileName, image, td);
// meta.setUUIDValue("urn:uuid:" + (String)UUID.nameUUIDFromBytes(fileName.getBytes()).toString(), image, td);
meta.setTiffDataPlaneCount(new NonNegativeInteger(1), image, td);
meta.setTiffDataFirstT(new NonNegativeInteger(t), image, td);
meta.setTiffDataFirstC(new NonNegativeInteger(0), image, td);
meta.setTiffDataFirstZ(new NonNegativeInteger(z), image, td);
};
};
meta.setPixelsSizeX(new PositiveInteger((int)core.getImageWidth()), image);
meta.setPixelsSizeY(new PositiveInteger((int)core.getImageHeight()), image);
meta.setPixelsSizeZ(new PositiveInteger(depth), image);
meta.setPixelsSizeC(new PositiveInteger(1), image);
meta.setPixelsSizeT(new PositiveInteger(timesteps), image);
meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()), image);
meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()), image);
meta.setPixelsPhysicalSizeZ(new PositiveFloat(row.getZStepSize()*1.5D), image); // TODO: This is hardcoded. Change the DAL.
meta.setPixelsTimeIncrement(new Double(deltat), image);
}
writer = new ImageWriter().getWriter(makeFilename(0, 0));
writer.setWriteSequentially(true);
writer.setMetadataRetrieve(meta);
writer.setInterleaved(false);
writer.setValidBitsPerPixel((int) core.getImageBitDepth());
writer.setCompression("Uncompressed");
} catch(Throwable t) {
t.printStackTrace();
throw new IllegalArgumentException(t);
}
}
| public OMETIFFHandler(CMMCore iCore, File outDir, String xyDev,
String cDev, String zDev, String tDev, AcqRow[] acqRows,
int iTimeSteps, double iDeltaT) {
if(outDir == null || !outDir.exists() || !outDir.isDirectory())
throw new IllegalArgumentException("Null path specified: " + outDir.toString());
imageCounter = -1;
sliceCounter = 0;
stacks = acqRows.length;
core = iCore;
timesteps = iTimeSteps;
deltat = iDeltaT;
outputDirectory = outDir;
this.acqRows = acqRows;
try {
meta = new ServiceFactory().getInstance(OMEXMLService.class).createOMEXMLMetadata();
meta.createRoot();
meta.setDatasetID(MetadataTools.createLSID("Dataset", 0), 0);
for (int image = 0; image < stacks; ++image) {
meta.setImageID(MetadataTools.createLSID("Image", image), image);
AcqRow row = acqRows[image];
int depth = row.getDepth();
meta.setPixelsID(MetadataTools.createLSID("Pixels", 0), image);
meta.setPixelsDimensionOrder(DimensionOrder.XYCZT, image);
meta.setPixelsBinDataBigEndian(Boolean.FALSE, image, 0);
meta.setPixelsType(core.getImageBitDepth() == 8 ? PixelType.UINT8 : PixelType.UINT16, image);
meta.setChannelID(MetadataTools.createLSID("Channel", 0), image, 0);
meta.setChannelSamplesPerPixel(new PositiveInteger(1), image, 0);
for (int t = 0; t < timesteps; ++t) {
String fileName = makeFilename(image, t);
for(int z = 0; z < depth; ++z) {
int td = depth*t + z;
meta.setUUIDFileName(fileName, image, td);
// meta.setUUIDValue("urn:uuid:" + (String)UUID.nameUUIDFromBytes(fileName.getBytes()).toString(), image, td);
meta.setTiffDataPlaneCount(new NonNegativeInteger(1), image, td);
meta.setTiffDataFirstT(new NonNegativeInteger(t), image, td);
meta.setTiffDataFirstC(new NonNegativeInteger(0), image, td);
meta.setTiffDataFirstZ(new NonNegativeInteger(z), image, td);
};
};
meta.setPixelsSizeX(new PositiveInteger((int)core.getImageWidth()), image);
meta.setPixelsSizeY(new PositiveInteger((int)core.getImageHeight()), image);
meta.setPixelsSizeZ(new PositiveInteger(depth), image);
meta.setPixelsSizeC(new PositiveInteger(1), image);
meta.setPixelsSizeT(new PositiveInteger(timesteps), image);
meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()*1.5D), image);
meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()*1.5D), image);
meta.setPixelsPhysicalSizeZ(new PositiveFloat(Math.max(row.getZStepSize(), 1.0D)*1.5D), image); // TODO: These are hardcoded. Change the DAL.
meta.setPixelsTimeIncrement(new Double(deltat), image);
}
writer = new ImageWriter().getWriter(makeFilename(0, 0));
writer.setWriteSequentially(true);
writer.setMetadataRetrieve(meta);
writer.setInterleaved(false);
writer.setValidBitsPerPixel((int) core.getImageBitDepth());
writer.setCompression("Uncompressed");
} catch(Throwable t) {
t.printStackTrace();
throw new IllegalArgumentException(t);
}
}
|
diff --git a/trunk/GeoBeagle/src/com/google/code/geobeagle/bcaching/progress/ProgressMessage.java b/trunk/GeoBeagle/src/com/google/code/geobeagle/bcaching/progress/ProgressMessage.java
index 5358d82e..e59f4a08 100644
--- a/trunk/GeoBeagle/src/com/google/code/geobeagle/bcaching/progress/ProgressMessage.java
+++ b/trunk/GeoBeagle/src/com/google/code/geobeagle/bcaching/progress/ProgressMessage.java
@@ -1,57 +1,58 @@
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.bcaching.progress;
import android.app.ProgressDialog;
public enum ProgressMessage {
SET_FILE {
@Override
void act(ProgressDialog progressDialog, int arg1, Object object) {
+ progressDialog.setTitle("Bcaching.com: " + (String)object);
progressDialog.incrementProgressBy(1);
}
},
SET_MAX {
@Override
void act(ProgressDialog progressDialog, int arg1, Object object) {
progressDialog.setMax(arg1);
}
},
SET_PROGRESS {
@Override
void act(ProgressDialog progressDialog, int arg1, Object object) {
progressDialog.setProgress(arg1);
}
},
DONE {
@Override
void act(ProgressDialog progressDialog, int arg1, Object object) {
progressDialog.dismiss();
}
},
START {
@Override
void act(ProgressDialog progressDialog, int arg1, Object object) {
progressDialog.show();
}
};
abstract void act(ProgressDialog progressDialog, int arg1, Object object);
static ProgressMessage fromInt(Integer i) {
return ProgressMessage.class.getEnumConstants()[i];
}
}
| true | true | void act(ProgressDialog progressDialog, int arg1, Object object) {
progressDialog.incrementProgressBy(1);
}
| void act(ProgressDialog progressDialog, int arg1, Object object) {
progressDialog.setTitle("Bcaching.com: " + (String)object);
progressDialog.incrementProgressBy(1);
}
|
diff --git a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java
index 5f5e4391..d1f0e7aa 100644
--- a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java
+++ b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java
@@ -1,559 +1,561 @@
/**
* $RCSfile: ,v $
* $Revision: $
* $Date: $
*
* Copyright (C) 2004-2010 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.sparkimpl.plugin.transcripts;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.html.HTMLEditorKit;
import org.jdesktop.swingx.calendar.DateUtils;
import org.jivesoftware.MainWindowListener;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.BackgroundPanel;
import org.jivesoftware.spark.plugin.ContextMenuListener;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomButton;
import org.jivesoftware.spark.ui.ChatRoomClosingListener;
import org.jivesoftware.spark.ui.ChatRoomListener;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.spark.ui.VCardPanel;
import org.jivesoftware.spark.ui.rooms.ChatRoomImpl;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
/**
* The <code>ChatTranscriptPlugin</code> is responsible for transcript handling within Spark.
*
* @author Derek DeMoro
*/
public class ChatTranscriptPlugin implements ChatRoomListener {
private final String timeFormat = "HH:mm:ss";
private final String dateFormat = ((SimpleDateFormat)SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();
private final SimpleDateFormat notificationDateFormatter;
private final SimpleDateFormat messageDateFormatter;
private HashMap<ChatRoom,Message> lastMessage = new HashMap<ChatRoom,Message>();
private JDialog Frame;
/**
* Register the listeners for transcript persistence.
*/
public ChatTranscriptPlugin() {
SparkManager.getChatManager().addChatRoomListener(this);
notificationDateFormatter = new SimpleDateFormat(dateFormat);
messageDateFormatter = new SimpleDateFormat(timeFormat);
final ContactList contactList = SparkManager.getWorkspace().getContactList();
final Action viewHistoryAction = new AbstractAction() {
private static final long serialVersionUID = -6498776252446416099L;
public void actionPerformed(ActionEvent actionEvent) {
ContactItem item = contactList.getSelectedUsers().iterator().next();
final String jid = item.getJID();
showHistory(jid);
}
};
viewHistoryAction.putValue(Action.NAME, Res.getString("menuitem.view.contact.history"));
viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));
final Action showStatusMessageAction = new AbstractAction() {
private static final long serialVersionUID = -5000370836304286019L;
public void actionPerformed(ActionEvent actionEvent) {
ContactItem item = contactList.getSelectedUsers().iterator().next();
showStatusMessage(item);
}
};
showStatusMessageAction.putValue(Action.NAME, Res.getString("menuitem.show.contact.statusmessage"));
contactList.addContextMenuListener(new ContextMenuListener() {
public void poppingUp(Object object, JPopupMenu popup) {
if (object instanceof ContactItem) {
popup.add(viewHistoryAction);
popup.add(showStatusMessageAction);
}
}
public void poppingDown(JPopupMenu popup) {
}
public boolean handleDefaultAction(MouseEvent e) {
return false;
}
});
SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {
public void shutdown() {
persistConversations();
}
public void mainWindowActivated() {
}
public void mainWindowDeactivated() {
}
});
SparkManager.getConnection().addConnectionListener(new ConnectionListener() {
public void connectionClosed() {
}
public void connectionClosedOnError(Exception e) {
persistConversations();
}
public void reconnectingIn(int i) {
}
public void reconnectionSuccessful() {
}
public void reconnectionFailed(Exception exception) {
}
});
}
public void persistConversations() {
for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {
if (room instanceof ChatRoomImpl) {
ChatRoomImpl roomImpl = (ChatRoomImpl)room;
if (roomImpl.isActive()) {
persistChatRoom(roomImpl);
}
}
}
}
public boolean canShutDown() {
return true;
}
public void chatRoomOpened(final ChatRoom room) {
LocalPreferences pref = SettingsManager.getLocalPreferences();
if (!pref.isChatHistoryEnabled()) {
return;
}
final String jid = room.getRoomname();
File transcriptFile = ChatTranscripts.getTranscriptFile(jid);
if (!transcriptFile.exists()) {
return;
}
if (room instanceof ChatRoomImpl) {
new ChatRoomDecorator(room);
}
}
public void chatRoomLeft(ChatRoom room) {
}
public void chatRoomClosed(final ChatRoom room) {
// Persist only agent to agent chat rooms.
if (room.getChatType() == Message.Type.chat) {
persistChatRoom(room);
}
}
public void persistChatRoom(final ChatRoom room) {
LocalPreferences pref = SettingsManager.getLocalPreferences();
if (!pref.isChatHistoryEnabled()) {
return;
}
final String jid = room.getRoomname();
final List<Message> transcripts = room.getTranscripts();
ChatTranscript transcript = new ChatTranscript();
int count = 0;
int i = 0;
if (lastMessage.get(room) != null)
{
count = transcripts.indexOf(lastMessage.get(room)) + 1;
}
for (Message message : transcripts) {
if (i < count)
{
i++;
continue;
}
lastMessage.put(room,message);
HistoryMessage history = new HistoryMessage();
history.setTo(message.getTo());
history.setFrom(message.getFrom());
history.setBody(message.getBody());
Date date = (Date)message.getProperty("date");
if (date != null) {
history.setDate(date);
}
else {
history.setDate(new Date());
}
transcript.addHistoryMessage(history);
}
ChatTranscripts.appendToTranscript(jid, transcript);
}
public void chatRoomActivated(ChatRoom room) {
}
public void userHasJoined(ChatRoom room, String userid) {
}
public void userHasLeft(ChatRoom room, String userid) {
}
public void uninstall() {
// Do nothing.
}
private void showHistory(final String jid) {
SwingWorker transcriptLoader = new SwingWorker() {
public Object construct() {
String bareJID = StringUtils.parseBareAddress(jid);
return ChatTranscripts.getChatTranscript(bareJID);
}
public void finished() {
final JPanel mainPanel = new BackgroundPanel();
mainPanel.setLayout(new BorderLayout());
// add search text input
final JPanel topPanel = new BackgroundPanel();
topPanel.setLayout(new GridBagLayout());
final VCardPanel vacardPanel = new VCardPanel(jid);
final JTextField searchField = new JTextField(25);
searchField.setText(Res.getString("message.search.for.history"));
searchField.setToolTipText(Res.getString("message.search.for.history"));
searchField.setForeground((Color) UIManager.get("TextField.lightforeground"));
topPanel.add(vacardPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 5, 1, 1), 0, 0));
topPanel.add(searchField, new GridBagConstraints(1, 0, GridBagConstraints.REMAINDER, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(1, 1, 6, 1), 0, 0));
mainPanel.add(topPanel, BorderLayout.NORTH);
final JEditorPane window = new JEditorPane();
window.setEditorKit(new HTMLEditorKit());
window.setBackground(Color.white);
final JScrollPane pane = new JScrollPane(window);
pane.getVerticalScrollBar().setBlockIncrement(200);
pane.getVerticalScrollBar().setUnitIncrement(20);
mainPanel.add(pane, BorderLayout.CENTER);
final JFrame frame = new JFrame(Res.getString("title.history.for", jid));
frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setSize(600, 400);
window.setCaretPosition(0);
window.requestFocus();
GraphicUtils.centerWindowOnScreen(frame);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
window.setText("");
}
});
window.setEditable(false);
final StringBuilder builder = new StringBuilder();
builder.append("<html><body><table cellpadding=0 cellspacing=0>");
final TimerTask transcriptTask = new TimerTask() {
public void run() {
final ChatTranscript transcript = (ChatTranscript)get();
- final List<HistoryMessage> list = transcript.getMessages();
+ final List<HistoryMessage> list = transcript.getMessage(
+ Res.getString("message.search.for.history").equals(searchField.getText())
+ ? null : searchField.getText());
final String personalNickname = SparkManager.getUserManager().getNickname();
Date lastPost = null;
String lastPerson = null;
boolean initialized = false;
for (HistoryMessage message : list) {
String color = "blue";
String from = message.getFrom();
String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
String body = org.jivesoftware.spark.util.StringUtils.escapeHTMLTags(message.getBody());
if (nickname.equals(message.getFrom())) {
String otherJID = StringUtils.parseBareAddress(message.getFrom());
String myJID = SparkManager.getSessionManager().getBareAddress();
if (otherJID.equals(myJID)) {
nickname = personalNickname;
}
else {
nickname = StringUtils.parseName(nickname);
}
}
if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) {
color = "red";
}
long lastPostTime = lastPost != null ? lastPost.getTime() : 0;
int diff = 0;
if (DateUtils.getDaysDiff(lastPostTime, message
.getDate().getTime()) != 0) {
diff = DateUtils.getDaysDiff(lastPostTime,
message.getDate().getTime());
} else {
diff = DateUtils.getDayOfWeek(lastPostTime)
- DateUtils.getDayOfWeek(message
.getDate().getTime());
}
if (diff != 0) {
if (initialized) {
builder.append("<tr><td><br></td></tr>");
}
builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>").append(notificationDateFormatter.format(message.getDate())).append("</u></b></font></td></tr>");
lastPerson = null;
initialized = true;
}
String value = "[" + messageDateFormatter.format(message.getDate()) + "] ";
boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname);
if (newInsertions) {
builder.append("<tr valign=top><td colspan=2 nowrap>");
builder.append("<font size=4 color='").append(color).append("'><b>");
builder.append(nickname);
builder.append("</b></font>");
builder.append("</td></tr>");
}
builder.append("<tr valign=top><td align=left nowrap>");
builder.append(value);
builder.append("</td><td align=left>");
builder.append(body);
builder.append("</td></tr>");
lastPost = message.getDate();
lastPerson = nickname;
}
builder.append("</table></body></html>");
// Handle no history
if (transcript.getMessages().size() == 0) {
builder.append("<b>").append(Res.getString("message.no.history.found")).append("</b>");
}
window.setText(builder.toString());
builder.replace(0, builder.length(), "");
}
};
searchField.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER) {
TaskEngine.getInstance().schedule(transcriptTask, 10);
searchField.requestFocus();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
});
searchField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
searchField.setText("");
searchField.setForeground((Color) UIManager.get("TextField.foreground"));
}
public void focusLost(FocusEvent e) {
searchField.setForeground((Color) UIManager.get("TextField.lightforeground"));
searchField.setText(Res.getString("message.search.for.history"));
}
});
TaskEngine.getInstance().schedule(transcriptTask, 10);
}
};
transcriptLoader.start();
}
private void showStatusMessage(ContactItem item)
{
Frame = new JDialog();
Frame.setTitle(item.getDisplayName() + " - Status");
JPanel pane = new JPanel();
JTextArea textArea = new JTextArea(5, 30);
JButton btn_close = new JButton(Res.getString("button.close"));
btn_close.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Frame.setVisible(false);
}
});
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
pane.add(new JScrollPane(textArea));
Frame.setLayout(new BorderLayout());
Frame.add(pane, BorderLayout.CENTER);
Frame.add(btn_close, BorderLayout.SOUTH);
textArea.setEditable(false);
textArea.setText(item.getStatus());
Frame.setLocationRelativeTo(SparkManager.getMainWindow());
Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);
Frame.setSize(350, 150);
Frame.setResizable(false);
Frame.setVisible(true);
}
/**
* Sort HistoryMessages by date.
*/
final Comparator dateComparator = new Comparator() {
public int compare(Object messageOne, Object messageTwo) {
final HistoryMessage historyMessageOne = (HistoryMessage)messageOne;
final HistoryMessage historyMessageTwo = (HistoryMessage)messageTwo;
long time1 = historyMessageOne.getDate().getTime();
long time2 = historyMessageTwo.getDate().getTime();
if (time1 < time2) {
return 1;
}
else if (time1 > time2) {
return -1;
}
return 0;
}
};
private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {
private ChatRoom chatRoom;
private ChatRoomButton chatHistoryButton;
private final LocalPreferences localPreferences;
public ChatRoomDecorator(ChatRoom chatRoom) {
this.chatRoom = chatRoom;
chatRoom.addClosingListener(this);
// Add History Button
localPreferences = SettingsManager.getLocalPreferences();
if (!localPreferences.isChatHistoryEnabled()) {
return;
}
chatHistoryButton = new ChatRoomButton(SparkRes.getImageIcon(SparkRes.HISTORY_24x24_IMAGE));
chatRoom.getToolBar().addChatRoomButton(chatHistoryButton);
chatHistoryButton.setToolTipText(Res.getString("tooltip.view.history"));
chatHistoryButton.addActionListener(this);
}
public void closing() {
if (localPreferences.isChatHistoryEnabled()) {
chatHistoryButton.removeActionListener(this);
}
chatRoom.removeClosingListener(this);
}
public void actionPerformed(ActionEvent e) {
ChatRoomImpl roomImpl = (ChatRoomImpl)chatRoom;
showHistory(roomImpl.getParticipantJID());
}
}
}
| true | true | private void showHistory(final String jid) {
SwingWorker transcriptLoader = new SwingWorker() {
public Object construct() {
String bareJID = StringUtils.parseBareAddress(jid);
return ChatTranscripts.getChatTranscript(bareJID);
}
public void finished() {
final JPanel mainPanel = new BackgroundPanel();
mainPanel.setLayout(new BorderLayout());
// add search text input
final JPanel topPanel = new BackgroundPanel();
topPanel.setLayout(new GridBagLayout());
final VCardPanel vacardPanel = new VCardPanel(jid);
final JTextField searchField = new JTextField(25);
searchField.setText(Res.getString("message.search.for.history"));
searchField.setToolTipText(Res.getString("message.search.for.history"));
searchField.setForeground((Color) UIManager.get("TextField.lightforeground"));
topPanel.add(vacardPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 5, 1, 1), 0, 0));
topPanel.add(searchField, new GridBagConstraints(1, 0, GridBagConstraints.REMAINDER, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(1, 1, 6, 1), 0, 0));
mainPanel.add(topPanel, BorderLayout.NORTH);
final JEditorPane window = new JEditorPane();
window.setEditorKit(new HTMLEditorKit());
window.setBackground(Color.white);
final JScrollPane pane = new JScrollPane(window);
pane.getVerticalScrollBar().setBlockIncrement(200);
pane.getVerticalScrollBar().setUnitIncrement(20);
mainPanel.add(pane, BorderLayout.CENTER);
final JFrame frame = new JFrame(Res.getString("title.history.for", jid));
frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setSize(600, 400);
window.setCaretPosition(0);
window.requestFocus();
GraphicUtils.centerWindowOnScreen(frame);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
window.setText("");
}
});
window.setEditable(false);
final StringBuilder builder = new StringBuilder();
builder.append("<html><body><table cellpadding=0 cellspacing=0>");
final TimerTask transcriptTask = new TimerTask() {
public void run() {
final ChatTranscript transcript = (ChatTranscript)get();
final List<HistoryMessage> list = transcript.getMessages();
final String personalNickname = SparkManager.getUserManager().getNickname();
Date lastPost = null;
String lastPerson = null;
boolean initialized = false;
for (HistoryMessage message : list) {
String color = "blue";
String from = message.getFrom();
String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
String body = org.jivesoftware.spark.util.StringUtils.escapeHTMLTags(message.getBody());
if (nickname.equals(message.getFrom())) {
String otherJID = StringUtils.parseBareAddress(message.getFrom());
String myJID = SparkManager.getSessionManager().getBareAddress();
if (otherJID.equals(myJID)) {
nickname = personalNickname;
}
else {
nickname = StringUtils.parseName(nickname);
}
}
if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) {
color = "red";
}
long lastPostTime = lastPost != null ? lastPost.getTime() : 0;
int diff = 0;
if (DateUtils.getDaysDiff(lastPostTime, message
.getDate().getTime()) != 0) {
diff = DateUtils.getDaysDiff(lastPostTime,
message.getDate().getTime());
} else {
diff = DateUtils.getDayOfWeek(lastPostTime)
- DateUtils.getDayOfWeek(message
.getDate().getTime());
}
if (diff != 0) {
if (initialized) {
builder.append("<tr><td><br></td></tr>");
}
builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>").append(notificationDateFormatter.format(message.getDate())).append("</u></b></font></td></tr>");
lastPerson = null;
initialized = true;
}
String value = "[" + messageDateFormatter.format(message.getDate()) + "] ";
boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname);
if (newInsertions) {
builder.append("<tr valign=top><td colspan=2 nowrap>");
builder.append("<font size=4 color='").append(color).append("'><b>");
builder.append(nickname);
builder.append("</b></font>");
builder.append("</td></tr>");
}
builder.append("<tr valign=top><td align=left nowrap>");
builder.append(value);
builder.append("</td><td align=left>");
builder.append(body);
builder.append("</td></tr>");
lastPost = message.getDate();
lastPerson = nickname;
}
builder.append("</table></body></html>");
// Handle no history
if (transcript.getMessages().size() == 0) {
builder.append("<b>").append(Res.getString("message.no.history.found")).append("</b>");
}
window.setText(builder.toString());
builder.replace(0, builder.length(), "");
}
};
searchField.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER) {
TaskEngine.getInstance().schedule(transcriptTask, 10);
searchField.requestFocus();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
});
searchField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
searchField.setText("");
searchField.setForeground((Color) UIManager.get("TextField.foreground"));
}
public void focusLost(FocusEvent e) {
searchField.setForeground((Color) UIManager.get("TextField.lightforeground"));
searchField.setText(Res.getString("message.search.for.history"));
}
});
TaskEngine.getInstance().schedule(transcriptTask, 10);
}
};
transcriptLoader.start();
}
| private void showHistory(final String jid) {
SwingWorker transcriptLoader = new SwingWorker() {
public Object construct() {
String bareJID = StringUtils.parseBareAddress(jid);
return ChatTranscripts.getChatTranscript(bareJID);
}
public void finished() {
final JPanel mainPanel = new BackgroundPanel();
mainPanel.setLayout(new BorderLayout());
// add search text input
final JPanel topPanel = new BackgroundPanel();
topPanel.setLayout(new GridBagLayout());
final VCardPanel vacardPanel = new VCardPanel(jid);
final JTextField searchField = new JTextField(25);
searchField.setText(Res.getString("message.search.for.history"));
searchField.setToolTipText(Res.getString("message.search.for.history"));
searchField.setForeground((Color) UIManager.get("TextField.lightforeground"));
topPanel.add(vacardPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 5, 1, 1), 0, 0));
topPanel.add(searchField, new GridBagConstraints(1, 0, GridBagConstraints.REMAINDER, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(1, 1, 6, 1), 0, 0));
mainPanel.add(topPanel, BorderLayout.NORTH);
final JEditorPane window = new JEditorPane();
window.setEditorKit(new HTMLEditorKit());
window.setBackground(Color.white);
final JScrollPane pane = new JScrollPane(window);
pane.getVerticalScrollBar().setBlockIncrement(200);
pane.getVerticalScrollBar().setUnitIncrement(20);
mainPanel.add(pane, BorderLayout.CENTER);
final JFrame frame = new JFrame(Res.getString("title.history.for", jid));
frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setSize(600, 400);
window.setCaretPosition(0);
window.requestFocus();
GraphicUtils.centerWindowOnScreen(frame);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
window.setText("");
}
});
window.setEditable(false);
final StringBuilder builder = new StringBuilder();
builder.append("<html><body><table cellpadding=0 cellspacing=0>");
final TimerTask transcriptTask = new TimerTask() {
public void run() {
final ChatTranscript transcript = (ChatTranscript)get();
final List<HistoryMessage> list = transcript.getMessage(
Res.getString("message.search.for.history").equals(searchField.getText())
? null : searchField.getText());
final String personalNickname = SparkManager.getUserManager().getNickname();
Date lastPost = null;
String lastPerson = null;
boolean initialized = false;
for (HistoryMessage message : list) {
String color = "blue";
String from = message.getFrom();
String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
String body = org.jivesoftware.spark.util.StringUtils.escapeHTMLTags(message.getBody());
if (nickname.equals(message.getFrom())) {
String otherJID = StringUtils.parseBareAddress(message.getFrom());
String myJID = SparkManager.getSessionManager().getBareAddress();
if (otherJID.equals(myJID)) {
nickname = personalNickname;
}
else {
nickname = StringUtils.parseName(nickname);
}
}
if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) {
color = "red";
}
long lastPostTime = lastPost != null ? lastPost.getTime() : 0;
int diff = 0;
if (DateUtils.getDaysDiff(lastPostTime, message
.getDate().getTime()) != 0) {
diff = DateUtils.getDaysDiff(lastPostTime,
message.getDate().getTime());
} else {
diff = DateUtils.getDayOfWeek(lastPostTime)
- DateUtils.getDayOfWeek(message
.getDate().getTime());
}
if (diff != 0) {
if (initialized) {
builder.append("<tr><td><br></td></tr>");
}
builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>").append(notificationDateFormatter.format(message.getDate())).append("</u></b></font></td></tr>");
lastPerson = null;
initialized = true;
}
String value = "[" + messageDateFormatter.format(message.getDate()) + "] ";
boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname);
if (newInsertions) {
builder.append("<tr valign=top><td colspan=2 nowrap>");
builder.append("<font size=4 color='").append(color).append("'><b>");
builder.append(nickname);
builder.append("</b></font>");
builder.append("</td></tr>");
}
builder.append("<tr valign=top><td align=left nowrap>");
builder.append(value);
builder.append("</td><td align=left>");
builder.append(body);
builder.append("</td></tr>");
lastPost = message.getDate();
lastPerson = nickname;
}
builder.append("</table></body></html>");
// Handle no history
if (transcript.getMessages().size() == 0) {
builder.append("<b>").append(Res.getString("message.no.history.found")).append("</b>");
}
window.setText(builder.toString());
builder.replace(0, builder.length(), "");
}
};
searchField.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER) {
TaskEngine.getInstance().schedule(transcriptTask, 10);
searchField.requestFocus();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
});
searchField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
searchField.setText("");
searchField.setForeground((Color) UIManager.get("TextField.foreground"));
}
public void focusLost(FocusEvent e) {
searchField.setForeground((Color) UIManager.get("TextField.lightforeground"));
searchField.setText(Res.getString("message.search.for.history"));
}
});
TaskEngine.getInstance().schedule(transcriptTask, 10);
}
};
transcriptLoader.start();
}
|
diff --git a/src/com/cooliris/media/Gallery.java b/src/com/cooliris/media/Gallery.java
index 361d16b..62d47e2 100644
--- a/src/com/cooliris/media/Gallery.java
+++ b/src/com/cooliris/media/Gallery.java
@@ -1,396 +1,403 @@
package com.cooliris.media;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.TimeZone;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore.Images;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import android.media.MediaScannerConnection;
import com.cooliris.cache.CacheService;
import com.cooliris.wallpaper.RandomDataSource;
import com.cooliris.wallpaper.Slideshow;
public final class Gallery extends Activity {
public static final TimeZone CURRENT_TIME_ZONE = TimeZone.getDefault();
public static float PIXEL_DENSITY = 0.0f;
public static final int CROP_MSG_INTERNAL = 100;
private static final String TAG = "Gallery";
private static final int CROP_MSG = 10;
private RenderView mRenderView = null;
private GridLayer mGridLayer;
private final Handler mHandler = new Handler();
private ReverseGeocoder mReverseGeocoder;
private boolean mPause;
private MediaScannerConnection mConnection;
private WakeLock mWakeLock;
private HashMap<String, Boolean> mAccountsEnabled = new HashMap<String, Boolean>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean imageManagerHasStorage = ImageManager.quickHasStorage();
+ boolean slideshowIntent = false;
+ if (isViewIntent()) {
+ Bundle extras = getIntent().getExtras();
+ if (extras != null) {
+ slideshowIntent = extras.getBoolean("slideshow", false);
+ }
+ }
if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI)
- && getIntent().getExtras().getBoolean("slideshow", false)) {
+ && slideshowIntent) {
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
finish();
} else {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "GridView.Slideshow.All");
mWakeLock.acquire();
Slideshow slideshow = new Slideshow(this);
slideshow.setDataSource(new RandomDataSource());
setContentView(slideshow);
}
return;
}
CacheService.computeDirtySets(this);
final boolean isCacheReady = CacheService.isCacheReady(false);
if (PIXEL_DENSITY == 0.0f) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
PIXEL_DENSITY = metrics.density;
}
mReverseGeocoder = new ReverseGeocoder(this);
mRenderView = new RenderView(this);
mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4),
mRenderView);
mRenderView.setRootLayer(mGridLayer);
setContentView(mRenderView);
// Creating the DataSource objects.
final PicasaDataSource picasaDataSource = new PicasaDataSource(this);
final LocalDataSource localDataSource = new LocalDataSource(this);
final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource);
// Depending upon the intent, we assign the right dataSource.
if (!isPickIntent() && !isViewIntent()) {
if (imageManagerHasStorage) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
} else if (!isCacheReady) {
Toast.makeText(this, getResources().getString(R.string.loading_new), Toast.LENGTH_LONG).show();
}
} else if (!isViewIntent()) {
final Intent intent = getIntent();
if (intent != null) {
final String type = intent.resolveType(this);
boolean includeImages = isImageType(type);
boolean includeVideos = isVideoType(type);
((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos);
if (includeImages) {
if (imageManagerHasStorage) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
} else {
mGridLayer.setDataSource(localDataSource);
}
mGridLayer.setPickIntent(true);
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG).show();
}
}
} else {
// View intent for images.
Uri uri = getIntent().getData();
boolean slideshow = getIntent().getBooleanExtra("slideshow", false);
final SingleDataSource singleDataSource = new SingleDataSource(this, uri.toString(), slideshow);
final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource);
mGridLayer.setDataSource(singleCombinedDataSource);
mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri));
if (singleDataSource.isSingleImage()) {
mGridLayer.setSingleImage(false);
} else if (slideshow) {
mGridLayer.setSingleImage(true);
mGridLayer.startSlideshow();
}
}
// We record the set of enabled accounts for picasa.
mAccountsEnabled = PicasaDataSource.getAccountStatus(this);
Log.i(TAG, "onCreate");
}
public ReverseGeocoder getReverseGeocoder() {
return mReverseGeocoder;
}
public Handler getHandler() {
return mHandler;
}
@Override
public void onRestart() {
super.onRestart();
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
CacheService.computeDirtySets(this);
CacheService.startCache(this, false);
if (mRenderView != null) {
mRenderView.onResume();
}
if (mPause) {
// We check to see if the authenticated accounts have changed, and
// if so, reload the datasource.
HashMap<String, Boolean> accountsEnabled = PicasaDataSource.getAccountStatus(this);
String[] keys = new String[accountsEnabled.size()];
keys = accountsEnabled.keySet().toArray(keys);
int numKeys = keys.length;
for (int i = 0; i < numKeys; ++i) {
String key = keys[i];
boolean newValue = accountsEnabled.get(key).booleanValue();
boolean oldValue = false;
Boolean oldValObj = mAccountsEnabled.get(key);
if (oldValObj != null) {
oldValue = oldValObj.booleanValue();
}
if (oldValue != newValue) {
// Reload the datasource.
if (mGridLayer != null)
mGridLayer.setDataSource(mGridLayer.getDataSource());
break;
}
}
mAccountsEnabled = accountsEnabled;
mPause = false;
}
}
@Override
public void onPause() {
super.onPause();
if (mRenderView != null)
mRenderView.onPause();
mPause = true;
}
public boolean isPaused() {
return mPause;
}
@Override
public void onStop() {
super.onStop();
if (mGridLayer != null)
mGridLayer.stop();
if (mReverseGeocoder != null) {
mReverseGeocoder.flushCache();
}
LocalDataSource.sThumbnailCache.flush();
LocalDataSource.sThumbnailCacheVideo.flush();
PicasaDataSource.sThumbnailCache.flush();
CacheService.startCache(this, true);
}
@Override
public void onDestroy() {
// Force GLThread to exit.
setContentView(R.layout.main);
if (mGridLayer != null) {
DataSource dataSource = mGridLayer.getDataSource();
if (dataSource != null) {
dataSource.shutdown();
}
mGridLayer.shutdown();
}
if (mWakeLock != null) {
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
mWakeLock = null;
}
if (mReverseGeocoder != null)
mReverseGeocoder.shutdown();
if (mRenderView != null) {
mRenderView.shutdown();
mRenderView = null;
}
mGridLayer = null;
super.onDestroy();
Log.i(TAG, "onDestroy");
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mGridLayer != null) {
mGridLayer.markDirty(30);
}
if (mRenderView != null)
mRenderView.requestRender();
Log.i(TAG, "onConfigurationChanged");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mRenderView != null) {
return mRenderView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
} else {
return super.onKeyDown(keyCode, event);
}
}
private boolean isPickIntent() {
String action = getIntent().getAction();
return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action));
}
private boolean isViewIntent() {
String action = getIntent().getAction();
return Intent.ACTION_VIEW.equals(action);
}
private boolean isImageType(String type) {
return type.equals("vnd.android.cursor.dir/image") || type.equals("image/*");
}
private boolean isVideoType(String type) {
return type.equals("vnd.android.cursor.dir/video") || type.equals("video/*");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CROP_MSG: {
if (resultCode == RESULT_OK) {
setResult(resultCode, data);
finish();
}
break;
}
case CROP_MSG_INTERNAL: {
// We cropped an image, we must try to set the focus of the camera
// to that image.
if (resultCode == RESULT_OK) {
String contentUri = data.getAction();
if (mGridLayer != null) {
mGridLayer.focusItem(contentUri);
}
}
break;
}
}
}
@Override
public void onLowMemory() {
if (mRenderView != null) {
mRenderView.handleLowMemory();
}
}
public void launchCropperOrFinish(final MediaItem item) {
final Bundle myExtras = getIntent().getExtras();
String cropValue = myExtras != null ? myExtras.getString("crop") : null;
final String contentUri = item.mContentUri;
if (cropValue != null) {
Bundle newExtras = new Bundle();
if (cropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
Intent cropIntent = new Intent();
cropIntent.setData(Uri.parse(contentUri));
cropIntent.setClass(this, CropImage.class);
cropIntent.putExtras(newExtras);
// Pass through any extras that were passed in.
cropIntent.putExtras(myExtras);
startActivityForResult(cropIntent, CROP_MSG);
} else {
if (contentUri.startsWith("http://")) {
// This is a http uri, we must save it locally first and
// generate a content uri from it.
final ProgressDialog dialog = ProgressDialog.show(this, this.getResources().getString(R.string.initializing),
getResources().getString(R.string.running_face_detection), true, false);
if (contentUri != null) {
MediaScannerConnection.MediaScannerConnectionClient client = new MediaScannerConnection.MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
if (mConnection != null) {
try {
final String path = UriTexture.writeHttpDataInDirectory(Gallery.this, contentUri,
LocalDataSource.DOWNLOAD_BUCKET_NAME);
if (path != null) {
mConnection.scanFile(path, item.mMimeType);
} else {
shutdown("");
}
} catch (Exception e) {
shutdown("");
}
}
}
public void onScanCompleted(String path, Uri uri) {
shutdown(uri.toString());
}
public void shutdown(String uri) {
dialog.dismiss();
performReturn(myExtras, uri.toString());
if (mConnection != null) {
mConnection.disconnect();
}
}
};
MediaScannerConnection connection = new MediaScannerConnection(Gallery.this, client);
connection.connect();
mConnection = connection;
}
} else {
performReturn(myExtras, contentUri);
}
}
}
private void performReturn(Bundle myExtras, String contentUri) {
Intent result = new Intent(null, Uri.parse(contentUri));
if (myExtras != null && myExtras.getBoolean("return-data")) {
// The size of a transaction should be below 100K.
Bitmap bitmap = null;
try {
bitmap = UriTexture.createFromUri(this, contentUri, 1024, 1024, 0, null);
} catch (IOException e) {
;
} catch (URISyntaxException e) {
;
}
if (bitmap != null) {
result.putExtra("data", bitmap);
}
}
setResult(RESULT_OK, result);
finish();
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean imageManagerHasStorage = ImageManager.quickHasStorage();
if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI)
&& getIntent().getExtras().getBoolean("slideshow", false)) {
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
finish();
} else {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "GridView.Slideshow.All");
mWakeLock.acquire();
Slideshow slideshow = new Slideshow(this);
slideshow.setDataSource(new RandomDataSource());
setContentView(slideshow);
}
return;
}
CacheService.computeDirtySets(this);
final boolean isCacheReady = CacheService.isCacheReady(false);
if (PIXEL_DENSITY == 0.0f) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
PIXEL_DENSITY = metrics.density;
}
mReverseGeocoder = new ReverseGeocoder(this);
mRenderView = new RenderView(this);
mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4),
mRenderView);
mRenderView.setRootLayer(mGridLayer);
setContentView(mRenderView);
// Creating the DataSource objects.
final PicasaDataSource picasaDataSource = new PicasaDataSource(this);
final LocalDataSource localDataSource = new LocalDataSource(this);
final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource);
// Depending upon the intent, we assign the right dataSource.
if (!isPickIntent() && !isViewIntent()) {
if (imageManagerHasStorage) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
} else if (!isCacheReady) {
Toast.makeText(this, getResources().getString(R.string.loading_new), Toast.LENGTH_LONG).show();
}
} else if (!isViewIntent()) {
final Intent intent = getIntent();
if (intent != null) {
final String type = intent.resolveType(this);
boolean includeImages = isImageType(type);
boolean includeVideos = isVideoType(type);
((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos);
if (includeImages) {
if (imageManagerHasStorage) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
} else {
mGridLayer.setDataSource(localDataSource);
}
mGridLayer.setPickIntent(true);
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG).show();
}
}
} else {
// View intent for images.
Uri uri = getIntent().getData();
boolean slideshow = getIntent().getBooleanExtra("slideshow", false);
final SingleDataSource singleDataSource = new SingleDataSource(this, uri.toString(), slideshow);
final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource);
mGridLayer.setDataSource(singleCombinedDataSource);
mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri));
if (singleDataSource.isSingleImage()) {
mGridLayer.setSingleImage(false);
} else if (slideshow) {
mGridLayer.setSingleImage(true);
mGridLayer.startSlideshow();
}
}
// We record the set of enabled accounts for picasa.
mAccountsEnabled = PicasaDataSource.getAccountStatus(this);
Log.i(TAG, "onCreate");
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean imageManagerHasStorage = ImageManager.quickHasStorage();
boolean slideshowIntent = false;
if (isViewIntent()) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
slideshowIntent = extras.getBoolean("slideshow", false);
}
}
if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI)
&& slideshowIntent) {
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
finish();
} else {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "GridView.Slideshow.All");
mWakeLock.acquire();
Slideshow slideshow = new Slideshow(this);
slideshow.setDataSource(new RandomDataSource());
setContentView(slideshow);
}
return;
}
CacheService.computeDirtySets(this);
final boolean isCacheReady = CacheService.isCacheReady(false);
if (PIXEL_DENSITY == 0.0f) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
PIXEL_DENSITY = metrics.density;
}
mReverseGeocoder = new ReverseGeocoder(this);
mRenderView = new RenderView(this);
mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4),
mRenderView);
mRenderView.setRootLayer(mGridLayer);
setContentView(mRenderView);
// Creating the DataSource objects.
final PicasaDataSource picasaDataSource = new PicasaDataSource(this);
final LocalDataSource localDataSource = new LocalDataSource(this);
final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource);
// Depending upon the intent, we assign the right dataSource.
if (!isPickIntent() && !isViewIntent()) {
if (imageManagerHasStorage) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
} else if (!isCacheReady) {
Toast.makeText(this, getResources().getString(R.string.loading_new), Toast.LENGTH_LONG).show();
}
} else if (!isViewIntent()) {
final Intent intent = getIntent();
if (intent != null) {
final String type = intent.resolveType(this);
boolean includeImages = isImageType(type);
boolean includeVideos = isVideoType(type);
((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos);
if (includeImages) {
if (imageManagerHasStorage) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
} else {
mGridLayer.setDataSource(localDataSource);
}
mGridLayer.setPickIntent(true);
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG).show();
}
}
} else {
// View intent for images.
Uri uri = getIntent().getData();
boolean slideshow = getIntent().getBooleanExtra("slideshow", false);
final SingleDataSource singleDataSource = new SingleDataSource(this, uri.toString(), slideshow);
final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource);
mGridLayer.setDataSource(singleCombinedDataSource);
mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri));
if (singleDataSource.isSingleImage()) {
mGridLayer.setSingleImage(false);
} else if (slideshow) {
mGridLayer.setSingleImage(true);
mGridLayer.startSlideshow();
}
}
// We record the set of enabled accounts for picasa.
mAccountsEnabled = PicasaDataSource.getAccountStatus(this);
Log.i(TAG, "onCreate");
}
|
diff --git a/source/de/anomic/kelondro/util/FileUtils.java b/source/de/anomic/kelondro/util/FileUtils.java
index 13e21ea49..bfdd15f2a 100644
--- a/source/de/anomic/kelondro/util/FileUtils.java
+++ b/source/de/anomic/kelondro/util/FileUtils.java
@@ -1,771 +1,771 @@
// serverFileUtils.java
// -------------------------------------------
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
// last major change: 05.08.2004
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.anomic.kelondro.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.Vector;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import de.anomic.kelondro.index.Row;
import de.anomic.kelondro.index.RowSet;
public final class FileUtils {
private static final int DEFAULT_BUFFER_SIZE = 1024; // this is also the maximum chunk size
public static long copy(final InputStream source, final OutputStream dest) throws IOException {
return copy(source, dest, -1);
}
/**
* Copies an InputStream to an OutputStream.
*
* @param source InputStream
* @param dest OutputStream
* @param count the total amount of bytes to copy (-1 for all, else must be greater than zero)
* @return Total number of bytes copied.
* @throws IOException
*
* @see #copy(InputStream source, File dest)
* @see #copyRange(File source, OutputStream dest, int start)
* @see #copy(File source, OutputStream dest)
* @see #copy(File source, File dest)
*/
public static long copy(final InputStream source, final OutputStream dest, final long count) throws IOException {
assert count == -1 || count > 0 : "precondition violated: count == -1 || count > 0 (nothing to copy)";
if(count == 0) {
// no bytes to copy
return 0;
}
final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int chunkSize = (int) ((count > 0) ? Math.min(count, DEFAULT_BUFFER_SIZE) : DEFAULT_BUFFER_SIZE);
int c; long total = 0;
while ((c = source.read(buffer, 0, chunkSize)) > 0) {
dest.write(buffer, 0, c);
dest.flush();
total += c;
if (count > 0) {
chunkSize = (int) Math.min(count-total, DEFAULT_BUFFER_SIZE);
if (chunkSize == 0) break;
}
}
dest.flush();
return total;
}
public static int copy(final File source, final Charset inputCharset, final Writer dest) throws IOException {
InputStream fis = null;
try {
fis = new FileInputStream(source);
return copy(fis, dest, inputCharset);
} finally {
if (fis != null) try { fis.close(); } catch (final Exception e) {}
}
}
public static int copy(final InputStream source, final Writer dest, final Charset inputCharset) throws IOException {
final InputStreamReader reader = new InputStreamReader(source,inputCharset);
return copy(reader,dest);
}
public static int copy(final String source, final Writer dest) throws IOException {
dest.write(source);
dest.flush();
return source.length();
}
public static int copy(final Reader source, final Writer dest) throws IOException {
final char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int count = 0;
int n = 0;
try {
while (-1 != (n = source.read(buffer))) {
dest.write(buffer, 0, n);
count += n;
}
dest.flush();
} catch (final Exception e) {
// an "sun.io.MalformedInputException: Missing byte-order mark" - exception may occur here
throw new IOException(e.getMessage());
}
return count;
}
public static void copy(final InputStream source, final File dest) throws IOException {
copy(source,dest,-1);
}
/**
* Copies an InputStream to a File.
*
* @param source InputStream
* @param dest File
* @param count the amount of bytes to copy
* @throws IOException
* @see #copy(InputStream source, OutputStream dest)
* @see #copyRange(File source, OutputStream dest, int start)
* @see #copy(File source, OutputStream dest)
* @see #copy(File source, File dest)
*/
public static void copy(final InputStream source, final File dest, final long count) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dest);
copy(source, fos, count);
} finally {
if (fos != null) try {fos.close();} catch (final Exception e) { Log.logWarning("FileUtils", "cannot close FileOutputStream for "+ dest +"! "+ e.getMessage()); }
}
}
/**
* Copies a part of a File to an OutputStream.
* @param source File
* @param dest OutputStream
* @param start Number of bytes to skip from the beginning of the File
* @throws IOException
* @see #copy(InputStream source, OutputStream dest)
* @see #copy(InputStream source, File dest)
* @see #copy(File source, OutputStream dest)
* @see #copy(File source, File dest)
*/
public static void copyRange(final File source, final OutputStream dest, final int start) throws IOException {
InputStream fis = null;
try {
fis = new FileInputStream(source);
final long skipped = fis.skip(start);
if (skipped != start) throw new IllegalStateException("Unable to skip '" + start + "' bytes. Only '" + skipped + "' bytes skipped.");
copy(fis, dest, -1);
} finally {
if (fis != null) try { fis.close(); } catch (final Exception e) {}
}
}
/**
* Copies a File to an OutputStream.
* @param source File
* @param dest OutputStream
* @throws IOException
* @see #copy(InputStream source, OutputStream dest)
* @see #copy(InputStream source, File dest)
* @see #copyRange(File source, OutputStream dest, int start)
* @see #copy(File source, File dest)
*/
public static void copy(final File source, final OutputStream dest) throws IOException {
InputStream fis = null;
try {
fis = new FileInputStream(source);
copy(fis, dest, -1);
} finally {
if (fis != null) try { fis.close(); } catch (final Exception e) {}
}
}
/**
* Copies a File to a File.
* @param source File
* @param dest File
* @param count the amount of bytes to copy
* @throws IOException
* @see #copy(InputStream source, OutputStream dest)
* @see #copy(InputStream source, File dest)
* @see #copyRange(File source, OutputStream dest, int start)
* @see #copy(File source, OutputStream dest)
*/
public static void copy(final File source, final File dest) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(dest);
copy(fis, fos, -1);
} finally {
if (fis != null) try {fis.close();} catch (final Exception e) {}
if (fos != null) try {fos.close();} catch (final Exception e) {}
}
}
public static void copy(final byte[] source, final OutputStream dest) throws IOException {
dest.write(source, 0, source.length);
dest.flush();
}
public static void copy(final byte[] source, final File dest) throws IOException {
copy(new ByteArrayInputStream(source), dest);
}
public static byte[] read(final InputStream source) throws IOException {
return read(source,-1);
}
public static byte[] read(final InputStream source, final int count) throws IOException {
if (count > 0) {
byte[] b = new byte[count];
int c = source.read(b, 0, count);
assert c == count: "count = " + count + ", c = " + c;
if (c != count) {
byte[] bb = new byte[c];
System.arraycopy(b, 0, bb, 0, c);
return bb;
}
return b;
} else {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
copy(source, baos, count);
baos.close();
return baos.toByteArray();
}
}
public static byte[] read(final File source) throws IOException {
final byte[] buffer = new byte[(int) source.length()];
InputStream fis = null;
try {
fis = new FileInputStream(source);
int p = 0, c;
while ((c = fis.read(buffer, p, buffer.length - p)) > 0) p += c;
} finally {
if (fis != null) try { fis.close(); } catch (final Exception e) {}
fis = null;
}
return buffer;
}
public static byte[] readAndZip(final File source) throws IOException {
ByteArrayOutputStream byteOut = null;
GZIPOutputStream zipOut = null;
try {
byteOut = new ByteArrayOutputStream((int)(source.length()/2));
zipOut = new GZIPOutputStream(byteOut);
copy(source, zipOut);
zipOut.close();
return byteOut.toByteArray();
} finally {
if (zipOut != null) try { zipOut.close(); } catch (final Exception e) {}
if (byteOut != null) try { byteOut.close(); } catch (final Exception e) {}
}
}
public static void writeAndGZip(final byte[] source, final File dest) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dest);
writeAndGZip(source, fos);
} finally {
if (fos != null) try {fos.close();} catch (final Exception e) {}
}
}
public static void writeAndGZip(final byte[] source, final OutputStream dest) throws IOException {
GZIPOutputStream zipOut = null;
try {
zipOut = new GZIPOutputStream(dest);
copy(source, zipOut);
zipOut.close();
} finally {
if (zipOut != null) try { zipOut.close(); } catch (final Exception e) {}
}
}
/**
* This function determines if a byte array is gzip compressed and uncompress it
* @param source properly gzip compressed byte array
* @return uncompressed byte array
* @throws IOException
*/
public static byte[] uncompressGZipArray(byte[] source) throws IOException {
if (source == null) return null;
// support of gzipped data (requested by roland)
/* "Bitwise OR of signed byte value
*
* [...] Values loaded from a byte array are sign extended to 32 bits before
* any any bitwise operations are performed on the value. Thus, if b[0]
* contains the value 0xff, and x is initially 0, then the code ((x <<
* 8) | b[0]) will sign extend 0xff to get 0xffffffff, and thus give the
* value 0xffffffff as the result. [...]" findbugs description of BIT_IOR_OF_SIGNED_BYTE
*/
if ((source.length > 1) && (((source[1] << 8) | (source[0] & 0xff)) == GZIPInputStream.GZIP_MAGIC)) {
System.out.println("DEBUG: uncompressGZipArray - uncompressing source");
try {
final ByteArrayInputStream byteInput = new ByteArrayInputStream(source);
final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(source.length / 5);
final GZIPInputStream zippedContent = new GZIPInputStream(byteInput);
final byte[] data = new byte[1024];
int read = 0;
// reading gzip file and store it uncompressed
while((read = zippedContent.read(data, 0, 1024)) != -1) {
byteOutput.write(data, 0, read);
}
zippedContent.close();
byteOutput.close();
source = byteOutput.toByteArray();
} catch (final Exception e) {
if (!e.getMessage().equals("Not in GZIP format")) {
throw new IOException(e.getMessage());
}
}
}
return source;
}
public static HashSet<String> loadList(final File file) {
final HashSet<String> set = new HashSet<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if ((line.length() > 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase());
}
br.close();
} catch (final IOException e) {
} finally {
if (br != null) try { br.close(); } catch (final Exception e) {}
}
return set;
}
public static Map<String, String> loadMap(final File f) {
// load props
try {
final byte[] b = read(f);
return table(strings(b, "UTF-8"));
} catch (final IOException e2) {
System.err.println("ERROR: " + f.toString() + " not found in settings path");
return null;
}
}
public static void saveMap(final File file, final Map<String, String> props, final String comment) throws IOException {
PrintWriter pw = null;
final File tf = new File(file.toString() + "." + (System.currentTimeMillis() % 1000));
pw = new PrintWriter(tf, "UTF-8");
pw.println("# " + comment);
String key, value;
for (final Map.Entry<String, String> entry: props.entrySet()) {
key = entry.getKey();
if (entry.getValue() == null) {
value = "";
} else {
value = entry.getValue().replaceAll("\n", "\\\\n");
}
pw.println(key + "=" + value);
}
pw.println("# EOF");
pw.close();
forceMove(tf, file);
}
public static Set<String> loadSet(final File file, final int chunksize, final boolean tree) throws IOException {
final Set<String> set = (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>();
final byte[] b = read(file);
for (int i = 0; (i + chunksize) <= b.length; i++) {
set.add(new String(b, i, chunksize, "UTF-8"));
}
return set;
}
public static Set<String> loadSet(final File file, final String sep, final boolean tree) throws IOException {
final Set<String> set = (tree) ? (Set<String>) new TreeSet<String>() : (Set<String>) new HashSet<String>();
final byte[] b = read(file);
final StringTokenizer st = new StringTokenizer(new String(b, "UTF-8"), sep);
while (st.hasMoreTokens()) {
set.add(st.nextToken());
}
return set;
}
public static void saveSet(final File file, final String format, final Set<String> set, final String sep) throws IOException {
final File tf = new File(file.toString() + ".tmp" + (System.currentTimeMillis() % 1000));
OutputStream os = null;
if ((format == null) || (format.equals("plain"))) {
os = new BufferedOutputStream(new FileOutputStream(tf));
} else if (format.equals("gzip")) {
os = new GZIPOutputStream(new FileOutputStream(tf));
} else if (format.equals("zip")) {
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
String name = file.getName();
if (name.endsWith(".zip")) name = name.substring(0, name.length() - 4);
zos.putNextEntry(new ZipEntry(name + ".txt"));
os = zos;
}
if(os != null) {
for (final Iterator<String> i = set.iterator(); i.hasNext(); ) {
os.write((i.next()).getBytes("UTF-8"));
if (sep != null) os.write(sep.getBytes("UTF-8"));
}
os.close();
}
forceMove(tf, file);
}
public static void saveSet(final File file, final String format, final RowSet set, final String sep) throws IOException {
final File tf = new File(file.toString() + ".tmp" + (System.currentTimeMillis() % 1000));
OutputStream os = null;
if ((format == null) || (format.equals("plain"))) {
os = new BufferedOutputStream(new FileOutputStream(tf));
} else if (format.equals("gzip")) {
os = new GZIPOutputStream(new FileOutputStream(tf));
} else if (format.equals("zip")) {
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
String name = file.getName();
if (name.endsWith(".zip")) name = name.substring(0, name.length() - 4);
zos.putNextEntry(new ZipEntry(name + ".txt"));
os = zos;
}
if (os != null) {
final Iterator<Row.Entry> i = set.iterator();
String key;
if (i.hasNext()) {
key = new String(i.next().getColBytes(0));
os.write(key.getBytes("UTF-8"));
}
while (i.hasNext()) {
key = new String((i.next()).getColBytes(0));
if (sep != null) os.write(sep.getBytes("UTF-8"));
os.write(key.getBytes("UTF-8"));
}
os.close();
}
forceMove(tf, file);
}
public static HashMap<String, String> table(final Vector<String> list) {
final Enumeration<String> i = list.elements();
int pos;
String line;
final HashMap<String, String> props = new HashMap<String, String>(list.size());
while (i.hasMoreElements()) {
line = (i.nextElement()).trim();
pos = line.indexOf("=");
if (pos > 0) props.put(line.substring(0, pos).trim(), line.substring(pos + 1).trim());
}
return props;
}
public static HashMap<String, String> table(final byte[] a, final String encoding) {
return table(strings(a, encoding));
}
/**
* parse config files
*
* splits the lines in list into pairs sperarated by =, lines beginning with # are ignored
* ie:
* abc=123
* # comment
* fg=dcf
* => Map{abc => 123, fg => dcf}
* @param list
* @return
*/
public static HashMap<String, String> table(final ArrayList<String> list) {
if (list == null) return new HashMap<String, String>();
final Iterator<String> i = list.iterator();
int pos;
String line;
final HashMap<String, String> props = new HashMap<String, String>(list.size());
while (i.hasNext()) {
line = (i.next()).trim();
if (line.startsWith("#")) continue; // exclude comments
//System.out.println("NXTOOLS_PROPS - LINE:" + line);
pos = line.indexOf("=");
if (pos > 0) props.put(line.substring(0, pos).trim(), line.substring(pos + 1).trim());
}
return props;
}
public static ArrayList<String> strings(final byte[] a) {
return strings(a, null);
}
public static ArrayList<String> strings(final byte[] a, final String encoding) {
if (a == null) return new ArrayList<String>();
int s = 0;
int e;
final ArrayList<String> v = new ArrayList<String>();
byte b;
while (s < a.length) {
// find eol
e = s;
while (e < a.length) {
b = a[e];
if ((b == 10) || (b == 13) || (b == 0)) break;
e++;
}
// read line
if (encoding == null) {
v.add(new String(a, s, e - s));
} else try {
v.add(new String(a, s, e - s, encoding));
} catch (final UnsupportedEncodingException xcptn) {
return v;
}
// eat up additional eol bytes
s = e + 1;
while (s < a.length) {
b = a[s];
if ((b != 10) && (b != 13)) break;
s++;
}
}
return v;
}
/**
* @param from
* @param to
* @throws IOException
*/
private static void forceMove(final File from, final File to) throws IOException {
if(!(to.delete() && from.renameTo(to))) {
// do it manually
copy(from, to);
FileUtils.deletedelete(from);
}
}
/**
* Moves all files from a directory to another.
* @param from_dir Directory which contents will be moved.
* @param to_dir Directory to move into. It must exist already.
*/
public static void moveAll(final File from_dir, final File to_dir) {
if (!(from_dir.isDirectory())) return;
if (!(to_dir.isDirectory())) return;
final String[] list = from_dir.list();
for (int i = 0; i < list.length; i++) {
if(!new File(from_dir, list[i]).renameTo(new File(to_dir, list[i])))
Log.logWarning("serverFileUtils", "moveAll(): could not move from "+ from_dir + list[i] +" to "+ to_dir + list[i]);
}
}
public static class dirlistComparator implements Comparator<File>, Serializable {
/**
* generated serial
*/
private static final long serialVersionUID = -5196490300039230135L;
public int compare(final File file1, final File file2) {
if (file1.isDirectory() && !file2.isDirectory()) {
return -1;
} else if (!file1.isDirectory() && file2.isDirectory()) {
return 1;
} else {
return file1.getName().compareToIgnoreCase(file2.getName());
}
}
}
public static void main(final String[] args) {
try {
writeAndGZip("ein zwei drei, Zauberei".getBytes(), new File("zauberei.txt.gz"));
} catch (final IOException e) {
e.printStackTrace();
}
}
/**
* copies the input stream to one output stream (byte per byte)
* @param in
* @param out
* @return number of copies bytes
* @throws IOException
*/
public static int copyToStream(final BufferedInputStream in, final BufferedOutputStream out) throws IOException {
int count = 0;
// copy bytes
int b;
while ((b = in.read()) != -1) {
count++;
out.write(b);
}
out.flush();
return count;
}
/**
* copies the input stream to both output streams (byte per byte)
* @param in
* @param out0
* @param out1
* @return number of copies bytes
* @throws IOException
*/
public static int copyToStreams(final BufferedInputStream in, final BufferedOutputStream out0, final BufferedOutputStream out1) throws IOException {
assert out0 != null;
assert out1 != null;
int count = 0;
// copy bytes
int b;
while((b = in.read()) != -1) {
count++;
out0.write(b);
out1.write(b);
}
out0.flush();
out1.flush();
return count;
}
/**
* copies the input stream to all writers (byte per byte)
* @param data
* @param writer
* @param charSet
* @return
* @throws IOException
*/
public static int copyToWriter(final BufferedInputStream data, final BufferedWriter writer, final Charset charSet) throws IOException {
// the docs say: "For top efficiency, consider wrapping an InputStreamReader within a BufferedReader."
final Reader sourceReader = new InputStreamReader(data, charSet);
int count = 0;
// copy bytes
int b;
while((b = sourceReader.read()) != -1) {
count++;
writer.write(b);
}
writer.flush();
return count;
}
public static int copyToWriters(final BufferedInputStream data, final BufferedWriter writer0, final BufferedWriter writer1, final Charset charSet) throws IOException {
// the docs say: "For top efficiency, consider wrapping an InputStreamReader within a BufferedReader."
assert writer0 != null;
assert writer1 != null;
final Reader sourceReader = new InputStreamReader(data, charSet);
int count = 0;
// copy bytes
int b;
while((b = sourceReader.read()) != -1) {
count++;
writer0.write(b);
writer1.write(b);
}
writer0.flush();
writer1.flush();
return count;
}
/**
* delete files and directories
* if a directory is not empty, delete also everything inside
* because deletion sometimes fails on windows, there is also a windows exec included
* @param path
*/
public static void deletedelete(final File path) {
if (!path.exists()) return;
// empty the directory first
if (path.isDirectory()) {
final String[] list = path.list();
if (list != null) {
for (String s: list) deletedelete(new File(path, s));
}
}
int c = 0;
while (c++ < 20) {
if (!path.exists()) break;
if (path.delete()) break;
// some OS may be slow when giving up file pointer
//System.runFinalization();
//System.gc();
try { Thread.sleep(200); } catch (InterruptedException e) { break; }
}
if (path.exists()) {
path.deleteOnExit();
String p = "";
try {
p = path.getCanonicalPath();
} catch (IOException e1) {
e1.printStackTrace();
}
if (System.getProperties().getProperty("os.name","").toLowerCase().startsWith("windows")) {
// deleting files on windows sometimes does not work with java
try {
- String command = "cmd /C del /F /Q " + p;
+ String command = "cmd /C del /F /Q \"" + p + "\"";
Process r = Runtime.getRuntime().exec(command);
if (r == null) {
Log.logSevere("FileUtils", "cannot execute command: " + command);
} else {
byte[] response = read(r.getInputStream());
Log.logInfo("FileUtils", "deletedelete: " + new String(response));
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (path.exists()) Log.logSevere("FileUtils", "cannot delete file " + p);
}
}
}
| true | true | public static void deletedelete(final File path) {
if (!path.exists()) return;
// empty the directory first
if (path.isDirectory()) {
final String[] list = path.list();
if (list != null) {
for (String s: list) deletedelete(new File(path, s));
}
}
int c = 0;
while (c++ < 20) {
if (!path.exists()) break;
if (path.delete()) break;
// some OS may be slow when giving up file pointer
//System.runFinalization();
//System.gc();
try { Thread.sleep(200); } catch (InterruptedException e) { break; }
}
if (path.exists()) {
path.deleteOnExit();
String p = "";
try {
p = path.getCanonicalPath();
} catch (IOException e1) {
e1.printStackTrace();
}
if (System.getProperties().getProperty("os.name","").toLowerCase().startsWith("windows")) {
// deleting files on windows sometimes does not work with java
try {
String command = "cmd /C del /F /Q " + p;
Process r = Runtime.getRuntime().exec(command);
if (r == null) {
Log.logSevere("FileUtils", "cannot execute command: " + command);
} else {
byte[] response = read(r.getInputStream());
Log.logInfo("FileUtils", "deletedelete: " + new String(response));
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (path.exists()) Log.logSevere("FileUtils", "cannot delete file " + p);
}
}
| public static void deletedelete(final File path) {
if (!path.exists()) return;
// empty the directory first
if (path.isDirectory()) {
final String[] list = path.list();
if (list != null) {
for (String s: list) deletedelete(new File(path, s));
}
}
int c = 0;
while (c++ < 20) {
if (!path.exists()) break;
if (path.delete()) break;
// some OS may be slow when giving up file pointer
//System.runFinalization();
//System.gc();
try { Thread.sleep(200); } catch (InterruptedException e) { break; }
}
if (path.exists()) {
path.deleteOnExit();
String p = "";
try {
p = path.getCanonicalPath();
} catch (IOException e1) {
e1.printStackTrace();
}
if (System.getProperties().getProperty("os.name","").toLowerCase().startsWith("windows")) {
// deleting files on windows sometimes does not work with java
try {
String command = "cmd /C del /F /Q \"" + p + "\"";
Process r = Runtime.getRuntime().exec(command);
if (r == null) {
Log.logSevere("FileUtils", "cannot execute command: " + command);
} else {
byte[] response = read(r.getInputStream());
Log.logInfo("FileUtils", "deletedelete: " + new String(response));
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (path.exists()) Log.logSevere("FileUtils", "cannot delete file " + p);
}
}
|
diff --git a/src/edu/cuny/qc/speech/AuToBI/AuToBI.java b/src/edu/cuny/qc/speech/AuToBI/AuToBI.java
index 0a20bcf..8a74300 100644
--- a/src/edu/cuny/qc/speech/AuToBI/AuToBI.java
+++ b/src/edu/cuny/qc/speech/AuToBI/AuToBI.java
@@ -1,1236 +1,1236 @@
/* AuToBI.java
Copyright (c) 2009-2012 Andrew Rosenberg
This file is part of the AuToBI prosodic analysis package.
AuToBI is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
AuToBI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with AuToBI. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.cuny.qc.speech.AuToBI;
import edu.cuny.qc.speech.AuToBI.classifier.AuToBIClassifier;
import edu.cuny.qc.speech.AuToBI.core.*;
import edu.cuny.qc.speech.AuToBI.featureextractor.*;
import edu.cuny.qc.speech.AuToBI.featureextractor.shapemodeling.CurveShapeFeatureExtractor;
import edu.cuny.qc.speech.AuToBI.featureextractor.shapemodeling.CurveShapeLikelihoodFeatureExtractor;
import edu.cuny.qc.speech.AuToBI.featureextractor.shapemodeling.PVALFeatureExtractor;
import edu.cuny.qc.speech.AuToBI.featureset.*;
import edu.cuny.qc.speech.AuToBI.io.*;
import edu.cuny.qc.speech.AuToBI.util.AuToBIUtils;
import edu.cuny.qc.speech.AuToBI.util.ClassifierUtils;
import edu.cuny.qc.speech.AuToBI.util.WordReaderUtils;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.BasicConfigurator;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static java.util.concurrent.Executors.newFixedThreadPool;
/**
* This is the main class for the AuToBI system.
* <p/>
* AuToBI generates hypothesized ToBI tones based on manual segmentation of words and an audio file.
* <p/>
* The prediction is divided into six tasks. 1) detection of pitch accents 2) classification of pitch accent types 3)
* detection of intonational phrase boundaries 4) classification of intonational phrase ending tones (phrase accent and
* boundary tone pairs) 5) detection of intermediate phrase boundaries 6) classification of intermediate phrase ending
* tones (phrase accents)
* <p/>
* Each of these tasks require distinct features to be extracted from the words that are being analyzed. To perform the
* feature extraction, each task has an associated FeatureSet which describes the features required for classification.
* AuToBI maintains a registry of FeatureExtractors describing the Features that they will calculate when processing a
* word. When extracting features for a FeatureSet, AuToBI only calls those FeatureExtractors necessary to generate the
* required features.
* <p/>
* This class manages command line parameters, the execution of feature extractors and the generation of hypothesized
* ToBI tones.
*
* @see FeatureSet
* @see FeatureExtractor
*/
public class AuToBI {
private AuToBIParameters params; // Command line parameters
// A map from feature names to the FeatureExtractors that generate them
private Map<String, FeatureExtractor> feature_registry;
// A set of FeatureExtractors that have already executed
protected Set<FeatureExtractor> executed_feature_extractors;
// A map from input filenames to serialized speaker normalization parameter files.
private Map<String, String> speaker_norm_file_mapping;
// A map of the number of times each feature is needed.
private HashMap<String, Integer> reference_count;
// A set of features to delete on the next garbage collection call
private Set<String> dead_features;
// A list of AuToBITasks to be executed.
protected HashMap<String, AuToBITask> tasks;
/**
* Constructs a new AuToBI object.
*/
public AuToBI() {
params = new AuToBIParameters();
feature_registry = new HashMap<String, FeatureExtractor>();
executed_feature_extractors = new HashSet<FeatureExtractor>();
speaker_norm_file_mapping = new HashMap<String, String>();
tasks = new HashMap<String, AuToBITask>();
}
/**
* Parses command line parameters and sets up log4j logging.
*
* @param args command line arguments.
*/
public void init(String[] args) {
params.readParameters(args);
if (params.hasParameter("log4j_config_file")) {
try {
PropertyConfigurator.configure(params.getParameter("log4j_config_file"));
} catch (Exception e) {
BasicConfigurator.configure();
AuToBIUtils.log("Couldn't read -log4j_config_file. BasicConfigurator logging to console");
}
} else {
BasicConfigurator.configure();
}
}
/**
* Gets the requested parameter.
*
* @param parameter the parameter name
* @return the parameter value
* @throws AuToBIException if the parameter was not set
*/
public String getParameter(String parameter) throws AuToBIException {
return params.getParameter(parameter);
}
/**
* Gets the requested parameter.
*
* @param parameter the parameter name
* @return the parameter value or null if the parameter was not set
*/
public String getOptionalParameter(String parameter) {
return params.getOptionalParameter(parameter);
}
/**
* Gets the requested boolean parameter with default value if the parameter is not set.
*
* @param parameter the parameter name
* @param default_value the default boolean value if not explicitly set.
* @return the parameter value or null if the parameter was not set
*/
public Boolean getBooleanParameter(String parameter, boolean default_value) {
return params.booleanParameter(parameter, default_value);
}
/**
* Gets the requested parameter with a default value if the parameter has not been set.
*
* @param parameter the parameter name
* @param default_value a default value
* @return The parameter value or default_value if the parameter has not been set.
*/
public String getOptionalParameter(String parameter, String default_value) {
return params.getOptionalParameter(parameter, default_value);
}
/**
* Determines if a parameter has been set or not.
*
* @param parameter the parameter name
* @return true if the parameter has been set, false otherwise
*/
public boolean hasParameter(String parameter) {
return params.hasParameter(parameter);
}
/**
* Sets the Feature Registry
*
* @param registry new feature registry
*/
public void setFeatureRegistry(Map<String, FeatureExtractor> registry) {
this.feature_registry = registry;
}
/**
* Retrieves the feature registry
*
* @return the feature registry
*/
public Map<String, FeatureExtractor> getFeatureRegistry() {
return feature_registry;
}
/**
* Registers a FeatureExtractor with AuToBI.
* <p/>
* A FeatureExtractor class is responsible for reporting what features it extracts.
*
* @param fe the feature extractor
*/
public void registerFeatureExtractor(FeatureExtractor fe) {
for (String feature_name : fe.getExtractedFeatures()) {
if (feature_registry.containsKey(feature_name)) {
AuToBIUtils.warn("Feature Registry already contains feature: " + feature_name);
}
feature_registry.put(feature_name, fe);
}
}
/**
* Clears the feature registry and the extracted features.
*/
public void unregisterAllFeatureExtractors() {
feature_registry = new HashMap<String, FeatureExtractor>();
executed_feature_extractors = new HashSet<FeatureExtractor>();
}
/**
* Extracts the features required for the feature set and optionally deletes intermediate features that may have been
* generated in their processing
*
* @param fs the feature set
* @throws FeatureExtractorException If any of the FeatureExtractors have a problem
* @throws AuToBIException If there are other problems
*/
public void extractFeatures(FeatureSet fs) throws FeatureExtractorException, AuToBIException {
initializeReferenceCounting(fs);
if (fs.getClassAttribute() != null)
extractFeature(fs.getClassAttribute(), fs);
extractFeatures(fs.getRequiredFeatures(), fs);
}
/**
* Extracts a set of features on data points stored in the given feature set
*
* @param features The requested features
* @param fs The feature set
* @throws FeatureExtractorException If any of the FeatureExtractors have a problem
* @throws AuToBIException If there are other problems
*/
public void extractFeatures(Set<String> features, FeatureSet fs)
throws FeatureExtractorException, AuToBIException {
for (String feature : features) {
extractFeature(feature, fs);
}
}
/**
* Initializes the number of times a feature is required by a FeatureSet. This allows AuToBI to guarantee that every
* stored feature is necessary, deleting unneeded intermediate features.
* <p/>
* After each feature is extracted its reference count is decremented. When a feature has a reference count of zero,
* it can safely be removed.
*
* @param fs the feature set
* @throws AuToBIException if there are features required that do not have associated registered feature extractors.
*/
public void initializeReferenceCounting(FeatureSet fs) throws AuToBIException {
reference_count = new HashMap<String, Integer>();
dead_features = new HashSet<String>();
Stack<String> features = new Stack<String>();
if (fs.getClassAttribute() != null)
features.add(fs.getClassAttribute());
features.addAll(fs.getRequiredFeatures());
while (features.size() != 0) {
String feature = features.pop();
if (!feature_registry.containsKey(feature)) {
throw new AuToBIException("No feature extractor registered for feature: " + feature);
}
incrementReferenceCount(feature);
// Add required features that wouldn't have been extracted previously.
if (feature_registry.get(feature) != null) {
features.addAll(feature_registry.get(feature).getRequiredFeatures());
}
}
}
/**
* Retrieves the remaining reference count for a given feature.
*
* @param feature the feature
* @return the current reference count for the feature
*/
public int getReferenceCount(String feature) {
if (reference_count.containsKey(feature)) {
return reference_count.get(feature);
} else {
return 0;
}
}
/**
* Increments the reference count for a given feature.
*
* @param feature the feature name
*/
public void incrementReferenceCount(String feature) {
if (!reference_count.containsKey(feature)) {
reference_count.put(feature, 0);
}
reference_count.put(feature, reference_count.get(feature) + 1);
// It is unlikely that a feature would get a new reference after being obliterated, but this guarantees
// that there are no features with positive reference counts in the dead feature set.
if (dead_features.contains(feature)) {
dead_features.remove(feature);
}
}
/**
* Decrement the reference count for a given feature.
*
* @param feature the feature name
*/
public void decrementReferenceCount(String feature) {
if (reference_count.containsKey(feature)) {
reference_count.put(feature, Math.max(0, reference_count.get(feature) - 1));
if (reference_count.get(feature) == 0) {
dead_features.add(feature);
}
}
}
/**
* Extracts a single feature on data points stored in the given feature set.
* <p/>
* If the registered FeatureExtractor requires any features for processing, this will result in recursive calls to
* extractFeatures(...).
*
* @param feature The requested feature
* @param fs The feature set
* @throws FeatureExtractorException If any of the FeatureExtractors have a problem
* @throws AuToBIException If there are other problems
*/
public void extractFeature(String feature, FeatureSet fs) throws FeatureExtractorException, AuToBIException {
if (!feature_registry.containsKey(feature))
throw new AuToBIException("No feature extractor registered for feature: " + feature);
FeatureExtractor extractor = feature_registry.get(feature);
AuToBIUtils.debug("Start Feature Extraction for: " + feature);
if (extractor != null) {
// Recursively extract the features required by the current FeatureExtractor.
extractFeatures(extractor.getRequiredFeatures(), fs);
if (!executed_feature_extractors.contains(extractor)) {
AuToBIUtils.debug("running feature extraction for: " + feature);
extractor.extractFeatures(fs.getDataPoints());
AuToBIUtils.debug("extracted features using: " + extractor.getClass().getCanonicalName());
executed_feature_extractors.add(extractor);
}
for (String rf : extractor.getRequiredFeatures()) {
decrementReferenceCount(rf);
}
featureGarbageCollection(fs);
}
AuToBIUtils.debug("End Feature Extraction for: " + feature);
}
/**
* Removes any features which are no longer referenced in the feature set.
*
* @param fs the feature set
*/
public void featureGarbageCollection(FeatureSet fs) {
for (String feature : dead_features) {
AuToBIUtils.debug("Removing feature: " + feature);
fs.removeFeatureFromDataPoints(feature);
}
dead_features.clear();
}
/**
* Evaluates the performance of a particular task.
*
* @param task a task identifier
* @param fs the feature set
* @return a string representation of the evaluation
* @throws AuToBIException if there is no task corresponding to the identifier
*/
protected String evaluateTaskPerformance(String task, FeatureSet fs) throws AuToBIException {
if (tasks.containsKey(task)) {
AuToBITask autobi_task = tasks.get(task);
return ClassifierUtils.evaluateClassification(autobi_task.getHypFeature(), autobi_task.getTrueFeature(), fs);
} else throw new AuToBIException(
"Task, " + task + ", is unavailable. Either no classifier has been set, or there is some other problem");
}
/**
* Generates predictions corresponding to a particular task
*
* @param task A task identifier
* @param fs The feature set
* @throws AuToBIException if there is no task associated with the identifier.
*/
public void generatePredictions(String task, FeatureSet fs) throws AuToBIException {
if (tasks.containsKey(task)) {
AuToBITask autobi_task = tasks.get(task);
ClassifierUtils
.generatePredictions(autobi_task.getClassifier(),
autobi_task.getHypFeature(),
autobi_task.getDefaultValue(),
fs);
} else throw new AuToBIException(
"Task, " + task + ", is unavailable. Either no classifier has been set, or there is some other problem");
}
/**
* Generates predictions with confidence scores corresponding to a particular task
*
* @param task A task identifier
* @param fs The feature set
* @throws AuToBIException if there is no task associated with the identifier.
*/
public void generatePredictionsWithConfidenceScores(String task, FeatureSet fs) throws AuToBIException {
if (tasks.containsKey(task)) {
AuToBITask autobi_task = tasks.get(task);
ClassifierUtils
.generatePredictionsWithConfidenceScores(autobi_task.getClassifier(),
autobi_task.getHypFeature(),
autobi_task.getConfFeature(),
autobi_task.getDefaultValue(),
fs);
} else throw new AuToBIException(
"Task, " + task + ", is unavailable. Either no classifier has been set, or there is some other problem");
}
/**
* Retrieves an empty feature set for the given task.
*
* @param task a task identifier.
* @return a corresponding FeatureSet object
* @throws AuToBIException If there is no FeatureSet defined for the task identifier
*/
public FeatureSet getTaskFeatureSet(String task) throws AuToBIException {
if (tasks.containsKey(task)) {
AuToBITask autobi_task = tasks.get(task);
if (autobi_task.getFeatureSet() == null) {
throw new AuToBIException("Task, " + task + ", does not have an associated feature set");
}
return autobi_task.getFeatureSet().newInstance();
} else throw new AuToBIException(
"Task, " + task + ", is unavailable. Either no classifier has been set, or there is some other problem");
}
/**
* Retrieves a default hypothesized feature name set for the given task.
*
* @param task a task identifier.
* @return a string for the hypothesized name
* @throws AuToBIException If there is no FeatureSet defined for the task identifier
*/
public String getHypotheizedFeature(String task) throws AuToBIException {
if (tasks.containsKey(task)) {
AuToBITask autobi_task = tasks.get(task);
return autobi_task.getHypFeature();
} else throw new AuToBIException(
"Task, " + task + ", is unavailable. Either no classifier has been set, or there is some other problem");
}
/**
* Retrieves a default feature distribution name set for the given task.
*
* @param task a task identifier.
* @return a string for the hypothesized name
* @throws AuToBIException If there is no FeatureSet defined for the task identifier
*/
public String getDistributionFeature(String task) throws AuToBIException {
if (tasks.containsKey(task)) {
AuToBITask autobi_task = tasks.get(task);
return autobi_task.getDistFeature();
} else throw new AuToBIException(
"Task, " + task + ", is unavailable. Either no classifier has been set, or there is some other problem");
}
/**
* Retrieves a previously loaded AuToBIClassifier for the given task.
*
* @param task a task identifier.
* @return a corresponding FeatureSet object
* @throws AuToBIException If there is no FeatureSet defined for the task identifier
*/
public AuToBIClassifier getTaskClassifier(String task) throws AuToBIException {
if (tasks.containsKey(task)) {
AuToBITask autobi_task = tasks.get(task);
return autobi_task.getClassifier();
} else throw new AuToBIException(
"Task, " + task + ", is unavailable. Either no classifier has been set, or there is some other problem");
}
/**
* Constructs a FeatureSet from a collection of filenames.
* <p/>
* This function handles both the file io of loading the set of data points and wav data, and the feature extraction
* routine.
*
* @param filenames the filenames containing data points.
* @param fs an empty feature set to propagate
* @throws UnsupportedAudioFileException if the wav file doesn't work out
*/
public void propagateFeatureSet(Collection<FormattedFile> filenames, FeatureSet fs)
throws UnsupportedAudioFileException {
if (fs.getClassAttribute() == null) {
AuToBIUtils.warn("FeatureSet has null class attribute. Classification experiments will generate errors.");
}
Set<Pair<String, String>> attr_omit = new HashSet<Pair<String, String>>();
Set<String> temp_features = new HashSet<String>();
if (hasParameter("attribute_omit") && getOptionalParameter("attribute_omit", "").contains(":")) {
try {
String[] omission = getParameter("attribute_omit").split(",");
for (String pair : omission) {
String[] av_pair = pair.split(":");
attr_omit.add(new Pair<String, String>(av_pair[0], av_pair[1]));
if (!fs.getRequiredFeatures().contains(av_pair[0])) {
temp_features.add(av_pair[0]);
fs.insertRequiredFeature(av_pair[0]);
}
}
} catch (AuToBIException e) {
e.printStackTrace();
}
}
ExecutorService threadpool = newFixedThreadPool(Integer.parseInt(getOptionalParameter("num_threads", "1")));
List<Future<FeatureSet>> results = new ArrayList<Future<FeatureSet>>();
for (FormattedFile filename : filenames) {
results.add(threadpool.submit(new FeatureSetPropagator(this, filename, fs)));
}
for (Future<FeatureSet> new_fs : results) {
if (new_fs != null) {
List<Word> words;
try {
words = new_fs.get().getDataPoints();
// Attribute omission by attribute values.
// This allows a user to omit data points with particular attributes, for
// example, to classify only phrase ending words.
if (attr_omit.size() > 0) {
for (Word w : words) {
boolean include = true;
for (Pair<String, String> e : attr_omit) {
if (w.hasAttribute(e.first) && w.getAttribute(e.first).equals(e.second)) {
include = false;
}
}
if (include) {
fs.getDataPoints().add(w);
}
}
} else {
fs.getDataPoints().addAll(words);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
for (String f : temp_features) {
fs.getRequiredFeatures().remove(f);
}
threadpool.shutdown();
fs.constructFeatures();
}
/**
* Initializes the Autobi task list. This is driven by loading classifiers from serialized objects.
* <p/>
* When a classifier is correctly loaded a corresponding task object is created to handle the appropriate bookkeeping
* <p/>
* Only those classifiers which have been specified using the following command line parameters are loaded:
* -pitch_accent_detector -pitch_accent_classifier -IP_detector -ip_detector -phrase_accent_classifier
* -boundary_tone_classifier
*/
public void initializeAuToBITasks() {
try {
String pad_filename = getParameter("pitch_accent_detector");
AuToBIClassifier pitch_accent_detector = ClassifierUtils.readAuToBIClassifier(pad_filename);
AuToBITask task = new AuToBITask();
task.setClassifier(pitch_accent_detector);
task.setTrueFeature("nominal_PitchAccent");
task.setHypFeature("hyp_pitch_accent");
task.setConfFeature("hyp_pitch_accent_conf");
task.setDistFeature("hyp_pitch_accent_dist");
task.setFeatureSet(new PitchAccentDetectionFeatureSet());
tasks.put("pitch_accent_detection", task);
} catch (AuToBIException ignored) {
}
try {
String pac_filename = getParameter("pitch_accent_classifier");
AuToBIClassifier pitch_accent_classifier = ClassifierUtils.readAuToBIClassifier(pac_filename);
AuToBITask task = new AuToBITask();
task.setClassifier(pitch_accent_classifier);
task.setTrueFeature("nominal_PitchAccentType");
task.setHypFeature("hyp_pitch_accent_type");
task.setConfFeature("hyp_pitch_accent_type_conf");
task.setDistFeature("hyp_pitch_accent_type_dist");
task.setFeatureSet(new PitchAccentClassificationFeatureSet());
tasks.put("pitch_accent_classification", task);
} catch (AuToBIException ignored) {
}
try {
String intonational_phrase_detector_filename = getParameter("IP_detector");
AuToBIClassifier intonational_phrase_boundary_detector =
ClassifierUtils.readAuToBIClassifier(intonational_phrase_detector_filename);
AuToBITask task = new AuToBITask();
task.setClassifier(intonational_phrase_boundary_detector);
task.setTrueFeature("nominal_IntonationalPhraseBoundary");
task.setHypFeature("hyp_IP_location");
task.setConfFeature("hyp_IP_location_conf");
task.setDistFeature("hyp_IP_location_dist");
task.setFeatureSet(new IntonationalPhraseBoundaryDetectionFeatureSet());
tasks.put("intonational_phrase_boundary_detection", task);
} catch (AuToBIException ignored) {
}
try {
String intermediate_phrase_detector_filename = getParameter("ip_detector");
AuToBIClassifier intermediate_phrase_boundary_detector =
ClassifierUtils.readAuToBIClassifier(intermediate_phrase_detector_filename);
AuToBITask task = new AuToBITask();
task.setClassifier(intermediate_phrase_boundary_detector);
task.setTrueFeature("nominal_IntermediatePhraseBoundary");
task.setHypFeature("hyp_ip_location");
task.setConfFeature("hyp_ip_location_conf");
task.setDistFeature("hyp_ip_location_dist");
task.setFeatureSet(new IntermediatePhraseBoundaryDetectionFeatureSet());
tasks.put("intermediate_phrase_boundary_detection", task);
} catch (AuToBIException ignored) {
}
try {
String phrase_accent_classifier_name = getParameter("phrase_accent_classifier");
AuToBIClassifier phrase_accent_classifier =
ClassifierUtils.readAuToBIClassifier(phrase_accent_classifier_name);
AuToBITask task = new AuToBITask();
task.setClassifier(phrase_accent_classifier);
task.setTrueFeature("nominal_PhraseAccent");
task.setHypFeature("hyp_phrase_accent");
task.setConfFeature("hyp_phrase_accent_conf");
task.setDistFeature("hyp_phrase_accent_dist");
task.setFeatureSet(new PhraseAccentClassificationFeatureSet());
tasks.put("phrase_accent_classification", task);
} catch (AuToBIException ignored) {
}
try {
String boundary_tone_classifier_name = getParameter("boundary_tone_classifier");
AuToBIClassifier boundary_tone_classifier =
ClassifierUtils.readAuToBIClassifier(boundary_tone_classifier_name);
AuToBITask task = new AuToBITask();
task.setClassifier(boundary_tone_classifier);
task.setTrueFeature("nominal_PhraseAccentBoundaryTone");
task.setHypFeature("hyp_pabt");
task.setConfFeature("hyp_pabt_conf");
task.setDistFeature("hyp_pabt_dist");
task.setFeatureSet(new PhraseAccentBoundaryToneClassificationFeatureSet());
tasks.put("boundary_tone_classification", task);
} catch (AuToBIException ignored) {
}
}
/**
* Retrieves a list of classification task identifiers corresponding to the tasks to be performed.
* <p/>
* Only those tasks corresponding to loaded classifiers are executed.
*
* @return a list of task identifiers.
*/
public Set<String> getClassificationTasks() {
return tasks.keySet();
}
/**
* Writes a TextGrid file containing words and hypothesized ToBI labels.
*
* @param words The words
* @param out_file The destination file
* @throws IOException If there is a problem writing to the destination file.
*/
public void writeTextGrid(List<Word> words, String out_file) throws IOException {
String text_grid = generateTextGridString(words);
AuToBIFileWriter writer = new AuToBIFileWriter(out_file);
writer.write(text_grid);
writer.close();
}
/**
* Generates a TextGrid representation of the words and hypothesized ToBI labels.
*
* @param words the words to output
* @return a string representing the textgrid contents of the words.
*/
public String generateTextGridString(List<Word> words) {
String text_grid = "File type = \"ooTextFile\"\n";
text_grid += "Object class = \"TextGrid\"\n";
text_grid += "xmin = 0\n";
text_grid += "xmax = " + words.get(words.size() - 1).getEnd() + "\n";
text_grid += "tiers? <exists>\n";
text_grid += "size = 3\n";
text_grid += "item []:\n";
text_grid += "item [1]:\n";
text_grid += "class = \"IntervalTier\"\n";
text_grid += "name = \"words\"\n";
text_grid += "xmin = 0\n";
text_grid += "xmax = " + words.get(words.size() - 1).getEnd() + "\n";
text_grid += "intervals: size = " + words.size() + "\n";
for (int i = 0; i < words.size(); ++i) {
Word w = words.get(i);
text_grid += "intervals [" + (i + 1) + "]:\n";
text_grid += "xmin = " + w.getStart() + "\n";
text_grid += "xmax = " + w.getEnd() + "\n";
text_grid += "text = \"" + w.getLabel() + "\"\n";
}
text_grid += "item [2]:\n";
text_grid += "class = \"IntervalTier\"\n";
text_grid += "name = \"pitch_accent_hypothesis\"\n";
text_grid += "xmin = 0\n";
text_grid += "xmax = " + words.get(words.size() - 1).getEnd() + "\n";
text_grid += "intervals: size = " + words.size() + "\n";
for (int i = 0; i < words.size(); ++i) {
Word w = words.get(i);
String text = "";
if (getBooleanParameter("distributions", false)) {
String det_dist_feature = tasks.get("pitch_accent_detection").getDistFeature();
String class_dist_feature = tasks.get("pitch_accent_classification").getDistFeature();
if (w.hasAttribute(det_dist_feature)) {
text = w.getAttribute(det_dist_feature).toString();
}
if (w.hasAttribute(class_dist_feature)) {
text += w.getAttribute(class_dist_feature).toString();
}
} else {
if (w.hasAttribute(tasks.get("pitch_accent_detection").getHypFeature())) {
text = w.getAttribute(tasks.get("pitch_accent_detection").getHypFeature()).toString();
}
}
text_grid += "intervals [" + (i + 1) + "]:\n";
text_grid += "xmin = " + w.getStart() + "\n";
text_grid += "xmax = " + w.getEnd() + "\n";
text_grid += "text = \"" + text + "\"\n";
}
text_grid += "item [3]:\n";
text_grid += "class = \"IntervalTier\"\n";
text_grid += "name = \"phrase_hypothesis\"\n";
text_grid += "xmin = 0\n";
text_grid += "xmax = " + words.get(words.size() - 1).getEnd() + "\n";
text_grid += "intervals: size = " + words.size() + "\n";
for (int i = 0; i < words.size(); ++i) {
Word w = words.get(i);
String text = "";
if (getBooleanParameter("distributions", false)) {
if (w.hasAttribute(tasks.get("intonational_phrase_boundary_detection").getDistFeature())) {
text = w.getAttribute(tasks.get("intonational_phrase_boundary_detection").getDistFeature()).toString();
}
if (w.hasAttribute(tasks.get("intermediate_phrase_boundary_detection").getDistFeature())) {
text = w.getAttribute(tasks.get("intermediate_phrase_boundary_detection").getDistFeature()).toString();
}
if (w.hasAttribute(tasks.get("boundary_tone_classification").getDistFeature())) {
text += w.getAttribute(tasks.get("boundary_tone_classification").getDistFeature()).toString();
}
if (w.hasAttribute(tasks.get("phrase_accent_classification").getDistFeature())) {
text += w.getAttribute(tasks.get("phrase_accent_classification").getDistFeature()).toString();
}
} else {
if (w.hasAttribute("hyp_phrase_boundary")) {
text = w.getAttribute("hyp_phrase_boundary").toString();
}
}
text_grid += "intervals [" + (i + 1) + "]:\n";
text_grid += "xmin = " + w.getStart() + "\n";
text_grid += "xmax = " + w.getEnd() + "\n";
text_grid += "text = \"" + text + "\"\n";
}
return text_grid;
}
/**
* Registers a large default set of feature extractors.
*
* @throws FeatureExtractorException If there is a problem registering (not running) feature extractors.
*/
public void registerAllFeatureExtractors()
throws FeatureExtractorException {
/** TODO: This approach needs to be rethought. As AuToBI's capabilities are increased, this function grows, and the
* size of the "default" feature registry increases.
*
* There are two approaches that seem possible:
* 1. Move this functionality to a config file. Only those feature extractors that are in the config file are
* constructed and registered. However, this won't help the issue of a cumbersome feature registry.
*
* 2. On-demand feature registry propagation. The idea here would be that you would need to know which
* features can be extracted from which feature extractor. But this information can be stored in a config file.
* Rather than constructing objects for every possible feature extractor, at extraction time, read the mapping of
* feature names and FeatureExtractor object names (and parameters). "Register" each of those feature extractors
* that are needed -- and recurse up the required features dependency graph. The run feature extraction as usual.
*
* This will keep the registry small, though there is more overhead when you read the config file. The other issue
* is how is config file gets propagated. Can it be done automatically? or does the author of a new feature extractor
* need to write it manually? Or one better, can we scan the featureextractor contents in memory? This last step is
* a reach goal and will need to be a part of the next version. I believe that it will require a more precise templating
* of derived feature names. This will require re-writing a lot of the feature extractors. While worth it, this
* will take some person hours. Possibly a good
*/
registerNullFeatureExtractor("wav");
String[] acoustic_features = new String[]{"f0", "log_f0", "I"};
registerFeatureExtractor(new PitchAccentFeatureExtractor("nominal_PitchAccent"));
registerFeatureExtractor(new PitchAccentTypeFeatureExtractor("nominal_PitchAccentType"));
registerFeatureExtractor(new PhraseAccentFeatureExtractor("nominal_PhraseAccentType"));
registerFeatureExtractor(new PhraseAccentBoundaryToneFeatureExtractor("nominal_PhraseAccentBoundaryTone"));
registerFeatureExtractor(new IntonationalPhraseBoundaryFeatureExtractor("nominal_IntonationalPhraseBoundary"));
registerFeatureExtractor(new IntermediatePhraseBoundaryFeatureExtractor("nominal_IntermediatePhraseBoundary"));
registerFeatureExtractor(new PitchFeatureExtractor("f0"));
registerFeatureExtractor(new LogContourFeatureExtractor("f0", "log_f0"));
registerFeatureExtractor(new IntensityFeatureExtractor("I"));
if (hasParameter("normalization_parameters")) {
String known_speaker = null;
if (getBooleanParameter("known_speaker", false)) {
known_speaker = "speaker_id";
}
try {
registerFeatureExtractor(new SNPAssignmentFeatureExtractor("normalization_parameters", known_speaker,
AuToBIUtils.glob(getOptionalParameter("normalization_parameters"))));
} catch (AuToBIException e) {
AuToBIUtils.error(e.getMessage());
}
} else {
registerFeatureExtractor(new NormalizationParameterFeatureExtractor("normalization_parameters"));
}
for (String acoustic : acoustic_features) {
registerFeatureExtractor(new NormalizedContourFeatureExtractor(acoustic, "normalization_parameters"));
}
// Register Subregion feature extractors
registerFeatureExtractor(new PseudosyllableFeatureExtractor("pseudosyllable"));
registerFeatureExtractor(new SubregionFeatureExtractor("200ms"));
// Register Delta Contour Extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
registerFeatureExtractor(new DeltaContourFeatureExtractor(norm + acoustic));
}
}
// Register subregion contour extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String subregion : new String[]{"pseudosyllable", "200ms"}) {
registerFeatureExtractor(new SubregionContourExtractor(slope + norm + acoustic, subregion));
}
}
}
}
// Register Contour Feature Extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String subregion : new String[]{"", "_pseudosyllable", "_200ms"}) {
registerFeatureExtractor(new ContourFeatureExtractor(slope + norm + acoustic + subregion));
}
}
}
}
registerFeatureExtractor(new SpectrumFeatureExtractor("spectrum"));
for (int low = 0; low <= 19; ++low) {
for (int high = low + 1; high <= 20; ++high) {
registerFeatureExtractor(new SpectralTiltFeatureExtractor("bark_tilt", "spectrum", low, high));
registerFeatureExtractor(new SpectrumBandFeatureExtractor("bark", "spectrum", low, high));
}
}
registerFeatureExtractor(new DurationFeatureExtractor());
////////////////////
// Reset Features //
////////////////////
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", null));
registerFeatureExtractor(new SubregionResetFeatureExtractor("200ms"));
registerFeatureExtractor(new SubregionResetFeatureExtractor("400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", "400ms"));
// Difference Features
List<String> difference_features = new ArrayList<String>();
difference_features.add("duration__duration");
for (String acoustic : new String[]{"f0", "log_f0", "I"}) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String agg : new String[]{"max", "mean", "stdev", "zMax"}) {
difference_features.add(slope + norm + acoustic + "__" + agg);
}
}
}
}
registerFeatureExtractor(new DifferenceFeatureExtractor(difference_features));
// Feature Extractors developed based on Mishra et al. INTERSPEECH 2012 and Rosenberg SLT 2012
registerFeatureExtractor(new AUContourFeatureExtractor("log_f0"));
registerFeatureExtractor(new AUContourFeatureExtractor("I"));
try {
registerFeatureExtractor(new SubregionFeatureExtractor("400ms"));
} catch (FeatureExtractorException e) {
e.printStackTrace();
}
difference_features = new ArrayList<String>();
for (String c : new String[]{"rnorm_I", "norm_log_f0", "norm_log_f0rnorm_I"}) {
for (String delta : new String[]{"delta_", ""}) {
if (!c.equals("norm_log_f0")) {
for (String subregion : new String[]{"pseudosyllable", "200ms", "400ms"}) {
registerFeatureExtractor(new SubregionContourExtractor(delta + c, subregion));
- registerFeatureExtractor(new ContourFeatureExtractor(delta + c + subregion));
+ registerFeatureExtractor(new ContourFeatureExtractor(delta + c + "_" + subregion));
}
}
for (String subregion : new String[]{"", "_pseudosyllable", "_200ms", "_400ms"}) {
registerFeatureExtractor(new PVALFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new CurveShapeFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new CurveShapeLikelihoodFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new HighLowComponentFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new HighLowDifferenceFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new ContourCenterOfGravityFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new AUContourFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new TiltFeatureExtractor(delta + c + subregion));
}
if (!c.equals("norm_log_f0")) {
for (String agg : new String[]{"max", "mean", "stdev", "zMax"}) {
difference_features.add(delta + c + "__" + agg);
}
}
}
}
registerFeatureExtractor(new DifferenceFeatureExtractor(difference_features));
registerFeatureExtractor(new VoicingRatioFeatureExtractor("log_f0"));
// Range normalization for I
registerFeatureExtractor(new RangeNormalizedContourFeatureExtractor("I", "normalization_parameters"));
// Combined contour
registerFeatureExtractor(new CombinedContourFeatureExtractor("norm_log_f0", "rnorm_I", 1));
registerFeatureExtractor(new DeltaContourFeatureExtractor("norm_log_f0rnorm_I"));
registerFeatureExtractor(new DeltaContourFeatureExtractor("rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("delta_rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("norm_log_f0rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("delta_norm_log_f0rnorm_I"));
// Skew
registerFeatureExtractor(new SkewFeatureExtractor("norm_log_f0", "rnorm_I"));
registerFeatureExtractor(new RatioFeatureExtractor("norm_log_f0__area", "rnorm_I__area"));
registerFeatureExtractor(new FeatureDifferenceFeatureExtractor("norm_log_f0__area", "rnorm_I__area"));
// Contour peak
registerFeatureExtractor(new RatioFeatureExtractor("norm_log_f0__PVLocation", "rnorm_I__PVLocation"));
registerFeatureExtractor(
new FeatureDifferenceFeatureExtractor("norm_log_f0__PVLocation", "rnorm_I__PVLocation"));
// Contour RMSE and Contour Error
registerFeatureExtractor(new ContourDifferenceFeatureExtractor("norm_log_f0", "rnorm_I"));
// Combined curve likelihood
registerFeatureExtractor(new TwoWayCurveLikelihoodShapeFeatureExtractor("norm_log_f0", "rnorm_I"));
}
@Deprecated
private void registerPitchAccentCollectionFeatureExtractors() throws FeatureExtractorException {
try {
String pad_filename = getParameter("spectral_pitch_accent_detector_collection");
PitchAccentDetectionClassifierCollection pacc;
/**
* TODO: this shouldn't happen here. This ensemble classifier should be an AuToBI classifier that is
* loaded from a special case pitch accent detection AuToBITask
*/
// Load PitchAccentDetectionClassifierCollection
FileInputStream fis;
ObjectInputStream in;
fis = new FileInputStream(pad_filename);
in = new ObjectInputStream(fis);
Object o = in.readObject();
if (o instanceof PitchAccentDetectionClassifierCollection) {
pacc = (PitchAccentDetectionClassifierCollection) o;
} else {
throw new FeatureExtractorException(
"Object read from -spectral_pitch_accent_detector_collection=" + pad_filename +
" is not a valid PitchAccentDetectionClassifierCollection");
}
// Register appropriate feature extractors for each classifier in the collection
Integer high_bark = Integer.parseInt(getOptionalParameter("high_bark", "20"));
for (int low = 0; low < high_bark; ++low) {
for (int high = low + 1; high <= high_bark; ++high) {
registerFeatureExtractor(
new SpectrumPADFeatureExtractor(low, high, pacc.getPitchAccentDetector(low, high),
new SpectrumPADFeatureSet(low, high)));
registerFeatureExtractor(
new CorrectionSpectrumPADFeatureExtractor(low, high, pacc.getCorrectionClassifier(low, high),
new CorrectionSpectrumPADFeatureSet(low, high)));
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (AuToBIException e) {
e.printStackTrace();
}
}
/**
* Reads a speaker normalization mapping file.
* <p/>
* The file is a comma separated value text file containing pairs of textgrid filenames and their associated speaker
* norm parameter filenames.
* <p/>
* Note: the filenames must be absolute filenames
*
* @param speaker_normalization_file The speaker normalization file
* @throws IOException If there is a problem reading the file
* @throws AuToBIException If there is a problem with the formatting of the file
*/
public void loadSpeakerNormalizationMapping(String speaker_normalization_file) throws IOException, AuToBIException {
AuToBIFileReader reader = new AuToBIFileReader(speaker_normalization_file);
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 2)
throw new AuToBIException("Malformed speaker normalization mapping file: " + speaker_normalization_file + "(" +
reader.getLineNumber() + ") : " + line);
speaker_norm_file_mapping.put(fields[0].trim(), fields[1].trim());
}
}
/**
* Retrieves a stored speaker normalization parameter filename for a textgrid filename
*
* @param filename The textgrid filename
* @return The associated speaker normalization parameter filename
*/
public String getSpeakerNormParamFilename(String filename) {
return speaker_norm_file_mapping.get(filename);
}
public static void main(String[] args) {
AuToBI autobi = new AuToBI();
autobi.init(args);
autobi.run();
}
public void run() {
try {
if (hasParameter("input_file") && hasParameter("cprom_file")) {
throw new AuToBIException(
"Both -input_file and -cprom_file are entered. Only one input file may be specified.");
}
String wav_filename = getParameter("wav_file");
WavReader reader = new WavReader();
WavData wav = reader.read(wav_filename);
String filename = getOptionalParameter("input_file");
AuToBIWordReader word_reader;
FormattedFile file;
if (hasParameter("input_file")) {
// Let the FormattedFile constructor determine the file based on the extension or other file name conventions
file = new FormattedFile(getOptionalParameter("input_file"));
word_reader = WordReaderUtils.getAppropriateReader(file, getParameters());
} else if (hasParameter("cprom_file")) {
// Since both C-Prom files and other TextGrid files use the ".TextGrid" extension, the user needs to specify cprom files explicitly
file = new FormattedFile(getOptionalParameter("cprom_file"), FormattedFile.Format.CPROM);
word_reader = WordReaderUtils.getAppropriateReader(file, getParameters());
} else {
AuToBIUtils.info(
"No -input_file or -cprom_file filename specified. Generating segmentation based on acoustic pseudosyllabification.");
wav.setFilename(wav_filename);
if (hasParameter("silence_threshold")) {
Double threshold = Double.parseDouble(getParameter("silence_threshold"));
word_reader = new PseudosyllableWordReader(wav, threshold);
} else {
word_reader = new PseudosyllableWordReader(wav);
}
}
AuToBIUtils.log("Reading words from: " + filename);
if (word_reader == null) {
AuToBIUtils.error("Unable to create wordreader for file: " + filename + "\n\tCheck the file extension.");
return;
}
if (hasParameter("silence_regex")) {
word_reader.setSilenceRegex(getParameter("silence_regex"));
}
List<Word> words = word_reader.readWords();
FeatureSet autobi_fs = new FeatureSet();
autobi_fs.setDataPoints(words);
for (Word w : words) {
w.setAttribute("wav", wav);
}
initializeAuToBITasks();
AuToBIUtils.log("Registering Feature Extractors");
registerAllFeatureExtractors();
registerNullFeatureExtractor("speaker_id");
for (AuToBITask task : tasks.values()) {
FeatureSet fs = task.getFeatureSet();
AuToBIClassifier classifier = task.getClassifier();
String hyp_feature = task.getHypFeature();
registerFeatureExtractor(new HypothesizedEventFeatureExtractor(hyp_feature, classifier, fs));
autobi_fs.insertRequiredFeature(hyp_feature);
if (getBooleanParameter("distributions", false)) {
String dist_feature = task.getDistFeature();
registerFeatureExtractor(new HypothesizedDistributionFeatureExtractor(dist_feature, classifier, fs));
autobi_fs.insertRequiredFeature(dist_feature);
}
autobi_fs.insertRequiredFeature(fs.getClassAttribute());
}
extractFeatures(autobi_fs);
autobi_fs.constructFeatures();
for (String task : getClassificationTasks()) {
AuToBIUtils.info(evaluateTaskPerformance(task, autobi_fs));
}
if (hasParameter("out_file")) {
AuToBIUtils.mergeAuToBIHypotheses(words);
String hypothesis_file = getParameter("out_file");
AuToBIUtils.info("Writing hypotheses to " + hypothesis_file);
writeTextGrid(words, hypothesis_file);
}
} catch (AuToBIException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (FeatureExtractorException e) {
e.printStackTrace();
}
}
/**
* Registers a null feature extractor with the registry.
* <p/>
* This implies that the feature will be manually set by the user outside the typical feature extraction process.
* <p/>
* This is used to satisfy feature requirements for feature extractors without writing a feature extractor for the
* requirement. This is often used for features that are assigned by a file reader.
*
* @param s the feature name
*/
public void registerNullFeatureExtractor(String s) {
this.feature_registry.put(s, null);
}
/**
* Gets command line parameters.
*
* @return an AuToBIParameters object
*/
public AuToBIParameters getParameters() {
return params;
}
/**
* Sets AuToBIParameters.
*
* @param params the parameters.
*/
public void setParameters(AuToBIParameters params) {
this.params = params;
}
}
| true | true | public void registerAllFeatureExtractors()
throws FeatureExtractorException {
/** TODO: This approach needs to be rethought. As AuToBI's capabilities are increased, this function grows, and the
* size of the "default" feature registry increases.
*
* There are two approaches that seem possible:
* 1. Move this functionality to a config file. Only those feature extractors that are in the config file are
* constructed and registered. However, this won't help the issue of a cumbersome feature registry.
*
* 2. On-demand feature registry propagation. The idea here would be that you would need to know which
* features can be extracted from which feature extractor. But this information can be stored in a config file.
* Rather than constructing objects for every possible feature extractor, at extraction time, read the mapping of
* feature names and FeatureExtractor object names (and parameters). "Register" each of those feature extractors
* that are needed -- and recurse up the required features dependency graph. The run feature extraction as usual.
*
* This will keep the registry small, though there is more overhead when you read the config file. The other issue
* is how is config file gets propagated. Can it be done automatically? or does the author of a new feature extractor
* need to write it manually? Or one better, can we scan the featureextractor contents in memory? This last step is
* a reach goal and will need to be a part of the next version. I believe that it will require a more precise templating
* of derived feature names. This will require re-writing a lot of the feature extractors. While worth it, this
* will take some person hours. Possibly a good
*/
registerNullFeatureExtractor("wav");
String[] acoustic_features = new String[]{"f0", "log_f0", "I"};
registerFeatureExtractor(new PitchAccentFeatureExtractor("nominal_PitchAccent"));
registerFeatureExtractor(new PitchAccentTypeFeatureExtractor("nominal_PitchAccentType"));
registerFeatureExtractor(new PhraseAccentFeatureExtractor("nominal_PhraseAccentType"));
registerFeatureExtractor(new PhraseAccentBoundaryToneFeatureExtractor("nominal_PhraseAccentBoundaryTone"));
registerFeatureExtractor(new IntonationalPhraseBoundaryFeatureExtractor("nominal_IntonationalPhraseBoundary"));
registerFeatureExtractor(new IntermediatePhraseBoundaryFeatureExtractor("nominal_IntermediatePhraseBoundary"));
registerFeatureExtractor(new PitchFeatureExtractor("f0"));
registerFeatureExtractor(new LogContourFeatureExtractor("f0", "log_f0"));
registerFeatureExtractor(new IntensityFeatureExtractor("I"));
if (hasParameter("normalization_parameters")) {
String known_speaker = null;
if (getBooleanParameter("known_speaker", false)) {
known_speaker = "speaker_id";
}
try {
registerFeatureExtractor(new SNPAssignmentFeatureExtractor("normalization_parameters", known_speaker,
AuToBIUtils.glob(getOptionalParameter("normalization_parameters"))));
} catch (AuToBIException e) {
AuToBIUtils.error(e.getMessage());
}
} else {
registerFeatureExtractor(new NormalizationParameterFeatureExtractor("normalization_parameters"));
}
for (String acoustic : acoustic_features) {
registerFeatureExtractor(new NormalizedContourFeatureExtractor(acoustic, "normalization_parameters"));
}
// Register Subregion feature extractors
registerFeatureExtractor(new PseudosyllableFeatureExtractor("pseudosyllable"));
registerFeatureExtractor(new SubregionFeatureExtractor("200ms"));
// Register Delta Contour Extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
registerFeatureExtractor(new DeltaContourFeatureExtractor(norm + acoustic));
}
}
// Register subregion contour extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String subregion : new String[]{"pseudosyllable", "200ms"}) {
registerFeatureExtractor(new SubregionContourExtractor(slope + norm + acoustic, subregion));
}
}
}
}
// Register Contour Feature Extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String subregion : new String[]{"", "_pseudosyllable", "_200ms"}) {
registerFeatureExtractor(new ContourFeatureExtractor(slope + norm + acoustic + subregion));
}
}
}
}
registerFeatureExtractor(new SpectrumFeatureExtractor("spectrum"));
for (int low = 0; low <= 19; ++low) {
for (int high = low + 1; high <= 20; ++high) {
registerFeatureExtractor(new SpectralTiltFeatureExtractor("bark_tilt", "spectrum", low, high));
registerFeatureExtractor(new SpectrumBandFeatureExtractor("bark", "spectrum", low, high));
}
}
registerFeatureExtractor(new DurationFeatureExtractor());
////////////////////
// Reset Features //
////////////////////
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", null));
registerFeatureExtractor(new SubregionResetFeatureExtractor("200ms"));
registerFeatureExtractor(new SubregionResetFeatureExtractor("400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", "400ms"));
// Difference Features
List<String> difference_features = new ArrayList<String>();
difference_features.add("duration__duration");
for (String acoustic : new String[]{"f0", "log_f0", "I"}) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String agg : new String[]{"max", "mean", "stdev", "zMax"}) {
difference_features.add(slope + norm + acoustic + "__" + agg);
}
}
}
}
registerFeatureExtractor(new DifferenceFeatureExtractor(difference_features));
// Feature Extractors developed based on Mishra et al. INTERSPEECH 2012 and Rosenberg SLT 2012
registerFeatureExtractor(new AUContourFeatureExtractor("log_f0"));
registerFeatureExtractor(new AUContourFeatureExtractor("I"));
try {
registerFeatureExtractor(new SubregionFeatureExtractor("400ms"));
} catch (FeatureExtractorException e) {
e.printStackTrace();
}
difference_features = new ArrayList<String>();
for (String c : new String[]{"rnorm_I", "norm_log_f0", "norm_log_f0rnorm_I"}) {
for (String delta : new String[]{"delta_", ""}) {
if (!c.equals("norm_log_f0")) {
for (String subregion : new String[]{"pseudosyllable", "200ms", "400ms"}) {
registerFeatureExtractor(new SubregionContourExtractor(delta + c, subregion));
registerFeatureExtractor(new ContourFeatureExtractor(delta + c + subregion));
}
}
for (String subregion : new String[]{"", "_pseudosyllable", "_200ms", "_400ms"}) {
registerFeatureExtractor(new PVALFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new CurveShapeFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new CurveShapeLikelihoodFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new HighLowComponentFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new HighLowDifferenceFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new ContourCenterOfGravityFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new AUContourFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new TiltFeatureExtractor(delta + c + subregion));
}
if (!c.equals("norm_log_f0")) {
for (String agg : new String[]{"max", "mean", "stdev", "zMax"}) {
difference_features.add(delta + c + "__" + agg);
}
}
}
}
registerFeatureExtractor(new DifferenceFeatureExtractor(difference_features));
registerFeatureExtractor(new VoicingRatioFeatureExtractor("log_f0"));
// Range normalization for I
registerFeatureExtractor(new RangeNormalizedContourFeatureExtractor("I", "normalization_parameters"));
// Combined contour
registerFeatureExtractor(new CombinedContourFeatureExtractor("norm_log_f0", "rnorm_I", 1));
registerFeatureExtractor(new DeltaContourFeatureExtractor("norm_log_f0rnorm_I"));
registerFeatureExtractor(new DeltaContourFeatureExtractor("rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("delta_rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("norm_log_f0rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("delta_norm_log_f0rnorm_I"));
// Skew
registerFeatureExtractor(new SkewFeatureExtractor("norm_log_f0", "rnorm_I"));
registerFeatureExtractor(new RatioFeatureExtractor("norm_log_f0__area", "rnorm_I__area"));
registerFeatureExtractor(new FeatureDifferenceFeatureExtractor("norm_log_f0__area", "rnorm_I__area"));
// Contour peak
registerFeatureExtractor(new RatioFeatureExtractor("norm_log_f0__PVLocation", "rnorm_I__PVLocation"));
registerFeatureExtractor(
new FeatureDifferenceFeatureExtractor("norm_log_f0__PVLocation", "rnorm_I__PVLocation"));
// Contour RMSE and Contour Error
registerFeatureExtractor(new ContourDifferenceFeatureExtractor("norm_log_f0", "rnorm_I"));
// Combined curve likelihood
registerFeatureExtractor(new TwoWayCurveLikelihoodShapeFeatureExtractor("norm_log_f0", "rnorm_I"));
}
| public void registerAllFeatureExtractors()
throws FeatureExtractorException {
/** TODO: This approach needs to be rethought. As AuToBI's capabilities are increased, this function grows, and the
* size of the "default" feature registry increases.
*
* There are two approaches that seem possible:
* 1. Move this functionality to a config file. Only those feature extractors that are in the config file are
* constructed and registered. However, this won't help the issue of a cumbersome feature registry.
*
* 2. On-demand feature registry propagation. The idea here would be that you would need to know which
* features can be extracted from which feature extractor. But this information can be stored in a config file.
* Rather than constructing objects for every possible feature extractor, at extraction time, read the mapping of
* feature names and FeatureExtractor object names (and parameters). "Register" each of those feature extractors
* that are needed -- and recurse up the required features dependency graph. The run feature extraction as usual.
*
* This will keep the registry small, though there is more overhead when you read the config file. The other issue
* is how is config file gets propagated. Can it be done automatically? or does the author of a new feature extractor
* need to write it manually? Or one better, can we scan the featureextractor contents in memory? This last step is
* a reach goal and will need to be a part of the next version. I believe that it will require a more precise templating
* of derived feature names. This will require re-writing a lot of the feature extractors. While worth it, this
* will take some person hours. Possibly a good
*/
registerNullFeatureExtractor("wav");
String[] acoustic_features = new String[]{"f0", "log_f0", "I"};
registerFeatureExtractor(new PitchAccentFeatureExtractor("nominal_PitchAccent"));
registerFeatureExtractor(new PitchAccentTypeFeatureExtractor("nominal_PitchAccentType"));
registerFeatureExtractor(new PhraseAccentFeatureExtractor("nominal_PhraseAccentType"));
registerFeatureExtractor(new PhraseAccentBoundaryToneFeatureExtractor("nominal_PhraseAccentBoundaryTone"));
registerFeatureExtractor(new IntonationalPhraseBoundaryFeatureExtractor("nominal_IntonationalPhraseBoundary"));
registerFeatureExtractor(new IntermediatePhraseBoundaryFeatureExtractor("nominal_IntermediatePhraseBoundary"));
registerFeatureExtractor(new PitchFeatureExtractor("f0"));
registerFeatureExtractor(new LogContourFeatureExtractor("f0", "log_f0"));
registerFeatureExtractor(new IntensityFeatureExtractor("I"));
if (hasParameter("normalization_parameters")) {
String known_speaker = null;
if (getBooleanParameter("known_speaker", false)) {
known_speaker = "speaker_id";
}
try {
registerFeatureExtractor(new SNPAssignmentFeatureExtractor("normalization_parameters", known_speaker,
AuToBIUtils.glob(getOptionalParameter("normalization_parameters"))));
} catch (AuToBIException e) {
AuToBIUtils.error(e.getMessage());
}
} else {
registerFeatureExtractor(new NormalizationParameterFeatureExtractor("normalization_parameters"));
}
for (String acoustic : acoustic_features) {
registerFeatureExtractor(new NormalizedContourFeatureExtractor(acoustic, "normalization_parameters"));
}
// Register Subregion feature extractors
registerFeatureExtractor(new PseudosyllableFeatureExtractor("pseudosyllable"));
registerFeatureExtractor(new SubregionFeatureExtractor("200ms"));
// Register Delta Contour Extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
registerFeatureExtractor(new DeltaContourFeatureExtractor(norm + acoustic));
}
}
// Register subregion contour extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String subregion : new String[]{"pseudosyllable", "200ms"}) {
registerFeatureExtractor(new SubregionContourExtractor(slope + norm + acoustic, subregion));
}
}
}
}
// Register Contour Feature Extractors
for (String acoustic : acoustic_features) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String subregion : new String[]{"", "_pseudosyllable", "_200ms"}) {
registerFeatureExtractor(new ContourFeatureExtractor(slope + norm + acoustic + subregion));
}
}
}
}
registerFeatureExtractor(new SpectrumFeatureExtractor("spectrum"));
for (int low = 0; low <= 19; ++low) {
for (int high = low + 1; high <= 20; ++high) {
registerFeatureExtractor(new SpectralTiltFeatureExtractor("bark_tilt", "spectrum", low, high));
registerFeatureExtractor(new SpectrumBandFeatureExtractor("bark", "spectrum", low, high));
}
}
registerFeatureExtractor(new DurationFeatureExtractor());
////////////////////
// Reset Features //
////////////////////
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", null));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", null));
registerFeatureExtractor(new SubregionResetFeatureExtractor("200ms"));
registerFeatureExtractor(new SubregionResetFeatureExtractor("400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", "200ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("log_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("I", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_log_f0", "400ms"));
registerFeatureExtractor(new ResetContourFeatureExtractor("norm_I", "400ms"));
// Difference Features
List<String> difference_features = new ArrayList<String>();
difference_features.add("duration__duration");
for (String acoustic : new String[]{"f0", "log_f0", "I"}) {
for (String norm : new String[]{"", "norm_"}) {
for (String slope : new String[]{"", "delta_"}) {
for (String agg : new String[]{"max", "mean", "stdev", "zMax"}) {
difference_features.add(slope + norm + acoustic + "__" + agg);
}
}
}
}
registerFeatureExtractor(new DifferenceFeatureExtractor(difference_features));
// Feature Extractors developed based on Mishra et al. INTERSPEECH 2012 and Rosenberg SLT 2012
registerFeatureExtractor(new AUContourFeatureExtractor("log_f0"));
registerFeatureExtractor(new AUContourFeatureExtractor("I"));
try {
registerFeatureExtractor(new SubregionFeatureExtractor("400ms"));
} catch (FeatureExtractorException e) {
e.printStackTrace();
}
difference_features = new ArrayList<String>();
for (String c : new String[]{"rnorm_I", "norm_log_f0", "norm_log_f0rnorm_I"}) {
for (String delta : new String[]{"delta_", ""}) {
if (!c.equals("norm_log_f0")) {
for (String subregion : new String[]{"pseudosyllable", "200ms", "400ms"}) {
registerFeatureExtractor(new SubregionContourExtractor(delta + c, subregion));
registerFeatureExtractor(new ContourFeatureExtractor(delta + c + "_" + subregion));
}
}
for (String subregion : new String[]{"", "_pseudosyllable", "_200ms", "_400ms"}) {
registerFeatureExtractor(new PVALFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new CurveShapeFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new CurveShapeLikelihoodFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new HighLowComponentFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new HighLowDifferenceFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new ContourCenterOfGravityFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new AUContourFeatureExtractor(delta + c + subregion));
registerFeatureExtractor(new TiltFeatureExtractor(delta + c + subregion));
}
if (!c.equals("norm_log_f0")) {
for (String agg : new String[]{"max", "mean", "stdev", "zMax"}) {
difference_features.add(delta + c + "__" + agg);
}
}
}
}
registerFeatureExtractor(new DifferenceFeatureExtractor(difference_features));
registerFeatureExtractor(new VoicingRatioFeatureExtractor("log_f0"));
// Range normalization for I
registerFeatureExtractor(new RangeNormalizedContourFeatureExtractor("I", "normalization_parameters"));
// Combined contour
registerFeatureExtractor(new CombinedContourFeatureExtractor("norm_log_f0", "rnorm_I", 1));
registerFeatureExtractor(new DeltaContourFeatureExtractor("norm_log_f0rnorm_I"));
registerFeatureExtractor(new DeltaContourFeatureExtractor("rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("delta_rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("norm_log_f0rnorm_I"));
registerFeatureExtractor(new ContourFeatureExtractor("delta_norm_log_f0rnorm_I"));
// Skew
registerFeatureExtractor(new SkewFeatureExtractor("norm_log_f0", "rnorm_I"));
registerFeatureExtractor(new RatioFeatureExtractor("norm_log_f0__area", "rnorm_I__area"));
registerFeatureExtractor(new FeatureDifferenceFeatureExtractor("norm_log_f0__area", "rnorm_I__area"));
// Contour peak
registerFeatureExtractor(new RatioFeatureExtractor("norm_log_f0__PVLocation", "rnorm_I__PVLocation"));
registerFeatureExtractor(
new FeatureDifferenceFeatureExtractor("norm_log_f0__PVLocation", "rnorm_I__PVLocation"));
// Contour RMSE and Contour Error
registerFeatureExtractor(new ContourDifferenceFeatureExtractor("norm_log_f0", "rnorm_I"));
// Combined curve likelihood
registerFeatureExtractor(new TwoWayCurveLikelihoodShapeFeatureExtractor("norm_log_f0", "rnorm_I"));
}
|
diff --git a/src/test/java/com/ritchey/chapelManage/domain/LcuchapelPunchTest.java b/src/test/java/com/ritchey/chapelManage/domain/LcuchapelPunchTest.java
index 52e9afe..3a678ca 100644
--- a/src/test/java/com/ritchey/chapelManage/domain/LcuchapelPunchTest.java
+++ b/src/test/java/com/ritchey/chapelManage/domain/LcuchapelPunchTest.java
@@ -1,72 +1,73 @@
package com.ritchey.chapelManage.domain;
import static org.junit.Assert.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ritchey.chapelManage.mapper.chapel.PunchMapper;
import com.ritchey.chapelManage.mapper.powercampus.AcademicCalendarMapper;
@Configurable
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/META-INF/spring/applicationContext.xml",
"classpath:/META-INF/spring/applicationContext-security.xml"})
public class LcuchapelPunchTest implements BeanFactoryAware {
private static Log log = LogFactory.getLog(LcuchapelPunchTest.class);
ConfigurableListableBeanFactory bf = null;
@Test
public void testMarkerMethod() {
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
bf = (ConfigurableListableBeanFactory) beanFactory;
}
@Test
public void testFindTerms() {
AcademicCalendarMapper p = (AcademicCalendarMapper) bf.getBean("academicCalendarMapper");
}
@Test
public void testMasterDetailCountAttendance() throws ParseException {
PunchMapper punchMapper = (PunchMapper) bf.getBean("punchMapper");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//(ChapelPunchServiceImpl.java:255) - select punched Events date = null id = null scheduleOnly = false
//select punched Events2 startday = Mon Aug 26 00:00:00 CDT 2013 date = null id = null scheduleOnly = false
RowBounds r = new RowBounds(0, 10);
Date startday = fmt.parse("2013-08-26 00:00:00");// Start of the term
Date date = null;
Integer id = null;
Boolean scheduleOnly = false;
Boolean punchesOnly = false;
List<Map> list = punchMapper.selectPunchedEvents(startday, date, id,scheduleOnly, punchesOnly, r);
System.err.println("master list 1st element = " + list.get(0));
Integer schedId = (Integer) list.get(0).get("id");
- List<Map> history = punchMapper.selectChapelHistory(null, null, null, null, schedId, true, new RowBounds(0, 10));
+ List<Map> history = punchMapper.selectChapelHistory(null, null, null, null, schedId, true, new RowBounds(0, ((Integer)list.get(0).get("total"))+10));
System.err.println("detail list size = " + history.size());
+ System.err.println("total list size = " + list.get(0).get("total"));
assertTrue(list.get(0).get("total").equals(history.size()));
}
}
| false | true | public void testMasterDetailCountAttendance() throws ParseException {
PunchMapper punchMapper = (PunchMapper) bf.getBean("punchMapper");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//(ChapelPunchServiceImpl.java:255) - select punched Events date = null id = null scheduleOnly = false
//select punched Events2 startday = Mon Aug 26 00:00:00 CDT 2013 date = null id = null scheduleOnly = false
RowBounds r = new RowBounds(0, 10);
Date startday = fmt.parse("2013-08-26 00:00:00");// Start of the term
Date date = null;
Integer id = null;
Boolean scheduleOnly = false;
Boolean punchesOnly = false;
List<Map> list = punchMapper.selectPunchedEvents(startday, date, id,scheduleOnly, punchesOnly, r);
System.err.println("master list 1st element = " + list.get(0));
Integer schedId = (Integer) list.get(0).get("id");
List<Map> history = punchMapper.selectChapelHistory(null, null, null, null, schedId, true, new RowBounds(0, 10));
System.err.println("detail list size = " + history.size());
assertTrue(list.get(0).get("total").equals(history.size()));
}
| public void testMasterDetailCountAttendance() throws ParseException {
PunchMapper punchMapper = (PunchMapper) bf.getBean("punchMapper");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//(ChapelPunchServiceImpl.java:255) - select punched Events date = null id = null scheduleOnly = false
//select punched Events2 startday = Mon Aug 26 00:00:00 CDT 2013 date = null id = null scheduleOnly = false
RowBounds r = new RowBounds(0, 10);
Date startday = fmt.parse("2013-08-26 00:00:00");// Start of the term
Date date = null;
Integer id = null;
Boolean scheduleOnly = false;
Boolean punchesOnly = false;
List<Map> list = punchMapper.selectPunchedEvents(startday, date, id,scheduleOnly, punchesOnly, r);
System.err.println("master list 1st element = " + list.get(0));
Integer schedId = (Integer) list.get(0).get("id");
List<Map> history = punchMapper.selectChapelHistory(null, null, null, null, schedId, true, new RowBounds(0, ((Integer)list.get(0).get("total"))+10));
System.err.println("detail list size = " + history.size());
System.err.println("total list size = " + list.get(0).get("total"));
assertTrue(list.get(0).get("total").equals(history.size()));
}
|
diff --git a/src/java/com/idega/block/image/presentation/ImageGallery.java b/src/java/com/idega/block/image/presentation/ImageGallery.java
index 1f3a9e7..518a3cf 100644
--- a/src/java/com/idega/block/image/presentation/ImageGallery.java
+++ b/src/java/com/idega/block/image/presentation/ImageGallery.java
@@ -1,489 +1,489 @@
package com.idega.block.image.presentation;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.idega.block.image.business.ImageProvider;
import com.idega.block.web2.business.Web2Business;
import com.idega.business.IBOLookup;
import com.idega.business.SpringBeanLookup;
import com.idega.core.builder.data.ICPage;
import com.idega.core.idgenerator.business.UUIDGenerator;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.Layer;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Paragraph;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.SubmitButton;
import com.idega.util.PresentationUtil;
/**
*
* Title: idegaWeb Description: ImageGallery is a block to show images that are
* stored in a specified folder. A subset of these images is shown at a time.
* The sample can be changed by clicking on a forward and a back button. If
* there are more than one ImageGallery on a single page each gallery works
* independently of the others.
*
* Copyright: Copyright (c) 2003 Company: idega software
*
* @author <a href="mailto:[email protected]">Eirikur S. Hrafnsson</a>
* @version 2.0
*/
public class ImageGallery extends Block {
public static final String STYLE_CLASS_GALLERY_IMAGE_TITLE = "galleryImageTitle";
public static final String STYLE_CLASS_LAST_IN_ROW = "lastInRow";
public static final String STYLE_CLASS_FIRST_IN_ROW = "firstInRow";
private static final String STYLE_CLASS_GALLERY_BUTTONS = "galleryButtons";
// slide path to resource folder
private String resourceFilePath = null;
// enlarge image to specified height and width
private boolean enlargeImage = false;
// height of the images
private int heightOfImages = -1;
// width of the images
private int widthOfImages = -1;
// show image in a special popup window
// show name of image in table
private boolean showNameOfImage = false;
// number of new images that is shown per step
private int numberOfImagesPerStep = 0;
// flag to show if the image should keep its proportion
private boolean scaleProportional = true;
private String heightOfGallery = null;
private String widthOfGallery = null;
private int rows = 1;
private int columns = 1;
// corresponding bundle
private static final String IW_BUNDLE_IDENTIFIER = "com.idega.block.image";
// string forward button
private static final String STRING_FORWARD_BUTTON = ">";
// string back button
private static final String STRING_BACK_BUTTON = "<";
public static final int BUTTON_POSITON_BOTTOM = 0;
public static final int BUTTON_POSITON_TOP = 1;
private int _posButton = BUTTON_POSITON_BOTTOM;
private String styleClassName = "imageGallery";
private String imageStyleClassName = "galleryImage";
// deprecated stuff
// border of all images
private int paddingOfImage = 0;
private boolean showButtons = true;
private int totalCountOfImages = -1;
// end of deprecated stuff
public ImageGallery() {
}
public String getBundleIdentifier() {
return ImageGallery.IW_BUNDLE_IDENTIFIER;
}
public void setFolderResourcePath(String resourcePath) {
this.resourceFilePath = resourcePath;
}
public void setHeightOfImages(int heightOfImages) {
this.heightOfImages = heightOfImages;
}
public void setWidthOfImages(int widthOfImages) {
this.widthOfImages = widthOfImages;
}
public void setEnlargeImage(boolean enlargeImage) {
this.enlargeImage = enlargeImage;
}
/**
*
* @param viewerPage
* @deprecated does nothing since image gallery uses slimbox (lightbox)
*/
public void setViewerPage(ICPage viewerPage) {
}
public void setScaleProportional(boolean scaleProportional) {
this.scaleProportional = scaleProportional;
}
/**
* @deprecated use useNumberOfImagePerStep
* @param rows
*/
public void setRows(int rows) {
if (rows > 0) {
this.rows = rows;
}
}
/**
* @deprecated use useNumberOfImagePerStep
* @param columns
*/
public void setColumns(int columns) {
if (columns > 0) {
this.columns = columns;
}
}
public void setShowNameOfImage(boolean showNameOfImage) {
this.showNameOfImage = showNameOfImage;
}
/**
* @deprecated now uses a lightbox
*/
public void setPopUpOriginalImageOnClick(boolean popUpOriginalImageOnClick) {
//does nothing
}
public void setNumberOfImagesPerStep(int numberOfImagesPerStep) {
this.numberOfImagesPerStep = numberOfImagesPerStep;
}
public int getNumberOfImagesPerStep() {
return this.numberOfImagesPerStep;
}
/**
* @deprecated use CSS style instead (default is galleryImage) , this sets
* padding to each image now via inline style
* @param cellPaddingTable
*/
public void setCellPadding(int cellPaddingTable) {
this.paddingOfImage = cellPaddingTable;
}
public void setStyleClass(String className) {
this.styleClassName = className;
}
public void setImageLayerStyleClass(String className) {
this.imageStyleClassName = className;
}
public void main(IWContext iwc) throws Exception {
Web2Business web2 = SpringBeanLookup.getInstance().getSpringBean(iwc, Web2Business.class);
List<String> scriptsUris = new ArrayList<String>();
scriptsUris.add(web2.getBundleURIToMootoolsLib());
scriptsUris.add(web2.getSlimboxScriptFilePath());
PresentationUtil.addJavaScriptSourcesLinesToHeader(iwc, scriptsUris); // JavaScript
PresentationUtil.addStyleSheetToHeader(iwc, web2.getSlimboxStyleFilePath()); // CSS
Layer imageGalleryLayer = new Layer(Layer.DIV);
imageGalleryLayer.setStyleClass("album-wrapper "+this.styleClassName);
//imageGalleryLayer.setStyleClass(this.styleClassName);
add(imageGalleryLayer);
switch (this._posButton) {
case BUTTON_POSITON_TOP:
if(this.showButtons){
addButtons(iwc, imageGalleryLayer);
}
addImages(iwc, imageGalleryLayer);
break;
default:
addImages(iwc, imageGalleryLayer);
if(this.showButtons){
addButtons(iwc, imageGalleryLayer);
}
break;
}
/* backward compatability */
if (this.heightOfGallery != null) {
imageGalleryLayer.setHeight(this.heightOfGallery);
}
if (this.widthOfGallery != null) {
imageGalleryLayer.setWidth(this.widthOfGallery);
}
/* backward compatability ends */
}
/**
* Adds images and text if needed to the imageGalleryLayer and sets various
* style class too the items
*
* @param iwc
* @param imageGalleryLayer
* @throws Exception
*/
protected void addImages(IWContext iwc, Layer imageGalleryLayer) throws Exception {
ArrayList<AdvancedImage> images = getImages(iwc);
String idOfGallery = this.getId();
Paragraph name = new Paragraph();
name.setStyleClass("thumbnail-caption " + STYLE_CLASS_GALLERY_IMAGE_TITLE);
Layer imageAndText = new Layer(Layer.DIV);
imageAndText.setStyleClass("thumbnail-wrap" +this.imageStyleClassName);
//imageAndText.setStyleClass(this.imageStyleClassName);
Layer imageLayer = new Layer(Layer.DIV);
imageLayer.setStyleClass("thumbnail-frame");
AdvancedImage image;
int count = -1;
Iterator<AdvancedImage> iterator = images.iterator();
int imageNumber = restoreNumberOfFirstImage(iwc);
while (iterator.hasNext()) {
count++;
image = iterator.next();
Layer wrapper = (Layer) imageAndText.clone();
wrapper.setId(UUIDGenerator.getInstance().generateId());
wrapper.setStyleAttribute("width", ""+this.widthOfImages);
if(this.heightOfImages==-1){
//yes height the same on purpose
wrapper.setStyleAttribute("height", ""+this.widthOfImages);
}
imageGalleryLayer.add(wrapper);
// Layer imageAndTitle = (Layer) imageLayer.clone();
// imageAndTitle.setId(UUIDGenerator.getInstance().generateId());
// imageAndTitle.setStyleAttribute("width", ""+this.widthOfImages);
//
// wrapper.add(imageAndTitle);
// todo have a set method
if (this.heightOfImages > 0) {
image.setHeight(this.heightOfImages);
}
if (this.widthOfImages > 0) {
image.setWidth(this.widthOfImages);
}
// set properties of advanced image
image.setEnlargeProperty(this.enlargeImage);
image.setScaleProportional(this.scaleProportional);
//image.setStyleClass("reflect rheight10");
// deprecated backward compatability stuff
if (this.paddingOfImage > 0) {
image.setPadding(this.paddingOfImage);
}
Link link = new Link(image);
String resourceURI = image.getResourceURI();
link.setToolTip(image.getName());
link.setURL(resourceURI);
- link.setMarkupAttribute("rel", "ligthbox["+idOfGallery+"]");
+ link.setMarkupAttribute("rel", "lightbox["+idOfGallery+"]");
imageNumber++;
int xPositionImage = ((count % this.columns) + 1);
// why clone?
//imageAndTitle.add(link);
wrapper.add(link);
// add extra style classes for first and last elements of each row
// for styling purposes
if (xPositionImage == 1) {
wrapper.setStyleClass(STYLE_CLASS_FIRST_IN_ROW);
//imageAndTitle.setStyleClass(STYLE_CLASS_FIRST_IN_ROW);
}
else if (xPositionImage == this.columns) {
wrapper.setStyleClass(STYLE_CLASS_LAST_IN_ROW);
// imageAndTitle.setStyleClass(STYLE_CLASS_LAST_IN_ROW);
}
if (this.showNameOfImage) {
Paragraph theName = (Paragraph) name.clone();
theName.add(image.getName());
// imageAndTitle.add(theName);
wrapper.add(theName);
}
}
}
private SubmitButton createButton(String displayText) {
SubmitButton button = new SubmitButton(Integer.toString(this.getICObjectInstanceID()), displayText);
button.setToEncloseByForm(true);
return button;
}
private void addButtons(IWContext iwc, Layer imageGalleryLayer) throws Exception {
SubmitButton backButton = createButton(STRING_BACK_BUTTON);
SubmitButton forwardButton = createButton(STRING_FORWARD_BUTTON);
Layer buttonsLayer = new Layer(Layer.DIV);
buttonsLayer.setStyleClass(STYLE_CLASS_GALLERY_BUTTONS);
// add everything
imageGalleryLayer.add(buttonsLayer);
int limit = 0;
if (this.resourceFilePath != null) {
limit = getTotalImageCount(iwc);
}
int startPosition = restoreNumberOfFirstImage(iwc);
int endPosition;
int imageSpotsAvailable = getNumberOfImagesPerStep();
if(imageSpotsAvailable==0){
imageSpotsAvailable = limit;
}
StringBuffer infoText = new StringBuffer();
if(limit<=imageSpotsAvailable && startPosition==1){
//all images can be shown if we are at the start and there are more spots available than number of all images
return;
}
if ((endPosition = startPosition + imageSpotsAvailable - 1) >= limit){
endPosition = limit;
}
// special case: If there are not any images do not show start position
// one but zero
int displayedStartPosition = (limit == 0) ? 0 : startPosition;
// create an info text showing the number of the first image and thelast image
// that are currently shown and the total numbers of images:
// for example: 2 - 6 of 9
// show: "2 - 6 of 9"
// special case: Only one image is shown, in this case avoid showing: "2 - 2 of 9"
if (displayedStartPosition != endPosition) {
infoText.append(" ").append(displayedStartPosition).append("-");
}
infoText.append(endPosition).append(" ").append(this.getResourceBundle(iwc).getLocalizedString("of", "of")).append(" ").append(limit);
// possibly disable buttons
if (startPosition == 1){
backButton.setDisabled(true);
}
if (endPosition == limit){
forwardButton.setDisabled(true);
}
buttonsLayer.add(backButton);
buttonsLayer.add(new Text(infoText.toString()));
buttonsLayer.add(forwardButton);
}
protected int getTotalImageCount(IWContext iwc) {
if(totalCountOfImages==-1){
try {
totalCountOfImages = getImageProvider(iwc).getImageCount(this.resourceFilePath);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return totalCountOfImages;
}
private String getParameter(IWContext iwc) throws Exception {
return iwc.getParameter(getObjectInstanceIdentifierString());
}
/**
* Gets a List of AdvancedImage objects
* @param iwc
* @return
* @throws Exception
*/
protected ArrayList<AdvancedImage> getImages(IWContext iwc) throws Exception {
int step = getNumberOfImagesPerStep();
int startPosition = restoreNumberOfFirstImage(iwc);
int newStartPosition;
int limit = 0;
if (this.resourceFilePath != null) {
limit = getTotalImageCount(iwc);
if(step==0){
step = limit;
}
}
String parameterValue = getParameter(iwc);
if (STRING_FORWARD_BUTTON.equals(parameterValue)) {
newStartPosition = startPosition + step;
}
else if (STRING_BACK_BUTTON.equals(parameterValue)) {
newStartPosition = startPosition - step;
}
else {
newStartPosition = startPosition;
}
if (newStartPosition > 0 && newStartPosition <= limit) {
startPosition = newStartPosition;
}
storeNumberOfFirstImage(iwc, startPosition);
return getImagesFromTo(iwc, startPosition, startPosition + step - 1);
}
protected ArrayList<AdvancedImage> getImagesFromTo(IWContext iwc, int startPosition, int endPosition) throws RemoteException {
//todo optimize calls to imageprovider, this is almost the same as before
return getImageProvider(iwc).getImagesFromTo(this.resourceFilePath, startPosition, endPosition);
}
private void storeNumberOfFirstImage(IWContext iwc, int firstImageNumber) {
iwc.setSessionAttribute(getObjectInstanceIdentifierString(), new Integer(firstImageNumber));
}
private int restoreNumberOfFirstImage(IWContext iwc) {
Integer i = (Integer) iwc.getSessionAttribute(getObjectInstanceIdentifierString());
if (i == null) {
return 1;
}
return i.intValue();
}
private String getObjectInstanceIdentifierString() {
return Integer.toString(this.getICObjectInstanceID());
}
protected ImageProvider getImageProvider(IWContext iwc) throws RemoteException {
return (ImageProvider) IBOLookup.getServiceInstance(iwc, ImageProvider.class);
}
public void setToShowButtons(boolean showButtons){
this.showButtons = showButtons;
}
/**
* @return
*/
public int getButtonPosition() {
return this._posButton;
}
/**
* @param posConst,
* one of the BOTTON_POSITION_... constants
*/
public void setButtonPosition(int posConst) {
this._posButton = posConst;
}
/**
* @param height
* @deprecated use CSS styles instead
*/
public void setHeightOfGallery(String height) {
this.heightOfGallery = height;
}
/**
* @param width
* @deprecated use CSS styles instead
*/
public void setWidthOfGallery(String width) {
this.widthOfGallery = width;
}
}
| true | true | protected void addImages(IWContext iwc, Layer imageGalleryLayer) throws Exception {
ArrayList<AdvancedImage> images = getImages(iwc);
String idOfGallery = this.getId();
Paragraph name = new Paragraph();
name.setStyleClass("thumbnail-caption " + STYLE_CLASS_GALLERY_IMAGE_TITLE);
Layer imageAndText = new Layer(Layer.DIV);
imageAndText.setStyleClass("thumbnail-wrap" +this.imageStyleClassName);
//imageAndText.setStyleClass(this.imageStyleClassName);
Layer imageLayer = new Layer(Layer.DIV);
imageLayer.setStyleClass("thumbnail-frame");
AdvancedImage image;
int count = -1;
Iterator<AdvancedImage> iterator = images.iterator();
int imageNumber = restoreNumberOfFirstImage(iwc);
while (iterator.hasNext()) {
count++;
image = iterator.next();
Layer wrapper = (Layer) imageAndText.clone();
wrapper.setId(UUIDGenerator.getInstance().generateId());
wrapper.setStyleAttribute("width", ""+this.widthOfImages);
if(this.heightOfImages==-1){
//yes height the same on purpose
wrapper.setStyleAttribute("height", ""+this.widthOfImages);
}
imageGalleryLayer.add(wrapper);
// Layer imageAndTitle = (Layer) imageLayer.clone();
// imageAndTitle.setId(UUIDGenerator.getInstance().generateId());
// imageAndTitle.setStyleAttribute("width", ""+this.widthOfImages);
//
// wrapper.add(imageAndTitle);
// todo have a set method
if (this.heightOfImages > 0) {
image.setHeight(this.heightOfImages);
}
if (this.widthOfImages > 0) {
image.setWidth(this.widthOfImages);
}
// set properties of advanced image
image.setEnlargeProperty(this.enlargeImage);
image.setScaleProportional(this.scaleProportional);
//image.setStyleClass("reflect rheight10");
// deprecated backward compatability stuff
if (this.paddingOfImage > 0) {
image.setPadding(this.paddingOfImage);
}
Link link = new Link(image);
String resourceURI = image.getResourceURI();
link.setToolTip(image.getName());
link.setURL(resourceURI);
link.setMarkupAttribute("rel", "ligthbox["+idOfGallery+"]");
imageNumber++;
int xPositionImage = ((count % this.columns) + 1);
// why clone?
//imageAndTitle.add(link);
wrapper.add(link);
// add extra style classes for first and last elements of each row
// for styling purposes
if (xPositionImage == 1) {
wrapper.setStyleClass(STYLE_CLASS_FIRST_IN_ROW);
//imageAndTitle.setStyleClass(STYLE_CLASS_FIRST_IN_ROW);
}
else if (xPositionImage == this.columns) {
wrapper.setStyleClass(STYLE_CLASS_LAST_IN_ROW);
// imageAndTitle.setStyleClass(STYLE_CLASS_LAST_IN_ROW);
}
if (this.showNameOfImage) {
Paragraph theName = (Paragraph) name.clone();
theName.add(image.getName());
// imageAndTitle.add(theName);
wrapper.add(theName);
}
}
}
| protected void addImages(IWContext iwc, Layer imageGalleryLayer) throws Exception {
ArrayList<AdvancedImage> images = getImages(iwc);
String idOfGallery = this.getId();
Paragraph name = new Paragraph();
name.setStyleClass("thumbnail-caption " + STYLE_CLASS_GALLERY_IMAGE_TITLE);
Layer imageAndText = new Layer(Layer.DIV);
imageAndText.setStyleClass("thumbnail-wrap" +this.imageStyleClassName);
//imageAndText.setStyleClass(this.imageStyleClassName);
Layer imageLayer = new Layer(Layer.DIV);
imageLayer.setStyleClass("thumbnail-frame");
AdvancedImage image;
int count = -1;
Iterator<AdvancedImage> iterator = images.iterator();
int imageNumber = restoreNumberOfFirstImage(iwc);
while (iterator.hasNext()) {
count++;
image = iterator.next();
Layer wrapper = (Layer) imageAndText.clone();
wrapper.setId(UUIDGenerator.getInstance().generateId());
wrapper.setStyleAttribute("width", ""+this.widthOfImages);
if(this.heightOfImages==-1){
//yes height the same on purpose
wrapper.setStyleAttribute("height", ""+this.widthOfImages);
}
imageGalleryLayer.add(wrapper);
// Layer imageAndTitle = (Layer) imageLayer.clone();
// imageAndTitle.setId(UUIDGenerator.getInstance().generateId());
// imageAndTitle.setStyleAttribute("width", ""+this.widthOfImages);
//
// wrapper.add(imageAndTitle);
// todo have a set method
if (this.heightOfImages > 0) {
image.setHeight(this.heightOfImages);
}
if (this.widthOfImages > 0) {
image.setWidth(this.widthOfImages);
}
// set properties of advanced image
image.setEnlargeProperty(this.enlargeImage);
image.setScaleProportional(this.scaleProportional);
//image.setStyleClass("reflect rheight10");
// deprecated backward compatability stuff
if (this.paddingOfImage > 0) {
image.setPadding(this.paddingOfImage);
}
Link link = new Link(image);
String resourceURI = image.getResourceURI();
link.setToolTip(image.getName());
link.setURL(resourceURI);
link.setMarkupAttribute("rel", "lightbox["+idOfGallery+"]");
imageNumber++;
int xPositionImage = ((count % this.columns) + 1);
// why clone?
//imageAndTitle.add(link);
wrapper.add(link);
// add extra style classes for first and last elements of each row
// for styling purposes
if (xPositionImage == 1) {
wrapper.setStyleClass(STYLE_CLASS_FIRST_IN_ROW);
//imageAndTitle.setStyleClass(STYLE_CLASS_FIRST_IN_ROW);
}
else if (xPositionImage == this.columns) {
wrapper.setStyleClass(STYLE_CLASS_LAST_IN_ROW);
// imageAndTitle.setStyleClass(STYLE_CLASS_LAST_IN_ROW);
}
if (this.showNameOfImage) {
Paragraph theName = (Paragraph) name.clone();
theName.add(image.getName());
// imageAndTitle.add(theName);
wrapper.add(theName);
}
}
}
|
diff --git a/src/lib/com/izforge/izpack/panels/TargetPanel.java b/src/lib/com/izforge/izpack/panels/TargetPanel.java
index c3e7ab94..d559f503 100644
--- a/src/lib/com/izforge/izpack/panels/TargetPanel.java
+++ b/src/lib/com/izforge/izpack/panels/TargetPanel.java
@@ -1,302 +1,302 @@
/*
* $Id$
* IzPack
* Copyright (C) 2001-2003 Julien Ponge
*
* File : TargetPanel.java
* Description : A panel to select the installation path.
* Author's email : [email protected]
* Author's Website : http://www.izforge.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.izforge.izpack.panels;
import com.izforge.izpack.*;
import com.izforge.izpack.gui.*;
import com.izforge.izpack.installer.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import net.n3.nanoxml.*;
/**
* The taget directory selection panel.
*
* @author Julien Ponge
* @created November 1, 2002
*/
public class TargetPanel extends IzPanel implements ActionListener
{
/** The default directory. */
private String defaultDir;
/** The info label. */
private JLabel infoLabel;
/** The text field. */
private JTextField textField;
/** The 'browse' button. */
private JButton browseButton;
/** The layout . */
private GridBagLayout layout;
/** The layout constraints. */
private GridBagConstraints gbConstraints;
/**
* The constructor.
*
* @param parent The parent window.
* @param idata The installation data.
*/
public TargetPanel(InstallerFrame parent, InstallData idata)
{
super(parent, idata);
// We initialize our layout
layout = new GridBagLayout();
gbConstraints = new GridBagConstraints();
setLayout(layout);
// load the default directory info (if present)
loadDefaultDir();
if (defaultDir != null)
// override the system default that uses app name (which is set in the Installer class)
idata.setInstallPath(defaultDir);
// We create and put the components
infoLabel = new JLabel(parent.langpack.getString("TargetPanel.info"),
parent.icons.getImageIcon("home"), JLabel.TRAILING);
parent.buildConstraints(gbConstraints, 0, 0, 2, 1, 3.0, 0.0);
gbConstraints.insets = new Insets(5, 5, 5, 5);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.anchor = GridBagConstraints.SOUTHWEST;
layout.addLayoutComponent(infoLabel, gbConstraints);
add(infoLabel);
textField = new JTextField(idata.getInstallPath(), 40);
textField.addActionListener(this);
parent.buildConstraints(gbConstraints, 0, 1, 1, 1, 3.0, 0.0);
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.anchor = GridBagConstraints.WEST;
layout.addLayoutComponent(textField, gbConstraints);
add(textField);
browseButton = ButtonFactory.createButton(parent.langpack.getString("TargetPanel.browse"),
parent.icons.getImageIcon("open"),
idata.buttonsHColor);
browseButton.addActionListener(this);
parent.buildConstraints(gbConstraints, 1, 1, 1, 1, 1.0, 0.0);
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.anchor = GridBagConstraints.EAST;
layout.addLayoutComponent(browseButton, gbConstraints);
add(browseButton);
}
/**
* Loads up the "dir" resource associated with TargetPanel. Acceptable dir
* resource names: <code>
* TargetPanel.dir.macosx
* TargetPanel.dir.mac
* TargetPanel.dir.windows
* TargetPanel.dir.unix
* TargetPanel.dir.xxx,
* where xxx is the lower case version of System.getProperty("os.name"),
* with any spaces replace with underscores
* TargetPanel.dir (generic that will be applied if none of above is found)
* </code> As with all IzPack resources, each the above ids should be
* associated with a separate filename, which is set in the install.xml file
* at compile time.
*/
public void loadDefaultDir()
{
BufferedReader br = null;
try
{
String os = System.getProperty("os.name");
InputStream in = null;
if (os.regionMatches(true, 0, "windows", 0, 7))
in = parent.getResource("TargetPanel.dir.windows");
- else if (os.regionMatches(true, 0, "macosx", 0, 6))
+ else if (os.regionMatches(true, 0, "mac os x", 0, 8))
in = parent.getResource("TargetPanel.dir.macosx");
else if (os.regionMatches(true, 0, "mac", 0, 3))
in = parent.getResource("TargetPanel.dir.mac");
else
{
// first try to look up by specific os name
os.replace(' ', '_');// avoid spaces in file names
os = os.toLowerCase();// for consistency among TargetPanel res files
in = parent.getResource("TargetPanel.dir.".concat(os));
// if not specific os, try getting generic 'unix' resource file
if (in == null)
in = parent.getResource("TargetPanel.dir.unix");
// if all those failed, try to look up a generic dir file
if (in == null)
in = parent.getResource("TargetPanel.dir");
}
// if all above tests failed, there is no resource file,
// so use system default
if (in == null)
return;
// now read the file, once we've identified which one to read
InputStreamReader isr = new InputStreamReader(in);
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
line = line.trim();
// use the first non-blank line
if (!line.equals(""))
break;
}
defaultDir = line;
}
catch (Exception e)
{
defaultDir = null;// leave unset to take the system default set by Installer class
}
finally
{
try
{
if (br != null)
br.close();
}
catch (IOException ignored)
{}
}
}
/**
* Indicates wether the panel has been validated or not.
*
* @return Wether the panel has been validated or not.
*/
public boolean isValidated()
{
String installPath = textField.getText();
boolean ok = true;
// We put a warning if the specified target is nameless
if (installPath.length() == 0)
{
int res = JOptionPane.showConfirmDialog(this,
parent.langpack.getString("TargetPanel.empty_target"),
parent.langpack.getString("installer.warning"),
JOptionPane.YES_NO_OPTION);
ok = (res == JOptionPane.YES_OPTION);
}
if (!ok) return ok;
// Normalize the path
File path = new File(installPath);
installPath = path.toString();
// We put a warning if the directory exists else we warn that it will be created
if (path.exists())
{
int res = JOptionPane.showConfirmDialog(this,
parent.langpack.getString("TargetPanel.warn"),
parent.langpack.getString("installer.warning"),
JOptionPane.YES_NO_OPTION);
ok = (res == JOptionPane.YES_OPTION);
}
else
JOptionPane.showMessageDialog(this, parent.langpack.getString("TargetPanel.createdir") +
"\n" + installPath);
idata.setInstallPath(installPath);
return ok;
}
/**
* Actions-handling method.
*
* @param e The event.
*/
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source != textField)
{
// The user wants to browse its filesystem
// Prepares the file chooser
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(textField.getText()));
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
// Shows it
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
textField.setText(fc.getSelectedFile().getAbsolutePath());
}
}
/**
* Asks to make the XML panel data.
*
* @param panelRoot The tree to put the data in.
*/
public void makeXMLData(XMLElement panelRoot)
{
// Installation path markup
XMLElement ipath = new XMLElement("installpath");
ipath.setContent(idata.getInstallPath());
panelRoot.addChild(ipath);
}
/**
* Asks to run in the automated mode.
*
* @param panelRoot The XML tree to read the data from.
*/
public void runAutomated(XMLElement panelRoot)
{
// We set the installation path
XMLElement ipath = panelRoot.getFirstChildNamed("installpath");
idata.setInstallPath(ipath.getContent());
}
}
| true | true | public void loadDefaultDir()
{
BufferedReader br = null;
try
{
String os = System.getProperty("os.name");
InputStream in = null;
if (os.regionMatches(true, 0, "windows", 0, 7))
in = parent.getResource("TargetPanel.dir.windows");
else if (os.regionMatches(true, 0, "macosx", 0, 6))
in = parent.getResource("TargetPanel.dir.macosx");
else if (os.regionMatches(true, 0, "mac", 0, 3))
in = parent.getResource("TargetPanel.dir.mac");
else
{
// first try to look up by specific os name
os.replace(' ', '_');// avoid spaces in file names
os = os.toLowerCase();// for consistency among TargetPanel res files
in = parent.getResource("TargetPanel.dir.".concat(os));
// if not specific os, try getting generic 'unix' resource file
if (in == null)
in = parent.getResource("TargetPanel.dir.unix");
// if all those failed, try to look up a generic dir file
if (in == null)
in = parent.getResource("TargetPanel.dir");
}
// if all above tests failed, there is no resource file,
// so use system default
if (in == null)
return;
// now read the file, once we've identified which one to read
InputStreamReader isr = new InputStreamReader(in);
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
line = line.trim();
// use the first non-blank line
if (!line.equals(""))
break;
}
defaultDir = line;
}
catch (Exception e)
{
defaultDir = null;// leave unset to take the system default set by Installer class
}
finally
{
try
{
if (br != null)
br.close();
}
catch (IOException ignored)
{}
}
}
| public void loadDefaultDir()
{
BufferedReader br = null;
try
{
String os = System.getProperty("os.name");
InputStream in = null;
if (os.regionMatches(true, 0, "windows", 0, 7))
in = parent.getResource("TargetPanel.dir.windows");
else if (os.regionMatches(true, 0, "mac os x", 0, 8))
in = parent.getResource("TargetPanel.dir.macosx");
else if (os.regionMatches(true, 0, "mac", 0, 3))
in = parent.getResource("TargetPanel.dir.mac");
else
{
// first try to look up by specific os name
os.replace(' ', '_');// avoid spaces in file names
os = os.toLowerCase();// for consistency among TargetPanel res files
in = parent.getResource("TargetPanel.dir.".concat(os));
// if not specific os, try getting generic 'unix' resource file
if (in == null)
in = parent.getResource("TargetPanel.dir.unix");
// if all those failed, try to look up a generic dir file
if (in == null)
in = parent.getResource("TargetPanel.dir");
}
// if all above tests failed, there is no resource file,
// so use system default
if (in == null)
return;
// now read the file, once we've identified which one to read
InputStreamReader isr = new InputStreamReader(in);
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
line = line.trim();
// use the first non-blank line
if (!line.equals(""))
break;
}
defaultDir = line;
}
catch (Exception e)
{
defaultDir = null;// leave unset to take the system default set by Installer class
}
finally
{
try
{
if (br != null)
br.close();
}
catch (IOException ignored)
{}
}
}
|
diff --git a/adapters/migration/src/main/java/org/atomhopper/migration/adapter/MigrationFeedPublisher.java b/adapters/migration/src/main/java/org/atomhopper/migration/adapter/MigrationFeedPublisher.java
index 17261787..43ccbd27 100644
--- a/adapters/migration/src/main/java/org/atomhopper/migration/adapter/MigrationFeedPublisher.java
+++ b/adapters/migration/src/main/java/org/atomhopper/migration/adapter/MigrationFeedPublisher.java
@@ -1,129 +1,127 @@
package org.atomhopper.migration.adapter;
import org.apache.abdera.model.Entry;
import org.apache.commons.lang.StringUtils;
import org.atomhopper.adapter.FeedPublisher;
import org.atomhopper.adapter.NotImplemented;
import org.atomhopper.adapter.jpa.PersistedEntry;
import org.atomhopper.adapter.request.adapter.DeleteEntryRequest;
import org.atomhopper.adapter.request.adapter.PostEntryRequest;
import org.atomhopper.adapter.request.adapter.PutEntryRequest;
import org.atomhopper.migration.domain.MigrationReadFrom;
import org.atomhopper.migration.domain.MigrationWriteTo;
import org.atomhopper.response.AdapterResponse;
import org.atomhopper.response.EmptyBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.UUID;
public class MigrationFeedPublisher implements FeedPublisher {
private static final Logger LOG = LoggerFactory.getLogger(MigrationFeedPublisher.class);
private static final String UUID_URI_SCHEME = "urn:uuid:";
private FeedPublisher oldFeedPublisher;
private FeedPublisher newFeedPublisher;
private MigrationWriteTo writeTo;
private MigrationReadFrom readFrom;
private boolean allowOverrideId = false;
private boolean allowOverrideDate = false;
public void setOldFeedPublisher(FeedPublisher oldFeedPublisher) {
this.oldFeedPublisher = oldFeedPublisher;
}
public void setNewFeedPublisher(FeedPublisher newFeedPublisher) {
this.newFeedPublisher = newFeedPublisher;
}
public void setWriteTo(MigrationWriteTo writeTo) {
this.writeTo = writeTo;
}
public void setReadFrom(MigrationReadFrom readFrom) {
this.readFrom = readFrom;
}
public void setAllowOverrideId(boolean allowOverrideId) {
this.allowOverrideId = allowOverrideId;
}
public void setAllowOverrideDate(boolean allowOverrideDate) {
this.allowOverrideDate = allowOverrideDate;
}
@Override
public AdapterResponse<Entry> postEntry(PostEntryRequest postEntryRequest) {
PersistedEntry entry = new PersistedEntry();
// If allowOverrideId is false then set the Id
// Also set the id if allowOverrideId is true, but no Id was sent in the entry
if (!allowOverrideId || postEntryRequest.getEntry().getId() == null || StringUtils.isBlank(postEntryRequest.getEntry().getId().toString().trim())) {
postEntryRequest.getEntry().setId(UUID_URI_SCHEME + UUID.randomUUID().toString());
}
// If allowOverrideDate is false then set the DateLastUpdated
// Also set the DateLastUpdated if allowOverrideDate is true, but no DateLastUpdated was sent in the entry
if (!allowOverrideDate || postEntryRequest.getEntry().getUpdated() == null) {
postEntryRequest.getEntry().setUpdated(entry.getDateLastUpdated());
}
switch (writeTo) {
case OLD:
return oldFeedPublisher.postEntry(postEntryRequest);
case NEW:
return newFeedPublisher.postEntry(postEntryRequest);
case BOTH:
default:
switch (readFrom) {
case NEW:
AdapterResponse<Entry> newEntry = newFeedPublisher.postEntry(postEntryRequest);
try {
- postEntryRequest.getEntry().getLinks().remove(postEntryRequest.getEntry().getLink("self"));
oldFeedPublisher.postEntry(postEntryRequest);
} catch (Exception ex) {
LOG.error("Error writing entry to OLD feed:" + postEntryRequest.getFeedName() + " EntryId=" + postEntryRequest.getEntry().getId());
}
return newEntry;
case OLD:
default:
AdapterResponse<Entry> oldEntry = oldFeedPublisher.postEntry(postEntryRequest);
try {
- postEntryRequest.getEntry().getLinks().remove(postEntryRequest.getEntry().getLink("self"));
newFeedPublisher.postEntry(postEntryRequest);
} catch (Exception ex) {
LOG.error("Error writing entry to NEW feed:" + postEntryRequest.getFeedName() + " EntryId=" + postEntryRequest.getEntry().getId());
}
return oldEntry;
}
}
}
@Override
@NotImplemented
public AdapterResponse<Entry> putEntry(PutEntryRequest putEntryRequest) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
@NotImplemented
public AdapterResponse<EmptyBody> deleteEntry(DeleteEntryRequest deleteEntryRequest) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
@NotImplemented
public void setParameters(Map<String, String> params) {
throw new UnsupportedOperationException("Not supported.");
}
}
| false | true | public AdapterResponse<Entry> postEntry(PostEntryRequest postEntryRequest) {
PersistedEntry entry = new PersistedEntry();
// If allowOverrideId is false then set the Id
// Also set the id if allowOverrideId is true, but no Id was sent in the entry
if (!allowOverrideId || postEntryRequest.getEntry().getId() == null || StringUtils.isBlank(postEntryRequest.getEntry().getId().toString().trim())) {
postEntryRequest.getEntry().setId(UUID_URI_SCHEME + UUID.randomUUID().toString());
}
// If allowOverrideDate is false then set the DateLastUpdated
// Also set the DateLastUpdated if allowOverrideDate is true, but no DateLastUpdated was sent in the entry
if (!allowOverrideDate || postEntryRequest.getEntry().getUpdated() == null) {
postEntryRequest.getEntry().setUpdated(entry.getDateLastUpdated());
}
switch (writeTo) {
case OLD:
return oldFeedPublisher.postEntry(postEntryRequest);
case NEW:
return newFeedPublisher.postEntry(postEntryRequest);
case BOTH:
default:
switch (readFrom) {
case NEW:
AdapterResponse<Entry> newEntry = newFeedPublisher.postEntry(postEntryRequest);
try {
postEntryRequest.getEntry().getLinks().remove(postEntryRequest.getEntry().getLink("self"));
oldFeedPublisher.postEntry(postEntryRequest);
} catch (Exception ex) {
LOG.error("Error writing entry to OLD feed:" + postEntryRequest.getFeedName() + " EntryId=" + postEntryRequest.getEntry().getId());
}
return newEntry;
case OLD:
default:
AdapterResponse<Entry> oldEntry = oldFeedPublisher.postEntry(postEntryRequest);
try {
postEntryRequest.getEntry().getLinks().remove(postEntryRequest.getEntry().getLink("self"));
newFeedPublisher.postEntry(postEntryRequest);
} catch (Exception ex) {
LOG.error("Error writing entry to NEW feed:" + postEntryRequest.getFeedName() + " EntryId=" + postEntryRequest.getEntry().getId());
}
return oldEntry;
}
}
}
| public AdapterResponse<Entry> postEntry(PostEntryRequest postEntryRequest) {
PersistedEntry entry = new PersistedEntry();
// If allowOverrideId is false then set the Id
// Also set the id if allowOverrideId is true, but no Id was sent in the entry
if (!allowOverrideId || postEntryRequest.getEntry().getId() == null || StringUtils.isBlank(postEntryRequest.getEntry().getId().toString().trim())) {
postEntryRequest.getEntry().setId(UUID_URI_SCHEME + UUID.randomUUID().toString());
}
// If allowOverrideDate is false then set the DateLastUpdated
// Also set the DateLastUpdated if allowOverrideDate is true, but no DateLastUpdated was sent in the entry
if (!allowOverrideDate || postEntryRequest.getEntry().getUpdated() == null) {
postEntryRequest.getEntry().setUpdated(entry.getDateLastUpdated());
}
switch (writeTo) {
case OLD:
return oldFeedPublisher.postEntry(postEntryRequest);
case NEW:
return newFeedPublisher.postEntry(postEntryRequest);
case BOTH:
default:
switch (readFrom) {
case NEW:
AdapterResponse<Entry> newEntry = newFeedPublisher.postEntry(postEntryRequest);
try {
oldFeedPublisher.postEntry(postEntryRequest);
} catch (Exception ex) {
LOG.error("Error writing entry to OLD feed:" + postEntryRequest.getFeedName() + " EntryId=" + postEntryRequest.getEntry().getId());
}
return newEntry;
case OLD:
default:
AdapterResponse<Entry> oldEntry = oldFeedPublisher.postEntry(postEntryRequest);
try {
newFeedPublisher.postEntry(postEntryRequest);
} catch (Exception ex) {
LOG.error("Error writing entry to NEW feed:" + postEntryRequest.getFeedName() + " EntryId=" + postEntryRequest.getEntry().getId());
}
return oldEntry;
}
}
}
|
diff --git a/src/org/dancres/paxos/impl/mina/io/TransportImpl.java b/src/org/dancres/paxos/impl/mina/io/TransportImpl.java
index fd10a76..baa95d1 100644
--- a/src/org/dancres/paxos/impl/mina/io/TransportImpl.java
+++ b/src/org/dancres/paxos/impl/mina/io/TransportImpl.java
@@ -1,83 +1,83 @@
package org.dancres.paxos.impl.mina.io;
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoSession;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
import org.dancres.paxos.Transport;
import org.dancres.paxos.NodeId;
import org.dancres.paxos.messages.Operations;
import org.dancres.paxos.messages.PaxosMessage;
public class TransportImpl implements Transport {
private ConcurrentHashMap<NodeId, IoSession> _sessions = new ConcurrentHashMap<NodeId, IoSession>();
/**
* The address where our unicast port is bound. We add a note of this to outgoing proposer messages so that
* where appropriate we can be called back.
*/
private InetSocketAddress _addr;
private NioDatagramConnector _unicastConnector;
/**
* @param aNodeAddr is the address of our unicast port
* @param aBroadcastSession is the session on which to send broadcast messages for acceptor learners
* @param aUnicastConnector is the connector to use for contacting hosts directly when specified via NodeId
*/
public TransportImpl(InetSocketAddress aNodeAddr, IoSession aBroadcastSession,
NioDatagramConnector aUnicastConnector) {
super();
_sessions.put(NodeId.BROADCAST, aBroadcastSession);
_addr = aNodeAddr;
_unicastConnector = aUnicastConnector;
}
public void send(PaxosMessage aMessage, NodeId anAddress) {
PaxosMessage myMessage;
switch (aMessage.getType()) {
case Operations.COLLECT :
case Operations.BEGIN :
case Operations.SUCCESS : {
myMessage = new ProposerHeader(aMessage, _addr.getPort());
break;
}
default : {
myMessage = aMessage;
break;
}
}
IoSession mySession = (IoSession) _sessions.get(anAddress);
- if (mySession != null) {
+ if (mySession == null) {
try {
ConnectFuture connFuture = _unicastConnector.connect(NodeId
.toAddress(anAddress));
connFuture.awaitUninterruptibly();
IoSession myNewSession = connFuture.getSession();
mySession = _sessions.putIfAbsent(anAddress, myNewSession);
/*
* We're racing to create the session, if we were beaten to it, mySession will be non-null
* and we must close the new session we just created. Otherwise, we're good to go with myNewSession
*/
if (mySession == null)
mySession = myNewSession;
else {
myNewSession.close();
}
} catch (Exception anE) {
throw new RuntimeException("Got connection problem", anE);
}
}
mySession.write(myMessage);
}
}
| true | true | public void send(PaxosMessage aMessage, NodeId anAddress) {
PaxosMessage myMessage;
switch (aMessage.getType()) {
case Operations.COLLECT :
case Operations.BEGIN :
case Operations.SUCCESS : {
myMessage = new ProposerHeader(aMessage, _addr.getPort());
break;
}
default : {
myMessage = aMessage;
break;
}
}
IoSession mySession = (IoSession) _sessions.get(anAddress);
if (mySession != null) {
try {
ConnectFuture connFuture = _unicastConnector.connect(NodeId
.toAddress(anAddress));
connFuture.awaitUninterruptibly();
IoSession myNewSession = connFuture.getSession();
mySession = _sessions.putIfAbsent(anAddress, myNewSession);
/*
* We're racing to create the session, if we were beaten to it, mySession will be non-null
* and we must close the new session we just created. Otherwise, we're good to go with myNewSession
*/
if (mySession == null)
mySession = myNewSession;
else {
myNewSession.close();
}
} catch (Exception anE) {
throw new RuntimeException("Got connection problem", anE);
}
}
mySession.write(myMessage);
}
| public void send(PaxosMessage aMessage, NodeId anAddress) {
PaxosMessage myMessage;
switch (aMessage.getType()) {
case Operations.COLLECT :
case Operations.BEGIN :
case Operations.SUCCESS : {
myMessage = new ProposerHeader(aMessage, _addr.getPort());
break;
}
default : {
myMessage = aMessage;
break;
}
}
IoSession mySession = (IoSession) _sessions.get(anAddress);
if (mySession == null) {
try {
ConnectFuture connFuture = _unicastConnector.connect(NodeId
.toAddress(anAddress));
connFuture.awaitUninterruptibly();
IoSession myNewSession = connFuture.getSession();
mySession = _sessions.putIfAbsent(anAddress, myNewSession);
/*
* We're racing to create the session, if we were beaten to it, mySession will be non-null
* and we must close the new session we just created. Otherwise, we're good to go with myNewSession
*/
if (mySession == null)
mySession = myNewSession;
else {
myNewSession.close();
}
} catch (Exception anE) {
throw new RuntimeException("Got connection problem", anE);
}
}
mySession.write(myMessage);
}
|
diff --git a/src/main/java/be/hehehe/supersonic/SupersonicTray.java b/src/main/java/be/hehehe/supersonic/SupersonicTray.java
index 7623ca9..a2ef3d0 100644
--- a/src/main/java/be/hehehe/supersonic/SupersonicTray.java
+++ b/src/main/java/be/hehehe/supersonic/SupersonicTray.java
@@ -1,126 +1,123 @@
package be.hehehe.supersonic;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import org.apache.commons.lang.SystemUtils;
import be.hehehe.supersonic.action.ExitAction;
import be.hehehe.supersonic.events.SongEvent;
import be.hehehe.supersonic.events.SongEvent.Type;
import be.hehehe.supersonic.model.SongModel;
import be.hehehe.supersonic.service.IconService;
import be.hehehe.supersonic.service.PreferencesService;
import be.hehehe.supersonic.utils.SwingUtils;
@Singleton
public class SupersonicTray {
@Inject
IconService iconService;
@Inject
ExitAction exitAction;
@Inject
PreferencesService preferencesService;
private TrayIcon trayIcon;
public boolean addTray(final Supersonic supersonic) {
if (!SystemTray.isSupported()) {
return false;
}
final JPopupMenu popup = new JPopupMenu();
trayIcon = new TrayIcon(iconService.getIcon("supersonic").getImage());
final SystemTray tray = SystemTray.getSystemTray();
JMenuItem restoreItem = new JMenuItem("Restore");
restoreItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
supersonic.showSupersonic();
}
});
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(exitAction);
popup.add(restoreItem);
popup.addSeparator();
popup.add(exitItem);
trayIcon.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.setLocation(e.getX(), e.getY());
popup.setInvoker(popup);
popup.setVisible(true);
}
}
});
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
- if (supersonic.isVisible()) {
- supersonic.hideSupersonic();
- } else {
- supersonic.showSupersonic();
- }
- } else if (e.getClickCount() == 1) {
+ supersonic.showSupersonic();
+ } else if (e.getClickCount() == 1
+ && e.getButton() == MouseEvent.BUTTON2) {
popup.setLocation(e.getX(), e.getY());
popup.setInvoker(popup);
popup.setVisible(true);
}
}
});
trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
supersonic.showSupersonic();
}
});
boolean trayAdded = false;
try {
tray.add(trayIcon);
trayAdded = true;
} catch (Exception e) {
trayAdded = false;
}
return trayAdded;
}
public void onEvent(@Observes final SongEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (e.getType() == Type.PLAY) {
if (preferencesService.isDisplayNotifications()) {
SongModel song = e.getSong();
String title = String.format("%s (%s)",
song.getTitle(),
SwingUtils.formatDuration(song.getDuration()));
String desc = song.getArtist()
+ SystemUtils.LINE_SEPARATOR
+ song.getAlbum()
+ (song.getYear() != 0 ? String.format(" (%d)",
song.getYear()) : "");
trayIcon.displayMessage(title, desc, MessageType.INFO);
}
}
}
});
}
}
| true | true | public boolean addTray(final Supersonic supersonic) {
if (!SystemTray.isSupported()) {
return false;
}
final JPopupMenu popup = new JPopupMenu();
trayIcon = new TrayIcon(iconService.getIcon("supersonic").getImage());
final SystemTray tray = SystemTray.getSystemTray();
JMenuItem restoreItem = new JMenuItem("Restore");
restoreItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
supersonic.showSupersonic();
}
});
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(exitAction);
popup.add(restoreItem);
popup.addSeparator();
popup.add(exitItem);
trayIcon.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.setLocation(e.getX(), e.getY());
popup.setInvoker(popup);
popup.setVisible(true);
}
}
});
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (supersonic.isVisible()) {
supersonic.hideSupersonic();
} else {
supersonic.showSupersonic();
}
} else if (e.getClickCount() == 1) {
popup.setLocation(e.getX(), e.getY());
popup.setInvoker(popup);
popup.setVisible(true);
}
}
});
trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
supersonic.showSupersonic();
}
});
boolean trayAdded = false;
try {
tray.add(trayIcon);
trayAdded = true;
} catch (Exception e) {
trayAdded = false;
}
return trayAdded;
}
| public boolean addTray(final Supersonic supersonic) {
if (!SystemTray.isSupported()) {
return false;
}
final JPopupMenu popup = new JPopupMenu();
trayIcon = new TrayIcon(iconService.getIcon("supersonic").getImage());
final SystemTray tray = SystemTray.getSystemTray();
JMenuItem restoreItem = new JMenuItem("Restore");
restoreItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
supersonic.showSupersonic();
}
});
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(exitAction);
popup.add(restoreItem);
popup.addSeparator();
popup.add(exitItem);
trayIcon.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.setLocation(e.getX(), e.getY());
popup.setInvoker(popup);
popup.setVisible(true);
}
}
});
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
supersonic.showSupersonic();
} else if (e.getClickCount() == 1
&& e.getButton() == MouseEvent.BUTTON2) {
popup.setLocation(e.getX(), e.getY());
popup.setInvoker(popup);
popup.setVisible(true);
}
}
});
trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
supersonic.showSupersonic();
}
});
boolean trayAdded = false;
try {
tray.add(trayIcon);
trayAdded = true;
} catch (Exception e) {
trayAdded = false;
}
return trayAdded;
}
|
diff --git a/src/com/subspace/network/NetworkSubspace.java b/src/com/subspace/network/NetworkSubspace.java
index 6262d82..729e094 100644
--- a/src/com/subspace/network/NetworkSubspace.java
+++ b/src/com/subspace/network/NetworkSubspace.java
@@ -1,507 +1,507 @@
/*
SubspaceMobile - A subspace/continuum client for mobile phones
Copyright (C) 2010 Kingsley Masters
Email: kshade2001 at users.sourceforge.net
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
REVISIONS:
*/
package com.subspace.network;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.util.Log;
import android.util.SparseArray;
/**
struct C2SSimplePing {
u32 timestamp;
};
the server replies with 8 bytes:
struct S2CSimplePing {
u32 total;
u32 timestamp;
};
*/
public class NetworkSubspace extends Network implements INetworkCallback {
//these can be set via preferences
public static boolean LOG_CORE_PACKETS = false;
public static boolean LOG_CONNECTION = true;
private static final String TAG = "Subspace";
public static final String CHAR_ENCODING = "ISO-8859-1";
public static final int MAX_RETRY = 5;
public static final int CONNECT_WAIT_TIME = 4000; //4 second
int sentNumber = 0;
int playerCount = -1;
int retryCount = 0;
INetworkEncryption enc;
boolean connected = false;
//reliable packet handling
int reliableNextOutbound;
int reliableNextExpected;
SparseArray<byte[]> reliableIncoming;
HashMap<Integer, byte[]> reliableOutgoing;
Timer reliableResendTimer = new Timer();
//chunked message
byte[] chunkArray = null;
//stream
int streamSize = 0;
int streamCount = 0; // Handles chunk pkt sizes
File streamFileCache;
FileOutputStream streamFileOutputStream;
ISubspaceCallback subspaceCallback;
protected Context _context;
public boolean isConnected() {
return connected;
}
public NetworkSubspace(Context context) {
super(null);
_context = context;
//set call back
setCallback(this);
enc = new NetworkEncryptionVIE();
//create stream backing file
File cacheDir= context.getCacheDir();
streamFileCache = new File(cacheDir, "download.temp");
//delete if it file already exists
if(streamFileCache.exists())
{
streamFileCache.delete();
}
//setup reliable
reliableNextOutbound = 0;
reliableNextExpected = 0;
reliableIncoming = new SparseArray<byte[]>();
reliableOutgoing = new HashMap<Integer,byte[]>();
reliableResendTimer.scheduleAtFixedRate(new TimerTask()
{
public void run() {
if (reliableOutgoing.size() > 0) {
// resend any in queue
Log.d(TAG, "Resending Packets " + reliableOutgoing.size());
for (byte[] bytes : reliableOutgoing.values()) {
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.order(ByteOrder.LITTLE_ENDIAN);
try {
SSSend(bb);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, Log.getStackTraceString(e));
}
}
}
}
}, 1000, 1000); // resend every second
}
public final void setDownloadCallback(ISubspaceCallback callback) {
this.subspaceCallback = callback;
}
public final boolean SSConnect(String host, int port) throws IOException {
connected = false;
this.Connect(host,port);
//send connection
synchronized (this) {
//block for wait
try {
retryCount = 0;
while ((!connected) && (retryCount < MAX_RETRY)) {
retryCount++;
//send login
this.Send(enc.CreateLogin());
this.wait(CONNECT_WAIT_TIME);
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
return connected;
}
public final void SSDisconnect() throws IOException {
//send 1 disconnect
this.SSSend(NetworkPacket.CreateDisconnect());
//signal that we've disconnected
this.connected = false;
Log.d(TAG,"Sent Disconnect");
//send disconnect 2 times to make sure
this.SSSend(NetworkPacket.CreateDisconnect());
this.SSSend(NetworkPacket.CreateDisconnect());
//now forceable close the connection
this.Close();
}
public final void SSSend(ByteBuffer buffer) throws IOException {
if(LOG_CORE_PACKETS)
{
Log.v(TAG,"CS: " + Util.ToHex(buffer));
}
buffer.rewind();
enc.Encrypt(buffer);
this.Send(buffer);
}
public final void SSSendReliable(ByteBuffer bytes) throws IOException {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Sent Reliable packet " + reliableNextOutbound);
}
ByteBuffer reliablePacket = NetworkPacket.CreateReliable(reliableNextOutbound, bytes);
reliablePacket.rewind();
//save into array
byte[] msg = new byte[reliablePacket.limit()];
//read into msg
reliablePacket.get(msg,0,msg.length);
reliablePacket.rewind();
//save to check if we've received
reliableOutgoing.put(reliableNextOutbound,msg);
//now send
this.SSSend(reliablePacket);
reliableNextOutbound++;
}
public final void SSSync() throws IOException {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Sent Sync packet");
}
this.SSSend(NetworkPacket.CreateSync(this.getRecvDatagramCount(), this.getSentDatagramCount()));
}
public ByteBuffer Recv(ByteBuffer data, boolean decryptPacket) {
if (data == null) {
return null;
}
try {
//if not connected pass to encryption handler
if (!this.connected && (data.get(0) == NetworkPacket.CORE)) {
//log packets
if(LOG_CORE_PACKETS)
{
Log.v(TAG,Util.ToHex(data));
}
if (data.get(1) == NetworkPacket.CORE_CONNECTIONACK) {
if(LOG_CONNECTION)
{
Log.d(TAG,"Received ConnectionAck: " + Util.ToHex(data));
}
synchronized (this) {
if (enc.HandleLoginAck(data)) {
this.connected = true;
this.notify();
} else {
Log.d(TAG,Util.ToHex(data));
}
}
}
else if (data.get(1) == NetworkPacket.CORE_SYNC) //handle subgame flood protection
{
if(LOG_CONNECTION)
{
Log.d(TAG,"Received Sync: " + Util.ToHex(data));
}
ByteBuffer syncResponse = NetworkPacket.CreateSyncResponse(data.getInt(2));
this.SSSend(syncResponse);
if(LOG_CONNECTION)
{
Log.d(TAG,"Send back Sync: " + Util.ToHex(syncResponse.array()));
}
} else if (data.get(1) == NetworkPacket.CORE_DISCONNECT) {
synchronized (this) {
this.connected = false;
this.notify();
Log.i(TAG,"Disconnected");
}
} else {
Log.i(TAG,"Unrecognised Packet: " + Util.ToHex(data));
}
}
else
{
//if packet needs decrypting
//do so
if (decryptPacket) {
enc.Decrypt(data);
}
//log packets
if(LOG_CORE_PACKETS)
{
if(data.limit() > 520)
{
Log.v(TAG,"CR: packet in excess of 520 recieived, cannot log at the moment");
} else {
Log.v(TAG,"CR: " + Util.ToHex(data));
}
}
byte packetType = data.get(0);
if (packetType == NetworkPacket.CORE) {
byte corePacketType = data.get(1);
switch (corePacketType) {
case NetworkPacket.CORE_RELIABLE: {
int id = data.getInt(2);
//send ack twice
this.SSSend(NetworkPacket.CreateReliableAck(id));
this.SSSend(NetworkPacket.CreateReliableAck(id));
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"New Reliable Packet Received: " + id);
}
//now handle
if (id == this.reliableNextExpected) {
this.reliableNextExpected++;
//its expected so send it for processing
data.position(6);
//copy to new buffer, but remember to update endian
ByteBuffer sliceBuffer = data.slice();
sliceBuffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(sliceBuffer, false);
//now check queue
if (this.reliableIncoming.size() > 0) {
while (true) {
//get stored value
byte[] b = (byte[]) this.reliableIncoming.get(this.reliableNextExpected);
//remove it
this.reliableIncoming.remove(this.reliableNextExpected);
//return null if no more left
if (b == null) {
return null;
}
//Increment next expected
reliableNextExpected++;
//copy to new buffer, but remember to update endian
ByteBuffer buffer = ByteBuffer.wrap(b);
buffer.order(ByteOrder.LITTLE_ENDIAN);
//now process received byte
this.callback.Recv(buffer, false);
}
}
} else if (id > this.reliableNextExpected) {
byte[] msg = new byte[data.limit() - 6];
//read into msg
data.position(6);
data.get(msg,0,msg.length);
this.reliableIncoming.put(id, msg);
} else {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Already received, resending ack for: " + id);
}
//we've already had this packet so send a 2 more acks to make sure we don't get it again
this.SSSend(NetworkPacket.CreateReliableAck(id));
this.SSSend(NetworkPacket.CreateReliableAck(id));
return null;
}
}
case NetworkPacket.CORE_RELIABLEACK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_RELIABLEACK " + data.getInt(2));
}
reliableOutgoing.remove(data.getInt(2));
break;
}
case NetworkPacket.CORE_SYNC: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_SYNC");
}
//send back ack
this.SSSend(NetworkPacket.CreateSyncResponse(data.getInt(2)));
break;
}
case NetworkPacket.CORE_SYNCACK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_SYNCACK");
}
break;
}
case NetworkPacket.CORE_DISCONNECT:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_DISCONNECT");
}
SSDisconnect();
return null;
case NetworkPacket.CORE_CHUNK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CHUNK");
}
int oldSize;
if (chunkArray == null) {
chunkArray = new byte[data.limit() - 2];
data.position(2); data.get(chunkArray, 0, data.limit() - 2);
} else {
oldSize = chunkArray.length;
byte[] newArray = new byte[oldSize + data.limit() - 2];
System.arraycopy(chunkArray, 0, newArray, 0, chunkArray.length);
chunkArray = newArray;
newArray = null;
- data.position(2); data.get(chunkArray, 0, data.limit() - 2);
+ data.position(2); data.get(chunkArray, oldSize, data.limit() - 2);
}
}
break;
case NetworkPacket.CORE_CHUNKEND: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CHUNKEND");
}
int oldSize;
oldSize = chunkArray.length;
byte[] newArray = new byte[oldSize + data.limit() - 2];
System.arraycopy(chunkArray, 0, newArray, 0, chunkArray.length);
chunkArray = newArray;
newArray = null;
- data.position(2); data.get(chunkArray, 0, data.limit() - 2);
+ data.position(2); data.get(chunkArray, oldSize, data.limit() - 2);
//copy to new buffer, but remember to update endian
ByteBuffer buffer = ByteBuffer.wrap(chunkArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(buffer, false);
chunkArray = null;
}
break;
case NetworkPacket.CORE_STREAM: {
if (streamCount == 0) {
streamSize = data.getInt(2);
streamCount = data.getInt(2);
streamFileOutputStream = new FileOutputStream (streamFileCache);
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadStarted();
}
}
//write buffer into file
data.position(6);
byte[] buf = new byte[data.limit()-6];
data.get(buf);
streamFileOutputStream.write(buf);
//Decrease stream count
streamCount -= (data.limit() - 6);
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Stream: " + (streamSize-streamCount) +"/" + streamSize);
}
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadProgressUpdate(streamSize-streamCount, streamSize);
}
if (streamCount <= 0) {
//close stream
streamFileOutputStream.close();
//copy it into memory
byte[] b = new byte[(int)streamFileCache.length()];
FileInputStream fis = new FileInputStream(streamFileCache);
fis.read(b);
fis.close();
ByteBuffer streamArray = ByteBuffer.wrap(b);
streamArray.order(ByteOrder.LITTLE_ENDIAN);
streamArray.rewind();
//send update
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadComplete();
}
//now send on
this.callback.Recv(streamArray, false);
//delete file
streamFileCache.delete();
}
}
break;
case NetworkPacket.CORE_STREAMCANCEL:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_STREAMCANCEL");
}
break;
case NetworkPacket.CORE_STREAMCANCELACK:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_STREAMCANCELACK");
}
break;
case NetworkPacket.CORE_CLUSTER: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CLUSTER");
}
int i = 2;
int size;
byte[] subMessage;
while (i < data.limit()) {
size = data.get(i) & 0xff;
subMessage = new byte[size];
data.position(i+1); data.get(subMessage, 0, size);
ByteBuffer buffer = ByteBuffer.wrap(subMessage);
buffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(buffer, false);
i += size + 1;
}
break;
}
default:
{
if(data.limit() > 520)
{
Log.i(TAG,"Unrecognised Core Packet: packet in excess of 520 recieived, cannot log at the moment");
} else {
Log.i(TAG,"Unrecognised Core Packet: " + Util.ToHex(data));
}
}
}
return null;
}
//not a core packet so just return the data
return data;
}
} catch (IOException ioe) {
Log.e(TAG,Log.getStackTraceString(ioe));
}
return null;
}
}
| false | true | public ByteBuffer Recv(ByteBuffer data, boolean decryptPacket) {
if (data == null) {
return null;
}
try {
//if not connected pass to encryption handler
if (!this.connected && (data.get(0) == NetworkPacket.CORE)) {
//log packets
if(LOG_CORE_PACKETS)
{
Log.v(TAG,Util.ToHex(data));
}
if (data.get(1) == NetworkPacket.CORE_CONNECTIONACK) {
if(LOG_CONNECTION)
{
Log.d(TAG,"Received ConnectionAck: " + Util.ToHex(data));
}
synchronized (this) {
if (enc.HandleLoginAck(data)) {
this.connected = true;
this.notify();
} else {
Log.d(TAG,Util.ToHex(data));
}
}
}
else if (data.get(1) == NetworkPacket.CORE_SYNC) //handle subgame flood protection
{
if(LOG_CONNECTION)
{
Log.d(TAG,"Received Sync: " + Util.ToHex(data));
}
ByteBuffer syncResponse = NetworkPacket.CreateSyncResponse(data.getInt(2));
this.SSSend(syncResponse);
if(LOG_CONNECTION)
{
Log.d(TAG,"Send back Sync: " + Util.ToHex(syncResponse.array()));
}
} else if (data.get(1) == NetworkPacket.CORE_DISCONNECT) {
synchronized (this) {
this.connected = false;
this.notify();
Log.i(TAG,"Disconnected");
}
} else {
Log.i(TAG,"Unrecognised Packet: " + Util.ToHex(data));
}
}
else
{
//if packet needs decrypting
//do so
if (decryptPacket) {
enc.Decrypt(data);
}
//log packets
if(LOG_CORE_PACKETS)
{
if(data.limit() > 520)
{
Log.v(TAG,"CR: packet in excess of 520 recieived, cannot log at the moment");
} else {
Log.v(TAG,"CR: " + Util.ToHex(data));
}
}
byte packetType = data.get(0);
if (packetType == NetworkPacket.CORE) {
byte corePacketType = data.get(1);
switch (corePacketType) {
case NetworkPacket.CORE_RELIABLE: {
int id = data.getInt(2);
//send ack twice
this.SSSend(NetworkPacket.CreateReliableAck(id));
this.SSSend(NetworkPacket.CreateReliableAck(id));
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"New Reliable Packet Received: " + id);
}
//now handle
if (id == this.reliableNextExpected) {
this.reliableNextExpected++;
//its expected so send it for processing
data.position(6);
//copy to new buffer, but remember to update endian
ByteBuffer sliceBuffer = data.slice();
sliceBuffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(sliceBuffer, false);
//now check queue
if (this.reliableIncoming.size() > 0) {
while (true) {
//get stored value
byte[] b = (byte[]) this.reliableIncoming.get(this.reliableNextExpected);
//remove it
this.reliableIncoming.remove(this.reliableNextExpected);
//return null if no more left
if (b == null) {
return null;
}
//Increment next expected
reliableNextExpected++;
//copy to new buffer, but remember to update endian
ByteBuffer buffer = ByteBuffer.wrap(b);
buffer.order(ByteOrder.LITTLE_ENDIAN);
//now process received byte
this.callback.Recv(buffer, false);
}
}
} else if (id > this.reliableNextExpected) {
byte[] msg = new byte[data.limit() - 6];
//read into msg
data.position(6);
data.get(msg,0,msg.length);
this.reliableIncoming.put(id, msg);
} else {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Already received, resending ack for: " + id);
}
//we've already had this packet so send a 2 more acks to make sure we don't get it again
this.SSSend(NetworkPacket.CreateReliableAck(id));
this.SSSend(NetworkPacket.CreateReliableAck(id));
return null;
}
}
case NetworkPacket.CORE_RELIABLEACK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_RELIABLEACK " + data.getInt(2));
}
reliableOutgoing.remove(data.getInt(2));
break;
}
case NetworkPacket.CORE_SYNC: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_SYNC");
}
//send back ack
this.SSSend(NetworkPacket.CreateSyncResponse(data.getInt(2)));
break;
}
case NetworkPacket.CORE_SYNCACK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_SYNCACK");
}
break;
}
case NetworkPacket.CORE_DISCONNECT:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_DISCONNECT");
}
SSDisconnect();
return null;
case NetworkPacket.CORE_CHUNK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CHUNK");
}
int oldSize;
if (chunkArray == null) {
chunkArray = new byte[data.limit() - 2];
data.position(2); data.get(chunkArray, 0, data.limit() - 2);
} else {
oldSize = chunkArray.length;
byte[] newArray = new byte[oldSize + data.limit() - 2];
System.arraycopy(chunkArray, 0, newArray, 0, chunkArray.length);
chunkArray = newArray;
newArray = null;
data.position(2); data.get(chunkArray, 0, data.limit() - 2);
}
}
break;
case NetworkPacket.CORE_CHUNKEND: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CHUNKEND");
}
int oldSize;
oldSize = chunkArray.length;
byte[] newArray = new byte[oldSize + data.limit() - 2];
System.arraycopy(chunkArray, 0, newArray, 0, chunkArray.length);
chunkArray = newArray;
newArray = null;
data.position(2); data.get(chunkArray, 0, data.limit() - 2);
//copy to new buffer, but remember to update endian
ByteBuffer buffer = ByteBuffer.wrap(chunkArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(buffer, false);
chunkArray = null;
}
break;
case NetworkPacket.CORE_STREAM: {
if (streamCount == 0) {
streamSize = data.getInt(2);
streamCount = data.getInt(2);
streamFileOutputStream = new FileOutputStream (streamFileCache);
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadStarted();
}
}
//write buffer into file
data.position(6);
byte[] buf = new byte[data.limit()-6];
data.get(buf);
streamFileOutputStream.write(buf);
//Decrease stream count
streamCount -= (data.limit() - 6);
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Stream: " + (streamSize-streamCount) +"/" + streamSize);
}
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadProgressUpdate(streamSize-streamCount, streamSize);
}
if (streamCount <= 0) {
//close stream
streamFileOutputStream.close();
//copy it into memory
byte[] b = new byte[(int)streamFileCache.length()];
FileInputStream fis = new FileInputStream(streamFileCache);
fis.read(b);
fis.close();
ByteBuffer streamArray = ByteBuffer.wrap(b);
streamArray.order(ByteOrder.LITTLE_ENDIAN);
streamArray.rewind();
//send update
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadComplete();
}
//now send on
this.callback.Recv(streamArray, false);
//delete file
streamFileCache.delete();
}
}
break;
case NetworkPacket.CORE_STREAMCANCEL:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_STREAMCANCEL");
}
break;
case NetworkPacket.CORE_STREAMCANCELACK:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_STREAMCANCELACK");
}
break;
case NetworkPacket.CORE_CLUSTER: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CLUSTER");
}
int i = 2;
int size;
byte[] subMessage;
while (i < data.limit()) {
size = data.get(i) & 0xff;
subMessage = new byte[size];
data.position(i+1); data.get(subMessage, 0, size);
ByteBuffer buffer = ByteBuffer.wrap(subMessage);
buffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(buffer, false);
i += size + 1;
}
break;
}
default:
{
if(data.limit() > 520)
{
Log.i(TAG,"Unrecognised Core Packet: packet in excess of 520 recieived, cannot log at the moment");
} else {
Log.i(TAG,"Unrecognised Core Packet: " + Util.ToHex(data));
}
}
}
return null;
}
//not a core packet so just return the data
return data;
}
} catch (IOException ioe) {
Log.e(TAG,Log.getStackTraceString(ioe));
}
return null;
}
| public ByteBuffer Recv(ByteBuffer data, boolean decryptPacket) {
if (data == null) {
return null;
}
try {
//if not connected pass to encryption handler
if (!this.connected && (data.get(0) == NetworkPacket.CORE)) {
//log packets
if(LOG_CORE_PACKETS)
{
Log.v(TAG,Util.ToHex(data));
}
if (data.get(1) == NetworkPacket.CORE_CONNECTIONACK) {
if(LOG_CONNECTION)
{
Log.d(TAG,"Received ConnectionAck: " + Util.ToHex(data));
}
synchronized (this) {
if (enc.HandleLoginAck(data)) {
this.connected = true;
this.notify();
} else {
Log.d(TAG,Util.ToHex(data));
}
}
}
else if (data.get(1) == NetworkPacket.CORE_SYNC) //handle subgame flood protection
{
if(LOG_CONNECTION)
{
Log.d(TAG,"Received Sync: " + Util.ToHex(data));
}
ByteBuffer syncResponse = NetworkPacket.CreateSyncResponse(data.getInt(2));
this.SSSend(syncResponse);
if(LOG_CONNECTION)
{
Log.d(TAG,"Send back Sync: " + Util.ToHex(syncResponse.array()));
}
} else if (data.get(1) == NetworkPacket.CORE_DISCONNECT) {
synchronized (this) {
this.connected = false;
this.notify();
Log.i(TAG,"Disconnected");
}
} else {
Log.i(TAG,"Unrecognised Packet: " + Util.ToHex(data));
}
}
else
{
//if packet needs decrypting
//do so
if (decryptPacket) {
enc.Decrypt(data);
}
//log packets
if(LOG_CORE_PACKETS)
{
if(data.limit() > 520)
{
Log.v(TAG,"CR: packet in excess of 520 recieived, cannot log at the moment");
} else {
Log.v(TAG,"CR: " + Util.ToHex(data));
}
}
byte packetType = data.get(0);
if (packetType == NetworkPacket.CORE) {
byte corePacketType = data.get(1);
switch (corePacketType) {
case NetworkPacket.CORE_RELIABLE: {
int id = data.getInt(2);
//send ack twice
this.SSSend(NetworkPacket.CreateReliableAck(id));
this.SSSend(NetworkPacket.CreateReliableAck(id));
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"New Reliable Packet Received: " + id);
}
//now handle
if (id == this.reliableNextExpected) {
this.reliableNextExpected++;
//its expected so send it for processing
data.position(6);
//copy to new buffer, but remember to update endian
ByteBuffer sliceBuffer = data.slice();
sliceBuffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(sliceBuffer, false);
//now check queue
if (this.reliableIncoming.size() > 0) {
while (true) {
//get stored value
byte[] b = (byte[]) this.reliableIncoming.get(this.reliableNextExpected);
//remove it
this.reliableIncoming.remove(this.reliableNextExpected);
//return null if no more left
if (b == null) {
return null;
}
//Increment next expected
reliableNextExpected++;
//copy to new buffer, but remember to update endian
ByteBuffer buffer = ByteBuffer.wrap(b);
buffer.order(ByteOrder.LITTLE_ENDIAN);
//now process received byte
this.callback.Recv(buffer, false);
}
}
} else if (id > this.reliableNextExpected) {
byte[] msg = new byte[data.limit() - 6];
//read into msg
data.position(6);
data.get(msg,0,msg.length);
this.reliableIncoming.put(id, msg);
} else {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Already received, resending ack for: " + id);
}
//we've already had this packet so send a 2 more acks to make sure we don't get it again
this.SSSend(NetworkPacket.CreateReliableAck(id));
this.SSSend(NetworkPacket.CreateReliableAck(id));
return null;
}
}
case NetworkPacket.CORE_RELIABLEACK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_RELIABLEACK " + data.getInt(2));
}
reliableOutgoing.remove(data.getInt(2));
break;
}
case NetworkPacket.CORE_SYNC: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_SYNC");
}
//send back ack
this.SSSend(NetworkPacket.CreateSyncResponse(data.getInt(2)));
break;
}
case NetworkPacket.CORE_SYNCACK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_SYNCACK");
}
break;
}
case NetworkPacket.CORE_DISCONNECT:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_DISCONNECT");
}
SSDisconnect();
return null;
case NetworkPacket.CORE_CHUNK: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CHUNK");
}
int oldSize;
if (chunkArray == null) {
chunkArray = new byte[data.limit() - 2];
data.position(2); data.get(chunkArray, 0, data.limit() - 2);
} else {
oldSize = chunkArray.length;
byte[] newArray = new byte[oldSize + data.limit() - 2];
System.arraycopy(chunkArray, 0, newArray, 0, chunkArray.length);
chunkArray = newArray;
newArray = null;
data.position(2); data.get(chunkArray, oldSize, data.limit() - 2);
}
}
break;
case NetworkPacket.CORE_CHUNKEND: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CHUNKEND");
}
int oldSize;
oldSize = chunkArray.length;
byte[] newArray = new byte[oldSize + data.limit() - 2];
System.arraycopy(chunkArray, 0, newArray, 0, chunkArray.length);
chunkArray = newArray;
newArray = null;
data.position(2); data.get(chunkArray, oldSize, data.limit() - 2);
//copy to new buffer, but remember to update endian
ByteBuffer buffer = ByteBuffer.wrap(chunkArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(buffer, false);
chunkArray = null;
}
break;
case NetworkPacket.CORE_STREAM: {
if (streamCount == 0) {
streamSize = data.getInt(2);
streamCount = data.getInt(2);
streamFileOutputStream = new FileOutputStream (streamFileCache);
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadStarted();
}
}
//write buffer into file
data.position(6);
byte[] buf = new byte[data.limit()-6];
data.get(buf);
streamFileOutputStream.write(buf);
//Decrease stream count
streamCount -= (data.limit() - 6);
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"Stream: " + (streamSize-streamCount) +"/" + streamSize);
}
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadProgressUpdate(streamSize-streamCount, streamSize);
}
if (streamCount <= 0) {
//close stream
streamFileOutputStream.close();
//copy it into memory
byte[] b = new byte[(int)streamFileCache.length()];
FileInputStream fis = new FileInputStream(streamFileCache);
fis.read(b);
fis.close();
ByteBuffer streamArray = ByteBuffer.wrap(b);
streamArray.order(ByteOrder.LITTLE_ENDIAN);
streamArray.rewind();
//send update
if(this.subspaceCallback!=null)
{
this.subspaceCallback.DownloadComplete();
}
//now send on
this.callback.Recv(streamArray, false);
//delete file
streamFileCache.delete();
}
}
break;
case NetworkPacket.CORE_STREAMCANCEL:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_STREAMCANCEL");
}
break;
case NetworkPacket.CORE_STREAMCANCELACK:
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_STREAMCANCELACK");
}
break;
case NetworkPacket.CORE_CLUSTER: {
if(LOG_CORE_PACKETS)
{
Log.d(TAG,"CORE_CLUSTER");
}
int i = 2;
int size;
byte[] subMessage;
while (i < data.limit()) {
size = data.get(i) & 0xff;
subMessage = new byte[size];
data.position(i+1); data.get(subMessage, 0, size);
ByteBuffer buffer = ByteBuffer.wrap(subMessage);
buffer.order(ByteOrder.LITTLE_ENDIAN);
this.callback.Recv(buffer, false);
i += size + 1;
}
break;
}
default:
{
if(data.limit() > 520)
{
Log.i(TAG,"Unrecognised Core Packet: packet in excess of 520 recieived, cannot log at the moment");
} else {
Log.i(TAG,"Unrecognised Core Packet: " + Util.ToHex(data));
}
}
}
return null;
}
//not a core packet so just return the data
return data;
}
} catch (IOException ioe) {
Log.e(TAG,Log.getStackTraceString(ioe));
}
return null;
}
|
diff --git a/components/loci-plugins/src/loci/plugins/Checker.java b/components/loci-plugins/src/loci/plugins/Checker.java
index 635ca04ad..88602a5d9 100644
--- a/components/loci-plugins/src/loci/plugins/Checker.java
+++ b/components/loci-plugins/src/loci/plugins/Checker.java
@@ -1,171 +1,171 @@
//
// Checker.java
//
/*
LOCI Plugins for ImageJ: a collection of ImageJ plugins including the
Bio-Formats Importer, Bio-Formats Exporter, Bio-Formats Macro Extensions,
Data Browser, Stack Colorizer and Stack Slicer. Copyright (C) 2005-@year@
Melissa Linkert, Curtis Rueden and Christopher Peterson.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.plugins;
import ij.IJ;
import java.util.HashSet;
import java.util.Iterator;
/**
* Utility methods for verifying that classes
* are present and versions are correct.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/loci-plugins/src/loci/plugins/Checker.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/loci-plugins/src/loci/plugins/Checker.java">SVN</a></dd></dl>
*/
public final class Checker {
// -- Constants --
/** Identifier for checking the Bio-Formats library is present. */
public static final int BIO_FORMATS = 1;
/** Identifier for checking the OME Java OME-XML library is present. */
public static final int OME_JAVA_XML = 2;
/** Identifier for checking the OME Java OMEDS library is present. */
public static final int OME_JAVA_DS = 3;
/** Identifier for checking the JGoodies Forms library is present. */
public static final int FORMS = 4;
// -- Constructor --
private Checker() { }
// -- Utility methods --
/** Checks whether the given class is available. */
public static boolean checkClass(String className) {
try { Class.forName(className); }
catch (Throwable t) { return false; }
return true;
}
/**
* Checks for a required library.
* @param library One of:<ul>
* <li>BIO_FORMATS</li>
* <li>OME_JAVA_XML</li>
* <li>OME_JAVA_DS</li>
* <li>FORMS</li>
* </ul>
*/
public static void checkLibrary(int library, HashSet missing) {
switch (library) {
case BIO_FORMATS:
checkLibrary("loci.formats.FormatHandler", "bio-formats.jar", missing);
checkLibrary("org.apache.poi.poifs.filesystem.POIFSFileSystem",
"poi-loci.jar", missing);
break;
case OME_JAVA_XML:
- checkLibrary("org.openmicroscopy.xml.OMENode", "ome-java.jar", missing);
+ checkLibrary("ome.xml.OMEXMLNode", "ome-xml.jar", missing);
break;
case OME_JAVA_DS:
checkLibrary("org.openmicroscopy.ds.DataServer",
"ome-java.jar", missing);
checkLibrary("org.apache.xmlrpc.XmlRpcClient",
"xmlrpc-1.2-b1.jar", missing);
checkLibrary("org.apache.commons.httpclient.HttpClient",
"commons-httpclient-2.0-rc2.jar", missing);
checkLibrary("org.apache.commons.logging.Log",
"commons-logging.jar", missing);
break;
case FORMS:
checkLibrary("com.jgoodies.forms.layout.FormLayout",
"forms-1.0.4.jar", missing);
break;
}
}
/**
* Checks whether the given class is available; if not,
* adds the specified JAR file name to the hash set
* (presumably to report it missing to the user).
*/
public static void checkLibrary(String className,
String jarFile, HashSet missing)
{
if (!checkClass(className)) missing.add(jarFile);
}
/** Checks for a new enough version of the Java Runtime Environment. */
public static boolean checkJava() {
String version = System.getProperty("java.version");
double ver = Double.parseDouble(version.substring(0, 3));
if (ver < 1.4) {
IJ.error("LOCI Plugins",
"Sorry, the LOCI plugins require Java 1.4 or later." +
"\nYou can download ImageJ with JRE 5.0 from the ImageJ web site.");
return false;
}
return true;
}
/** Checks whether the version of ImageJ is new enough. */
public static boolean checkImageJ() {
boolean success;
try {
String version = IJ.getVersion();
success = version != null && version.compareTo("1.34") >= 0;
}
catch (NoSuchMethodError err) {
success = false;
}
if (!success) {
IJ.error("LOCI Plugins",
"Sorry, the LOCI plugins require ImageJ v1.34 or later.");
}
return success;
}
/**
* Reports missing libraries in the given hash set to the user.
* @return true iff no libraries are missing (the hash set is empty).
*/
public static boolean checkMissing(HashSet missing) {
int num = missing.size();
if (num == 0) return true;
StringBuffer sb = new StringBuffer();
sb.append("The following librar");
sb.append(num == 1 ? "y was" : "ies were");
sb.append(" not found:");
Iterator iter = missing.iterator();
for (int i=0; i<num; i++) sb.append("\n " + iter.next());
String them = num == 1 ? "it" : "them";
sb.append("\nPlease download ");
sb.append(them);
sb.append(" from the LOCI website at");
sb.append("\n http://www.loci.wisc.edu/software/");
sb.append("\nand place ");
sb.append(them);
sb.append(" in the ImageJ plugins folder.");
IJ.error("LOCI Plugins", sb.toString());
return false;
}
}
| true | true | public static void checkLibrary(int library, HashSet missing) {
switch (library) {
case BIO_FORMATS:
checkLibrary("loci.formats.FormatHandler", "bio-formats.jar", missing);
checkLibrary("org.apache.poi.poifs.filesystem.POIFSFileSystem",
"poi-loci.jar", missing);
break;
case OME_JAVA_XML:
checkLibrary("org.openmicroscopy.xml.OMENode", "ome-java.jar", missing);
break;
case OME_JAVA_DS:
checkLibrary("org.openmicroscopy.ds.DataServer",
"ome-java.jar", missing);
checkLibrary("org.apache.xmlrpc.XmlRpcClient",
"xmlrpc-1.2-b1.jar", missing);
checkLibrary("org.apache.commons.httpclient.HttpClient",
"commons-httpclient-2.0-rc2.jar", missing);
checkLibrary("org.apache.commons.logging.Log",
"commons-logging.jar", missing);
break;
case FORMS:
checkLibrary("com.jgoodies.forms.layout.FormLayout",
"forms-1.0.4.jar", missing);
break;
}
}
| public static void checkLibrary(int library, HashSet missing) {
switch (library) {
case BIO_FORMATS:
checkLibrary("loci.formats.FormatHandler", "bio-formats.jar", missing);
checkLibrary("org.apache.poi.poifs.filesystem.POIFSFileSystem",
"poi-loci.jar", missing);
break;
case OME_JAVA_XML:
checkLibrary("ome.xml.OMEXMLNode", "ome-xml.jar", missing);
break;
case OME_JAVA_DS:
checkLibrary("org.openmicroscopy.ds.DataServer",
"ome-java.jar", missing);
checkLibrary("org.apache.xmlrpc.XmlRpcClient",
"xmlrpc-1.2-b1.jar", missing);
checkLibrary("org.apache.commons.httpclient.HttpClient",
"commons-httpclient-2.0-rc2.jar", missing);
checkLibrary("org.apache.commons.logging.Log",
"commons-logging.jar", missing);
break;
case FORMS:
checkLibrary("com.jgoodies.forms.layout.FormLayout",
"forms-1.0.4.jar", missing);
break;
}
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/CreateAcquisitionPurchaseOrderDocument.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/CreateAcquisitionPurchaseOrderDocument.java
index 4f529e8e..019148b8 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/CreateAcquisitionPurchaseOrderDocument.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/CreateAcquisitionPurchaseOrderDocument.java
@@ -1,217 +1,217 @@
package pt.ist.expenditureTrackingSystem.domain.acquisitions.simplified.activities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import module.finance.domain.SupplierContact;
import module.workflow.activities.ActivityInformation;
import module.workflow.activities.WorkflowActivity;
import myorg._development.PropertiesManager;
import myorg.domain.User;
import myorg.domain.VirtualHost;
import myorg.domain.exceptions.DomainException;
import myorg.domain.util.Address;
import myorg.util.BundleUtil;
import net.sf.jasperreports.engine.JRException;
import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.AcquisitionRequest;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.AcquisitionRequestItem;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.PurchaseOrderDocument;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.RegularAcquisitionProcess;
import pt.ist.expenditureTrackingSystem.util.ReportUtils;
public class CreateAcquisitionPurchaseOrderDocument extends
WorkflowActivity<RegularAcquisitionProcess, CreateAcquisitionPurchaseOrderDocumentInformation> {
private static final String EXTENSION_PDF = "pdf";
@Override
public boolean isActive(RegularAcquisitionProcess process, User user) {
return isUserProcessOwner(process, user)
&& process.getAcquisitionProcessState().isAuthorized()
&& ExpenditureTrackingSystem.isAcquisitionCentralGroupMember(user)
&& process.getRequest().hasSelectedSupplier()
&& process.isCommitted();
}
@Override
protected void process(CreateAcquisitionPurchaseOrderDocumentInformation activityInformation) {
RegularAcquisitionProcess process = activityInformation.getProcess();
String requestID = process.getAcquisitionRequestDocumentID();
byte[] file = createPurchaseOrderDocument(process.getAcquisitionRequest(), requestID, activityInformation.getSupplierContact());
new PurchaseOrderDocument(process, file, requestID + "." + EXTENSION_PDF, requestID);
}
@Override
public ActivityInformation<RegularAcquisitionProcess> getActivityInformation(RegularAcquisitionProcess process) {
return new CreateAcquisitionPurchaseOrderDocumentInformation(process, this);
}
@Override
public String getLocalizedName() {
return BundleUtil.getStringFromResourceBundle(getUsedBundle(), "label." + getClass().getName());
}
@Override
public String getUsedBundle() {
return "resources/AcquisitionResources";
}
@Override
public boolean isConfirmationNeeded(RegularAcquisitionProcess process) {
return !process.getFiles(PurchaseOrderDocument.class).isEmpty();
}
protected byte[] createPurchaseOrderDocument(final AcquisitionRequest acquisitionRequest, final String requestID, final SupplierContact supplierContact) {
final Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("acquisitionRequest", acquisitionRequest);
paramMap.put("supplierContact", supplierContact);
paramMap.put("requestID", requestID);
paramMap.put("responsibleName", getLoggedPerson().getExpenditurePerson().getName());
DeliveryLocalList deliveryLocalList = new DeliveryLocalList();
List<AcquisitionRequestItemBean> acquisitionRequestItemBeans = new ArrayList<AcquisitionRequestItemBean>();
createBeansLists(acquisitionRequest, deliveryLocalList, acquisitionRequestItemBeans);
paramMap.put("deliveryLocals", deliveryLocalList);
paramMap.put("institutionSocialSecurityNumber",
PropertiesManager.getProperty(VirtualHost.getVirtualHostForThread().getHostname() + ".ssn"));
paramMap.put("cae", PropertiesManager.getProperty(VirtualHost.getVirtualHostForThread().getHostname() + ".cae"));
paramMap.put("logoFilename", "Logo_" + VirtualHost.getVirtualHostForThread().getHostname() + ".png");
paramMap.put("commitmentNumbers", acquisitionRequest.getCommitmentNumbers());
final ResourceBundle resourceBundle = ResourceBundle.getBundle("resources/AcquisitionResources");
try {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
- final String documentName = virtualHost.getHostname().equals("dot.ist.utl.pt") || true ?
+ final String documentName = virtualHost.getHostname().equals("dot.ist.utl.pt") ?
"acquisitionRequestDocument" : "acquisitionRequestPurchaseOrder";
byte[] byteArray = ReportUtils.exportToPdfFileAsByteArray(documentName, paramMap,
resourceBundle, acquisitionRequestItemBeans);
return byteArray;
} catch (JRException e) {
e.printStackTrace();
throw new DomainException("acquisitionRequestDocument.message.exception.failedCreation");
}
}
private void createBeansLists(AcquisitionRequest acquisitionRequest, DeliveryLocalList deliveryLocalList,
List<AcquisitionRequestItemBean> acquisitionRequestItemBeans) {
for (AcquisitionRequestItem acquisitionRequestItem : acquisitionRequest.getOrderedRequestItemsSet()) {
DeliveryLocal deliveryLocal = deliveryLocalList.getDeliveryLocal(acquisitionRequestItem.getRecipient(),
acquisitionRequestItem.getRecipientPhone(), acquisitionRequestItem.getRecipientEmail(),
acquisitionRequestItem.getAddress());
acquisitionRequestItemBeans.add(new AcquisitionRequestItemBean(deliveryLocal.getIdentification(),
acquisitionRequestItem));
}
}
public static class AcquisitionRequestItemBean {
private String identification;
private AcquisitionRequestItem acquisitionRequestItem;
public AcquisitionRequestItemBean(String identification, AcquisitionRequestItem acquisitionRequestItem) {
setIdentification(identification);
setAcquisitionRequestItem(acquisitionRequestItem);
}
public String getIdentification() {
return identification;
}
public void setIdentification(String identification) {
this.identification = identification;
}
public void setAcquisitionRequestItem(AcquisitionRequestItem acquisitionRequestItem) {
this.acquisitionRequestItem = acquisitionRequestItem;
}
public AcquisitionRequestItem getAcquisitionRequestItem() {
return acquisitionRequestItem;
}
}
public static class DeliveryLocalList extends ArrayList<DeliveryLocal> {
private char id = 'A';
public DeliveryLocal getDeliveryLocal(String personName, String phone, String email, Address address) {
for (DeliveryLocal deliveryLocal : this) {
if (deliveryLocal.getPersonName().equals(personName) && deliveryLocal.getPhone().equals(phone)
&& deliveryLocal.getEmail().equals(email) && deliveryLocal.getAddress().equals(address)) {
return deliveryLocal;
}
}
DeliveryLocal newDelDeliveryLocal = new DeliveryLocal("" + id, personName, phone, email, address);
id++;
add(newDelDeliveryLocal);
return newDelDeliveryLocal;
}
}
public static class DeliveryLocal {
private String identification;
private String personName;
private String phone;
private String email;
private Address address;
public DeliveryLocal(String identification, String personName, String phone, String email, Address address) {
setIdentification(identification);
setPersonName(personName);
setPhone(phone);
setEmail(email);
setAddress(address);
}
public String getIdentification() {
return identification;
}
public void setIdentification(String identification) {
this.identification = identification;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@Override
public boolean isDefaultInputInterfaceUsed() {
return false;
}
}
| true | true | protected byte[] createPurchaseOrderDocument(final AcquisitionRequest acquisitionRequest, final String requestID, final SupplierContact supplierContact) {
final Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("acquisitionRequest", acquisitionRequest);
paramMap.put("supplierContact", supplierContact);
paramMap.put("requestID", requestID);
paramMap.put("responsibleName", getLoggedPerson().getExpenditurePerson().getName());
DeliveryLocalList deliveryLocalList = new DeliveryLocalList();
List<AcquisitionRequestItemBean> acquisitionRequestItemBeans = new ArrayList<AcquisitionRequestItemBean>();
createBeansLists(acquisitionRequest, deliveryLocalList, acquisitionRequestItemBeans);
paramMap.put("deliveryLocals", deliveryLocalList);
paramMap.put("institutionSocialSecurityNumber",
PropertiesManager.getProperty(VirtualHost.getVirtualHostForThread().getHostname() + ".ssn"));
paramMap.put("cae", PropertiesManager.getProperty(VirtualHost.getVirtualHostForThread().getHostname() + ".cae"));
paramMap.put("logoFilename", "Logo_" + VirtualHost.getVirtualHostForThread().getHostname() + ".png");
paramMap.put("commitmentNumbers", acquisitionRequest.getCommitmentNumbers());
final ResourceBundle resourceBundle = ResourceBundle.getBundle("resources/AcquisitionResources");
try {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
final String documentName = virtualHost.getHostname().equals("dot.ist.utl.pt") || true ?
"acquisitionRequestDocument" : "acquisitionRequestPurchaseOrder";
byte[] byteArray = ReportUtils.exportToPdfFileAsByteArray(documentName, paramMap,
resourceBundle, acquisitionRequestItemBeans);
return byteArray;
} catch (JRException e) {
e.printStackTrace();
throw new DomainException("acquisitionRequestDocument.message.exception.failedCreation");
}
}
| protected byte[] createPurchaseOrderDocument(final AcquisitionRequest acquisitionRequest, final String requestID, final SupplierContact supplierContact) {
final Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("acquisitionRequest", acquisitionRequest);
paramMap.put("supplierContact", supplierContact);
paramMap.put("requestID", requestID);
paramMap.put("responsibleName", getLoggedPerson().getExpenditurePerson().getName());
DeliveryLocalList deliveryLocalList = new DeliveryLocalList();
List<AcquisitionRequestItemBean> acquisitionRequestItemBeans = new ArrayList<AcquisitionRequestItemBean>();
createBeansLists(acquisitionRequest, deliveryLocalList, acquisitionRequestItemBeans);
paramMap.put("deliveryLocals", deliveryLocalList);
paramMap.put("institutionSocialSecurityNumber",
PropertiesManager.getProperty(VirtualHost.getVirtualHostForThread().getHostname() + ".ssn"));
paramMap.put("cae", PropertiesManager.getProperty(VirtualHost.getVirtualHostForThread().getHostname() + ".cae"));
paramMap.put("logoFilename", "Logo_" + VirtualHost.getVirtualHostForThread().getHostname() + ".png");
paramMap.put("commitmentNumbers", acquisitionRequest.getCommitmentNumbers());
final ResourceBundle resourceBundle = ResourceBundle.getBundle("resources/AcquisitionResources");
try {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
final String documentName = virtualHost.getHostname().equals("dot.ist.utl.pt") ?
"acquisitionRequestDocument" : "acquisitionRequestPurchaseOrder";
byte[] byteArray = ReportUtils.exportToPdfFileAsByteArray(documentName, paramMap,
resourceBundle, acquisitionRequestItemBeans);
return byteArray;
} catch (JRException e) {
e.printStackTrace();
throw new DomainException("acquisitionRequestDocument.message.exception.failedCreation");
}
}
|
diff --git a/java/sodium/src/sodium/Event.java b/java/sodium/src/sodium/Event.java
index 0e73a41..b298f7b 100644
--- a/java/sodium/src/sodium/Event.java
+++ b/java/sodium/src/sodium/Event.java
@@ -1,499 +1,502 @@
package sodium;
import java.util.ArrayList;
import java.util.List;
public class Event<A> {
private static final class ListenerImplementation<A> extends Listener {
/**
* It's essential that we keep the listener alive while the caller holds
* the Listener, so that the finalizer doesn't get triggered.
*/
private final Event<A> event;
private final TransactionHandler<A> action;
private final Node target;
private ListenerImplementation(Event<A> event, TransactionHandler<A> action, Node target) {
this.event = event;
this.action = action;
this.target = target;
}
public void unlisten() {
event.listeners.remove(action);
event.node.unlinkTo(target);
}
protected void finalize() throws Throwable {
unlisten();
}
}
protected final ArrayList<TransactionHandler<A>> listeners = new ArrayList<TransactionHandler<A>>();
protected final List<Listener> finalizers = new ArrayList<Listener>();
Node node = new Node(0L);
protected final List<A> firings = new ArrayList<A>();
/**
* An event that never fires.
*/
public Event() {
}
protected Object[] sampleNow() { return null; }
/**
* Listen for firings of this event. The returned Listener has an unlisten()
* method to cause the listener to be removed. This is the observer pattern.
*/
public final Listener listen(final Handler<A> action) {
return listen_(Node.NULL, new TransactionHandler<A>() {
public void run(Transaction trans2, A a) {
action.run(a);
}
});
}
final Listener listen_(final Node target, final TransactionHandler<A> action) {
return Transaction.apply(new Lambda1<Transaction, Listener>() {
public Listener apply(Transaction trans1) {
return listen(target, trans1, action, false);
}
});
}
@SuppressWarnings("unchecked")
final Listener listen(Node target, Transaction trans, TransactionHandler<A> action, boolean suppressEarlierFirings) {
if (node.linkTo(target))
trans.toRegen = true;
Object[] aNow = sampleNow();
if (aNow != null) { // In cases like values(), we start with an initial value.
for (int i = 0; i < aNow.length; i++)
action.run(trans, (A)aNow[i]); // <-- unchecked warning is here
}
listeners.add(action);
if (!suppressEarlierFirings) {
// Anything sent already in this transaction must be sent now so that
// there's no order dependency between send and listen.
for (A a : firings)
action.run(trans, a);
}
return new ListenerImplementation<A>(this, action, target);
}
/**
* Transform the event's value according to the supplied function.
*/
public final <B> Event<B> map(final Lambda1<A,B> f)
{
final Event<A> ev = this;
final EventSink<B> out = new EventSink<B>() {
@SuppressWarnings("unchecked")
@Override
protected Object[] sampleNow()
{
Object[] oi = ev.sampleNow();
if (oi != null) {
Object[] oo = new Object[oi.length];
for (int i = 0; i < oo.length; i++)
oo[i] = f.apply((A)oi[i]);
return oo;
}
else
return null;
}
};
Listener l = listen_(out.node, new TransactionHandler<A>() {
public void run(Transaction trans2, A a) {
out.send(trans2, f.apply(a));
}
});
return out.addCleanup(l);
}
/**
* Create a behavior with the specified initial value, that gets updated
* by the values coming through the event. The 'current value' of the behavior
* is notionally the value as it was 'at the start of the transaction'.
* That is, state updates caused by event firings get processed at the end of
* the transaction.
*/
public final Behavior<A> hold(final A initValue) {
return Transaction.apply(new Lambda1<Transaction, Behavior<A>>() {
public Behavior<A> apply(Transaction trans) {
return new Behavior<A>(lastFiringOnly(trans), initValue);
}
});
}
/**
* Variant of snapshot that throws away the event's value and captures the behavior's.
*/
public final <B> Event<B> snapshot(Behavior<B> beh)
{
return snapshot(beh, new Lambda2<A,B,B>() {
public B apply(A a, B b) {
return b;
}
});
}
/**
* Sample the behavior at the time of the event firing. Note that the 'current value'
* of the behavior that's sampled is the value as at the start of the transaction
* before any state changes of the current transaction are applied through 'hold's.
*/
public final <B,C> Event<C> snapshot(final Behavior<B> b, final Lambda2<A,B,C> f)
{
final Event<A> ev = this;
final EventSink<C> out = new EventSink<C>() {
@SuppressWarnings("unchecked")
@Override
protected Object[] sampleNow()
{
Object[] oi = ev.sampleNow();
if (oi != null) {
Object[] oo = new Object[oi.length];
for (int i = 0; i < oo.length; i++)
oo[i] = f.apply((A)oi[i], b.value);
return oo;
}
else
return null;
}
};
Listener l = listen_(out.node, new TransactionHandler<A>() {
public void run(Transaction trans2, A a) {
out.send(trans2, f.apply(a, b.value));
}
});
return out.addCleanup(l);
}
/**
* Merge two streams of events of the same type.
*
* In the case where two event occurrences are simultaneous (i.e. both
* within the same transaction), both will be delivered in the same
* transaction. If the event firings are ordered for some reason, then
* their ordering is retained. In many common cases the ordering will
* be undefined.
*/
public static <A> Event<A> merge(final Event<A> ea, final Event<A> eb)
{
final EventSink<A> out = new EventSink<A>() {
@Override
protected Object[] sampleNow()
{
Object[] oa = ea.sampleNow();
Object[] ob = eb.sampleNow();
if (oa != null && ob != null) {
Object[] oo = new Object[oa.length + ob.length];
int j = 0;
for (int i = 0; i < oa.length; i++) oo[j++] = oa[i];
for (int i = 0; i < ob.length; i++) oo[j++] = ob[i];
return oo;
}
else
if (oa != null)
return oa;
else
return ob;
}
};
TransactionHandler<A> h = new TransactionHandler<A>() {
public void run(Transaction trans, A a) {
out.send(trans, a);
}
};
Listener l1 = ea.listen_(out.node, h);
Listener l2 = eb.listen_(out.node, h);
return out.addCleanup(l1).addCleanup(l2);
}
/**
* If there's more than one firing in a single transaction, combine them into
* one using the specified combining function.
*
* If the event firings are ordered, then the first will appear at the left
* input of the combining function. In most common cases it's best not to
* make any assumptions about the ordering, and the combining function would
* ideally be commutative.
*/
public final Event<A> coalesce(final Lambda2<A,A,A> f)
{
return Transaction.apply(new Lambda1<Transaction, Event<A>>() {
public Event<A> apply(Transaction trans) {
return coalesce(trans, f);
}
});
}
final Event<A> coalesce(Transaction trans1, final Lambda2<A,A,A> f)
{
final Event<A> ev = this;
final EventSink<A> out = new EventSink<A>() {
@SuppressWarnings("unchecked")
@Override
protected Object[] sampleNow()
{
Object[] oi = ev.sampleNow();
if (oi != null) {
A o = (A)oi[0];
for (int i = 1; i < oi.length; i++)
o = f.apply(o, (A)oi[i]);
return new Object[] { o };
}
else
return null;
}
};
TransactionHandler<A> h = new CoalesceHandler<A>(f, out);
Listener l = listen(out.node, trans1, h, false);
return out.addCleanup(l);
}
/**
* Clean up the output by discarding any firing other than the last one.
*/
final Event<A> lastFiringOnly(Transaction trans)
{
return coalesce(trans, new Lambda2<A,A,A>() {
public A apply(A first, A second) { return second; }
});
}
/**
* Merge two streams of events of the same type, combining simultaneous
* event occurrences.
*
* In the case where multiple event occurrences are simultaneous (i.e. all
* within the same transaction), they are combined using the same logic as
* 'coalesce'.
*/
public static <A> Event<A> mergeWith(Lambda2<A,A,A> f, Event<A> ea, Event<A> eb)
{
return merge(ea, eb).coalesce(f);
}
/**
* Only keep event occurrences for which the predicate returns true.
*/
public final Event<A> filter(final Lambda1<A,Boolean> f)
{
final Event<A> ev = this;
final EventSink<A> out = new EventSink<A>() {
@SuppressWarnings("unchecked")
@Override
protected Object[] sampleNow()
{
Object[] oi = ev.sampleNow();
if (oi != null) {
Object[] oo = new Object[oi.length];
int j = 0;
for (int i = 0; i < oi.length; i++)
if (f.apply((A)oi[i]))
oo[j++] = oi[i];
+ if (j == 0)
+ oo = null;
+ else
if (j < oo.length) {
Object[] oo2 = new Object[j];
for (int i = 0; i < j; i++)
oo2[i] = oo[i];
oo = oo2;
}
return oo;
}
else
return null;
}
};
Listener l = listen_(out.node, new TransactionHandler<A>() {
public void run(Transaction trans2, A a) {
if (f.apply(a)) out.send(trans2, a);
}
});
return out.addCleanup(l);
}
/**
* Filter out any event occurrences whose value is a Java null pointer.
*/
public final Event<A> filterNotNull()
{
return filter(new Lambda1<A,Boolean>() {
public Boolean apply(A a) { return a != null; }
});
}
/**
* Loop an event round so it can effectively be forward referenced.
* This adds a cycle to your graph of relationships between events and behaviors.
*/
public static <A,B> B loop(Lambda1<Event<A>,Tuple2<B,Event<A>>> f)
{
final EventSink<A> ea_in = new EventSink<A>();
Tuple2<B,Event<A>> b_ea = f.apply(ea_in);
B b = b_ea.a;
Event<A> ea_out = b_ea.b;
Listener l = ea_out.listen_(ea_in.node, new TransactionHandler<A>() {
public void run(Transaction trans, A a) {
ea_in.send(trans, a);
}
});
ea_in.addCleanup(l);
return b;
}
/**
* Let event occurrences through only when the behavior's value is True.
* Note that the behavior's value is as it was at the start of the transaction,
* that is, no state changes from the current transaction are taken into account.
*/
public final Event<A> gate(Behavior<Boolean> bPred)
{
return snapshot(bPred, new Lambda2<A,Boolean,A>() {
public A apply(A a, Boolean pred) { return pred ? a : null; }
}).filterNotNull();
}
/**
* Transform an event with a generalized state loop (a mealy machine). The function
* is passed the input and the old state and returns the new state and output value.
*/
public final <B,S> Event<B> collect(final S initState, final Lambda2<A, S, Tuple2<B, S>> f)
{
final Event<A> ea = this;
return Event.loop(
new Lambda1<Event<S>, Tuple2<Event<B>,Event<S>>>() {
public Tuple2<Event<B>,Event<S>> apply(Event<S> es) {
Behavior<S> s = es.hold(initState);
Event<Tuple2<B,S>> ebs = ea.snapshot(s, f);
Event<B> eb = ebs.map(new Lambda1<Tuple2<B,S>,B>() {
public B apply(Tuple2<B,S> bs) { return bs.a; }
});
Event<S> es_out = ebs.map(new Lambda1<Tuple2<B,S>,S>() {
public S apply(Tuple2<B,S> bs) { return bs.b; }
});
return new Tuple2<Event<B>,Event<S>>(eb, es_out);
}
}
);
}
/**
* Accumulate on input event, outputting the new state each time.
*/
public final <S> Event<S> accum(final S initState, final Lambda2<A, S, S> f)
{
final Event<A> ea = this;
return Event.loop(
new Lambda1<Event<S>, Tuple2<Event<S>,Event<S>>>() {
public Tuple2<Event<S>,Event<S>> apply(Event<S> es) {
Behavior<S> s = es.hold(initState);
Event<S> es_out = ea.snapshot(s, f);
return new Tuple2<Event<S>,Event<S>>(es_out, es_out);
}
}
);
}
/**
* Count event occurrences, starting with 1 for the first occurrence.
*/
public final Event<Integer> countE()
{
return map(new Lambda1<A,Integer>() {
public Integer apply(A a) { return 1; }
}).accum(0, new Lambda2<Integer,Integer,Integer>() {
public Integer apply(Integer a, Integer b) { return a+b; }
});
}
/**
* Count event occurrences, giving a behavior that starts with 0 before the first occurrence.
*/
public final Behavior<Integer> count()
{
return countE().hold(0);
}
/**
* Throw away all event occurrences except for the first one.
*/
public final Event<A> once()
{
// This is a bit long-winded but it's efficient because it deregisters
// the listener.
final Event<A> ev = this;
final Listener[] la = new Listener[1];
final EventSink<A> out = new EventSink<A>() {
@Override
protected Object[] sampleNow()
{
Object[] oi = ev.sampleNow();
Object[] oo = oi;
if (oo != null) {
if (oo.length > 1)
oo = new Object[] { oi[0] };
if (la[0] != null) {
la[0].unlisten();
la[0] = null;
}
}
return oo;
}
};
la[0] = ev.listen_(out.node, new TransactionHandler<A>() {
public void run(Transaction trans, A a) {
out.send(trans, a);
if (la[0] != null) {
la[0].unlisten();
la[0] = null;
}
}
});
return out.addCleanup(la[0]);
}
Event<A> addCleanup(Listener cleanup)
{
finalizers.add(cleanup);
return this;
}
@Override
protected void finalize() throws Throwable {
for (Listener l : finalizers)
l.unlisten();
}
}
class CoalesceHandler<A> implements TransactionHandler<A>
{
public CoalesceHandler(Lambda2<A,A,A> f, EventSink<A> out)
{
this.f = f;
this.out = out;
}
private Lambda2<A,A,A> f;
private EventSink<A> out;
private boolean accumValid = false;
private A accum;
@Override
public void run(Transaction trans1, A a) {
if (accumValid)
accum = f.apply(accum, a);
else {
final CoalesceHandler<A> thiz = this;
trans1.prioritized(out.node, new Handler<Transaction>() {
public void run(Transaction trans2) {
out.send(trans2, thiz.accum);
thiz.accumValid = false;
thiz.accum = null;
}
});
accum = a;
accumValid = true;
}
}
}
| true | true | public final Event<A> filter(final Lambda1<A,Boolean> f)
{
final Event<A> ev = this;
final EventSink<A> out = new EventSink<A>() {
@SuppressWarnings("unchecked")
@Override
protected Object[] sampleNow()
{
Object[] oi = ev.sampleNow();
if (oi != null) {
Object[] oo = new Object[oi.length];
int j = 0;
for (int i = 0; i < oi.length; i++)
if (f.apply((A)oi[i]))
oo[j++] = oi[i];
if (j < oo.length) {
Object[] oo2 = new Object[j];
for (int i = 0; i < j; i++)
oo2[i] = oo[i];
oo = oo2;
}
return oo;
}
else
return null;
}
};
Listener l = listen_(out.node, new TransactionHandler<A>() {
public void run(Transaction trans2, A a) {
if (f.apply(a)) out.send(trans2, a);
}
});
return out.addCleanup(l);
}
| public final Event<A> filter(final Lambda1<A,Boolean> f)
{
final Event<A> ev = this;
final EventSink<A> out = new EventSink<A>() {
@SuppressWarnings("unchecked")
@Override
protected Object[] sampleNow()
{
Object[] oi = ev.sampleNow();
if (oi != null) {
Object[] oo = new Object[oi.length];
int j = 0;
for (int i = 0; i < oi.length; i++)
if (f.apply((A)oi[i]))
oo[j++] = oi[i];
if (j == 0)
oo = null;
else
if (j < oo.length) {
Object[] oo2 = new Object[j];
for (int i = 0; i < j; i++)
oo2[i] = oo[i];
oo = oo2;
}
return oo;
}
else
return null;
}
};
Listener l = listen_(out.node, new TransactionHandler<A>() {
public void run(Transaction trans2, A a) {
if (f.apply(a)) out.send(trans2, a);
}
});
return out.addCleanup(l);
}
|
diff --git a/src/main/java/org/swordapp/server/DepositReceipt.java b/src/main/java/org/swordapp/server/DepositReceipt.java
index c5deff4..7161eb2 100644
--- a/src/main/java/org/swordapp/server/DepositReceipt.java
+++ b/src/main/java/org/swordapp/server/DepositReceipt.java
@@ -1,290 +1,290 @@
package org.swordapp.server;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.ExtensibleElement;
import org.apache.abdera.model.Link;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DepositReceipt
{
private List<String> packagingFormats = new ArrayList<String>();
private IRI editIRI = null;
private IRI seIRI = null;
private IRI emIRI = null;
private IRI feedIRI = null;
private IRI location = null;
private Entry entry;
private Map<String, String> statements = new HashMap<String, String>();
private String treatment = "no treatment information available";
private String verboseDescription = null;
private String splashUri = null;
private String originalDepositUri = null;
private String originalDepositType = null;
private Map<String, String> derivedResources = new HashMap<String, String>();
private boolean empty = false;
private Date lastModified = null;
public DepositReceipt()
{
Abdera abdera = new Abdera();
this.entry = abdera.newEntry();
}
public Entry getWrappedEntry()
{
return this.entry;
}
public Entry getAbderaEntry()
{
Entry abderaEntry = (Entry) this.entry.clone();
// use the edit iri as the id
abderaEntry.setId(this.editIRI.toString());
// add the Edit IRI Link
if (this.editIRI != null)
{
abderaEntry.addLink(this.editIRI.toString(), "edit");
}
// add the Sword Edit IRI link
if (this.seIRI != null)
{
abderaEntry.addLink(this.seIRI.toString(), UriRegistry.REL_SWORD_EDIT);
}
// add the atom formatted feed
if (this.feedIRI != null)
{
Link fl = abderaEntry.addLink(this.feedIRI.toString(), "edit-media");
fl.setMimeType("application/atom+xml;type=feed");
}
// add the edit-media link
if (this.emIRI != null)
{
abderaEntry.addLink(this.emIRI.toString(), "edit-media");
}
// add the packaging formats
for (String pf : this.packagingFormats)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_PACKAGING, pf);
}
// add the statement URIs
for (String statement : this.statements.keySet())
{
Link link = abderaEntry.addLink(statement, UriRegistry.REL_STATEMENT);
link.setMimeType(this.statements.get(statement));
}
if (this.treatment != null)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_TREATMENT, this.treatment);
}
if (this.verboseDescription != null)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_VERBOSE_DESCRIPTION, this.verboseDescription);
}
- if (this.splashUri == null)
+ if (this.splashUri != null)
{
abderaEntry.addLink(this.splashUri, "alternate");
}
if (this.originalDepositUri != null)
{
Link link = abderaEntry.addLink(this.originalDepositUri, UriRegistry.REL_ORIGINAL_DEPOSIT);
if (this.originalDepositType != null)
{
link.setMimeType(this.originalDepositType);
}
}
for (String uri : this.derivedResources.keySet())
{
Link link = abderaEntry.addLink(uri, UriRegistry.REL_DERIVED_RESOURCE);
if (this.derivedResources.get(uri) != null)
{
link.setMimeType(this.derivedResources.get(uri));
}
}
return abderaEntry;
}
public Date getLastModified()
{
return lastModified;
}
public void setLastModified(Date lastModified)
{
this.lastModified = lastModified;
}
public boolean isEmpty()
{
return empty;
}
public void setEmpty(boolean empty)
{
this.empty = empty;
}
public void setMediaFeedIRI(IRI feedIRI)
{
this.feedIRI = feedIRI;
}
public void setEditMediaIRI(IRI emIRI)
{
this.emIRI = emIRI;
}
public void setEditIRI(IRI editIRI)
{
this.editIRI = editIRI;
// set the SE-IRI as the same if it has not already been set
if (this.seIRI == null)
{
this.seIRI = editIRI;
}
}
public IRI getLocation()
{
return this.location == null ? this.editIRI : this.location;
}
public void setLocation(IRI location)
{
this.location = location;
}
public IRI getEditIRI()
{
return this.editIRI;
}
public IRI getSwordEditIRI()
{
return this.seIRI;
}
public void setSwordEditIRI(IRI seIRI)
{
this.seIRI = seIRI;
// set the Edit-IRI the same if it has not already been set
if (this.editIRI == null)
{
this.editIRI = seIRI;
}
}
public void setContent(IRI href, String mediaType)
{
this.entry.setContent(href, mediaType);
}
public void addEditMediaIRI(IRI href)
{
this.entry.addLink(href.toString(), "edit-media");
}
public void addEditMediaIRI(IRI href, String mediaType)
{
Abdera abdera = new Abdera();
Link link = abdera.getFactory().newLink();
link.setHref(href.toString());
link.setRel("edit-media");
link.setMimeType(mediaType);
this.entry.addLink(link);
}
public void addEditMediaFeedIRI(IRI href)
{
this.addEditMediaIRI(href, "application/atom+xml;type=feed");
}
public void setPackaging(List<String> packagingFormats)
{
this.packagingFormats = packagingFormats;
}
public void addPackaging(String packagingFormat)
{
this.packagingFormats.add(packagingFormat);
}
public void setOREStatementURI(String statement)
{
this.setStatementURI("application/rdf+xml", statement);
}
public void setAtomStatementURI(String statement)
{
this.setStatementURI("application/atom+xml;type=feed", statement);
}
public void setStatementURI(String type, String statement)
{
this.statements.put(statement, type);
}
public Element addSimpleExtension(QName qname, String value)
{
return this.entry.addSimpleExtension(qname, value);
}
public Element addDublinCore(String element, String value)
{
return this.entry.addSimpleExtension(new QName(UriRegistry.DC_NAMESPACE, element), value);
}
public void setTreatment(String treatment)
{
this.treatment = treatment;
}
public void setVerboseDescription(String verboseDescription)
{
this.verboseDescription = verboseDescription;
}
public void setSplashUri(String splashUri)
{
this.splashUri = splashUri;
}
public void setOriginalDeposit(String originalDepositUri, String originalDepositType)
{
this.originalDepositUri = originalDepositUri;
this.originalDepositType = originalDepositType;
}
public void setDerivedResources(Map<String, String> derivedResources)
{
this.derivedResources = derivedResources;
}
public void addDerivedResource(String resourceUri, String resourceType)
{
this.derivedResources.put(resourceUri, resourceType);
}
}
| true | true | public Entry getAbderaEntry()
{
Entry abderaEntry = (Entry) this.entry.clone();
// use the edit iri as the id
abderaEntry.setId(this.editIRI.toString());
// add the Edit IRI Link
if (this.editIRI != null)
{
abderaEntry.addLink(this.editIRI.toString(), "edit");
}
// add the Sword Edit IRI link
if (this.seIRI != null)
{
abderaEntry.addLink(this.seIRI.toString(), UriRegistry.REL_SWORD_EDIT);
}
// add the atom formatted feed
if (this.feedIRI != null)
{
Link fl = abderaEntry.addLink(this.feedIRI.toString(), "edit-media");
fl.setMimeType("application/atom+xml;type=feed");
}
// add the edit-media link
if (this.emIRI != null)
{
abderaEntry.addLink(this.emIRI.toString(), "edit-media");
}
// add the packaging formats
for (String pf : this.packagingFormats)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_PACKAGING, pf);
}
// add the statement URIs
for (String statement : this.statements.keySet())
{
Link link = abderaEntry.addLink(statement, UriRegistry.REL_STATEMENT);
link.setMimeType(this.statements.get(statement));
}
if (this.treatment != null)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_TREATMENT, this.treatment);
}
if (this.verboseDescription != null)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_VERBOSE_DESCRIPTION, this.verboseDescription);
}
if (this.splashUri == null)
{
abderaEntry.addLink(this.splashUri, "alternate");
}
if (this.originalDepositUri != null)
{
Link link = abderaEntry.addLink(this.originalDepositUri, UriRegistry.REL_ORIGINAL_DEPOSIT);
if (this.originalDepositType != null)
{
link.setMimeType(this.originalDepositType);
}
}
for (String uri : this.derivedResources.keySet())
{
Link link = abderaEntry.addLink(uri, UriRegistry.REL_DERIVED_RESOURCE);
if (this.derivedResources.get(uri) != null)
{
link.setMimeType(this.derivedResources.get(uri));
}
}
return abderaEntry;
}
| public Entry getAbderaEntry()
{
Entry abderaEntry = (Entry) this.entry.clone();
// use the edit iri as the id
abderaEntry.setId(this.editIRI.toString());
// add the Edit IRI Link
if (this.editIRI != null)
{
abderaEntry.addLink(this.editIRI.toString(), "edit");
}
// add the Sword Edit IRI link
if (this.seIRI != null)
{
abderaEntry.addLink(this.seIRI.toString(), UriRegistry.REL_SWORD_EDIT);
}
// add the atom formatted feed
if (this.feedIRI != null)
{
Link fl = abderaEntry.addLink(this.feedIRI.toString(), "edit-media");
fl.setMimeType("application/atom+xml;type=feed");
}
// add the edit-media link
if (this.emIRI != null)
{
abderaEntry.addLink(this.emIRI.toString(), "edit-media");
}
// add the packaging formats
for (String pf : this.packagingFormats)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_PACKAGING, pf);
}
// add the statement URIs
for (String statement : this.statements.keySet())
{
Link link = abderaEntry.addLink(statement, UriRegistry.REL_STATEMENT);
link.setMimeType(this.statements.get(statement));
}
if (this.treatment != null)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_TREATMENT, this.treatment);
}
if (this.verboseDescription != null)
{
abderaEntry.addSimpleExtension(UriRegistry.SWORD_VERBOSE_DESCRIPTION, this.verboseDescription);
}
if (this.splashUri != null)
{
abderaEntry.addLink(this.splashUri, "alternate");
}
if (this.originalDepositUri != null)
{
Link link = abderaEntry.addLink(this.originalDepositUri, UriRegistry.REL_ORIGINAL_DEPOSIT);
if (this.originalDepositType != null)
{
link.setMimeType(this.originalDepositType);
}
}
for (String uri : this.derivedResources.keySet())
{
Link link = abderaEntry.addLink(uri, UriRegistry.REL_DERIVED_RESOURCE);
if (this.derivedResources.get(uri) != null)
{
link.setMimeType(this.derivedResources.get(uri));
}
}
return abderaEntry;
}
|
diff --git a/src/com/podevs/android/pokemononline/NetworkService.java b/src/com/podevs/android/pokemononline/NetworkService.java
index 90c09b53..d2bc2e4c 100644
--- a/src/com/podevs/android/pokemononline/NetworkService.java
+++ b/src/com/podevs/android/pokemononline/NetworkService.java
@@ -1,1300 +1,1304 @@
package com.podevs.android.pokemononline;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.Html;
import android.util.Log;
import android.widget.Toast;
import com.podevs.android.pokemononline.battle.Battle;
import com.podevs.android.pokemononline.battle.BattleActivity;
import com.podevs.android.pokemononline.battle.BattleConf;
import com.podevs.android.pokemononline.battle.BattleDesc;
import com.podevs.android.pokemononline.battle.ChallengeEnums;
import com.podevs.android.pokemononline.battle.SpectatingBattle;
import com.podevs.android.pokemononline.chat.Channel;
import com.podevs.android.pokemononline.chat.ChatActivity;
import com.podevs.android.pokemononline.player.FullPlayerInfo;
import com.podevs.android.pokemononline.player.PlayerInfo;
import com.podevs.android.pokemononline.pms.PrivateMessageActivity;
import com.podevs.android.pokemononline.pms.PrivateMessageList;
import com.podevs.android.pokemononline.poke.ShallowBattlePoke;
import com.podevs.android.utilities.Bais;
import com.podevs.android.utilities.Baos;
import com.podevs.android.utilities.StringUtilities;
public class NetworkService extends Service {
static final String TAG = "Network Service";
final static String pkgName = "com.podevs.android.pokemononline";
final static String defaultKey = "default chan for ";
private final IBinder binder = new LocalBinder();
//public Channel currentChannel = null;
public LinkedList<Channel> joinedChannels = new LinkedList<Channel>();
Thread sThread, rThread;
volatile public PokeClientSocket socket = null;
public boolean findingBattle = false;
public boolean registered = false;
public ChatActivity chatActivity = null;
public LinkedList<IncomingChallenge> challenges = new LinkedList<IncomingChallenge>();
public boolean askedForPass = false;
private String salt = null;
public boolean failedConnect = false;
private boolean reconnectDenied = false;
public DataBaseHelper db;
public String serverName = "Not Connected";
private volatile boolean halted = false;
public final ProtocolVersion version = new ProtocolVersion();
public boolean serverSupportsZipCompression = false;
private byte reconnectSecret[] = null;
/**
* Are we engaged in a battle?
* @return True if we are at least in one battle
*/
public boolean isBattling() {
return !activeBattles.isEmpty();
}
/**
* Are we engaged in a battle with that particular battle ID?
* @param battleId the battle ID
* @return true if we are a player of the battle with the battle ID
*/
public boolean isBattling(int battleId) {
return activeBattles.containsKey(battleId);
}
private Battle activeBattle(int battleId) {
return activeBattles.get(battleId);
}
public FullPlayerInfo meLoginPlayer;
public Hashtable<Integer, Battle> activeBattles = new Hashtable<Integer, Battle>();
public Hashtable<Integer, SpectatingBattle> spectatedBattles = new Hashtable<Integer, SpectatingBattle>();
public Tier superTier = new Tier();
public int myid = -1;
public PlayerInfo me = new PlayerInfo();
public Hashtable<Integer, Channel> channels = new Hashtable<Integer, Channel>();
public Hashtable<Integer, PlayerInfo> players = new Hashtable<Integer, PlayerInfo>();
public Hashtable<Integer, BattleDesc> battles = new Hashtable<Integer, BattleDesc>();
static public HashSet<Integer> pmedPlayers = new HashSet<Integer>();
public PrivateMessageList pms = new PrivateMessageList(me);
public class LocalBinder extends Binder {
public NetworkService getService() {
return NetworkService.this;
}
}
/**
* Is the player in any of the same channels as us?
* @param pid the id of the player we are interested in
* @return true if the player shares a channel with us, false otherwise
*/
public boolean isOnAnyChannel(int pid) {
for (Channel c: channels.values()) {
if (c.players.containsKey(pid)) {
return true;
}
}
return false;
}
/**
* Called by a channel when a player leaves. If the player is not on any channel
* and there's no special circumstances (as in PM), the player will get removed
* @param pid The id of the player that left
*/
public void onPlayerLeaveChannel(int pid) {
if (!isOnAnyChannel(pid) && !pmedPlayers.contains(pid)) {
removePlayer(pid);
}
}
public void addBattle(int battleid, BattleDesc desc) {
battles.put(battleid, desc);
if (players.containsKey(desc.p1)) {
players.get(desc.p1).addBattle(battleid);
}
if (players.containsKey(desc.p2)) {
players.get(desc.p2).addBattle(battleid);
}
}
/**
* Removes a battle from memory
* @param battleID the battle id of the battle to remove
*/
private void removeBattle(int battleID) {
if (!battles.containsKey(battleID)) {
return;
}
BattleDesc battle = battles.get(battleID);
if (hasPlayer(battle.p1)) {
players.get(battle.p1).removeBattle(battleID);
}
if (hasPlayer(battle.p2)) {
players.get(battle.p2).removeBattle(battleID);
}
}
/**
* Returns a list of all the battles fought or spectated
* @return the battles fought/spectated
*/
public Collection<SpectatingBattle> getBattles() {
LinkedList<SpectatingBattle> ret = new LinkedList<SpectatingBattle>();
ret.addAll(activeBattles.values());
ret.addAll(spectatedBattles.values());
return ret;
}
/**
* Checks all battles spectated or fought and removes/destroys the ones
* that are finished
*/
public void checkBattlesToEnd() {
for (SpectatingBattle battle: getBattles()) {
if (battle.gotEnd) {
closeBattle(battle.bID);
}
}
}
/**
* Removes a battle spectated/fought from memory and destroys it
* @param bID The id of the battle to remove
*/
public void closeBattle(int bID) {
if (isBattling(bID)) {
activeBattles.remove(bID).destroy();
}
if (spectatedBattles.containsKey(bID)) {
spectatedBattles.remove(bID).destroy();
}
/* Remove the battle notification */
NotificationManager mNotificationManager = getNotificationManager();
mNotificationManager.cancel("battle", bID);
}
/**
* Does the player exist in memory
* @param pid the id of the player we're interested in
* @return true if the player is in memory, or false
*/
public boolean hasPlayer(int pid) {
return players.containsKey(pid);
}
public boolean hasChannel(int cid) {
return channels.containsKey(cid);
}
/**
* Checks if the players of the battle are online, and remove the battle from memory if not
* @param battleid the id of the battle to check
*/
private void testRemoveBattle(Integer battleid) {
BattleDesc battle = battles.get(battleid);
if (battle != null) {
if (!players.containsKey(battle.p1) && !players.containsKey(battle.p2)) {
battles.remove(battle);
}
}
}
/**
* Gets the name of a player or "???" if the player couldn't be found
* @param playerId id of the player we're interested in
* @return name of the player or "???" if not found
*/
public String playerName(int playerId) {
PlayerInfo player = players.get(playerId);
if (player == null) {
return "???";
} else {
return player.nick();
}
}
public int playerAuth(int playerId) {
PlayerInfo player = players.get(playerId);
if (player == null) {
return 0;
} else {
return player.auth;
}
}
/**
* Removes a player from memory
* @param pid The id of the player to remove
*/
public void removePlayer(int pid) {
PlayerInfo player = players.remove(pid);
if (pmedPlayers.contains(pid)) {
//TODO: close the PM?
pmedPlayers.remove(pid);
}
if (player != null) {
for(Integer battleid: player.battles) {
testRemoveBattle(battleid);
}
}
}
@Override
// This is *NOT* called every time someone binds to us, I don't really know why
// but onServiceConnected is correctly called in the activity sooo....
public IBinder onBind(Intent intent) {
return binder;
}
@Override
// This is called once
public void onCreate() {
db = new DataBaseHelper(NetworkService.this);
super.onCreate();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Chat - Pokemon Online")
.setContentText("Pokemon Online is running")
.setOngoing(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ChatActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP + Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT));
startForeground(R.id.networkService, mBuilder.build());
}
@Override
public void onDestroy() {
// XXX TODO be more graceful
Log.d(TAG, "NETWORK SERVICE DESTROYED; EXPECT BAD THINGS TO HAPPEN");
for(SpectatingBattle battle : getBattles()) {
closeBattle(battle.bID);
}
stopForeground(true);
halted = true;
}
private String ip;
private int port;
public void connect(String ip, int port) {
this.ip = ip;
this.port = port;
// XXX This should probably have a timeout
new Thread(new Runnable() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void run() {
try {
socket = new PokeClientSocket(NetworkService.this.ip, NetworkService.this.port);
} catch (IOException e) {
failedConnect = true;
if(chatActivity != null) {
chatActivity.notifyFailedConnection();
}
return;
}
//socket.sendMessage(meLoginPlayer.serializeBytes(), Command.Login);
Baos loginCmd = new Baos();
loginCmd.putBaos(version); //Protocol version
String defaultChannel = null;
Set<String> autoJoinChannels = null;
SharedPreferences prefs = getSharedPreferences("autoJoinChannels", MODE_PRIVATE);
String key = NetworkService.this.ip + ":" + NetworkService.this.port;
if (prefs.contains(key)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
autoJoinChannels = prefs.getStringSet(key, null);
}
}
defaultChannel = prefs.getString(defaultKey+key, null);
/* Network Flags: hasClientType, hasVersionNumber, hasReconnect, hasDefaultChannel, hasAdditionalChannels,
* hasColor, hasTrainerInfo, hasNewTeam, hasEventSpecification, hasPluginList. */
loginCmd.putFlags(new boolean []{true,true,true,defaultChannel != null, autoJoinChannels != null,
meLoginPlayer.color().isValid(), true, meLoginPlayer.team.isValid()}); //Network flags
loginCmd.putString("android");
short versionCode;
try {
versionCode = (short)getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
} catch (NameNotFoundException e1) {
versionCode = 0;
}
loginCmd.putShort(versionCode);
loginCmd.putString(meLoginPlayer.nick());
/* Data Flags: supportsZipCompression, isLadderEnabled, wantsIdsWithMessages, isIdle */
loginCmd.putFlags(new boolean []{false,true,true,getSharedPreferences("clientOptions", MODE_PRIVATE).getBoolean("idle", false)});
/* Reconnect even if all the bits are different */
loginCmd.write(0);
if (defaultChannel != null) {
loginCmd.putString(defaultChannel);
}
if (autoJoinChannels != null) {
Object channels [] = autoJoinChannels.toArray();
loginCmd.putInt(channels.length);
for (int i = 0; i < channels.length; i++) {
loginCmd.putString(channels[i].toString());
}
}
if (meLoginPlayer.color().isValid()) {
loginCmd.putBaos(meLoginPlayer.color());
}
loginCmd.putBaos(meLoginPlayer.profile.trainerInfo);
if (meLoginPlayer.team.isValid()) {
loginCmd.write(1); // number of teams
loginCmd.putBaos(meLoginPlayer.team);
}
socket.sendMessage(loginCmd, Command.Login);
do {
readSocketMessages(socket);
if (halted) {
return;
}
writeMessage("(" + StringUtilities.timeStamp() + ") Disconnected from server");
reconnect();
} while (!reconnectDenied && !halted);
}
}).start();
}
private void reconnect() {
/* Impossible to reconnect with -1 id */
if (myid == -1 || reconnectSecret == null) {
reconnectDenied = true;
return;
}
while (!halted) {
try {
socket = new PokeClientSocket(NetworkService.this.ip, NetworkService.this.port);
} catch (IOException e) {
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
continue;
}
Baos msgToSend = new Baos();
msgToSend.putInt(me.id);
msgToSend.putBytes(reconnectSecret);
socket.sendMessage(msgToSend, Command.Reconnect);
return;
}
}
private void readSocketMessages(PokeClientSocket socket) {
while(!halted && socket.isConnected()) {
try {
// Get some data from the wire
socket.recvMessagePoll();
} catch (IOException e) {
// Disconnected
break;
} catch (ParseException e) {
// Got message that overflowed length from server.
// No way to recover.
// TODO die completely
break;
}
Baos tmp;
// Handle any messages that completed
while ((tmp = socket.getMsg()) != null) {
Bais msg = new Bais(tmp.toByteArray());
handleMsg(msg);
}
/* Do not use too much CPU */
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Bundle bundle = null;
if (intent != null) // Intent can be null if service restarts after being killed
// XXX We probably don't handle such restarts very gracefully
bundle = intent.getExtras();
if (bundle != null && bundle.containsKey("loginPlayer")) {
meLoginPlayer = new FullPlayerInfo(new Bais(bundle.getByteArray("loginPlayer")));
me.setTo(new PlayerInfo (meLoginPlayer));
}
if (bundle != null && bundle.containsKey("ip"))
connect(bundle.getString("ip"), bundle.getShort("port"));
return START_STICKY;
}
public void handleMsg(Bais msg) {
byte i = msg.readByte();
if (i < 0 || i >= Command.values().length) {
Log.w(TAG, "Command out of bounds: " +i);
}
Command c = Command.values()[i];
//Log.d(TAG, "Received: " + c);
switch (c) {
case ChannelPlayers:
case JoinChannel:
case LeaveChannel:{
Channel ch = channels.get(msg.readInt());
if(ch != null) {
ch.handleChannelMsg(c, msg);
} else {
Log.e(TAG, "Received message for nonexistent channel");
}
break;
} case VersionControl: {
ProtocolVersion serverVersion = new ProtocolVersion(msg);
if (serverVersion.compareTo(version) > 0) {
Log.d(TAG, "Server has newer protocol version than we expect");
} else if (serverVersion.compareTo(version) < 0) {
Log.d(TAG, "PO Android uses newer protocol than Server");
}
serverSupportsZipCompression = msg.readBool();
ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg);
ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg);
ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg);
if (serverVersion.compareTo(version) > 0) {
if (lastVersionWithoutFeatures.compareTo(version) > 0) {
Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show();
} else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) {
Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show();
} else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) {
Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show();
}
}
serverName = msg.readString();
if (chatActivity != null) {
chatActivity.updateTitle();
}
break;
} case Register: {
// Username not registered
break;
} case Login: {
reconnectDenied = false;
Bais flags = msg.readFlags();
Boolean hasReconnPass = flags.readBool();
if (hasReconnPass) {
reconnectSecret = msg.readQByteArray();
} else {
reconnectSecret = null;
}
me.setTo(new PlayerInfo(msg));
myid = me.id;
int numTiers = msg.readInt();
for (int j = 0; j < numTiers; j++) {
// Tiers for each of our teams
// TODO Do something with this info?
msg.readString();
}
players.put(myid, me);
break;
} case TierSelection: {
msg.readInt(); // Number of tiers
Tier prevTier = new Tier(msg.readByte(), msg.readString());
prevTier.parentTier = superTier;
superTier.subTiers.add(prevTier);
while(msg.available() != 0) { // While there's another tier available
Tier t = new Tier(msg.readByte(), msg.readString());
if(t.level == prevTier.level) { // Sibling case
prevTier.parentTier.addSubTier(t);
t.parentTier = prevTier.parentTier;
}
else if(t.level < prevTier.level) { // Uncle case
while(t.level < prevTier.level)
prevTier = prevTier.parentTier;
prevTier.parentTier.addSubTier(t);
t.parentTier = prevTier.parentTier;
}
else if(t.level > prevTier.level) { // Child case
prevTier.addSubTier(t);
t.parentTier = prevTier;
}
prevTier = t;
}
break;
} case ChannelsList: {
int numChannels = msg.readInt();
for(int j = 0; j < numChannels; j++) {
int chanId = msg.readInt();
if (hasChannel(chanId)) {
Channel ch = channels.get(chanId);
ch.name = msg.readString();
} else {
Channel ch = new Channel(chanId, msg.readString(), this);
channels.put(chanId, ch);
}
//addChannel(msg.readQString(),chanId);
}
Log.d(TAG, channels.toString());
break;
} case PlayersList: {
while (msg.available() != 0) { // While there's playerInfo's available
PlayerInfo p = new PlayerInfo(msg);
PlayerInfo oldPlayer = players.get(p.id);
players.put(p.id, p);
if (oldPlayer != null) {
p.battles = oldPlayer.battles;
if (chatActivity != null) {
/* Updates the player in the adapter memory */
chatActivity.updatePlayer(p, oldPlayer);
}
}
/* Updates self player */
if (p.id == myid) {
me.setTo(p);
}
}
break;
} case OptionsChanged: {
int id = msg.readInt();
Bais dataFlags = msg.readFlags();
PlayerInfo p = players.get(id);
if (p != null) {
p.hasLadderEnabled = dataFlags.readBool();
p.isAway = dataFlags.readBool();
if (p.id == myid) {
me.setTo(p);
}
}
break;
} case SendMessage: {
Bais netFlags = msg.readFlags();
boolean hasChannel = netFlags.readBool();
boolean hasId = netFlags.readBool();
Bais dataFlags = msg.readFlags();
boolean isHtml = dataFlags.readBool();
Channel chan = null;
PlayerInfo player = null;
int pId = 0;
if (hasChannel) {
chan = channels.get(msg.readInt());
}
if (hasId) {
player = players.get(pId = msg.readInt());
}
CharSequence message = msg.readString();
if (hasId) {
CharSequence color = (player == null ? "orange" : player.color.toHexString());
CharSequence name = playerName(pId);
String beg = "<font color='" + color + "'><b>";
if (playerAuth(pId) > 0 && playerAuth(pId) < 4) {
beg += "+<i>" + name + ": </i></b></font>";
} else {
beg += name + ": </b></font>";
}
if (isHtml) {
message = Html.fromHtml(beg + message);
} else {
message = Html.fromHtml(beg + StringUtilities.escapeHtml((String)message));
}
} else {
if (isHtml) {
message = Html.fromHtml((String)message);
} else {
String str = StringUtilities.escapeHtml((String)message);
int index = str.indexOf(':');
if (str.startsWith("*** ")) {
message = Html.fromHtml("<font color='#FF00FF'>" + str + "</font>");
} else if (index != -1) {
String firstPart = str.substring(0, index);
String secondPart;
try {
secondPart = str.substring(index+2);
} catch (IndexOutOfBoundsException ex) {
secondPart = "";
}
CharSequence color = "#318739";
if (firstPart.equals("Welcome Message")) {
color = "blue";
} else if (firstPart.equals("~~Server~~")) {
color = "orange";
}
message = Html.fromHtml("<font color='" + color + "'><b>" + firstPart +
": </b></font>" + secondPart);
}
}
}
if (!hasChannel) {
// Broadcast message
if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent?
chatActivity.makeToast(message.toString(), "long");
else {
Iterator<Channel> it = joinedChannels.iterator();
while (it.hasNext()) {
it.next().writeToHist(message);
}
}
} else {
if (chan == null) {
Log.e(TAG, "Received message for nonexistent channel");
} else {
chan.writeToHist(message);
}
}
break;
}
case BattleList: {
msg.readInt(); //channel, but irrelevant
int numBattles = msg.readInt();
for (; numBattles > 0; numBattles--) {
int battleId = msg.readInt();
//byte mode = msg.readByte(); /* protocol is messed up */
int player1 = msg.readInt();
int player2 = msg.readInt();
addBattle(battleId, new BattleDesc(player1, player2));
}
break;
}
case ChannelBattle: {
msg.readInt(); //channel, but irrelevant
int battleId = msg.readInt();
//byte mode = msg.readByte();
int player1 = msg.readInt();
int player2 = msg.readInt();
addBattle(battleId, new BattleDesc(player1, player2));
break;
} case ChallengeStuff: {
IncomingChallenge challenge = new IncomingChallenge(msg);
challenge.setNick(players.get(challenge.opponent));
+ if (challenge.desc < 0 || challenge.desc >= ChallengeEnums.ChallengeDesc.values().length) {
+ Log.w(TAG, "Challenge description out of bounds: " + challenge.desc);
+ break;
+ }
switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) {
case Sent:
if (challenge.isValidChallenge(players)) {
challenges.addFirst(challenge);
if (chatActivity != null && chatActivity.hasWindowFocus()) {
chatActivity.notifyChallenge();
} else {
Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis());
note.setLatestEventInfo(this, "Pokemon Online", "You've been challenged!", PendingIntent.getActivity(this, 0,
new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK));
getNotificationManager().notify(IncomingChallenge.note, note);
}
}
break;
case Refused:
if(challenge.oppName != null && chatActivity != null) {
chatActivity.makeToast(challenge.oppName + " refused your challenge", "short");
}
break;
case Busy:
if(challenge.oppName != null && chatActivity != null) {
chatActivity.makeToast(challenge.oppName + " is busy", "short");
}
break;
case InvalidTeam:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid team", "long");
break;
case InvalidGen:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid gen", "long");
break;
case InvalidTier:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid tier", "long");
break;
}
break;
} case Reconnect: {
boolean success = msg.readBool();
if (success) {
reconnectDenied = false;
writeMessage("(" + StringUtilities.timeStamp() + ") Reconnected to server");
for (Channel ch: joinedChannels) {
ch.clearData();
}
joinedChannels.clear();
} else {
reconnectDenied = true;
}
break;
} case Logout: {
// Only sent when player is in a PM with you and logs out
int playerID = msg.readInt();
removePlayer(playerID);
//System.out.println("Player " + playerID + " logged out.");
break;
} case BattleFinished: {
int battleID = msg.readInt();
byte battleDesc = msg.readByte();
msg.readByte(); // battle mode
int id1 = msg.readInt();
int id2 = msg.readInt();
//Log.i(TAG, "bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2);
String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "};
if (isBattling(battleID) || spectatedBattles.containsKey(battleID)) {
if (isBattling(battleID)) {
//TODO: notification on win/lose
// if (mePlayer.id == id1 && battleDesc < 2) {
// showNotification(ChatActivity.class, "Chat", "You won!");
// } else if (mePlayer.id == id2 && battleDesc < 2) {
// showNotification(ChatActivity.class, "Chat", "You lost!");
// } else if (battleDesc == 2) {
// showNotification(ChatActivity.class, "Chat", "You tied!");
// }
}
if (battleDesc < 2) {
joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" +
StringUtilities.escapeHtml(playerName(id1)) + outcome[battleDesc] +
StringUtilities.escapeHtml(playerName(id2)) + ".</b></i>"));
}
if (battleDesc == 0 || battleDesc == 3) {
closeBattle(battleID);
}
}
removeBattle(battleID);
break;
} case SendPM: {
int playerId = msg.readInt();
String message = msg.readString();
dealWithPM(playerId, message);
break;
}/* case SendTeam: {
PlayerInfo p = new PlayerInfo(msg);
if (players.containsKey(p.id)) {
PlayerInfo player = players.get(p.id);
player.update(p);
Enumeration<Channel> e = channels.elements();
while (e.hasMoreElements()) {
Channel ch = e.nextElement();
if (ch.players.containsKey(player.id)) {
ch.updatePlayer(player);
}
}
}
break;
} */ case BattleMessage: {
int battleId = msg.readInt(); // currently support only one battle, unneeded
msg.readInt(); // discard the size, unneeded
if (isBattling(battleId)) {
activeBattle(battleId).receiveCommand(msg);
}
break;
} case EngageBattle: {
int battleId = msg.readInt();
Bais flags = msg.readFlags();
byte mode = msg.readByte();
int p1 = msg.readInt();
int p2 = msg.readInt();
addBattle(battleId, new BattleDesc(p1, p2, mode));
if(flags.readBool()) { // This is us!
BattleConf conf = new BattleConf(msg);
// Start the battle
Battle battle = new Battle(conf, msg, getNonNullPlayer(conf.id(0)),
getNonNullPlayer(conf.id(1)), myid, battleId, this);
activeBattles.put(battleId, battle);
joinedChannels.peek().writeToHist("Battle between " + playerName(p1) +
" and " + playerName(p2) + " started!");
Intent intent;
intent = new Intent(this, BattleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("battleId", battleId);
startActivity(intent);
findingBattle = false;
showBattleNotification("Battle", battleId, conf);
}
if (chatActivity != null) {
chatActivity.updatePlayer(players.get(p1), players.get(p1));
chatActivity.updatePlayer(players.get(p2), players.get(p2));
}
break;
}
case SpectateBattle: {
Bais flags = msg.readFlags();
int battleId = msg.readInt();
if (flags.readBool()) {
if (spectatedBattles.contains(battleId)) {
Log.e(TAG, "Already watching battle " + battleId);
return;
}
BattleConf conf = new BattleConf(msg);
PlayerInfo p1 = getNonNullPlayer(conf.id(0));
PlayerInfo p2 = getNonNullPlayer(conf.id(1));
SpectatingBattle battle = new SpectatingBattle(conf, p1, p2, battleId, this);
spectatedBattles.put(battleId, battle);
Intent intent = new Intent(this, BattleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("battleId", battleId);
startActivity(intent);
showBattleNotification("Spectated Battle", battleId, conf);
} else {
closeBattle(battleId);
}
break;
}
case SpectateBattleMessage: {
int battleId = msg.readInt();
msg.readInt(); // discard the size, unneeded
if (spectatedBattles.containsKey(battleId)) {
spectatedBattles.get(battleId).receiveCommand(msg);
}
break;
}
case AskForPass: {
salt = msg.readString();
// XXX not sure what the second half is supposed to check
// from analyze.cpp : 265 of PO's code
if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7)
System.out.println("Protocol Error: The server requires insecure authentication");
break;
}
askedForPass = true;
if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) {
chatActivity.notifyAskForPass();
}
break;
} case AddChannel: {
addChannel(msg.readString(),msg.readInt());
break;
} case RemoveChannel: {
int chanId = msg.readInt();
if (chatActivity != null)
chatActivity.removeChannel(channels.get(chanId));
channels.remove(chanId);
break;
} case ChanNameChange: {
int chanId = msg.readInt();
if (chatActivity != null)
chatActivity.removeChannel(channels.get(chanId));
channels.remove(chanId);
channels.put(chanId, new Channel(chanId, msg.readString(), this));
break;
} default: {
System.out.println("Unimplented message");
}
}
for(SpectatingBattle battle : getBattles()) {
if (battle.activity != null && battle.histDelta.length() != 0) {
battle.activity.updateBattleInfo(false);
}
}
if (chatActivity != null && chatActivity.currentChannel() != null)
chatActivity.updateChat();
}
private void writeMessage(String s) {
if (chatActivity != null && chatActivity.currentChannel() != null) {
chatActivity.currentChannel().writeToHist("\n"+s);
chatActivity.updateChat();
} else if (joinedChannels.size() > 0) {
for (Channel c: joinedChannels) {
c.writeToHist("\n"+s);
}
}
}
private PlayerInfo getNonNullPlayer(int id) {
PlayerInfo p = players.get(id);
if (p == null) {
p = new PlayerInfo();
p.nick = "???";
p.id = id;
}
return p;
}
/**
* Creates a PM window with the other guy
* @param playerId the other guy's id
*/
public void createPM(int playerId) {
pms.createPM(players.get(playerId));
}
private void dealWithPM(int playerId, String message) {
pmedPlayers.add(playerId);
createPM(playerId);
pms.newMessage(players.get(playerId), message);
showPMNotification(playerId);
}
private void showPMNotification(int playerId) {
PlayerInfo p = players.get(playerId);
if (p == null) {
p = new PlayerInfo();
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_action_mail)
.setContentTitle("PM - Pokemon Online")
.setContentText("New message from " + p.nick())
.setOngoing(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, PrivateMessageActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
resultIntent.putExtra("playerId", playerId);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ChatActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
//PendingIntent resultPendingIntent = PendingIntent.getActivity(this, battleId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = getNotificationManager();
// mId allows you to update the notification later on.
mNotificationManager.notify("pm", 0, mBuilder.build());
}
private void showBattleNotification(String title, int battleId, BattleConf conf) {
PlayerInfo p1 = getNonNullPlayer(conf.id(0));
PlayerInfo p2 = getNonNullPlayer(conf.id(1));
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(p1.nick() + " vs " + p2.nick())
.setOngoing(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, BattleActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
resultIntent.putExtra("battleId", battleId);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ChatActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
battleId,
PendingIntent.FLAG_UPDATE_CURRENT
);
//PendingIntent resultPendingIntent = PendingIntent.getActivity(this, battleId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = getNotificationManager();
// mId allows you to update the notification later on.
mNotificationManager.notify("battle", battleId, mBuilder.build());
}
NotificationManager getNotificationManager() {
return (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
public void sendPass(String s) {
getSharedPreferences("passwords", MODE_PRIVATE).edit().putString(salt, s).commit();
askedForPass = false;
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
Baos hashPass = new Baos();
hashPass.putBytes(md5.digest(mashBytes(toHex(md5.digest(s.getBytes("ISO-8859-1"))).getBytes("ISO-8859-1"), salt.getBytes("ISO-8859-1"))));
socket.sendMessage(hashPass, Command.AskForPass);
} catch (NoSuchAlgorithmException nsae) {
} catch (UnsupportedEncodingException uee) {
}
}
private byte[] mashBytes(final byte[] a, final byte[] b) {
byte[] ret = new byte[a.length + b.length];
System.arraycopy(a, 0, ret, 0, a.length);
System.arraycopy(b, 0, ret, a.length, b.length);
return ret;
}
private String toHex(byte[] b) {
String ret = new BigInteger(1, b).toString(16);
while (ret.length() < 32)
ret = "0" + ret;
return ret;
}
protected void addChannel(String chanName, int chanId) {
Channel c = new Channel(chanId, chanName, this);
channels.put(chanId, c);
if(chatActivity != null)
chatActivity.addChannel(c);
}
public void playCry(final SpectatingBattle battle, ShallowBattlePoke poke) {
final int ringMode = ((AudioManager)getSystemService(Context.AUDIO_SERVICE)).getRingerMode();
/* Don't ring if in silent mode */
if (ringMode == AudioManager.RINGER_MODE_NORMAL) {
new Thread(new CryPlayer(poke, battle)).start();
} else if (ringMode == AudioManager.RINGER_MODE_VIBRATE) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 700 milliseconds
v.vibrate(700);
}
/* In other cases, the cry's end will call notify on its own */
if (ringMode != AudioManager.RINGER_MODE_NORMAL) {
/* Can't notify right away, would be before the wait */
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(ringMode == AudioManager.RINGER_MODE_VIBRATE ? 1000 : 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (battle) {
battle.notify();
}
}
});
}
}
class CryPlayer implements Runnable {
ShallowBattlePoke poke;
SpectatingBattle battle;
public CryPlayer(ShallowBattlePoke poke, SpectatingBattle battle) {
this.poke = poke;
this.battle = battle;
}
public void run() {
int resID = getResources().getIdentifier("p" + poke.uID.pokeNum,
"raw", pkgName);
if (resID != 0) {
MediaPlayer cryPlayer = MediaPlayer.create(NetworkService.this, resID);
cryPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
synchronized (mp) {
mp.notify();
}
}
});
synchronized (cryPlayer) {
cryPlayer.start();
try {
cryPlayer.wait(5000);
} catch (InterruptedException e) {}
}
cryPlayer.release();
synchronized (battle) {
battle.notify();
}
cryPlayer = null;
}
}
}
public void disconnect() {
if (socket != null && socket.isConnected()) {
halted = true;
socket.close();
}
this.stopForeground(true);
this.stopSelf();
}
public PlayerInfo getPlayerByName(String playerName) {
Enumeration<Integer> e = players.keys();
while(e.hasMoreElements()) {
PlayerInfo info = players.get(e.nextElement());
if (info.nick().equals(playerName))
return info;
}
return null;
}
public BattleDesc battle(Integer battleid) {
return battles.get(battleid);
}
/**
* Tells the server we're not spectating a battle anymore, and close the appropriate
* spectating window
* @param bID the battle we're not watching anymore
*/
public void stopWatching(int bID) {
socket.sendMessage(new Baos().putInt(bID).putBool(false), Command.SpectateBattle);
closeBattle(bID);
}
/**
* Sends a private message to a user
* @param id Id of the user dest
* @param message message to send
*/
public void sendPM(int id, String message) {
Baos bb = new Baos();
bb.putInt(id);
bb.putString(message);
socket.sendMessage(bb, Command.SendPM);
pmedPlayers.add(id);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void updateJoinedChannels() {
if (chatActivity != null) {
chatActivity.populateUI(true);
chatActivity.progressDialog.dismiss();
}
SharedPreferences prefs = getSharedPreferences("autoJoinChannels", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
String key = this.ip + ":" + this.port;
if (joinedChannels.size() == 1 && joinedChannels.getFirst().id == 0) {
/* Only joined default channel! */
edit.remove(key).remove(defaultKey+key);
} else {
boolean hasDefault = false;
HashSet<String> autoJoin = new HashSet<String>();
for (Channel chan : joinedChannels) {
if (chan.id == 0) {
hasDefault = true;
} else {
autoJoin.add(chan.name);
}
}
if (hasDefault) {
edit.remove(defaultKey+key);
} else {
String firstChan = joinedChannels.getFirst().name;
autoJoin.remove(firstChan);
edit.putString(defaultKey+key, firstChan);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
edit.putStringSet(key, autoJoin);
}
}
edit.commit();
}
public String getDefaultPass() {
return getSharedPreferences("passwords", MODE_PRIVATE).getString(salt, "");
}
}
| true | true | public void handleMsg(Bais msg) {
byte i = msg.readByte();
if (i < 0 || i >= Command.values().length) {
Log.w(TAG, "Command out of bounds: " +i);
}
Command c = Command.values()[i];
//Log.d(TAG, "Received: " + c);
switch (c) {
case ChannelPlayers:
case JoinChannel:
case LeaveChannel:{
Channel ch = channels.get(msg.readInt());
if(ch != null) {
ch.handleChannelMsg(c, msg);
} else {
Log.e(TAG, "Received message for nonexistent channel");
}
break;
} case VersionControl: {
ProtocolVersion serverVersion = new ProtocolVersion(msg);
if (serverVersion.compareTo(version) > 0) {
Log.d(TAG, "Server has newer protocol version than we expect");
} else if (serverVersion.compareTo(version) < 0) {
Log.d(TAG, "PO Android uses newer protocol than Server");
}
serverSupportsZipCompression = msg.readBool();
ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg);
ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg);
ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg);
if (serverVersion.compareTo(version) > 0) {
if (lastVersionWithoutFeatures.compareTo(version) > 0) {
Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show();
} else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) {
Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show();
} else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) {
Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show();
}
}
serverName = msg.readString();
if (chatActivity != null) {
chatActivity.updateTitle();
}
break;
} case Register: {
// Username not registered
break;
} case Login: {
reconnectDenied = false;
Bais flags = msg.readFlags();
Boolean hasReconnPass = flags.readBool();
if (hasReconnPass) {
reconnectSecret = msg.readQByteArray();
} else {
reconnectSecret = null;
}
me.setTo(new PlayerInfo(msg));
myid = me.id;
int numTiers = msg.readInt();
for (int j = 0; j < numTiers; j++) {
// Tiers for each of our teams
// TODO Do something with this info?
msg.readString();
}
players.put(myid, me);
break;
} case TierSelection: {
msg.readInt(); // Number of tiers
Tier prevTier = new Tier(msg.readByte(), msg.readString());
prevTier.parentTier = superTier;
superTier.subTiers.add(prevTier);
while(msg.available() != 0) { // While there's another tier available
Tier t = new Tier(msg.readByte(), msg.readString());
if(t.level == prevTier.level) { // Sibling case
prevTier.parentTier.addSubTier(t);
t.parentTier = prevTier.parentTier;
}
else if(t.level < prevTier.level) { // Uncle case
while(t.level < prevTier.level)
prevTier = prevTier.parentTier;
prevTier.parentTier.addSubTier(t);
t.parentTier = prevTier.parentTier;
}
else if(t.level > prevTier.level) { // Child case
prevTier.addSubTier(t);
t.parentTier = prevTier;
}
prevTier = t;
}
break;
} case ChannelsList: {
int numChannels = msg.readInt();
for(int j = 0; j < numChannels; j++) {
int chanId = msg.readInt();
if (hasChannel(chanId)) {
Channel ch = channels.get(chanId);
ch.name = msg.readString();
} else {
Channel ch = new Channel(chanId, msg.readString(), this);
channels.put(chanId, ch);
}
//addChannel(msg.readQString(),chanId);
}
Log.d(TAG, channels.toString());
break;
} case PlayersList: {
while (msg.available() != 0) { // While there's playerInfo's available
PlayerInfo p = new PlayerInfo(msg);
PlayerInfo oldPlayer = players.get(p.id);
players.put(p.id, p);
if (oldPlayer != null) {
p.battles = oldPlayer.battles;
if (chatActivity != null) {
/* Updates the player in the adapter memory */
chatActivity.updatePlayer(p, oldPlayer);
}
}
/* Updates self player */
if (p.id == myid) {
me.setTo(p);
}
}
break;
} case OptionsChanged: {
int id = msg.readInt();
Bais dataFlags = msg.readFlags();
PlayerInfo p = players.get(id);
if (p != null) {
p.hasLadderEnabled = dataFlags.readBool();
p.isAway = dataFlags.readBool();
if (p.id == myid) {
me.setTo(p);
}
}
break;
} case SendMessage: {
Bais netFlags = msg.readFlags();
boolean hasChannel = netFlags.readBool();
boolean hasId = netFlags.readBool();
Bais dataFlags = msg.readFlags();
boolean isHtml = dataFlags.readBool();
Channel chan = null;
PlayerInfo player = null;
int pId = 0;
if (hasChannel) {
chan = channels.get(msg.readInt());
}
if (hasId) {
player = players.get(pId = msg.readInt());
}
CharSequence message = msg.readString();
if (hasId) {
CharSequence color = (player == null ? "orange" : player.color.toHexString());
CharSequence name = playerName(pId);
String beg = "<font color='" + color + "'><b>";
if (playerAuth(pId) > 0 && playerAuth(pId) < 4) {
beg += "+<i>" + name + ": </i></b></font>";
} else {
beg += name + ": </b></font>";
}
if (isHtml) {
message = Html.fromHtml(beg + message);
} else {
message = Html.fromHtml(beg + StringUtilities.escapeHtml((String)message));
}
} else {
if (isHtml) {
message = Html.fromHtml((String)message);
} else {
String str = StringUtilities.escapeHtml((String)message);
int index = str.indexOf(':');
if (str.startsWith("*** ")) {
message = Html.fromHtml("<font color='#FF00FF'>" + str + "</font>");
} else if (index != -1) {
String firstPart = str.substring(0, index);
String secondPart;
try {
secondPart = str.substring(index+2);
} catch (IndexOutOfBoundsException ex) {
secondPart = "";
}
CharSequence color = "#318739";
if (firstPart.equals("Welcome Message")) {
color = "blue";
} else if (firstPart.equals("~~Server~~")) {
color = "orange";
}
message = Html.fromHtml("<font color='" + color + "'><b>" + firstPart +
": </b></font>" + secondPart);
}
}
}
if (!hasChannel) {
// Broadcast message
if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent?
chatActivity.makeToast(message.toString(), "long");
else {
Iterator<Channel> it = joinedChannels.iterator();
while (it.hasNext()) {
it.next().writeToHist(message);
}
}
} else {
if (chan == null) {
Log.e(TAG, "Received message for nonexistent channel");
} else {
chan.writeToHist(message);
}
}
break;
}
case BattleList: {
msg.readInt(); //channel, but irrelevant
int numBattles = msg.readInt();
for (; numBattles > 0; numBattles--) {
int battleId = msg.readInt();
//byte mode = msg.readByte(); /* protocol is messed up */
int player1 = msg.readInt();
int player2 = msg.readInt();
addBattle(battleId, new BattleDesc(player1, player2));
}
break;
}
case ChannelBattle: {
msg.readInt(); //channel, but irrelevant
int battleId = msg.readInt();
//byte mode = msg.readByte();
int player1 = msg.readInt();
int player2 = msg.readInt();
addBattle(battleId, new BattleDesc(player1, player2));
break;
} case ChallengeStuff: {
IncomingChallenge challenge = new IncomingChallenge(msg);
challenge.setNick(players.get(challenge.opponent));
switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) {
case Sent:
if (challenge.isValidChallenge(players)) {
challenges.addFirst(challenge);
if (chatActivity != null && chatActivity.hasWindowFocus()) {
chatActivity.notifyChallenge();
} else {
Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis());
note.setLatestEventInfo(this, "Pokemon Online", "You've been challenged!", PendingIntent.getActivity(this, 0,
new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK));
getNotificationManager().notify(IncomingChallenge.note, note);
}
}
break;
case Refused:
if(challenge.oppName != null && chatActivity != null) {
chatActivity.makeToast(challenge.oppName + " refused your challenge", "short");
}
break;
case Busy:
if(challenge.oppName != null && chatActivity != null) {
chatActivity.makeToast(challenge.oppName + " is busy", "short");
}
break;
case InvalidTeam:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid team", "long");
break;
case InvalidGen:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid gen", "long");
break;
case InvalidTier:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid tier", "long");
break;
}
break;
} case Reconnect: {
boolean success = msg.readBool();
if (success) {
reconnectDenied = false;
writeMessage("(" + StringUtilities.timeStamp() + ") Reconnected to server");
for (Channel ch: joinedChannels) {
ch.clearData();
}
joinedChannels.clear();
} else {
reconnectDenied = true;
}
break;
} case Logout: {
// Only sent when player is in a PM with you and logs out
int playerID = msg.readInt();
removePlayer(playerID);
//System.out.println("Player " + playerID + " logged out.");
break;
} case BattleFinished: {
int battleID = msg.readInt();
byte battleDesc = msg.readByte();
msg.readByte(); // battle mode
int id1 = msg.readInt();
int id2 = msg.readInt();
//Log.i(TAG, "bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2);
String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "};
if (isBattling(battleID) || spectatedBattles.containsKey(battleID)) {
if (isBattling(battleID)) {
//TODO: notification on win/lose
// if (mePlayer.id == id1 && battleDesc < 2) {
// showNotification(ChatActivity.class, "Chat", "You won!");
// } else if (mePlayer.id == id2 && battleDesc < 2) {
// showNotification(ChatActivity.class, "Chat", "You lost!");
// } else if (battleDesc == 2) {
// showNotification(ChatActivity.class, "Chat", "You tied!");
// }
}
if (battleDesc < 2) {
joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" +
StringUtilities.escapeHtml(playerName(id1)) + outcome[battleDesc] +
StringUtilities.escapeHtml(playerName(id2)) + ".</b></i>"));
}
if (battleDesc == 0 || battleDesc == 3) {
closeBattle(battleID);
}
}
removeBattle(battleID);
break;
} case SendPM: {
int playerId = msg.readInt();
String message = msg.readString();
dealWithPM(playerId, message);
break;
}/* case SendTeam: {
PlayerInfo p = new PlayerInfo(msg);
if (players.containsKey(p.id)) {
PlayerInfo player = players.get(p.id);
player.update(p);
Enumeration<Channel> e = channels.elements();
while (e.hasMoreElements()) {
Channel ch = e.nextElement();
if (ch.players.containsKey(player.id)) {
ch.updatePlayer(player);
}
}
}
break;
} */ case BattleMessage: {
int battleId = msg.readInt(); // currently support only one battle, unneeded
msg.readInt(); // discard the size, unneeded
if (isBattling(battleId)) {
activeBattle(battleId).receiveCommand(msg);
}
break;
} case EngageBattle: {
int battleId = msg.readInt();
Bais flags = msg.readFlags();
byte mode = msg.readByte();
int p1 = msg.readInt();
int p2 = msg.readInt();
addBattle(battleId, new BattleDesc(p1, p2, mode));
if(flags.readBool()) { // This is us!
BattleConf conf = new BattleConf(msg);
// Start the battle
Battle battle = new Battle(conf, msg, getNonNullPlayer(conf.id(0)),
getNonNullPlayer(conf.id(1)), myid, battleId, this);
activeBattles.put(battleId, battle);
joinedChannels.peek().writeToHist("Battle between " + playerName(p1) +
" and " + playerName(p2) + " started!");
Intent intent;
intent = new Intent(this, BattleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("battleId", battleId);
startActivity(intent);
findingBattle = false;
showBattleNotification("Battle", battleId, conf);
}
if (chatActivity != null) {
chatActivity.updatePlayer(players.get(p1), players.get(p1));
chatActivity.updatePlayer(players.get(p2), players.get(p2));
}
break;
}
case SpectateBattle: {
Bais flags = msg.readFlags();
int battleId = msg.readInt();
if (flags.readBool()) {
if (spectatedBattles.contains(battleId)) {
Log.e(TAG, "Already watching battle " + battleId);
return;
}
BattleConf conf = new BattleConf(msg);
PlayerInfo p1 = getNonNullPlayer(conf.id(0));
PlayerInfo p2 = getNonNullPlayer(conf.id(1));
SpectatingBattle battle = new SpectatingBattle(conf, p1, p2, battleId, this);
spectatedBattles.put(battleId, battle);
Intent intent = new Intent(this, BattleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("battleId", battleId);
startActivity(intent);
showBattleNotification("Spectated Battle", battleId, conf);
} else {
closeBattle(battleId);
}
break;
}
case SpectateBattleMessage: {
int battleId = msg.readInt();
msg.readInt(); // discard the size, unneeded
if (spectatedBattles.containsKey(battleId)) {
spectatedBattles.get(battleId).receiveCommand(msg);
}
break;
}
case AskForPass: {
salt = msg.readString();
// XXX not sure what the second half is supposed to check
// from analyze.cpp : 265 of PO's code
if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7)
System.out.println("Protocol Error: The server requires insecure authentication");
break;
}
askedForPass = true;
if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) {
chatActivity.notifyAskForPass();
}
break;
} case AddChannel: {
addChannel(msg.readString(),msg.readInt());
break;
} case RemoveChannel: {
int chanId = msg.readInt();
if (chatActivity != null)
chatActivity.removeChannel(channels.get(chanId));
channels.remove(chanId);
break;
} case ChanNameChange: {
int chanId = msg.readInt();
if (chatActivity != null)
chatActivity.removeChannel(channels.get(chanId));
channels.remove(chanId);
channels.put(chanId, new Channel(chanId, msg.readString(), this));
break;
} default: {
System.out.println("Unimplented message");
}
}
for(SpectatingBattle battle : getBattles()) {
if (battle.activity != null && battle.histDelta.length() != 0) {
battle.activity.updateBattleInfo(false);
}
}
if (chatActivity != null && chatActivity.currentChannel() != null)
chatActivity.updateChat();
}
| public void handleMsg(Bais msg) {
byte i = msg.readByte();
if (i < 0 || i >= Command.values().length) {
Log.w(TAG, "Command out of bounds: " +i);
}
Command c = Command.values()[i];
//Log.d(TAG, "Received: " + c);
switch (c) {
case ChannelPlayers:
case JoinChannel:
case LeaveChannel:{
Channel ch = channels.get(msg.readInt());
if(ch != null) {
ch.handleChannelMsg(c, msg);
} else {
Log.e(TAG, "Received message for nonexistent channel");
}
break;
} case VersionControl: {
ProtocolVersion serverVersion = new ProtocolVersion(msg);
if (serverVersion.compareTo(version) > 0) {
Log.d(TAG, "Server has newer protocol version than we expect");
} else if (serverVersion.compareTo(version) < 0) {
Log.d(TAG, "PO Android uses newer protocol than Server");
}
serverSupportsZipCompression = msg.readBool();
ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg);
ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg);
ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg);
if (serverVersion.compareTo(version) > 0) {
if (lastVersionWithoutFeatures.compareTo(version) > 0) {
Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show();
} else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) {
Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show();
} else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) {
Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show();
}
}
serverName = msg.readString();
if (chatActivity != null) {
chatActivity.updateTitle();
}
break;
} case Register: {
// Username not registered
break;
} case Login: {
reconnectDenied = false;
Bais flags = msg.readFlags();
Boolean hasReconnPass = flags.readBool();
if (hasReconnPass) {
reconnectSecret = msg.readQByteArray();
} else {
reconnectSecret = null;
}
me.setTo(new PlayerInfo(msg));
myid = me.id;
int numTiers = msg.readInt();
for (int j = 0; j < numTiers; j++) {
// Tiers for each of our teams
// TODO Do something with this info?
msg.readString();
}
players.put(myid, me);
break;
} case TierSelection: {
msg.readInt(); // Number of tiers
Tier prevTier = new Tier(msg.readByte(), msg.readString());
prevTier.parentTier = superTier;
superTier.subTiers.add(prevTier);
while(msg.available() != 0) { // While there's another tier available
Tier t = new Tier(msg.readByte(), msg.readString());
if(t.level == prevTier.level) { // Sibling case
prevTier.parentTier.addSubTier(t);
t.parentTier = prevTier.parentTier;
}
else if(t.level < prevTier.level) { // Uncle case
while(t.level < prevTier.level)
prevTier = prevTier.parentTier;
prevTier.parentTier.addSubTier(t);
t.parentTier = prevTier.parentTier;
}
else if(t.level > prevTier.level) { // Child case
prevTier.addSubTier(t);
t.parentTier = prevTier;
}
prevTier = t;
}
break;
} case ChannelsList: {
int numChannels = msg.readInt();
for(int j = 0; j < numChannels; j++) {
int chanId = msg.readInt();
if (hasChannel(chanId)) {
Channel ch = channels.get(chanId);
ch.name = msg.readString();
} else {
Channel ch = new Channel(chanId, msg.readString(), this);
channels.put(chanId, ch);
}
//addChannel(msg.readQString(),chanId);
}
Log.d(TAG, channels.toString());
break;
} case PlayersList: {
while (msg.available() != 0) { // While there's playerInfo's available
PlayerInfo p = new PlayerInfo(msg);
PlayerInfo oldPlayer = players.get(p.id);
players.put(p.id, p);
if (oldPlayer != null) {
p.battles = oldPlayer.battles;
if (chatActivity != null) {
/* Updates the player in the adapter memory */
chatActivity.updatePlayer(p, oldPlayer);
}
}
/* Updates self player */
if (p.id == myid) {
me.setTo(p);
}
}
break;
} case OptionsChanged: {
int id = msg.readInt();
Bais dataFlags = msg.readFlags();
PlayerInfo p = players.get(id);
if (p != null) {
p.hasLadderEnabled = dataFlags.readBool();
p.isAway = dataFlags.readBool();
if (p.id == myid) {
me.setTo(p);
}
}
break;
} case SendMessage: {
Bais netFlags = msg.readFlags();
boolean hasChannel = netFlags.readBool();
boolean hasId = netFlags.readBool();
Bais dataFlags = msg.readFlags();
boolean isHtml = dataFlags.readBool();
Channel chan = null;
PlayerInfo player = null;
int pId = 0;
if (hasChannel) {
chan = channels.get(msg.readInt());
}
if (hasId) {
player = players.get(pId = msg.readInt());
}
CharSequence message = msg.readString();
if (hasId) {
CharSequence color = (player == null ? "orange" : player.color.toHexString());
CharSequence name = playerName(pId);
String beg = "<font color='" + color + "'><b>";
if (playerAuth(pId) > 0 && playerAuth(pId) < 4) {
beg += "+<i>" + name + ": </i></b></font>";
} else {
beg += name + ": </b></font>";
}
if (isHtml) {
message = Html.fromHtml(beg + message);
} else {
message = Html.fromHtml(beg + StringUtilities.escapeHtml((String)message));
}
} else {
if (isHtml) {
message = Html.fromHtml((String)message);
} else {
String str = StringUtilities.escapeHtml((String)message);
int index = str.indexOf(':');
if (str.startsWith("*** ")) {
message = Html.fromHtml("<font color='#FF00FF'>" + str + "</font>");
} else if (index != -1) {
String firstPart = str.substring(0, index);
String secondPart;
try {
secondPart = str.substring(index+2);
} catch (IndexOutOfBoundsException ex) {
secondPart = "";
}
CharSequence color = "#318739";
if (firstPart.equals("Welcome Message")) {
color = "blue";
} else if (firstPart.equals("~~Server~~")) {
color = "orange";
}
message = Html.fromHtml("<font color='" + color + "'><b>" + firstPart +
": </b></font>" + secondPart);
}
}
}
if (!hasChannel) {
// Broadcast message
if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent?
chatActivity.makeToast(message.toString(), "long");
else {
Iterator<Channel> it = joinedChannels.iterator();
while (it.hasNext()) {
it.next().writeToHist(message);
}
}
} else {
if (chan == null) {
Log.e(TAG, "Received message for nonexistent channel");
} else {
chan.writeToHist(message);
}
}
break;
}
case BattleList: {
msg.readInt(); //channel, but irrelevant
int numBattles = msg.readInt();
for (; numBattles > 0; numBattles--) {
int battleId = msg.readInt();
//byte mode = msg.readByte(); /* protocol is messed up */
int player1 = msg.readInt();
int player2 = msg.readInt();
addBattle(battleId, new BattleDesc(player1, player2));
}
break;
}
case ChannelBattle: {
msg.readInt(); //channel, but irrelevant
int battleId = msg.readInt();
//byte mode = msg.readByte();
int player1 = msg.readInt();
int player2 = msg.readInt();
addBattle(battleId, new BattleDesc(player1, player2));
break;
} case ChallengeStuff: {
IncomingChallenge challenge = new IncomingChallenge(msg);
challenge.setNick(players.get(challenge.opponent));
if (challenge.desc < 0 || challenge.desc >= ChallengeEnums.ChallengeDesc.values().length) {
Log.w(TAG, "Challenge description out of bounds: " + challenge.desc);
break;
}
switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) {
case Sent:
if (challenge.isValidChallenge(players)) {
challenges.addFirst(challenge);
if (chatActivity != null && chatActivity.hasWindowFocus()) {
chatActivity.notifyChallenge();
} else {
Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis());
note.setLatestEventInfo(this, "Pokemon Online", "You've been challenged!", PendingIntent.getActivity(this, 0,
new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK));
getNotificationManager().notify(IncomingChallenge.note, note);
}
}
break;
case Refused:
if(challenge.oppName != null && chatActivity != null) {
chatActivity.makeToast(challenge.oppName + " refused your challenge", "short");
}
break;
case Busy:
if(challenge.oppName != null && chatActivity != null) {
chatActivity.makeToast(challenge.oppName + " is busy", "short");
}
break;
case InvalidTeam:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid team", "long");
break;
case InvalidGen:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid gen", "long");
break;
case InvalidTier:
if (chatActivity != null)
chatActivity.makeToast("Challenge failed due to invalid tier", "long");
break;
}
break;
} case Reconnect: {
boolean success = msg.readBool();
if (success) {
reconnectDenied = false;
writeMessage("(" + StringUtilities.timeStamp() + ") Reconnected to server");
for (Channel ch: joinedChannels) {
ch.clearData();
}
joinedChannels.clear();
} else {
reconnectDenied = true;
}
break;
} case Logout: {
// Only sent when player is in a PM with you and logs out
int playerID = msg.readInt();
removePlayer(playerID);
//System.out.println("Player " + playerID + " logged out.");
break;
} case BattleFinished: {
int battleID = msg.readInt();
byte battleDesc = msg.readByte();
msg.readByte(); // battle mode
int id1 = msg.readInt();
int id2 = msg.readInt();
//Log.i(TAG, "bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2);
String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "};
if (isBattling(battleID) || spectatedBattles.containsKey(battleID)) {
if (isBattling(battleID)) {
//TODO: notification on win/lose
// if (mePlayer.id == id1 && battleDesc < 2) {
// showNotification(ChatActivity.class, "Chat", "You won!");
// } else if (mePlayer.id == id2 && battleDesc < 2) {
// showNotification(ChatActivity.class, "Chat", "You lost!");
// } else if (battleDesc == 2) {
// showNotification(ChatActivity.class, "Chat", "You tied!");
// }
}
if (battleDesc < 2) {
joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" +
StringUtilities.escapeHtml(playerName(id1)) + outcome[battleDesc] +
StringUtilities.escapeHtml(playerName(id2)) + ".</b></i>"));
}
if (battleDesc == 0 || battleDesc == 3) {
closeBattle(battleID);
}
}
removeBattle(battleID);
break;
} case SendPM: {
int playerId = msg.readInt();
String message = msg.readString();
dealWithPM(playerId, message);
break;
}/* case SendTeam: {
PlayerInfo p = new PlayerInfo(msg);
if (players.containsKey(p.id)) {
PlayerInfo player = players.get(p.id);
player.update(p);
Enumeration<Channel> e = channels.elements();
while (e.hasMoreElements()) {
Channel ch = e.nextElement();
if (ch.players.containsKey(player.id)) {
ch.updatePlayer(player);
}
}
}
break;
} */ case BattleMessage: {
int battleId = msg.readInt(); // currently support only one battle, unneeded
msg.readInt(); // discard the size, unneeded
if (isBattling(battleId)) {
activeBattle(battleId).receiveCommand(msg);
}
break;
} case EngageBattle: {
int battleId = msg.readInt();
Bais flags = msg.readFlags();
byte mode = msg.readByte();
int p1 = msg.readInt();
int p2 = msg.readInt();
addBattle(battleId, new BattleDesc(p1, p2, mode));
if(flags.readBool()) { // This is us!
BattleConf conf = new BattleConf(msg);
// Start the battle
Battle battle = new Battle(conf, msg, getNonNullPlayer(conf.id(0)),
getNonNullPlayer(conf.id(1)), myid, battleId, this);
activeBattles.put(battleId, battle);
joinedChannels.peek().writeToHist("Battle between " + playerName(p1) +
" and " + playerName(p2) + " started!");
Intent intent;
intent = new Intent(this, BattleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("battleId", battleId);
startActivity(intent);
findingBattle = false;
showBattleNotification("Battle", battleId, conf);
}
if (chatActivity != null) {
chatActivity.updatePlayer(players.get(p1), players.get(p1));
chatActivity.updatePlayer(players.get(p2), players.get(p2));
}
break;
}
case SpectateBattle: {
Bais flags = msg.readFlags();
int battleId = msg.readInt();
if (flags.readBool()) {
if (spectatedBattles.contains(battleId)) {
Log.e(TAG, "Already watching battle " + battleId);
return;
}
BattleConf conf = new BattleConf(msg);
PlayerInfo p1 = getNonNullPlayer(conf.id(0));
PlayerInfo p2 = getNonNullPlayer(conf.id(1));
SpectatingBattle battle = new SpectatingBattle(conf, p1, p2, battleId, this);
spectatedBattles.put(battleId, battle);
Intent intent = new Intent(this, BattleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("battleId", battleId);
startActivity(intent);
showBattleNotification("Spectated Battle", battleId, conf);
} else {
closeBattle(battleId);
}
break;
}
case SpectateBattleMessage: {
int battleId = msg.readInt();
msg.readInt(); // discard the size, unneeded
if (spectatedBattles.containsKey(battleId)) {
spectatedBattles.get(battleId).receiveCommand(msg);
}
break;
}
case AskForPass: {
salt = msg.readString();
// XXX not sure what the second half is supposed to check
// from analyze.cpp : 265 of PO's code
if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7)
System.out.println("Protocol Error: The server requires insecure authentication");
break;
}
askedForPass = true;
if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) {
chatActivity.notifyAskForPass();
}
break;
} case AddChannel: {
addChannel(msg.readString(),msg.readInt());
break;
} case RemoveChannel: {
int chanId = msg.readInt();
if (chatActivity != null)
chatActivity.removeChannel(channels.get(chanId));
channels.remove(chanId);
break;
} case ChanNameChange: {
int chanId = msg.readInt();
if (chatActivity != null)
chatActivity.removeChannel(channels.get(chanId));
channels.remove(chanId);
channels.put(chanId, new Channel(chanId, msg.readString(), this));
break;
} default: {
System.out.println("Unimplented message");
}
}
for(SpectatingBattle battle : getBattles()) {
if (battle.activity != null && battle.histDelta.length() != 0) {
battle.activity.updateBattleInfo(false);
}
}
if (chatActivity != null && chatActivity.currentChannel() != null)
chatActivity.updateChat();
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/KeyMapper.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/KeyMapper.java
index c7c9657e..dd811046 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/KeyMapper.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/KeyMapper.java
@@ -1,81 +1,88 @@
package net.sourceforge.vrapper.vim.modes.commandline;
import static net.sourceforge.vrapper.keymap.vim.ConstructorWrappers.parseKeyStrokes;
import java.util.Queue;
import net.sourceforge.vrapper.keymap.KeyMap;
import net.sourceforge.vrapper.keymap.KeyStroke;
import net.sourceforge.vrapper.keymap.SimpleRemapping;
import net.sourceforge.vrapper.keymap.vim.ConstructorWrappers;
import net.sourceforge.vrapper.vim.EditorAdaptor;
public abstract class KeyMapper implements Evaluator {
final String[] keymaps;
public KeyMapper(String... keymaps) {
this.keymaps = keymaps;
}
public static class Map extends KeyMapper {
private final boolean recursive;
public Map(boolean recursive, String... keymaps) {
super(keymaps);
this.recursive = recursive;
}
public Object evaluate(EditorAdaptor vim, Queue<String> command) {
String lhs = command.poll();
String rhs = "";
while( ! command.isEmpty()) {
//restore spaces between extra parameters
rhs += command.poll() + " ";
}
if (lhs != null && ! "".equals(rhs)) {
+ boolean useRecursive = recursive;
+ // Simple prefix maps are non-recursive, e.g. nmap n nzz - Vim detects this as well.
+ if (recursive && rhs.startsWith(lhs)) {
+ useRecursive = false;
+ vim.getUserInterfaceService().setInfoMessage("Changing recursive remap '" + lhs
+ + "' to non-recursive.");
+ }
for (String name : keymaps) {
KeyMap map = vim.getKeyMapProvider().getKeyMap(name);
map.addMapping(
parseKeyStrokes(lhs),
- new SimpleRemapping(parseKeyStrokes(rhs.trim()), recursive));
+ new SimpleRemapping(parseKeyStrokes(rhs.trim()), useRecursive));
}
}
return null;
}
}
public static class Unmap extends KeyMapper {
public Unmap(String... keymaps) {
super(keymaps);
}
public Object evaluate(EditorAdaptor vim, Queue<String> command) {
if (!command.isEmpty()) {
Iterable<KeyStroke> mapping = ConstructorWrappers.parseKeyStrokes(command.poll());
for (String name : keymaps) {
KeyMap map = vim.getKeyMapProvider().getKeyMap(name);
map.removeMapping(mapping);
}
}
return null;
}
}
public static class Clear extends KeyMapper {
public Clear(String... keymaps) {
super(keymaps);
}
public Object evaluate(EditorAdaptor vim, Queue<String> command) {
for (String name : keymaps) {
KeyMap map = vim.getKeyMapProvider().getKeyMap(name);
map.clear();
}
return null;
}
}
}
| false | true | public Object evaluate(EditorAdaptor vim, Queue<String> command) {
String lhs = command.poll();
String rhs = "";
while( ! command.isEmpty()) {
//restore spaces between extra parameters
rhs += command.poll() + " ";
}
if (lhs != null && ! "".equals(rhs)) {
for (String name : keymaps) {
KeyMap map = vim.getKeyMapProvider().getKeyMap(name);
map.addMapping(
parseKeyStrokes(lhs),
new SimpleRemapping(parseKeyStrokes(rhs.trim()), recursive));
}
}
return null;
}
| public Object evaluate(EditorAdaptor vim, Queue<String> command) {
String lhs = command.poll();
String rhs = "";
while( ! command.isEmpty()) {
//restore spaces between extra parameters
rhs += command.poll() + " ";
}
if (lhs != null && ! "".equals(rhs)) {
boolean useRecursive = recursive;
// Simple prefix maps are non-recursive, e.g. nmap n nzz - Vim detects this as well.
if (recursive && rhs.startsWith(lhs)) {
useRecursive = false;
vim.getUserInterfaceService().setInfoMessage("Changing recursive remap '" + lhs
+ "' to non-recursive.");
}
for (String name : keymaps) {
KeyMap map = vim.getKeyMapProvider().getKeyMap(name);
map.addMapping(
parseKeyStrokes(lhs),
new SimpleRemapping(parseKeyStrokes(rhs.trim()), useRecursive));
}
}
return null;
}
|
diff --git a/webcam-capture/src/main/java/com/github/sarxos/webcam/log/WebcamLogConfigurator.java b/webcam-capture/src/main/java/com/github/sarxos/webcam/log/WebcamLogConfigurator.java
index 0a8c93c..4978d26 100644
--- a/webcam-capture/src/main/java/com/github/sarxos/webcam/log/WebcamLogConfigurator.java
+++ b/webcam-capture/src/main/java/com/github/sarxos/webcam/log/WebcamLogConfigurator.java
@@ -1,101 +1,100 @@
package com.github.sarxos.webcam.log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Configure loggers.
*
* @author Bartosz Firyn (SarXos)
*/
public class WebcamLogConfigurator {
/**
* Logger instance.
*/
private static final Logger LOG = LoggerFactory.getLogger(WebcamLogConfigurator.class);
/**
* Configure SLF4J.
*
* @param is input stream to logback configuration xml
*/
public static void configure(InputStream is) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
String[] names = {
"ch.qos.logback.classic.LoggerContext",
"ch.qos.logback.classic.joran.JoranConfigurator",
- "ch.qos.logback.core.Context"
};
for (String name : names) {
Class.forName(name, false, cl);
}
Object context = LoggerFactory.getILoggerFactory();
Class<?> cfgc = Class.forName("ch.qos.logback.classic.joran.JoranConfigurator");
Object configurator = cfgc.newInstance();
Method setContext = cfgc.getMethod("setContext");
setContext.invoke(configurator, context);
Method reset = context.getClass().getMethod("reset");
reset.invoke(context, new Object[0]);
Method doConfigure = cfgc.getMethod("doConfigure");
doConfigure.invoke(configurator, is);
} catch (ClassNotFoundException e) {
- System.err.println("WLogC: Logback JAR is missing inc lasspath");
+ System.err.println("WLogC: Logback JARs are missing in classpath");
} catch (Exception e) {
LOG.error("Joran configuration exception", e);
}
}
/**
* Configure SLF4J.
*
* @param file logback configuration file
*/
public static void configure(File file) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
configure(fis);
} catch (FileNotFoundException e) {
LOG.error("File not found " + file, e);
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
LOG.error("Cannot close file " + file, e);
e.printStackTrace();
}
}
}
}
/**
* Configure SLF4J.
*
* @param file logback configuration file path
*/
public static void configure(String file) {
configure(new File(file));
}
}
| false | true | public static void configure(InputStream is) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
String[] names = {
"ch.qos.logback.classic.LoggerContext",
"ch.qos.logback.classic.joran.JoranConfigurator",
"ch.qos.logback.core.Context"
};
for (String name : names) {
Class.forName(name, false, cl);
}
Object context = LoggerFactory.getILoggerFactory();
Class<?> cfgc = Class.forName("ch.qos.logback.classic.joran.JoranConfigurator");
Object configurator = cfgc.newInstance();
Method setContext = cfgc.getMethod("setContext");
setContext.invoke(configurator, context);
Method reset = context.getClass().getMethod("reset");
reset.invoke(context, new Object[0]);
Method doConfigure = cfgc.getMethod("doConfigure");
doConfigure.invoke(configurator, is);
} catch (ClassNotFoundException e) {
System.err.println("WLogC: Logback JAR is missing inc lasspath");
} catch (Exception e) {
LOG.error("Joran configuration exception", e);
}
}
| public static void configure(InputStream is) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
String[] names = {
"ch.qos.logback.classic.LoggerContext",
"ch.qos.logback.classic.joran.JoranConfigurator",
};
for (String name : names) {
Class.forName(name, false, cl);
}
Object context = LoggerFactory.getILoggerFactory();
Class<?> cfgc = Class.forName("ch.qos.logback.classic.joran.JoranConfigurator");
Object configurator = cfgc.newInstance();
Method setContext = cfgc.getMethod("setContext");
setContext.invoke(configurator, context);
Method reset = context.getClass().getMethod("reset");
reset.invoke(context, new Object[0]);
Method doConfigure = cfgc.getMethod("doConfigure");
doConfigure.invoke(configurator, is);
} catch (ClassNotFoundException e) {
System.err.println("WLogC: Logback JARs are missing in classpath");
} catch (Exception e) {
LOG.error("Joran configuration exception", e);
}
}
|
diff --git a/src/main/java/com/bananity/models/IndexModelBean.java b/src/main/java/com/bananity/models/IndexModelBean.java
index 7b43cd8..ef3b935 100644
--- a/src/main/java/com/bananity/models/IndexModelBean.java
+++ b/src/main/java/com/bananity/models/IndexModelBean.java
@@ -1,218 +1,222 @@
package com.bananity.models;
// Bananity Classes
import com.bananity.caches.CacheBean;
import com.bananity.constants.StorageConstantsBean;
import com.bananity.storages.IIndexStorage;
import com.bananity.storages.StoragesFactoryBean;
import com.bananity.util.StorageItemComparator;
// Google Caches
import com.google.common.cache.Cache;
// Java utils
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
// Bean Setup
import javax.ejb.EJB;
import javax.ejb.Startup;
import javax.ejb.Singleton;
import javax.annotation.PostConstruct;
// Concurrency Management
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.DependsOn;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
// Timeouts
import javax.ejb.AccessTimeout;
import javax.ejb.ConcurrentAccessTimeoutException;
// Log4j
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;
/**
* This bean is the generic model (in the MVC pattern) to access the indexed collections
*
* @author Andreu Correa Casablanca
* @version 0.4
*/
@Startup
@Singleton
@DependsOn({"StorageConstantsBean", "CacheBean", "StoragesFactoryBean"})
//@AccessTimeout(value=10000)
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class IndexModelBean {
// TODO: Pasar a ConcurrencyManagementType.BEAN
// y manejar bloqueos en insert de forma lo más atómica posible
/**
* Storage Factory reference
*/
@EJB
private StoragesFactoryBean sfB;
/**
* Caches handler reference
*/
@EJB
private CacheBean cB;
/**
* Storage Constants reference
*/
@EJB
private StorageConstantsBean scB;
/**
* Storage reference
*/
private IIndexStorage storage;
/**
* Log4j reference
*/
private static Logger log;
/**
* Configuration Value
*/
private static int tokenEntrySize;
/**
* This method initializes the logger and storage references
*/
@Lock(LockType.WRITE)
@PostConstruct
void init() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
PropertyConfigurator.configure(classLoader.getResource("log4j.properties"));
log = Logger.getLogger(IndexModelBean.class);
// Loading storage
storage = sfB.getIndexStorage();
tokenEntrySize = scB.getTokenEntrySize();
}
/**
* This method looks for indexed content using every subtoken in 'subTokens' in the specified collection (collName)
*
* @param collName Collection Name (where the search will be done)
* @param subTokens Tokens used to do the search
* @param limit (At this moment) unused parameter
*
* @return List of strings (found results in storage)
*/
@Lock(LockType.READ)
public ArrayList<String> find (String collName, Collection<String> subTokens, int limit) throws Exception {
Cache<String, ArrayList<String>> cache = cB.getTokensCache(collName);
if (cache == null) {
throw new Exception("¡Cache not foud for collection \""+collName+"\"!");
}
ArrayList<String> subTokenResult;
ArrayList<String> result = new ArrayList<String>();
for (String subToken : subTokens) {
subTokenResult = cache.getIfPresent(subToken);
if (subTokenResult == null) {
subTokenResult = storage.findSubToken (collName, subToken);
subTokenResult.trimToSize();
cache.put(subToken, subTokenResult);
}
result.addAll(subTokenResult);
}
return result;
}
/**
* This method inserts an 'item' into the specified collection (collName) through many 'subTokens'
*
* @param collName Collection Name (where the insert will be done)
* @param item Item to be inserted
* @param subTokens Tokens used to index the item
*/
@Lock(LockType.READ)
public void insert (String collName, String item, Collection<String> subTokens) throws Exception {
Cache<String, ArrayList<String>> cache = cB.getTokensCache(collName);
if (cache == null) {
throw new Exception("¡Cache not foud for collection \""+collName+"\"!");
}
boolean addedItem, mustTrim, recoveredFromStorage;
String sortingTmpValue;
for (String subToken : subTokens) {
ArrayList<String> subTokenRelatedItems = cache.getIfPresent(subToken);
if (subTokenRelatedItems == null) {
subTokenRelatedItems = storage.findSubToken (collName, subToken);
recoveredFromStorage = true;
mustTrim = true;
} else {
recoveredFromStorage = false;
mustTrim = false;
}
// Este enfoque (más complejo que un simple Collections.sort)
// se aplica para evitar copias en memoria, inserciones en mongo,
// y ordenaciones inútiles
- if (subTokenRelatedItems.size() < tokenEntrySize) {
- subTokenRelatedItems.add(item);
- addedItem = true;
- mustTrim = true;
- } else if (subTokenRelatedItems.get(tokenEntrySize-1).compareTo(item) > 0) {
- subTokenRelatedItems.set(tokenEntrySize-1, item);
- addedItem = true;
+ if (!subTokenRelatedItems.contains(item)) {
+ if (subTokenRelatedItems.size() < tokenEntrySize) {
+ subTokenRelatedItems.add(item);
+ addedItem = true;
+ mustTrim = true;
+ } else if (subTokenRelatedItems.get(tokenEntrySize-1).compareTo(item) > 0) {
+ subTokenRelatedItems.set(tokenEntrySize-1, item);
+ addedItem = true;
+ } else {
+ addedItem = false;
+ }
} else {
addedItem = false;
}
if (addedItem) {
for (int i=subTokenRelatedItems.size()-1; i>0 && subTokenRelatedItems.get(i).compareTo(subTokenRelatedItems.get(i-1)) < 0; i--) {
sortingTmpValue = subTokenRelatedItems.get(i);
subTokenRelatedItems.set(i, subTokenRelatedItems.get(i-1));
subTokenRelatedItems.set(i-1, sortingTmpValue);
}
storage.insert(collName, subToken, subTokenRelatedItems);
}
if (addedItem || recoveredFromStorage) {
cache.put(subToken, subTokenRelatedItems);
}
if (mustTrim) {
subTokenRelatedItems.trimToSize();
}
}
}
/**
* This method removes an 'item' from the specified collection (collName) through many 'subTokens'
*
* @param collName Collection Name (where the remove will be done)
* @param item Item to be removed
* @param subTokens Tokens used to index the item
*/
@Lock(LockType.READ)
public void remove (String collName, String item, Collection<String> subTokens) throws Exception {
// TODO
}
}
| true | true | public void insert (String collName, String item, Collection<String> subTokens) throws Exception {
Cache<String, ArrayList<String>> cache = cB.getTokensCache(collName);
if (cache == null) {
throw new Exception("¡Cache not foud for collection \""+collName+"\"!");
}
boolean addedItem, mustTrim, recoveredFromStorage;
String sortingTmpValue;
for (String subToken : subTokens) {
ArrayList<String> subTokenRelatedItems = cache.getIfPresent(subToken);
if (subTokenRelatedItems == null) {
subTokenRelatedItems = storage.findSubToken (collName, subToken);
recoveredFromStorage = true;
mustTrim = true;
} else {
recoveredFromStorage = false;
mustTrim = false;
}
// Este enfoque (más complejo que un simple Collections.sort)
// se aplica para evitar copias en memoria, inserciones en mongo,
// y ordenaciones inútiles
if (subTokenRelatedItems.size() < tokenEntrySize) {
subTokenRelatedItems.add(item);
addedItem = true;
mustTrim = true;
} else if (subTokenRelatedItems.get(tokenEntrySize-1).compareTo(item) > 0) {
subTokenRelatedItems.set(tokenEntrySize-1, item);
addedItem = true;
} else {
addedItem = false;
}
if (addedItem) {
for (int i=subTokenRelatedItems.size()-1; i>0 && subTokenRelatedItems.get(i).compareTo(subTokenRelatedItems.get(i-1)) < 0; i--) {
sortingTmpValue = subTokenRelatedItems.get(i);
subTokenRelatedItems.set(i, subTokenRelatedItems.get(i-1));
subTokenRelatedItems.set(i-1, sortingTmpValue);
}
storage.insert(collName, subToken, subTokenRelatedItems);
}
if (addedItem || recoveredFromStorage) {
cache.put(subToken, subTokenRelatedItems);
}
if (mustTrim) {
subTokenRelatedItems.trimToSize();
}
}
}
| public void insert (String collName, String item, Collection<String> subTokens) throws Exception {
Cache<String, ArrayList<String>> cache = cB.getTokensCache(collName);
if (cache == null) {
throw new Exception("¡Cache not foud for collection \""+collName+"\"!");
}
boolean addedItem, mustTrim, recoveredFromStorage;
String sortingTmpValue;
for (String subToken : subTokens) {
ArrayList<String> subTokenRelatedItems = cache.getIfPresent(subToken);
if (subTokenRelatedItems == null) {
subTokenRelatedItems = storage.findSubToken (collName, subToken);
recoveredFromStorage = true;
mustTrim = true;
} else {
recoveredFromStorage = false;
mustTrim = false;
}
// Este enfoque (más complejo que un simple Collections.sort)
// se aplica para evitar copias en memoria, inserciones en mongo,
// y ordenaciones inútiles
if (!subTokenRelatedItems.contains(item)) {
if (subTokenRelatedItems.size() < tokenEntrySize) {
subTokenRelatedItems.add(item);
addedItem = true;
mustTrim = true;
} else if (subTokenRelatedItems.get(tokenEntrySize-1).compareTo(item) > 0) {
subTokenRelatedItems.set(tokenEntrySize-1, item);
addedItem = true;
} else {
addedItem = false;
}
} else {
addedItem = false;
}
if (addedItem) {
for (int i=subTokenRelatedItems.size()-1; i>0 && subTokenRelatedItems.get(i).compareTo(subTokenRelatedItems.get(i-1)) < 0; i--) {
sortingTmpValue = subTokenRelatedItems.get(i);
subTokenRelatedItems.set(i, subTokenRelatedItems.get(i-1));
subTokenRelatedItems.set(i-1, sortingTmpValue);
}
storage.insert(collName, subToken, subTokenRelatedItems);
}
if (addedItem || recoveredFromStorage) {
cache.put(subToken, subTokenRelatedItems);
}
if (mustTrim) {
subTokenRelatedItems.trimToSize();
}
}
}
|
diff --git a/modules/library/render/src/test/java/org/geotools/renderer/lite/StreamingRendererTest.java b/modules/library/render/src/test/java/org/geotools/renderer/lite/StreamingRendererTest.java
index c4e3217f7..4a7d0d3ff 100644
--- a/modules/library/render/src/test/java/org/geotools/renderer/lite/StreamingRendererTest.java
+++ b/modules/library/render/src/test/java/org/geotools/renderer/lite/StreamingRendererTest.java
@@ -1,186 +1,186 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.renderer.lite;
import static org.easymock.EasyMock.*;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.HashSet;
import java.util.Iterator;
import junit.framework.TestCase;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.DefaultMapContext;
import org.geotools.map.MapContext;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.renderer.RenderListener;
import org.geotools.styling.Style;
import org.geotools.styling.StyleBuilder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
/**
* Test the inner workings of StreamingRenderer.
* <p>
* Rendering is a pretty high level concept
* @author Jody
*/
public class StreamingRendererTest extends TestCase {
private SimpleFeatureType testFeatureType;
private GeometryFactory gf = new GeometryFactory();
protected int errors;
protected int features;
protected void setUp() throws Exception {
super.setUp();
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Lines");
builder.add("geom", LineString.class, DefaultGeographicCRS.WGS84);
testFeatureType = builder.buildFeatureType();
}
public FeatureCollection<SimpleFeatureType, SimpleFeature> createLineCollection() throws Exception {
FeatureCollection<SimpleFeatureType, SimpleFeature> fc = FeatureCollections.newCollection();
fc.add(createLine(-177, 0, -177, 10));
fc.add(createLine(-177, 0, -200, 0));
fc.add(createLine(-177, 0, -177, 100));
return fc;
}
private SimpleFeature createLine(double x1, double y1, double x2, double y2) {
Coordinate[] coords = new Coordinate[] { new Coordinate(x1, y1), new Coordinate(x2, y2) };
return SimpleFeatureBuilder.build(testFeatureType, new Object[] { gf.createLineString(coords) }, null);
}
private Style createLineStyle() {
StyleBuilder sb = new StyleBuilder();
return sb.createStyle(sb.createLineSymbolizer());
}
public void testRenderStuff() throws Exception {
// build map context
MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
mapContext.addLayer(createLineCollection(), createLineStyle());
// build projected envelope to work with (small one around the area of
// validity of utm zone 1, which being a Gauss projection is a vertical
// slice parallel to the central meridian, -177°)
ReferencedEnvelope reWgs = new ReferencedEnvelope(new Envelope(-180,
-170, 20, 40), DefaultGeographicCRS.WGS84);
CoordinateReferenceSystem utm1N = CRS.decode("EPSG:32601");
System.out.println(CRS.getGeographicBoundingBox(utm1N));
ReferencedEnvelope reUtm = reWgs.transform(utm1N, true);
BufferedImage image = new BufferedImage(200, 200,BufferedImage.TYPE_4BYTE_ABGR);
// setup the renderer and listen for errors
StreamingRenderer sr = new StreamingRenderer();
sr.setContext(mapContext);
sr.addRenderListener(new RenderListener() {
public void featureRenderer(SimpleFeature feature) {
features++;
}
public void errorOccurred(Exception e) {
errors++;
}
});
errors = 0;
features = 0;
sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200),reUtm);
// we should get two errors since there are two features that cannot be
// projected but the renderer itself should not throw exceptions
assertTrue( features > 0 );
}
public void testInfiniteLoopAvoidance() throws Exception {
final Exception sentinel = new RuntimeException("This is the one that should be thrown in hasNext()");
// setup the mock necessary to have the renderer hit into the exception in hasNext()
- FeatureIterator it2 = createNiceMock(FeatureIterator.class);
+ Iterator it2 = createNiceMock(Iterator.class);
expect(it2.hasNext()).andThrow(sentinel).anyTimes();
replay(it2);
FeatureCollection fc = createNiceMock(FeatureCollection.class);
- expect(fc.features()).andReturn(it2);
+ expect(fc.iterator()).andReturn(it2);
expect(fc.size()).andReturn(200);
expect(fc.getSchema()).andReturn(testFeatureType).anyTimes();
replay(fc);
FeatureSource fs = createNiceMock(FeatureSource.class);
expect(fs.getFeatures((Query) anyObject())).andReturn(fc);
expect(fs.getSchema()).andReturn(testFeatureType).anyTimes();
expect(fs.getSupportedHints()).andReturn(new HashSet());
replay(fs);
// build map context
MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
mapContext.addLayer(fs, createLineStyle());
// setup the renderer and listen for errors
final StreamingRenderer sr = new StreamingRenderer();
sr.setContext(mapContext);
sr.addRenderListener(new RenderListener() {
public void featureRenderer(SimpleFeature feature) {
features++;
}
public void errorOccurred(Exception e) {
errors++;
if(errors > 2) {
// we dont' want to block the loop in case of regression on this bug
sr.stopRendering();
}
// but we want to make sure we're getting
Throwable t = e;
while(t != sentinel && t.getCause() != null)
t = t.getCause();
assertSame(sentinel, t);
}
});
errors = 0;
features = 0;
BufferedImage image = new BufferedImage(200, 200,BufferedImage.TYPE_4BYTE_ABGR);
ReferencedEnvelope reWgs = new ReferencedEnvelope(new Envelope(-180,
-170, 20, 40), DefaultGeographicCRS.WGS84);
sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200),reWgs);
// we should get two errors since there are two features that cannot be
// projected but the renderer itself should not throw exceptions
assertEquals(0, features);
assertEquals(1, errors);
}
}
| false | true | public void testInfiniteLoopAvoidance() throws Exception {
final Exception sentinel = new RuntimeException("This is the one that should be thrown in hasNext()");
// setup the mock necessary to have the renderer hit into the exception in hasNext()
FeatureIterator it2 = createNiceMock(FeatureIterator.class);
expect(it2.hasNext()).andThrow(sentinel).anyTimes();
replay(it2);
FeatureCollection fc = createNiceMock(FeatureCollection.class);
expect(fc.features()).andReturn(it2);
expect(fc.size()).andReturn(200);
expect(fc.getSchema()).andReturn(testFeatureType).anyTimes();
replay(fc);
FeatureSource fs = createNiceMock(FeatureSource.class);
expect(fs.getFeatures((Query) anyObject())).andReturn(fc);
expect(fs.getSchema()).andReturn(testFeatureType).anyTimes();
expect(fs.getSupportedHints()).andReturn(new HashSet());
replay(fs);
// build map context
MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
mapContext.addLayer(fs, createLineStyle());
// setup the renderer and listen for errors
final StreamingRenderer sr = new StreamingRenderer();
sr.setContext(mapContext);
sr.addRenderListener(new RenderListener() {
public void featureRenderer(SimpleFeature feature) {
features++;
}
public void errorOccurred(Exception e) {
errors++;
if(errors > 2) {
// we dont' want to block the loop in case of regression on this bug
sr.stopRendering();
}
// but we want to make sure we're getting
Throwable t = e;
while(t != sentinel && t.getCause() != null)
t = t.getCause();
assertSame(sentinel, t);
}
});
errors = 0;
features = 0;
BufferedImage image = new BufferedImage(200, 200,BufferedImage.TYPE_4BYTE_ABGR);
ReferencedEnvelope reWgs = new ReferencedEnvelope(new Envelope(-180,
-170, 20, 40), DefaultGeographicCRS.WGS84);
sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200),reWgs);
// we should get two errors since there are two features that cannot be
// projected but the renderer itself should not throw exceptions
assertEquals(0, features);
assertEquals(1, errors);
}
| public void testInfiniteLoopAvoidance() throws Exception {
final Exception sentinel = new RuntimeException("This is the one that should be thrown in hasNext()");
// setup the mock necessary to have the renderer hit into the exception in hasNext()
Iterator it2 = createNiceMock(Iterator.class);
expect(it2.hasNext()).andThrow(sentinel).anyTimes();
replay(it2);
FeatureCollection fc = createNiceMock(FeatureCollection.class);
expect(fc.iterator()).andReturn(it2);
expect(fc.size()).andReturn(200);
expect(fc.getSchema()).andReturn(testFeatureType).anyTimes();
replay(fc);
FeatureSource fs = createNiceMock(FeatureSource.class);
expect(fs.getFeatures((Query) anyObject())).andReturn(fc);
expect(fs.getSchema()).andReturn(testFeatureType).anyTimes();
expect(fs.getSupportedHints()).andReturn(new HashSet());
replay(fs);
// build map context
MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
mapContext.addLayer(fs, createLineStyle());
// setup the renderer and listen for errors
final StreamingRenderer sr = new StreamingRenderer();
sr.setContext(mapContext);
sr.addRenderListener(new RenderListener() {
public void featureRenderer(SimpleFeature feature) {
features++;
}
public void errorOccurred(Exception e) {
errors++;
if(errors > 2) {
// we dont' want to block the loop in case of regression on this bug
sr.stopRendering();
}
// but we want to make sure we're getting
Throwable t = e;
while(t != sentinel && t.getCause() != null)
t = t.getCause();
assertSame(sentinel, t);
}
});
errors = 0;
features = 0;
BufferedImage image = new BufferedImage(200, 200,BufferedImage.TYPE_4BYTE_ABGR);
ReferencedEnvelope reWgs = new ReferencedEnvelope(new Envelope(-180,
-170, 20, 40), DefaultGeographicCRS.WGS84);
sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200),reWgs);
// we should get two errors since there are two features that cannot be
// projected but the renderer itself should not throw exceptions
assertEquals(0, features);
assertEquals(1, errors);
}
|
diff --git a/src/com/android/contacts/model/ExchangeSource.java b/src/com/android/contacts/model/ExchangeSource.java
index 11ccd448c..3f2ab6c34 100644
--- a/src/com/android/contacts/model/ExchangeSource.java
+++ b/src/com/android/contacts/model/ExchangeSource.java
@@ -1,316 +1,316 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.model;
import com.android.contacts.R;
import com.google.android.collect.Lists;
import android.content.ContentValues;
import android.content.Context;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.CommonDataKinds.Website;
import java.util.Locale;
public class ExchangeSource extends FallbackSource {
public static final String ACCOUNT_TYPE = "com.android.exchange";
public ExchangeSource(String resPackageName) {
this.accountType = ACCOUNT_TYPE;
this.resPackageName = null;
this.summaryResPackageName = resPackageName;
}
@Override
protected void inflate(Context context, int inflateLevel) {
inflateStructuredName(context, inflateLevel);
inflateNickname(context, inflateLevel);
inflatePhone(context, inflateLevel);
inflateEmail(context, inflateLevel);
inflateStructuredPostal(context, inflateLevel);
inflateIm(context, inflateLevel);
inflateOrganization(context, inflateLevel);
inflatePhoto(context, inflateLevel);
inflateNote(context, inflateLevel);
inflateWebsite(context, inflateLevel);
setInflatedLevel(inflateLevel);
}
@Override
protected DataKind inflateStructuredName(Context context, int inflateLevel) {
final DataKind kind = super.inflateStructuredName(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
- final boolean useJapaneseOrder =
- Locale.JAPANESE.getLanguage().equals(Locale.getDefault().getLanguage());
+ boolean displayOrderPrimary =
+ context.getResources().getBoolean(R.bool.config_editor_field_order_primary);
kind.typeOverallMax = 1;
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(StructuredName.PREFIX, R.string.name_prefix,
FLAGS_PERSON_NAME).setOptional(true));
- if (useJapaneseOrder) {
+ if (!displayOrderPrimary) {
kind.fieldList.add(new EditField(StructuredName.FAMILY_NAME,
R.string.name_family, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.MIDDLE_NAME,
R.string.name_middle, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.GIVEN_NAME,
R.string.name_given, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.SUFFIX,
R.string.name_suffix, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_FAMILY_NAME,
R.string.name_phonetic_family, FLAGS_PHONETIC).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_GIVEN_NAME,
R.string.name_phonetic_given, FLAGS_PHONETIC).setOptional(true));
} else {
kind.fieldList.add(new EditField(StructuredName.GIVEN_NAME,
R.string.name_given, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.MIDDLE_NAME,
R.string.name_middle, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.FAMILY_NAME,
R.string.name_family, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.SUFFIX,
R.string.name_suffix, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_GIVEN_NAME,
R.string.name_phonetic_given, FLAGS_PHONETIC).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_FAMILY_NAME,
R.string.name_phonetic_family, FLAGS_PHONETIC).setOptional(true));
}
}
return kind;
}
@Override
protected DataKind inflateNickname(Context context, int inflateLevel) {
final DataKind kind = super.inflateNickname(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.isList = false;
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Nickname.NAME, R.string.nicknameLabelsGroup,
FLAGS_PERSON_NAME));
}
return kind;
}
@Override
protected DataKind inflatePhone(Context context, int inflateLevel) {
final DataKind kind = super.inflatePhone(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.typeColumn = Phone.TYPE;
kind.typeList = Lists.newArrayList();
kind.typeList.add(buildPhoneType(Phone.TYPE_HOME).setSpecificMax(2));
kind.typeList.add(buildPhoneType(Phone.TYPE_MOBILE).setSpecificMax(1));
kind.typeList.add(buildPhoneType(Phone.TYPE_WORK).setSpecificMax(2));
kind.typeList.add(buildPhoneType(Phone.TYPE_FAX_WORK).setSecondary(true)
.setSpecificMax(1));
kind.typeList.add(buildPhoneType(Phone.TYPE_FAX_HOME).setSecondary(true)
.setSpecificMax(1));
kind.typeList
.add(buildPhoneType(Phone.TYPE_PAGER).setSecondary(true).setSpecificMax(1));
kind.typeList.add(buildPhoneType(Phone.TYPE_CAR).setSecondary(true).setSpecificMax(1));
kind.typeList.add(buildPhoneType(Phone.TYPE_COMPANY_MAIN).setSecondary(true)
.setSpecificMax(1));
kind.typeList.add(buildPhoneType(Phone.TYPE_MMS).setSecondary(true).setSpecificMax(1));
kind.typeList
.add(buildPhoneType(Phone.TYPE_RADIO).setSecondary(true).setSpecificMax(1));
kind.typeList.add(buildPhoneType(Phone.TYPE_ASSISTANT).setSecondary(true)
.setSpecificMax(1).setCustomColumn(Phone.LABEL));
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Phone.NUMBER, R.string.phoneLabelsGroup, FLAGS_PHONE));
}
return kind;
}
@Override
protected DataKind inflateEmail(Context context, int inflateLevel) {
final DataKind kind = super.inflateEmail(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.typeOverallMax = 3;
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Email.DATA, R.string.emailLabelsGroup, FLAGS_EMAIL));
}
return kind;
}
@Override
protected DataKind inflateStructuredPostal(Context context, int inflateLevel) {
final DataKind kind = super.inflateStructuredPostal(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
final boolean useJapaneseOrder =
Locale.JAPANESE.getLanguage().equals(Locale.getDefault().getLanguage());
kind.typeColumn = StructuredPostal.TYPE;
kind.typeList = Lists.newArrayList();
kind.typeList.add(buildPostalType(StructuredPostal.TYPE_WORK).setSpecificMax(1));
kind.typeList.add(buildPostalType(StructuredPostal.TYPE_HOME).setSpecificMax(1));
kind.typeList.add(buildPostalType(StructuredPostal.TYPE_OTHER).setSpecificMax(1));
kind.fieldList = Lists.newArrayList();
if (useJapaneseOrder) {
kind.fieldList.add(new EditField(StructuredPostal.COUNTRY,
R.string.postal_country, FLAGS_POSTAL).setOptional(true));
kind.fieldList.add(new EditField(StructuredPostal.POSTCODE,
R.string.postal_postcode, FLAGS_POSTAL));
kind.fieldList.add(new EditField(StructuredPostal.REGION,
R.string.postal_region, FLAGS_POSTAL));
kind.fieldList.add(new EditField(StructuredPostal.CITY,
R.string.postal_city,FLAGS_POSTAL));
kind.fieldList.add(new EditField(StructuredPostal.STREET,
R.string.postal_street, FLAGS_POSTAL));
} else {
kind.fieldList.add(new EditField(StructuredPostal.STREET,
R.string.postal_street, FLAGS_POSTAL));
kind.fieldList.add(new EditField(StructuredPostal.CITY,
R.string.postal_city,FLAGS_POSTAL));
kind.fieldList.add(new EditField(StructuredPostal.REGION,
R.string.postal_region, FLAGS_POSTAL));
kind.fieldList.add(new EditField(StructuredPostal.POSTCODE,
R.string.postal_postcode, FLAGS_POSTAL));
kind.fieldList.add(new EditField(StructuredPostal.COUNTRY,
R.string.postal_country, FLAGS_POSTAL).setOptional(true));
}
}
return kind;
}
@Override
protected DataKind inflateIm(Context context, int inflateLevel) {
final DataKind kind = super.inflateIm(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.typeOverallMax = 3;
// NOTE: even though a traditional "type" exists, for editing
// purposes we're using the protocol to pick labels
kind.defaultValues = new ContentValues();
kind.defaultValues.put(Im.TYPE, Im.TYPE_OTHER);
kind.typeColumn = Im.PROTOCOL;
kind.typeList = Lists.newArrayList();
kind.typeList.add(buildImType(Im.PROTOCOL_AIM));
kind.typeList.add(buildImType(Im.PROTOCOL_MSN));
kind.typeList.add(buildImType(Im.PROTOCOL_YAHOO));
kind.typeList.add(buildImType(Im.PROTOCOL_SKYPE));
kind.typeList.add(buildImType(Im.PROTOCOL_QQ));
kind.typeList.add(buildImType(Im.PROTOCOL_GOOGLE_TALK));
kind.typeList.add(buildImType(Im.PROTOCOL_ICQ));
kind.typeList.add(buildImType(Im.PROTOCOL_JABBER));
kind.typeList.add(buildImType(Im.PROTOCOL_CUSTOM).setSecondary(true).setCustomColumn(
Im.CUSTOM_PROTOCOL));
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Im.DATA, R.string.imLabelsGroup, FLAGS_EMAIL));
}
return kind;
}
@Override
protected DataKind inflateOrganization(Context context, int inflateLevel) {
final DataKind kind = super.inflateOrganization(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.isList = false;
kind.typeColumn = Organization.TYPE;
kind.typeList = Lists.newArrayList();
kind.typeList.add(buildOrgType(Organization.TYPE_WORK).setSpecificMax(1));
kind.typeList.add(buildOrgType(Organization.TYPE_OTHER).setSpecificMax(1));
kind.typeList.add(buildOrgType(Organization.TYPE_CUSTOM).setSecondary(true)
.setSpecificMax(1));
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Organization.COMPANY, R.string.ghostData_company,
FLAGS_GENERIC_NAME));
kind.fieldList.add(new EditField(Organization.TITLE, R.string.ghostData_title,
FLAGS_GENERIC_NAME));
}
return kind;
}
@Override
protected DataKind inflatePhoto(Context context, int inflateLevel) {
final DataKind kind = super.inflatePhoto(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.typeOverallMax = 1;
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Photo.PHOTO, -1, -1));
}
return kind;
}
@Override
protected DataKind inflateNote(Context context, int inflateLevel) {
final DataKind kind = super.inflateNote(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Note.NOTE, R.string.label_notes, FLAGS_NOTE));
}
return kind;
}
@Override
protected DataKind inflateWebsite(Context context, int inflateLevel) {
final DataKind kind = super.inflateWebsite(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
kind.isList = false;
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(Website.URL, R.string.websiteLabelsGroup, FLAGS_WEBSITE));
}
return kind;
}
@Override
public int getHeaderColor(Context context) {
return 0xffd5ba96;
}
@Override
public int getSideBarColor(Context context) {
return 0xffb58e59;
}
}
| false | true | protected DataKind inflateStructuredName(Context context, int inflateLevel) {
final DataKind kind = super.inflateStructuredName(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
final boolean useJapaneseOrder =
Locale.JAPANESE.getLanguage().equals(Locale.getDefault().getLanguage());
kind.typeOverallMax = 1;
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(StructuredName.PREFIX, R.string.name_prefix,
FLAGS_PERSON_NAME).setOptional(true));
if (useJapaneseOrder) {
kind.fieldList.add(new EditField(StructuredName.FAMILY_NAME,
R.string.name_family, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.MIDDLE_NAME,
R.string.name_middle, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.GIVEN_NAME,
R.string.name_given, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.SUFFIX,
R.string.name_suffix, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_FAMILY_NAME,
R.string.name_phonetic_family, FLAGS_PHONETIC).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_GIVEN_NAME,
R.string.name_phonetic_given, FLAGS_PHONETIC).setOptional(true));
} else {
kind.fieldList.add(new EditField(StructuredName.GIVEN_NAME,
R.string.name_given, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.MIDDLE_NAME,
R.string.name_middle, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.FAMILY_NAME,
R.string.name_family, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.SUFFIX,
R.string.name_suffix, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_GIVEN_NAME,
R.string.name_phonetic_given, FLAGS_PHONETIC).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_FAMILY_NAME,
R.string.name_phonetic_family, FLAGS_PHONETIC).setOptional(true));
}
}
return kind;
}
| protected DataKind inflateStructuredName(Context context, int inflateLevel) {
final DataKind kind = super.inflateStructuredName(context, ContactsSource.LEVEL_MIMETYPES);
if (inflateLevel >= ContactsSource.LEVEL_CONSTRAINTS) {
boolean displayOrderPrimary =
context.getResources().getBoolean(R.bool.config_editor_field_order_primary);
kind.typeOverallMax = 1;
kind.fieldList = Lists.newArrayList();
kind.fieldList.add(new EditField(StructuredName.PREFIX, R.string.name_prefix,
FLAGS_PERSON_NAME).setOptional(true));
if (!displayOrderPrimary) {
kind.fieldList.add(new EditField(StructuredName.FAMILY_NAME,
R.string.name_family, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.MIDDLE_NAME,
R.string.name_middle, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.GIVEN_NAME,
R.string.name_given, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.SUFFIX,
R.string.name_suffix, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_FAMILY_NAME,
R.string.name_phonetic_family, FLAGS_PHONETIC).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_GIVEN_NAME,
R.string.name_phonetic_given, FLAGS_PHONETIC).setOptional(true));
} else {
kind.fieldList.add(new EditField(StructuredName.GIVEN_NAME,
R.string.name_given, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.MIDDLE_NAME,
R.string.name_middle, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.FAMILY_NAME,
R.string.name_family, FLAGS_PERSON_NAME));
kind.fieldList.add(new EditField(StructuredName.SUFFIX,
R.string.name_suffix, FLAGS_PERSON_NAME).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_GIVEN_NAME,
R.string.name_phonetic_given, FLAGS_PHONETIC).setOptional(true));
kind.fieldList.add(new EditField(StructuredName.PHONETIC_FAMILY_NAME,
R.string.name_phonetic_family, FLAGS_PHONETIC).setOptional(true));
}
}
return kind;
}
|
diff --git a/Chart.java b/Chart.java
index 19dc0f5..6d66d88 100644
--- a/Chart.java
+++ b/Chart.java
@@ -1,85 +1,85 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.Map;
import java.util.LinkedHashMap;
public class Chart
{
private Map<String, String> data;
public Chart(String[][] contents){
// LinkedHashMap will retain insertion ordering
this.data = new LinkedHashMap<String, String>();
this.setRows(contents);
}
// produces the chart
public String toString() {
String rt = "";
- int labelWidth = 0, dataWidth = 0;
+ int labelWidth = 1, dataWidth = 1;
// calculate padding for label and data columns
for (Map.Entry<String, String> i : data.entrySet()){
labelWidth = Math.max(i.getKey().length(), labelWidth);
dataWidth = Math.max(i.getValue().length(), dataWidth);
}
// build header line
String head = "";
for (int i = 0; i < labelWidth+dataWidth+7; i++) {
head += "-";
}
head += "\n";
rt += head;
// actually make the chart now
for (Map.Entry<String, String> i : data.entrySet()){
// use the computed padding to align labels and data left with given padding
rt += String.format(String.format("| %s | %s |", "%-"+labelWidth+"s", "%-"+dataWidth+"s"), i.getKey(), i.getValue())+"\n";
}
// footer line
rt += head;
return rt;
}
// add a row of data
/**
* @param row Should be a array with length 2. The first value will be the
* row label, the second the row data.
*/
public void addRow(String[] row) {
data.put(row[0], row[1]);
}
/**
* Converts the row from the internal data structure to a 2D Array of strings.
* @return Array of String arrays with length 2. Each array is a row. First
* value is label, second value is value.
*/
public String[][] getRows() {
Set<Map.Entry<String, String>> temp = data.entrySet();
// finish conversion
String[][] rows = new String[data.size()][2];
int i = 0;
for (Map.Entry<String, String> e: temp) {
rows[i][0] = e.getKey();
rows[i][1] = e.getValue();
i++;
}
return rows;
}
/**
* @param rows 2D array of form {{label, value}, {label, value}}
*/
public void setRows(String[][] rows) {
data.clear();
for (String[] row: rows) {
data.put(row[0], row[1]);
}
}
}
| true | true | public String toString() {
String rt = "";
int labelWidth = 0, dataWidth = 0;
// calculate padding for label and data columns
for (Map.Entry<String, String> i : data.entrySet()){
labelWidth = Math.max(i.getKey().length(), labelWidth);
dataWidth = Math.max(i.getValue().length(), dataWidth);
}
// build header line
String head = "";
for (int i = 0; i < labelWidth+dataWidth+7; i++) {
head += "-";
}
head += "\n";
rt += head;
// actually make the chart now
for (Map.Entry<String, String> i : data.entrySet()){
// use the computed padding to align labels and data left with given padding
rt += String.format(String.format("| %s | %s |", "%-"+labelWidth+"s", "%-"+dataWidth+"s"), i.getKey(), i.getValue())+"\n";
}
// footer line
rt += head;
return rt;
}
| public String toString() {
String rt = "";
int labelWidth = 1, dataWidth = 1;
// calculate padding for label and data columns
for (Map.Entry<String, String> i : data.entrySet()){
labelWidth = Math.max(i.getKey().length(), labelWidth);
dataWidth = Math.max(i.getValue().length(), dataWidth);
}
// build header line
String head = "";
for (int i = 0; i < labelWidth+dataWidth+7; i++) {
head += "-";
}
head += "\n";
rt += head;
// actually make the chart now
for (Map.Entry<String, String> i : data.entrySet()){
// use the computed padding to align labels and data left with given padding
rt += String.format(String.format("| %s | %s |", "%-"+labelWidth+"s", "%-"+dataWidth+"s"), i.getKey(), i.getValue())+"\n";
}
// footer line
rt += head;
return rt;
}
|
diff --git a/src/Export/Schema.java b/src/Export/Schema.java
index 51fd230..fab91d5 100644
--- a/src/Export/Schema.java
+++ b/src/Export/Schema.java
@@ -1,118 +1,118 @@
/**
* This file is part of libRibbonIO library (check README).
* Copyright (C) 2012-2013 Stanislav Nepochatov
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
package Export;
import Utils.IOControl;
/**
* Export schema class.
* @author Stanislav Nepochatov <[email protected]>
*/
public class Schema {
/**
* Type of exporter.
*/
public String type;
/**
* Name of export schema.
*/
public String name;
/**
* Exporter class link.
*/
private Class<Exporter> exporterModule;
/**
* Export formater.
*/
public Formater currFormater;
/**
* Current export config.
*/
public java.util.Properties currConfig;
public static enum EM_ACTION {
PLACE_ERRQ_DIRTY,
DROP_WARN,
DROP_WARN_DIRTY
}
EM_ACTION currAction = EM_ACTION.PLACE_ERRQ_DIRTY;
/**
* Default constructor.
* @param givenConfig config for export;
* @param givenModule export module class link.
*/
public Schema(java.util.Properties givenConfig, Class<Exporter> givenModule) {
currConfig = givenConfig;
exporterModule = givenModule;
type = currConfig.getProperty("export_type");
name = currConfig.getProperty("export_name");
if (currConfig.containsKey("export_template")) {
try {
- currFormater = new Formater(new String(java.nio.file.Files.readAllBytes(new java.io.File(currConfig.getProperty("export_template")).toPath())));
+ currFormater = new Formater(currConfig, new String(java.nio.file.Files.readAllBytes(new java.io.File(currConfig.getProperty("export_template")).toPath())));
} catch (java.io.IOException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "помилка завантаження шаблону " + IOControl.dispathcer.exportDirPath + "/" + currConfig.getProperty("export_template"));
}
}
if (currConfig.containsKey("opt_em_action")) {
try {
currAction = EM_ACTION.valueOf(currConfig.getProperty("opt_em_action"));
} catch (IllegalArgumentException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "тип аварійної дії '" + currConfig.getProperty("opt_em_action") + "' не підтримується системою.");
}
}
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 3, "завантажено схему експорту '" + this.name + "'");
}
/**
* Get timeout befor export.
* @return integer value for time waiting before export;
*/
public Integer getTimeout() {
return Integer.parseInt(currConfig.getProperty("export_timeout")) * 60 * 1000;
}
/**
* Get new export task thread.
* @param givenMessage message to export;
* @param givenSwitch switch;
* @param givenDir called dir;
* @return new export task;
*/
public Exporter getNewExportTask(MessageClasses.Message givenMessage, ReleaseSwitch givenSwitch, String givenDir) {
Exporter newExport = null;
try {
newExport = (Exporter) this.exporterModule.getConstructor(MessageClasses.Message.class, Schema.class, ReleaseSwitch.class, String.class).newInstance(givenMessage, this, givenSwitch, givenDir);
} catch (java.lang.reflect.InvocationTargetException ex) {
ex.getTargetException().printStackTrace();
} catch (Exception ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 1, "неможливо опрацювати класс " + this.exporterModule.getName());
IOControl.serverWrapper.enableDirtyState(type, name, this.currConfig.getProperty("export_print"));
ex.printStackTrace();
}
return newExport;
}
}
| true | true | public Schema(java.util.Properties givenConfig, Class<Exporter> givenModule) {
currConfig = givenConfig;
exporterModule = givenModule;
type = currConfig.getProperty("export_type");
name = currConfig.getProperty("export_name");
if (currConfig.containsKey("export_template")) {
try {
currFormater = new Formater(new String(java.nio.file.Files.readAllBytes(new java.io.File(currConfig.getProperty("export_template")).toPath())));
} catch (java.io.IOException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "помилка завантаження шаблону " + IOControl.dispathcer.exportDirPath + "/" + currConfig.getProperty("export_template"));
}
}
if (currConfig.containsKey("opt_em_action")) {
try {
currAction = EM_ACTION.valueOf(currConfig.getProperty("opt_em_action"));
} catch (IllegalArgumentException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "тип аварійної дії '" + currConfig.getProperty("opt_em_action") + "' не підтримується системою.");
}
}
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 3, "завантажено схему експорту '" + this.name + "'");
}
| public Schema(java.util.Properties givenConfig, Class<Exporter> givenModule) {
currConfig = givenConfig;
exporterModule = givenModule;
type = currConfig.getProperty("export_type");
name = currConfig.getProperty("export_name");
if (currConfig.containsKey("export_template")) {
try {
currFormater = new Formater(currConfig, new String(java.nio.file.Files.readAllBytes(new java.io.File(currConfig.getProperty("export_template")).toPath())));
} catch (java.io.IOException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "помилка завантаження шаблону " + IOControl.dispathcer.exportDirPath + "/" + currConfig.getProperty("export_template"));
}
}
if (currConfig.containsKey("opt_em_action")) {
try {
currAction = EM_ACTION.valueOf(currConfig.getProperty("opt_em_action"));
} catch (IllegalArgumentException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "тип аварійної дії '" + currConfig.getProperty("opt_em_action") + "' не підтримується системою.");
}
}
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 3, "завантажено схему експорту '" + this.name + "'");
}
|
diff --git a/applications/manufacturing/src/org/ofbiz/manufacturing/routing/RoutingServices.java b/applications/manufacturing/src/org/ofbiz/manufacturing/routing/RoutingServices.java
index b84a8e7d6..602a4bba7 100644
--- a/applications/manufacturing/src/org/ofbiz/manufacturing/routing/RoutingServices.java
+++ b/applications/manufacturing/src/org/ofbiz/manufacturing/routing/RoutingServices.java
@@ -1,84 +1,84 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.manufacturing.routing;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.manufacturing.jobshopmgt.ProductionRun;
/**
* Routing related services
*
*/
public class RoutingServices {
public static final String module = RoutingServices.class.getName();
public static final String resource = "ManufacturingUiLabels";
/**
* Computes the estimated time needed to perform the task.
* @param ctx The DispatchContext that this service is operating in.
* @param context Map containing the input parameters.
* @return Map with the result of the service, the output parameters.
*/
public static Map getEstimatedTaskTime(DispatchContext ctx, Map context) {
Map result = new HashMap();
GenericDelegator delegator = ctx.getDelegator();
LocalDispatcher dispatcher = ctx.getDispatcher();
// The mandatory IN parameters
String taskId = (String) context.get("taskId");
BigDecimal quantity = (BigDecimal) context.get("quantity");
// The optional IN parameters
String productId = (String) context.get("productId");
String routingId = (String) context.get("routingId");
if (quantity == null) {
quantity = BigDecimal.ONE;
}
GenericValue task = null;
try {
task = delegator.findByPrimaryKey("WorkEffort", UtilMisc.toMap("workEffortId", taskId));
} catch (GenericEntityException gee) {
ServiceUtil.returnError("Error finding routing task with id: " + taskId);
}
// FIXME: the ProductionRun.getEstimatedTaskTime(...) method will be removed and
// its logic will be implemented inside this method.
long estimatedTaskTime = ProductionRun.getEstimatedTaskTime(task, quantity, productId, routingId, dispatcher);
result.put("estimatedTaskTime", new Long(estimatedTaskTime));
if (task != null && task.get("estimatedSetupMillis") != null) {
- result.put("setupTime", task.getDouble("estimatedSetupMillis"));
+ result.put("setupTime", task.getBigDecimal("estimatedSetupMillis"));
}
if (task != null && task.get("estimatedMilliSeconds") != null) {
- result.put("taskUnitTime", task.getDouble("estimatedMilliSeconds"));
+ result.put("taskUnitTime", task.getBigDecimal("estimatedMilliSeconds"));
}
return result;
}
}
| false | true | public static Map getEstimatedTaskTime(DispatchContext ctx, Map context) {
Map result = new HashMap();
GenericDelegator delegator = ctx.getDelegator();
LocalDispatcher dispatcher = ctx.getDispatcher();
// The mandatory IN parameters
String taskId = (String) context.get("taskId");
BigDecimal quantity = (BigDecimal) context.get("quantity");
// The optional IN parameters
String productId = (String) context.get("productId");
String routingId = (String) context.get("routingId");
if (quantity == null) {
quantity = BigDecimal.ONE;
}
GenericValue task = null;
try {
task = delegator.findByPrimaryKey("WorkEffort", UtilMisc.toMap("workEffortId", taskId));
} catch (GenericEntityException gee) {
ServiceUtil.returnError("Error finding routing task with id: " + taskId);
}
// FIXME: the ProductionRun.getEstimatedTaskTime(...) method will be removed and
// its logic will be implemented inside this method.
long estimatedTaskTime = ProductionRun.getEstimatedTaskTime(task, quantity, productId, routingId, dispatcher);
result.put("estimatedTaskTime", new Long(estimatedTaskTime));
if (task != null && task.get("estimatedSetupMillis") != null) {
result.put("setupTime", task.getDouble("estimatedSetupMillis"));
}
if (task != null && task.get("estimatedMilliSeconds") != null) {
result.put("taskUnitTime", task.getDouble("estimatedMilliSeconds"));
}
return result;
}
| public static Map getEstimatedTaskTime(DispatchContext ctx, Map context) {
Map result = new HashMap();
GenericDelegator delegator = ctx.getDelegator();
LocalDispatcher dispatcher = ctx.getDispatcher();
// The mandatory IN parameters
String taskId = (String) context.get("taskId");
BigDecimal quantity = (BigDecimal) context.get("quantity");
// The optional IN parameters
String productId = (String) context.get("productId");
String routingId = (String) context.get("routingId");
if (quantity == null) {
quantity = BigDecimal.ONE;
}
GenericValue task = null;
try {
task = delegator.findByPrimaryKey("WorkEffort", UtilMisc.toMap("workEffortId", taskId));
} catch (GenericEntityException gee) {
ServiceUtil.returnError("Error finding routing task with id: " + taskId);
}
// FIXME: the ProductionRun.getEstimatedTaskTime(...) method will be removed and
// its logic will be implemented inside this method.
long estimatedTaskTime = ProductionRun.getEstimatedTaskTime(task, quantity, productId, routingId, dispatcher);
result.put("estimatedTaskTime", new Long(estimatedTaskTime));
if (task != null && task.get("estimatedSetupMillis") != null) {
result.put("setupTime", task.getBigDecimal("estimatedSetupMillis"));
}
if (task != null && task.get("estimatedMilliSeconds") != null) {
result.put("taskUnitTime", task.getBigDecimal("estimatedMilliSeconds"));
}
return result;
}
|
diff --git a/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java b/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java
index 51423055..cf14d288 100644
--- a/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java
+++ b/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java
@@ -1,117 +1,117 @@
/*
* Copyright 2009-2011 Carsten Hufe devproof.org
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.devproof.portal.module.blog.page;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTester;
import org.devproof.portal.module.blog.entity.Blog;
import org.devproof.portal.test.MockContextLoader;
import org.devproof.portal.test.PortalTestUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.ServletContext;
import static org.junit.Assert.assertFalse;
/**
* @author Carsten Hufe
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = MockContextLoader.class,
locations = {"classpath:/org/devproof/portal/module/blog/test-datasource.xml" })
public class BlogEditPageTest {
@SuppressWarnings({"SpringJavaAutowiringInspection"})
@Autowired
private ServletContext servletContext;
private WicketTester tester;
@Before
public void setUp() throws Exception {
tester = PortalTestUtil.createWicketTester(servletContext);
PortalTestUtil.loginDefaultAdminUser(tester);
}
@After
public void tearDown() throws Exception {
PortalTestUtil.destroy(tester);
}
@Test
public void testRenderDefaultPage() {
tester.startPage(createNewBlogEditPage());
tester.assertRenderedPage(BlogEditPage.class);
}
private BlogEditPage createNewBlogEditPage() {
return new BlogEditPage(Model.of(new Blog()));
}
@Test
public void testSaveBlogEntry() {
callBlogEditPage();
submitBlogForm();
assertBlogPage();
}
private void callBlogEditPage() {
tester.startPage(createNewBlogEditPage());
tester.assertRenderedPage(BlogEditPage.class);
}
@Test
public void testEditBlogEntry() {
navigateToBlogEditPage();
submitBlogForm();
assertBlogPage();
String s = tester.getServletResponse().getDocument();
assertFalse(s.contains("This is a sample blog entry."));
}
private void navigateToBlogEditPage() {
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("This is a sample blog entry.");
tester.debugComponentTrees();
- tester.clickLink("repeatingBlogEntries:1:blogView:authorButtons:editLink");
+ tester.clickLink("repeatingBlogEntries:2:blogView:authorButtons:editLink");
tester.assertRenderedPage(BlogEditPage.class);
tester.assertContains("This is a sample blog entry.");
}
private void assertBlogPage() {
String expectedMsgs[] = PortalTestUtil.getMessage("msg.saved", createNewBlogEditPage());
tester.assertRenderedPage(BlogPage.class);
tester.assertInfoMessages(expectedMsgs);
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("testing headline");
tester.assertContains("testing content");
}
private void submitBlogForm() {
FormTester form = tester.newFormTester("form");
form.setValue("tags", "these are tags");
form.setValue("headline", "testing headline");
form.setValue("content", "testing content");
form.submit();
}
}
| true | true | private void navigateToBlogEditPage() {
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("This is a sample blog entry.");
tester.debugComponentTrees();
tester.clickLink("repeatingBlogEntries:1:blogView:authorButtons:editLink");
tester.assertRenderedPage(BlogEditPage.class);
tester.assertContains("This is a sample blog entry.");
}
| private void navigateToBlogEditPage() {
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("This is a sample blog entry.");
tester.debugComponentTrees();
tester.clickLink("repeatingBlogEntries:2:blogView:authorButtons:editLink");
tester.assertRenderedPage(BlogEditPage.class);
tester.assertContains("This is a sample blog entry.");
}
|
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/bizlogic/SPPXMLParser.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/bizlogic/SPPXMLParser.java
index f64103e30..1ef1c1c5c 100644
--- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/bizlogic/SPPXMLParser.java
+++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/bizlogic/SPPXMLParser.java
@@ -1,164 +1,164 @@
package edu.wustl.catissuecore.bizlogic;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.xml.bind.JAXBElement;
import org.xml.sax.SAXException;
import edu.common.dynamicextensions.domain.userinterface.Container;
import edu.common.dynamicextensions.domaininterface.AbstractEntityInterface;
import edu.common.dynamicextensions.domaininterface.EntityGroupInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.common.dynamicextensions.util.DynamicExtensionsUtility;
import edu.wustl.catissuecore.domain.processingprocedure.Action;
import edu.wustl.catissuecore.processingprocedure.EventType;
import edu.wustl.catissuecore.processingprocedure.SPPType;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.metadata.XMLUtility;
import edu.wustl.common.exception.ApplicationException;
import edu.wustl.common.exception.BizLogicException;
public final class SPPXMLParser
{
private static SPPXMLParser parser;
private SPPXMLParser()
{
}
/**
* get the only instance of this class
* @return the only instance of this class
*/
public static SPPXMLParser getInstance()
{
if (parser==null)
{
parser= new SPPXMLParser();
}
return parser;
}
/**
* Parses the XML file and returns the list of action objects.
* @param xmlFile xmlFile
* @param inputStream inputStream
* @return actionList
* @throws DynamicExtensionsSystemException DynamicExtensionsSystemException
* @throws SAXException SAXException
* @throws BizLogicException
*/
public Set<Action> parseXML(String xmlFile, InputStream inputStream) throws DynamicExtensionsSystemException, SAXException, BizLogicException
{
Set<Action> actionList = new HashSet<Action>();
final String packageName = SPPType.class.getPackage().getName();
final JAXBElement jAXBElement = (JAXBElement) XMLUtility.getJavaObjectForXML(xmlFile,
inputStream, packageName, Constants.SPP_XSD_FILENAME);
SPPType spp = (SPPType)jAXBElement.getValue();
List<EventType> events = spp.getEvent();
for(EventType event : events)
{
populateActionList(actionList, event);
}
handleActionErrors(actionList);
return actionList;
}
/**
* Populates the list of actions belonging to an SPP.
* @param actionList actionList
* @param event event
* @throws DynamicExtensionsSystemException
*/
private void populateActionList(Set<Action> actionList, EventType event) throws DynamicExtensionsSystemException
{
String name = event.getName();
String barcode = event.getBarcode();
Long order = event.getOrder();
String entityGrp = event.getEntityGroupName();
String activity = event.getActivity();
String uniqueId = event.getUniqueId();
if(activity == null)
{
activity = Constants.ACTIVE;
}
if(barcode != null && barcode.length() == 0)
{
barcode = null;
}
Action actionObj = new Action();
EntityGroupInterface entityGroup = DynamicExtensionsUtility.getEntityGroupByName(entityGrp);
if(entityGroup == null)
{
- throw new DynamicExtensionsSystemException(Constants.SPP_ENTITY_GRP_ERROR+": '"+entityGrp+"'");
+ throw new DynamicExtensionsSystemException("The group name '"+entityGrp+"' specified is not present in the system");
}
EntityInterface entity = entityGroup.getEntityByName(name);
if(entity == null)
{
- throw new DynamicExtensionsSystemException(Constants.SPP_EVENT_ERROR+": '"+name+"'");
+ throw new DynamicExtensionsSystemException("The event name '"+name+"' specified is not present in the system");
}
Collection<AbstractEntityInterface> containers = entity.getContainerCollection();
Iterator<AbstractEntityInterface> itr = containers.iterator();
if(itr.hasNext())
{
Container container = (Container)itr.next();
actionObj.setContainerId(container.getId());
}
actionObj.setBarcode(barcode);
actionObj.setActionOrder(order);
actionObj.setUniqueId(uniqueId);
actionObj.setActivityStatus(activity);
actionList.add(actionObj);
}
/**
* Check the XML for validations and throw appropriate exception depending upon the error.
* @param actionList actionList
* @throws BizLogicException BizLogicException
*/
private void handleActionErrors(Set<Action> actionList) throws BizLogicException
{
for (Action action : actionList)
{
for (Action currentAction : actionList)
{
if (action != currentAction)
{
if (action.getUniqueId().equals(currentAction.getUniqueId()))
{
ApplicationException appExp = new ApplicationException(null, null,
Constants.UNIQUE_ID_ERROR);
appExp.setCustomizedMsg(Constants.UNIQUE_ID_ERROR);
throw new BizLogicException(appExp.getErrorKey(), appExp, Constants.UNIQUE_ID_ERROR);
}
else if (action.getBarcode() != null
&& action.getBarcode().equals(currentAction.getBarcode()))
{
ApplicationException appExp = new ApplicationException(null, null,
Constants.EVENT_BARCODE_ERROR);
appExp.setCustomizedMsg(Constants.EVENT_BARCODE_ERROR);
throw new BizLogicException(appExp.getErrorKey(), appExp, Constants.EVENT_BARCODE_ERROR);
}
else if (action.getActionOrder().equals(currentAction.getActionOrder()))
{
ApplicationException appExp = new ApplicationException(null, null,
Constants.EVENT_ORDER_ERROR);
appExp.setCustomizedMsg(Constants.EVENT_ORDER_ERROR);
throw new BizLogicException(appExp.getErrorKey(), appExp, Constants.EVENT_ORDER_ERROR);
}
}
}
}
}
}
| false | true | private void populateActionList(Set<Action> actionList, EventType event) throws DynamicExtensionsSystemException
{
String name = event.getName();
String barcode = event.getBarcode();
Long order = event.getOrder();
String entityGrp = event.getEntityGroupName();
String activity = event.getActivity();
String uniqueId = event.getUniqueId();
if(activity == null)
{
activity = Constants.ACTIVE;
}
if(barcode != null && barcode.length() == 0)
{
barcode = null;
}
Action actionObj = new Action();
EntityGroupInterface entityGroup = DynamicExtensionsUtility.getEntityGroupByName(entityGrp);
if(entityGroup == null)
{
throw new DynamicExtensionsSystemException(Constants.SPP_ENTITY_GRP_ERROR+": '"+entityGrp+"'");
}
EntityInterface entity = entityGroup.getEntityByName(name);
if(entity == null)
{
throw new DynamicExtensionsSystemException(Constants.SPP_EVENT_ERROR+": '"+name+"'");
}
Collection<AbstractEntityInterface> containers = entity.getContainerCollection();
Iterator<AbstractEntityInterface> itr = containers.iterator();
if(itr.hasNext())
{
Container container = (Container)itr.next();
actionObj.setContainerId(container.getId());
}
actionObj.setBarcode(barcode);
actionObj.setActionOrder(order);
actionObj.setUniqueId(uniqueId);
actionObj.setActivityStatus(activity);
actionList.add(actionObj);
}
| private void populateActionList(Set<Action> actionList, EventType event) throws DynamicExtensionsSystemException
{
String name = event.getName();
String barcode = event.getBarcode();
Long order = event.getOrder();
String entityGrp = event.getEntityGroupName();
String activity = event.getActivity();
String uniqueId = event.getUniqueId();
if(activity == null)
{
activity = Constants.ACTIVE;
}
if(barcode != null && barcode.length() == 0)
{
barcode = null;
}
Action actionObj = new Action();
EntityGroupInterface entityGroup = DynamicExtensionsUtility.getEntityGroupByName(entityGrp);
if(entityGroup == null)
{
throw new DynamicExtensionsSystemException("The group name '"+entityGrp+"' specified is not present in the system");
}
EntityInterface entity = entityGroup.getEntityByName(name);
if(entity == null)
{
throw new DynamicExtensionsSystemException("The event name '"+name+"' specified is not present in the system");
}
Collection<AbstractEntityInterface> containers = entity.getContainerCollection();
Iterator<AbstractEntityInterface> itr = containers.iterator();
if(itr.hasNext())
{
Container container = (Container)itr.next();
actionObj.setContainerId(container.getId());
}
actionObj.setBarcode(barcode);
actionObj.setActionOrder(order);
actionObj.setUniqueId(uniqueId);
actionObj.setActivityStatus(activity);
actionList.add(actionObj);
}
|
diff --git a/luni/src/test/java/libcore/java/util/FormatterTest.java b/luni/src/test/java/libcore/java/util/FormatterTest.java
index ce33c271a..00d0ab74c 100644
--- a/luni/src/test/java/libcore/java/util/FormatterTest.java
+++ b/luni/src/test/java/libcore/java/util/FormatterTest.java
@@ -1,129 +1,129 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libcore.java.util;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
public class FormatterTest extends junit.framework.TestCase {
public void test_numberLocalization() throws Exception {
Locale arabic = new Locale("ar");
// Check the fast path for %d:
assertEquals("12 \u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u0660 34",
String.format(arabic, "12 %d 34", 1234567890));
// And the slow path too:
assertEquals("12 \u0661\u066c\u0662\u0663\u0664\u066c\u0665\u0666\u0667\u066c\u0668\u0669\u0660 34",
String.format(arabic, "12 %,d 34", 1234567890));
// And three localized floating point formats:
- assertEquals("12 \u0661\u066b\u0662\u0663\u0660e+\u0660\u0660 34",
+ assertEquals("12 \u0661\u066b\u0662\u0663\u0660\u0627\u0633+\u0660\u0660 34",
String.format(arabic, "12 %.3e 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663\u0660 34",
String.format(arabic, "12 %.3f 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663 34",
String.format(arabic, "12 %.3g 34", 1.23));
// And date/time formatting (we assume that all time/date number formatting is done by the
// same code, so this is representative):
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-08:00"));
c.setTimeInMillis(0);
assertEquals("12 \u0661\u0666:\u0660\u0660:\u0660\u0660 34",
String.format(arabic, "12 %tT 34", c));
// These shouldn't get localized:
assertEquals("1234", String.format(arabic, "1234"));
assertEquals("1234", String.format(arabic, "%s", "1234"));
assertEquals("1234", String.format(arabic, "%s", 1234));
assertEquals("2322", String.format(arabic, "%o", 1234));
assertEquals("4d2", String.format(arabic, "%x", 1234));
assertEquals("0x1.0p0", String.format(arabic, "%a", 1.0));
}
// http://b/2301938
public void test_uppercaseConversions() throws Exception {
// In most locales, the upper-case equivalent of "i" is "I".
assertEquals("JAKOB ARJOUNI", String.format(Locale.US, "%S", "jakob arjouni"));
// In Turkish-language locales, there's a dotted capital "i".
assertEquals("JAKOB ARJOUN\u0130", String.format(new Locale("tr", "TR"), "%S", "jakob arjouni"));
}
// Creating a NumberFormat is expensive, so we like to reuse them, but we need to be careful
// because they're mutable.
public void test_NumberFormat_reuse() throws Exception {
assertEquals("7.000000 7", String.format("%.6f %d", 7.0, 7));
}
public void test_grouping() throws Exception {
// The interesting case is -123, where you might naively output "-,123" if you're just
// inserting a separator every three characters. The cases where there are three digits
// before the first separator may also be interesting.
assertEquals("-1", String.format("%,d", -1));
assertEquals("-12", String.format("%,d", -12));
assertEquals("-123", String.format("%,d", -123));
assertEquals("-1,234", String.format("%,d", -1234));
assertEquals("-12,345", String.format("%,d", -12345));
assertEquals("-123,456", String.format("%,d", -123456));
assertEquals("-1,234,567", String.format("%,d", -1234567));
assertEquals("-12,345,678", String.format("%,d", -12345678));
assertEquals("-123,456,789", String.format("%,d", -123456789));
assertEquals("1", String.format("%,d", 1));
assertEquals("12", String.format("%,d", 12));
assertEquals("123", String.format("%,d", 123));
assertEquals("1,234", String.format("%,d", 1234));
assertEquals("12,345", String.format("%,d", 12345));
assertEquals("123,456", String.format("%,d", 123456));
assertEquals("1,234,567", String.format("%,d", 1234567));
assertEquals("12,345,678", String.format("%,d", 12345678));
assertEquals("123,456,789", String.format("%,d", 123456789));
}
public void test_formatNull() throws Exception {
// We fast-path %s and %d (with no configuration) but need to make sure we handle the
// special case of the null argument...
assertEquals("null", String.format(Locale.US, "%s", (String) null));
assertEquals("null", String.format(Locale.US, "%d", (Integer) null));
// ...without screwing up conversions that don't take an argument.
assertEquals("%", String.format(Locale.US, "%%"));
}
// Alleged regression tests for historical bugs. (It's unclear whether the bugs were in
// BigDecimal or Formatter.)
public void test_BigDecimalFormatting() throws Exception {
BigDecimal[] input = new BigDecimal[] {
new BigDecimal("20.00000"),
new BigDecimal("20.000000"),
new BigDecimal(".2"),
new BigDecimal("2"),
new BigDecimal("-2"),
new BigDecimal("200000000000000000000000"),
new BigDecimal("20000000000000000000000000000000000000000000000000")
};
String[] output = new String[] {
"20.00",
"20.00",
"0.20",
"2.00",
"-2.00",
"200000000000000000000000.00",
"20000000000000000000000000000000000000000000000000.00"
};
for (int i = 0; i < input.length; ++i) {
String result = String.format("%.2f", input[i]);
assertEquals("input=\"" + input[i] + "\", " + ",expected=" + output[i] + ",actual=" + result,
output[i], result);
}
}
}
| true | true | public void test_numberLocalization() throws Exception {
Locale arabic = new Locale("ar");
// Check the fast path for %d:
assertEquals("12 \u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u0660 34",
String.format(arabic, "12 %d 34", 1234567890));
// And the slow path too:
assertEquals("12 \u0661\u066c\u0662\u0663\u0664\u066c\u0665\u0666\u0667\u066c\u0668\u0669\u0660 34",
String.format(arabic, "12 %,d 34", 1234567890));
// And three localized floating point formats:
assertEquals("12 \u0661\u066b\u0662\u0663\u0660e+\u0660\u0660 34",
String.format(arabic, "12 %.3e 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663\u0660 34",
String.format(arabic, "12 %.3f 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663 34",
String.format(arabic, "12 %.3g 34", 1.23));
// And date/time formatting (we assume that all time/date number formatting is done by the
// same code, so this is representative):
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-08:00"));
c.setTimeInMillis(0);
assertEquals("12 \u0661\u0666:\u0660\u0660:\u0660\u0660 34",
String.format(arabic, "12 %tT 34", c));
// These shouldn't get localized:
assertEquals("1234", String.format(arabic, "1234"));
assertEquals("1234", String.format(arabic, "%s", "1234"));
assertEquals("1234", String.format(arabic, "%s", 1234));
assertEquals("2322", String.format(arabic, "%o", 1234));
assertEquals("4d2", String.format(arabic, "%x", 1234));
assertEquals("0x1.0p0", String.format(arabic, "%a", 1.0));
}
| public void test_numberLocalization() throws Exception {
Locale arabic = new Locale("ar");
// Check the fast path for %d:
assertEquals("12 \u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u0660 34",
String.format(arabic, "12 %d 34", 1234567890));
// And the slow path too:
assertEquals("12 \u0661\u066c\u0662\u0663\u0664\u066c\u0665\u0666\u0667\u066c\u0668\u0669\u0660 34",
String.format(arabic, "12 %,d 34", 1234567890));
// And three localized floating point formats:
assertEquals("12 \u0661\u066b\u0662\u0663\u0660\u0627\u0633+\u0660\u0660 34",
String.format(arabic, "12 %.3e 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663\u0660 34",
String.format(arabic, "12 %.3f 34", 1.23));
assertEquals("12 \u0661\u066b\u0662\u0663 34",
String.format(arabic, "12 %.3g 34", 1.23));
// And date/time formatting (we assume that all time/date number formatting is done by the
// same code, so this is representative):
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-08:00"));
c.setTimeInMillis(0);
assertEquals("12 \u0661\u0666:\u0660\u0660:\u0660\u0660 34",
String.format(arabic, "12 %tT 34", c));
// These shouldn't get localized:
assertEquals("1234", String.format(arabic, "1234"));
assertEquals("1234", String.format(arabic, "%s", "1234"));
assertEquals("1234", String.format(arabic, "%s", 1234));
assertEquals("2322", String.format(arabic, "%o", 1234));
assertEquals("4d2", String.format(arabic, "%x", 1234));
assertEquals("0x1.0p0", String.format(arabic, "%a", 1.0));
}
|
diff --git a/src/vm/Start.java b/src/vm/Start.java
index c6318e4..9282e95 100644
--- a/src/vm/Start.java
+++ b/src/vm/Start.java
@@ -1,45 +1,45 @@
package vm;
public class Start {
public static void main(String[] args) {
// byte[] instructions =
// {0x00, 0x00, 0x00, 0x00, //0-3: 4-bytes header
// 0x02, 0x01, //4-5: load 1
// //:add_loop
// 0x02, 0x01, //6-7: load 1
// 0x01, //8: add
//
// 0x02, 0x00, //9-10: load 0
// 0x22, //11: load stack[sp - stack[sp]]
// 0x02, 0x04, //12-13: load 4
//
// 0x04, //14: cmp
//
// 0x02, 0x06, //15-16
// 0x02, 0x00, //17-18
// 0x02, 0x00, //19-20
// 0x02, 0x00, //20-21
// (byte)0xB5, //21: jmpnz 0x00000006 (:add_loop)
//
// 0x16}; //20: halt
byte[] instructions =
{0x00, 0x00, 0x00, 0x00, //0-3: 4-bytes header
- 0x02, 0x01, //4-5: load 1
+ 0x02, 0x02, //4-5: load 1
0x02, 0x01, //6-7: load 1
- 0x11, //8: sub
+ 0x71, //8: sub
0x16}; //20: halt
VM vm = new VM();
int processID = vm.createProcess(instructions);
Process process = vm.getProcess(processID);
while(process.isRunning()) {
vm.iterate();
}
System.out.println("1 + 1 + 1 + 1 = " + process.getStack()[process.getSp()]);
System.out.println("flags are: " + process.getFlags() + " (0x1 = ZERO/EQUAL, 0x2 = OVERFLOW/GREATER)");
}
}
| false | true | public static void main(String[] args) {
// byte[] instructions =
// {0x00, 0x00, 0x00, 0x00, //0-3: 4-bytes header
// 0x02, 0x01, //4-5: load 1
// //:add_loop
// 0x02, 0x01, //6-7: load 1
// 0x01, //8: add
//
// 0x02, 0x00, //9-10: load 0
// 0x22, //11: load stack[sp - stack[sp]]
// 0x02, 0x04, //12-13: load 4
//
// 0x04, //14: cmp
//
// 0x02, 0x06, //15-16
// 0x02, 0x00, //17-18
// 0x02, 0x00, //19-20
// 0x02, 0x00, //20-21
// (byte)0xB5, //21: jmpnz 0x00000006 (:add_loop)
//
// 0x16}; //20: halt
byte[] instructions =
{0x00, 0x00, 0x00, 0x00, //0-3: 4-bytes header
0x02, 0x01, //4-5: load 1
0x02, 0x01, //6-7: load 1
0x11, //8: sub
0x16}; //20: halt
VM vm = new VM();
int processID = vm.createProcess(instructions);
Process process = vm.getProcess(processID);
while(process.isRunning()) {
vm.iterate();
}
System.out.println("1 + 1 + 1 + 1 = " + process.getStack()[process.getSp()]);
System.out.println("flags are: " + process.getFlags() + " (0x1 = ZERO/EQUAL, 0x2 = OVERFLOW/GREATER)");
}
| public static void main(String[] args) {
// byte[] instructions =
// {0x00, 0x00, 0x00, 0x00, //0-3: 4-bytes header
// 0x02, 0x01, //4-5: load 1
// //:add_loop
// 0x02, 0x01, //6-7: load 1
// 0x01, //8: add
//
// 0x02, 0x00, //9-10: load 0
// 0x22, //11: load stack[sp - stack[sp]]
// 0x02, 0x04, //12-13: load 4
//
// 0x04, //14: cmp
//
// 0x02, 0x06, //15-16
// 0x02, 0x00, //17-18
// 0x02, 0x00, //19-20
// 0x02, 0x00, //20-21
// (byte)0xB5, //21: jmpnz 0x00000006 (:add_loop)
//
// 0x16}; //20: halt
byte[] instructions =
{0x00, 0x00, 0x00, 0x00, //0-3: 4-bytes header
0x02, 0x02, //4-5: load 1
0x02, 0x01, //6-7: load 1
0x71, //8: sub
0x16}; //20: halt
VM vm = new VM();
int processID = vm.createProcess(instructions);
Process process = vm.getProcess(processID);
while(process.isRunning()) {
vm.iterate();
}
System.out.println("1 + 1 + 1 + 1 = " + process.getStack()[process.getSp()]);
System.out.println("flags are: " + process.getFlags() + " (0x1 = ZERO/EQUAL, 0x2 = OVERFLOW/GREATER)");
}
|
diff --git a/src/test/java/org/weymouth/demo/model/DataTest.java b/src/test/java/org/weymouth/demo/model/DataTest.java
index d2b869f..96eb3db 100755
--- a/src/test/java/org/weymouth/demo/model/DataTest.java
+++ b/src/test/java/org/weymouth/demo/model/DataTest.java
@@ -1,18 +1,18 @@
package org.weymouth.demo.model;
import junit.framework.Assert;
import org.junit.Test;
public class DataTest {
@Test
public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
- // data = null; // this will cause the test to fail; without being a compile error
+ data = null; // this will cause the test to fail; without being a compile error
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
}
| true | true | public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
// data = null; // this will cause the test to fail; without being a compile error
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
| public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
data = null; // this will cause the test to fail; without being a compile error
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
|
diff --git a/vlc-android/src/org/videolan/vlc/gui/video/MediaInfoAdapter.java b/vlc-android/src/org/videolan/vlc/gui/video/MediaInfoAdapter.java
index e2bb7073..6b24fc98 100644
--- a/vlc-android/src/org/videolan/vlc/gui/video/MediaInfoAdapter.java
+++ b/vlc-android/src/org/videolan/vlc/gui/video/MediaInfoAdapter.java
@@ -1,105 +1,105 @@
/*****************************************************************************
* MediaInfoAdapter.java
*****************************************************************************
* Copyright © 2011-2012 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.gui.video;
import org.videolan.vlc.R;
import org.videolan.vlc.TrackInfo;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MediaInfoAdapter extends ArrayAdapter<TrackInfo> {
public MediaInfoAdapter(Context context) {
super(context, 0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- v = inflater.inflate(R.layout.audio_browser_playlist_child, parent, false);
+ v = inflater.inflate(R.layout.audio_browser_item, parent, false);
holder = new ViewHolder();
holder.title = (TextView) v.findViewById(R.id.title);
- holder.text = (TextView) v.findViewById(R.id.text);
+ holder.text = (TextView) v.findViewById(R.id.artist);
v.setTag(holder);
} else
holder = (ViewHolder) v.getTag();
TrackInfo track = getItem(position);
String title;
StringBuilder textBuilder = new StringBuilder(1024);
Resources res = getContext().getResources();
switch (track.Type)
{
case TrackInfo.TYPE_AUDIO:
title = res.getString(R.string.track_audio);
appendCommon(textBuilder, res, track);
appendAudio(textBuilder, res, track);
break;
case TrackInfo.TYPE_VIDEO:
title = res.getString(R.string.track_video);
appendCommon(textBuilder, res, track);
appendVideo(textBuilder, res, track);
break;
case TrackInfo.TYPE_TEXT:
title = res.getString(R.string.track_text);
appendCommon(textBuilder, res, track);
break;
default:
title = res.getString(R.string.track_unknown);
}
holder.title.setText(title);
holder.text.setText(textBuilder.toString());
return v;
}
private void appendCommon(StringBuilder textBuilder, Resources res, TrackInfo track) {
textBuilder.append(res.getString(R.string.track_codec_info, track.Codec));
if (track.Language != null && !track.Language.equalsIgnoreCase("und"))
textBuilder.append(res.getString(R.string.track_language_info, track.Language));
}
private void appendAudio(StringBuilder textBuilder, Resources res, TrackInfo track) {
textBuilder.append(res.getQuantityString(R.plurals.track_channels_info, track.Channels, track.Channels));
textBuilder.append(res.getString(R.string.track_samplerate_info, track.Samplerate));
}
private void appendVideo(StringBuilder textBuilder, Resources res, TrackInfo track) {
textBuilder.append(res.getString(R.string.track_resolution_info, track.Width, track.Height));
textBuilder.append(res.getString(R.string.track_framerate_info, track.Framerate));
}
static class ViewHolder {
TextView title;
TextView text;
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.audio_browser_playlist_child, parent, false);
holder = new ViewHolder();
holder.title = (TextView) v.findViewById(R.id.title);
holder.text = (TextView) v.findViewById(R.id.text);
v.setTag(holder);
} else
holder = (ViewHolder) v.getTag();
TrackInfo track = getItem(position);
String title;
StringBuilder textBuilder = new StringBuilder(1024);
Resources res = getContext().getResources();
switch (track.Type)
{
case TrackInfo.TYPE_AUDIO:
title = res.getString(R.string.track_audio);
appendCommon(textBuilder, res, track);
appendAudio(textBuilder, res, track);
break;
case TrackInfo.TYPE_VIDEO:
title = res.getString(R.string.track_video);
appendCommon(textBuilder, res, track);
appendVideo(textBuilder, res, track);
break;
case TrackInfo.TYPE_TEXT:
title = res.getString(R.string.track_text);
appendCommon(textBuilder, res, track);
break;
default:
title = res.getString(R.string.track_unknown);
}
holder.title.setText(title);
holder.text.setText(textBuilder.toString());
return v;
}
| public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.audio_browser_item, parent, false);
holder = new ViewHolder();
holder.title = (TextView) v.findViewById(R.id.title);
holder.text = (TextView) v.findViewById(R.id.artist);
v.setTag(holder);
} else
holder = (ViewHolder) v.getTag();
TrackInfo track = getItem(position);
String title;
StringBuilder textBuilder = new StringBuilder(1024);
Resources res = getContext().getResources();
switch (track.Type)
{
case TrackInfo.TYPE_AUDIO:
title = res.getString(R.string.track_audio);
appendCommon(textBuilder, res, track);
appendAudio(textBuilder, res, track);
break;
case TrackInfo.TYPE_VIDEO:
title = res.getString(R.string.track_video);
appendCommon(textBuilder, res, track);
appendVideo(textBuilder, res, track);
break;
case TrackInfo.TYPE_TEXT:
title = res.getString(R.string.track_text);
appendCommon(textBuilder, res, track);
break;
default:
title = res.getString(R.string.track_unknown);
}
holder.title.setText(title);
holder.text.setText(textBuilder.toString());
return v;
}
|
diff --git a/diagnostic/command/src/main/java/org/apache/karaf/diagnostic/command/DumpCommand.java b/diagnostic/command/src/main/java/org/apache/karaf/diagnostic/command/DumpCommand.java
index eba3812e..cc1951ed 100644
--- a/diagnostic/command/src/main/java/org/apache/karaf/diagnostic/command/DumpCommand.java
+++ b/diagnostic/command/src/main/java/org/apache/karaf/diagnostic/command/DumpCommand.java
@@ -1,101 +1,101 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.diagnostic.command;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.apache.karaf.diagnostic.core.DumpDestination;
import org.apache.karaf.diagnostic.core.DumpProvider;
import org.apache.karaf.diagnostic.core.common.DirectoryDumpDestination;
import org.apache.karaf.diagnostic.core.common.ZipDumpDestination;
import org.apache.karaf.shell.console.OsgiCommandSupport;
/**
* Command to create dump from shell.
*
* @author ldywicki
*/
@Command(scope = "dev", name = "create-dump", description = "Creates zip archive wich diagnostic info.")
public class DumpCommand extends OsgiCommandSupport {
/**
* Registered dump providers.
*/
private List<DumpProvider> providers = new LinkedList<DumpProvider>();
/**
* Directory switch.
*/
@Option(name = "-d", aliases = "--directory", description = "Creates dump in directory instead ZIP")
boolean directory;
/**
* Name of created directory or archive.
*/
@Argument(name = "name", description = "Name of created zip or directory", required = false)
String fileName;
@Override
protected Object doExecute() throws Exception {
DumpDestination destination;
if (providers.isEmpty()) {
session.getConsole().println("Unable to create dump. No providers were found");
return null;
}
// create default file name if none provided
- if (fileName == null || fileName.isEmpty()) {
+ if (fileName == null || fileName.trim().length() == 0) {
fileName = SimpleDateFormat.getDateTimeInstance().format(new Date());
if (!directory) {
fileName += ".zip";
}
}
File target = new File(fileName);
// if directory switch is on, create dump in directory
if (directory) {
destination = new DirectoryDumpDestination(target);
} else {
destination = new ZipDumpDestination(target);
}
for (DumpProvider provider : providers) {
provider.createDump(destination);
}
destination.save();
session.getConsole().println("Diagnostic dump created.");
return null;
}
/**
* Sets dump providers to use.
*
* @param providers Providers.
*/
public void setProviders(List<DumpProvider> providers) {
this.providers = providers;
}
}
| true | true | protected Object doExecute() throws Exception {
DumpDestination destination;
if (providers.isEmpty()) {
session.getConsole().println("Unable to create dump. No providers were found");
return null;
}
// create default file name if none provided
if (fileName == null || fileName.isEmpty()) {
fileName = SimpleDateFormat.getDateTimeInstance().format(new Date());
if (!directory) {
fileName += ".zip";
}
}
File target = new File(fileName);
// if directory switch is on, create dump in directory
if (directory) {
destination = new DirectoryDumpDestination(target);
} else {
destination = new ZipDumpDestination(target);
}
for (DumpProvider provider : providers) {
provider.createDump(destination);
}
destination.save();
session.getConsole().println("Diagnostic dump created.");
return null;
}
| protected Object doExecute() throws Exception {
DumpDestination destination;
if (providers.isEmpty()) {
session.getConsole().println("Unable to create dump. No providers were found");
return null;
}
// create default file name if none provided
if (fileName == null || fileName.trim().length() == 0) {
fileName = SimpleDateFormat.getDateTimeInstance().format(new Date());
if (!directory) {
fileName += ".zip";
}
}
File target = new File(fileName);
// if directory switch is on, create dump in directory
if (directory) {
destination = new DirectoryDumpDestination(target);
} else {
destination = new ZipDumpDestination(target);
}
for (DumpProvider provider : providers) {
provider.createDump(destination);
}
destination.save();
session.getConsole().println("Diagnostic dump created.");
return null;
}
|
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/seasons/TVShowSeasonImageGalleryAdapter.java b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/seasons/TVShowSeasonImageGalleryAdapter.java
index e8003e09..e97b98e3 100644
--- a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/seasons/TVShowSeasonImageGalleryAdapter.java
+++ b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/tv/seasons/TVShowSeasonImageGalleryAdapter.java
@@ -1,227 +1,227 @@
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package us.nineworlds.serenity.ui.browser.tv.seasons;
import java.util.ArrayList;
import java.util.List;
import us.nineworlds.serenity.SerenityApplication;
import us.nineworlds.serenity.core.model.impl.AbstractSeriesContentInfo;
import us.nineworlds.serenity.core.model.impl.TVShowSeriesInfo;
import us.nineworlds.serenity.core.services.ShowSeasonRetrievalIntentService;
import us.nineworlds.serenity.ui.util.ImageUtils;
import us.nineworlds.serenity.ui.views.TVShowImageView;
import us.nineworlds.serenity.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
/**
*
* @author dcarver
*
*/
public class TVShowSeasonImageGalleryAdapter extends BaseAdapter {
private static List<TVShowSeriesInfo> seasonList = null;
private static Activity context;
private ImageLoader imageLoader;
private static ProgressDialog pd;
private Handler handler;
private String key;
private static TVShowSeasonImageGalleryAdapter notifyAdapter;
public TVShowSeasonImageGalleryAdapter(Context c, String key) {
context = (Activity) c;
this.key = key;
seasonList = new ArrayList<TVShowSeriesInfo>();
imageLoader = SerenityApplication.getImageLoader();
notifyAdapter = this;
fetchData();
}
protected void fetchData() {
pd = ProgressDialog.show(context, "", "Retrieving Seasons");
handler = new ShowSeasonRetrievalHandler();
Messenger messenger = new Messenger(handler);
Intent intent = new Intent(context,
ShowSeasonRetrievalIntentService.class);
intent.putExtra("MESSENGER", messenger);
intent.putExtra("key", key);
context.startService(intent);
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return seasonList.size();
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem(int position) {
return seasonList.get(position);
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId(int position) {
return position;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View galleryCellView = context.getLayoutInflater().inflate(R.layout.poster_tvshow_indicator_view, null);
AbstractSeriesContentInfo pi = seasonList.get(position);
TVShowImageView mpiv = (TVShowImageView) galleryCellView.findViewById(R.id.posterImageView);
mpiv.setPosterInfo(pi);
mpiv.setBackgroundResource(R.drawable.gallery_item_background);
mpiv.setScaleType(ImageView.ScaleType.FIT_XY);
- int width = ImageUtils.getDPI(160, context);
- int height = ImageUtils.getDPI(220, context);
+ int width = ImageUtils.getDPI(120, context);
+ int height = ImageUtils.getDPI(180, context);
mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height));
imageLoader.displayImage(pi.getImageURL(), mpiv);
galleryCellView.setLayoutParams(new Gallery.LayoutParams(width, height));
int unwatched = 0;
if (pi.getShowsUnwatched() != null) {
unwatched = Integer.parseInt(pi.getShowsUnwatched());
}
ImageView watchedView = (ImageView) galleryCellView.findViewById(R.id.posterWatchedIndicator);
if (unwatched == 0) {
watchedView.setImageResource(R.drawable.overlaywatched);
}
int watched = 0;
if (pi.getShowsWatched() != null ) {
watched = Integer.parseInt(pi.getShowsWatched());
}
int totalShows = unwatched + watched;
if (unwatched != totalShows) {
toggleProgressIndicator(galleryCellView, watched, totalShows, watchedView);
}
return galleryCellView;
}
/**
* @param galleryCellView
* @param pi
* @param watchedView
*/
protected void toggleProgressIndicator(View galleryCellView, int dividend,
int divisor, ImageView watchedView) {
final float percentWatched = Float.valueOf(dividend)
/ Float.valueOf(divisor);
if (percentWatched < 0.99f) {
final ProgressBar view = (ProgressBar) galleryCellView
.findViewById(R.id.posterInprogressIndicator);
int progress = Float.valueOf(percentWatched * 100).intValue();
if (progress < 10) {
progress = 10;
}
view.setProgress(progress);
view.setVisibility(View.VISIBLE);
watchedView.setVisibility(View.INVISIBLE);
}
}
private static class ShowSeasonRetrievalHandler extends Handler {
@Override
public void handleMessage(Message msg) {
seasonList = (List<TVShowSeriesInfo>) msg.obj;
notifyAdapter.notifyDataSetChanged();
pd.dismiss();
if (seasonList != null) {
if (!seasonList.isEmpty()) {
TextView titleView = (TextView) context
.findViewById(R.id.tvShowSeasonsDetailText);
titleView.setText(seasonList.get(0).getParentTitle());
TextView textView = (TextView) context
.findViewById(R.id.tvShowSeasonsItemCount);
textView.setText(Integer.toString(seasonList.size())
+ context.getString(R.string._item_s_));
}
}
Gallery gallery = (Gallery) context.findViewById(R.id.tvShowSeasonImageGallery);
if (gallery != null) {
gallery.requestFocusFromTouch();
}
}
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
View galleryCellView = context.getLayoutInflater().inflate(R.layout.poster_tvshow_indicator_view, null);
AbstractSeriesContentInfo pi = seasonList.get(position);
TVShowImageView mpiv = (TVShowImageView) galleryCellView.findViewById(R.id.posterImageView);
mpiv.setPosterInfo(pi);
mpiv.setBackgroundResource(R.drawable.gallery_item_background);
mpiv.setScaleType(ImageView.ScaleType.FIT_XY);
int width = ImageUtils.getDPI(160, context);
int height = ImageUtils.getDPI(220, context);
mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height));
imageLoader.displayImage(pi.getImageURL(), mpiv);
galleryCellView.setLayoutParams(new Gallery.LayoutParams(width, height));
int unwatched = 0;
if (pi.getShowsUnwatched() != null) {
unwatched = Integer.parseInt(pi.getShowsUnwatched());
}
ImageView watchedView = (ImageView) galleryCellView.findViewById(R.id.posterWatchedIndicator);
if (unwatched == 0) {
watchedView.setImageResource(R.drawable.overlaywatched);
}
int watched = 0;
if (pi.getShowsWatched() != null ) {
watched = Integer.parseInt(pi.getShowsWatched());
}
int totalShows = unwatched + watched;
if (unwatched != totalShows) {
toggleProgressIndicator(galleryCellView, watched, totalShows, watchedView);
}
return galleryCellView;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View galleryCellView = context.getLayoutInflater().inflate(R.layout.poster_tvshow_indicator_view, null);
AbstractSeriesContentInfo pi = seasonList.get(position);
TVShowImageView mpiv = (TVShowImageView) galleryCellView.findViewById(R.id.posterImageView);
mpiv.setPosterInfo(pi);
mpiv.setBackgroundResource(R.drawable.gallery_item_background);
mpiv.setScaleType(ImageView.ScaleType.FIT_XY);
int width = ImageUtils.getDPI(120, context);
int height = ImageUtils.getDPI(180, context);
mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height));
imageLoader.displayImage(pi.getImageURL(), mpiv);
galleryCellView.setLayoutParams(new Gallery.LayoutParams(width, height));
int unwatched = 0;
if (pi.getShowsUnwatched() != null) {
unwatched = Integer.parseInt(pi.getShowsUnwatched());
}
ImageView watchedView = (ImageView) galleryCellView.findViewById(R.id.posterWatchedIndicator);
if (unwatched == 0) {
watchedView.setImageResource(R.drawable.overlaywatched);
}
int watched = 0;
if (pi.getShowsWatched() != null ) {
watched = Integer.parseInt(pi.getShowsWatched());
}
int totalShows = unwatched + watched;
if (unwatched != totalShows) {
toggleProgressIndicator(galleryCellView, watched, totalShows, watchedView);
}
return galleryCellView;
}
|
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java
index c488fe5cf..39032117c 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java
@@ -1,137 +1,151 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (c) 2010 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*
* Sun gratefully acknowledges that this software was originally authored
* and developed by Kenneth Bradley Russell and Christopher John Kline.
*/
package jogamp.opengl.x11.glx;
import javax.media.nativewindow.*;
import javax.media.nativewindow.x11.*;
import javax.media.opengl.*;
import jogamp.opengl.*;
import jogamp.nativewindow.WrappedSurface;
public class X11ExternalGLXContext extends X11GLXContext {
private GLContext lastContext;
private X11ExternalGLXContext(Drawable drawable, long ctx) {
super(drawable, null);
this.contextHandle = ctx;
GLContextShareSet.contextCreated(this);
setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY);
getGLStateTracker().setEnabled(false); // external context usage can't track state in Java
}
protected static X11ExternalGLXContext create(GLDrawableFactory factory, GLProfile glp) {
long ctx = GLX.glXGetCurrentContext();
if (ctx == 0) {
throw new GLException("Error: current context null");
}
long display = GLX.glXGetCurrentDisplay();
if (display == 0) {
throw new GLException("Error: current display null");
}
long drawable = GLX.glXGetCurrentDrawable();
if (drawable == 0) {
throw new GLException("Error: attempted to make an external GLDrawable without a drawable/context current");
}
int[] val = new int[1];
GLX.glXQueryContext(display, ctx, GLX.GLX_SCREEN, val, 0);
X11GraphicsScreen x11Screen = (X11GraphicsScreen) X11GraphicsScreen.createScreenDevice(display, val[0]);
GLX.glXQueryContext(display, ctx, GLX.GLX_FBCONFIG_ID, val, 0);
- X11GLXGraphicsConfiguration cfg = X11GLXGraphicsConfiguration.create(glp, x11Screen, val[0]);
+ X11GLXGraphicsConfiguration cfg = null;
+ // sometimes glXQueryContext on an external context gives us a framebuffer config ID
+ // of 0, which doesn't work in a subsequent call to glXChooseFBConfig; if this happens,
+ // create and use a default config (this has been observed when running on CentOS 5.5 inside
+ // of VMWare Server 2.0 with the Mesa 6.5.1 drivers)
+ if( 0 == X11GLXGraphicsConfiguration.glXFBConfigID2FBConfig(display, x11Screen.getIndex(), val[0]) ) {
+ GLCapabilities glcapsDefault = new GLCapabilities(GLProfile.getDefault());
+ cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(glcapsDefault, glcapsDefault, null, x11Screen);
+ if(DEBUG) {
+ System.err.println("X11ExternalGLXContext invalid FBCONFIG_ID "+val[0]+", using default cfg: " + cfg);
+ }
+ }
+ else {
+ cfg = X11GLXGraphicsConfiguration.create(glp, x11Screen, val[0]);
+ }
WrappedSurface ns = new WrappedSurface(cfg);
ns.setSurfaceHandle(drawable);
return new X11ExternalGLXContext(new Drawable(factory, ns), ctx);
}
protected boolean createImpl() {
return true;
}
public int makeCurrent() throws GLException {
// Save last context if necessary to allow external GLContexts to
// talk to other GLContexts created by this library
GLContext cur = getCurrent();
if (cur != null && cur != this) {
lastContext = cur;
setCurrent(null);
}
return super.makeCurrent();
}
public void release() throws GLException {
super.release();
setCurrent(lastContext);
lastContext = null;
}
protected void makeCurrentImpl(boolean newCreated) throws GLException {
}
protected void releaseImpl() throws GLException {
}
protected void destroyImpl() throws GLException {
}
// Need to provide the display connection to extension querying APIs
static class Drawable extends X11GLXDrawable {
Drawable(GLDrawableFactory factory, NativeSurface comp) {
super(factory, comp, true);
}
public GLContext createContext(GLContext shareWith) {
throw new GLException("Should not call this");
}
public int getWidth() {
throw new GLException("Should not call this");
}
public int getHeight() {
throw new GLException("Should not call this");
}
public void setSize(int width, int height) {
throw new GLException("Should not call this");
}
}
}
| true | true | protected static X11ExternalGLXContext create(GLDrawableFactory factory, GLProfile glp) {
long ctx = GLX.glXGetCurrentContext();
if (ctx == 0) {
throw new GLException("Error: current context null");
}
long display = GLX.glXGetCurrentDisplay();
if (display == 0) {
throw new GLException("Error: current display null");
}
long drawable = GLX.glXGetCurrentDrawable();
if (drawable == 0) {
throw new GLException("Error: attempted to make an external GLDrawable without a drawable/context current");
}
int[] val = new int[1];
GLX.glXQueryContext(display, ctx, GLX.GLX_SCREEN, val, 0);
X11GraphicsScreen x11Screen = (X11GraphicsScreen) X11GraphicsScreen.createScreenDevice(display, val[0]);
GLX.glXQueryContext(display, ctx, GLX.GLX_FBCONFIG_ID, val, 0);
X11GLXGraphicsConfiguration cfg = X11GLXGraphicsConfiguration.create(glp, x11Screen, val[0]);
WrappedSurface ns = new WrappedSurface(cfg);
ns.setSurfaceHandle(drawable);
return new X11ExternalGLXContext(new Drawable(factory, ns), ctx);
}
| protected static X11ExternalGLXContext create(GLDrawableFactory factory, GLProfile glp) {
long ctx = GLX.glXGetCurrentContext();
if (ctx == 0) {
throw new GLException("Error: current context null");
}
long display = GLX.glXGetCurrentDisplay();
if (display == 0) {
throw new GLException("Error: current display null");
}
long drawable = GLX.glXGetCurrentDrawable();
if (drawable == 0) {
throw new GLException("Error: attempted to make an external GLDrawable without a drawable/context current");
}
int[] val = new int[1];
GLX.glXQueryContext(display, ctx, GLX.GLX_SCREEN, val, 0);
X11GraphicsScreen x11Screen = (X11GraphicsScreen) X11GraphicsScreen.createScreenDevice(display, val[0]);
GLX.glXQueryContext(display, ctx, GLX.GLX_FBCONFIG_ID, val, 0);
X11GLXGraphicsConfiguration cfg = null;
// sometimes glXQueryContext on an external context gives us a framebuffer config ID
// of 0, which doesn't work in a subsequent call to glXChooseFBConfig; if this happens,
// create and use a default config (this has been observed when running on CentOS 5.5 inside
// of VMWare Server 2.0 with the Mesa 6.5.1 drivers)
if( 0 == X11GLXGraphicsConfiguration.glXFBConfigID2FBConfig(display, x11Screen.getIndex(), val[0]) ) {
GLCapabilities glcapsDefault = new GLCapabilities(GLProfile.getDefault());
cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(glcapsDefault, glcapsDefault, null, x11Screen);
if(DEBUG) {
System.err.println("X11ExternalGLXContext invalid FBCONFIG_ID "+val[0]+", using default cfg: " + cfg);
}
}
else {
cfg = X11GLXGraphicsConfiguration.create(glp, x11Screen, val[0]);
}
WrappedSurface ns = new WrappedSurface(cfg);
ns.setSurfaceHandle(drawable);
return new X11ExternalGLXContext(new Drawable(factory, ns), ctx);
}
|
diff --git a/tests/src/org/jboss/test/messaging/core/plugin/postoffice/cluster/DefaultRouterTest.java b/tests/src/org/jboss/test/messaging/core/plugin/postoffice/cluster/DefaultRouterTest.java
index f28b38b6c..640ffaea3 100644
--- a/tests/src/org/jboss/test/messaging/core/plugin/postoffice/cluster/DefaultRouterTest.java
+++ b/tests/src/org/jboss/test/messaging/core/plugin/postoffice/cluster/DefaultRouterTest.java
@@ -1,401 +1,401 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.messaging.core.plugin.postoffice.cluster;
import java.util.List;
import org.jboss.messaging.core.FilterFactory;
import org.jboss.messaging.core.plugin.contract.ClusteredPostOffice;
import org.jboss.messaging.core.plugin.postoffice.Binding;
import org.jboss.messaging.core.plugin.postoffice.cluster.ClusterRouterFactory;
import org.jboss.messaging.core.plugin.postoffice.cluster.DefaultClusteredPostOffice;
import org.jboss.messaging.core.plugin.postoffice.cluster.DefaultRouterFactory;
import org.jboss.messaging.core.plugin.postoffice.cluster.LocalClusteredQueue;
import org.jboss.messaging.core.plugin.postoffice.cluster.MessagePullPolicy;
import org.jboss.messaging.core.plugin.postoffice.cluster.NullMessagePullPolicy;
import org.jboss.test.messaging.core.SimpleFilterFactory;
import org.jboss.test.messaging.core.SimpleReceiver;
import org.jboss.test.messaging.core.plugin.base.ClusteringTestBase;
import EDU.oswego.cs.dl.util.concurrent.QueuedExecutor;
/**
*
* A DefaultRouterTest
*
* @author <a href="mailto:[email protected]">Tim Fox</a>
* @version <tt>$Revision: 1.1 $</tt>
*
* $Id$
*
*/
public class DefaultRouterTest extends ClusteringTestBase
{
// Constants -----------------------------------------------------
// Static --------------------------------------------------------
// Attributes ----------------------------------------------------
// Constructors --------------------------------------------------
public DefaultRouterTest(String name)
{
super(name);
}
// Public --------------------------------------------------------
public void setUp() throws Exception
{
super.setUp();
}
public void tearDown() throws Exception
{
super.tearDown();
}
public void testNotLocalPersistent() throws Throwable
{
notLocal(true);
}
public void testNotLocalNonPersistent() throws Throwable
{
notLocal(false);
}
public void testLocalPersistent() throws Throwable
{
local(true);
}
public void testLocalNonPersistent() throws Throwable
{
local(false);
}
protected void notLocal(boolean persistent) throws Throwable
{
ClusteredPostOffice office1 = null;
ClusteredPostOffice office2 = null;
ClusteredPostOffice office3 = null;
ClusteredPostOffice office4 = null;
ClusteredPostOffice office5 = null;
ClusteredPostOffice office6 = null;
try
{
office1 = createClusteredPostOffice("node1", "testgroup");
office2 = createClusteredPostOffice("node2", "testgroup");
office3 = createClusteredPostOffice("node3", "testgroup");
office4 = createClusteredPostOffice("node4", "testgroup");
office5 = createClusteredPostOffice("node5", "testgroup");
office6 = createClusteredPostOffice("node6", "testgroup");
LocalClusteredQueue queue1 = new LocalClusteredQueue(office2, "node2", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding1 = office2.bindClusteredQueue("topic", queue1);
SimpleReceiver receiver1 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue1.add(receiver1);
LocalClusteredQueue queue2 = new LocalClusteredQueue(office3, "node3", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding2 = office3.bindClusteredQueue("topic", queue2);
SimpleReceiver receiver2 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue2.add(receiver2);
LocalClusteredQueue queue3 = new LocalClusteredQueue(office4, "node4", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding3 = office4.bindClusteredQueue("topic", queue3);
SimpleReceiver receiver3 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue3.add(receiver3);
LocalClusteredQueue queue4 = new LocalClusteredQueue(office5, "node5", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding4 = office5.bindClusteredQueue("topic", queue4);
SimpleReceiver receiver4 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue4.add(receiver4);
LocalClusteredQueue queue5 = new LocalClusteredQueue(office6, "node6", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding5 = office6.bindClusteredQueue("topic", queue5);
SimpleReceiver receiver5 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue5.add(receiver5);
- List msgs = sendMessages("topic", persistent, office1, 3, null);
+ List msgs = sendMessages("topic", persistent, office1, 1, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
- msgs = sendMessages("topic", persistent, office1, 3, null);
+ msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
- msgs = sendMessages("topic", persistent, office1, 3, null);
+ msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkContainsAndAcknowledge(msgs, receiver3, queue1);
checkEmpty(receiver4);
checkEmpty(receiver5);
- msgs = sendMessages("topic", persistent, office1, 3, null);
+ msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkContainsAndAcknowledge(msgs, receiver4, queue1);
checkEmpty(receiver5);
- msgs = sendMessages("topic", persistent, office1, 3, null);
+ msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkContainsAndAcknowledge(msgs, receiver5, queue1);
- msgs = sendMessages("topic", persistent, office1, 3, null);
+ msgs = sendMessages("topic", persistent, office1, 1, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
- msgs = sendMessages("topic", persistent, office1, 3, null);
+ msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
}
finally
{
if (office1 != null)
{
office1.stop();
}
if (office2 != null)
{
office2.stop();
}
if (office3 != null)
{
office3.stop();
}
if (office4 != null)
{
office4.stop();
}
if (office5 != null)
{
office5.stop();
}
if (office6 != null)
{
office6.stop();
}
}
}
protected void local(boolean persistent) throws Throwable
{
ClusteredPostOffice office1 = null;
ClusteredPostOffice office2 = null;
ClusteredPostOffice office3 = null;
ClusteredPostOffice office4 = null;
ClusteredPostOffice office5 = null;
ClusteredPostOffice office6 = null;
try
{
office1 = createClusteredPostOffice("node1", "testgroup");
office2 = createClusteredPostOffice("node2", "testgroup");
office3 = createClusteredPostOffice("node3", "testgroup");
office4 = createClusteredPostOffice("node4", "testgroup");
office5 = createClusteredPostOffice("node5", "testgroup");
office6 = createClusteredPostOffice("node6", "testgroup");
LocalClusteredQueue queue1 = new LocalClusteredQueue(office2, "node2", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding1 = office2.bindClusteredQueue("topic", queue1);
SimpleReceiver receiver1 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue1.add(receiver1);
LocalClusteredQueue queue2 = new LocalClusteredQueue(office3, "node3", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding2 = office3.bindClusteredQueue("topic", queue2);
SimpleReceiver receiver2 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue2.add(receiver2);
LocalClusteredQueue queue3 = new LocalClusteredQueue(office4, "node4", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding3 = office4.bindClusteredQueue("topic", queue3);
SimpleReceiver receiver3 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue3.add(receiver3);
LocalClusteredQueue queue4 = new LocalClusteredQueue(office5, "node5", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding4 = office5.bindClusteredQueue("topic", queue4);
SimpleReceiver receiver4 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue4.add(receiver4);
LocalClusteredQueue queue5 = new LocalClusteredQueue(office6, "node6", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding5 = office6.bindClusteredQueue("topic", queue5);
SimpleReceiver receiver5 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue5.add(receiver5);
List msgs = sendMessages("topic", persistent, office2, 3, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office2, 3, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office2, 3, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office3, 3, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office3, 3, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office3, 3, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
}
finally
{
if (office1 != null)
{
office1.stop();
}
if (office2 != null)
{
office2.stop();
}
if (office3 != null)
{
office3.stop();
}
if (office4 != null)
{
office4.stop();
}
if (office5 != null)
{
office5.stop();
}
if (office6 != null)
{
office6.stop();
}
}
}
protected ClusteredPostOffice createClusteredPostOffice(String nodeId, String groupName) throws Exception
{
MessagePullPolicy redistPolicy = new NullMessagePullPolicy();
FilterFactory ff = new SimpleFilterFactory();
ClusterRouterFactory rf = new DefaultRouterFactory();
DefaultClusteredPostOffice postOffice =
new DefaultClusteredPostOffice(sc.getDataSource(), sc.getTransactionManager(),
null, true, nodeId, "Clustered", ms, pm, tr, ff, pool,
groupName,
JGroupsUtil.getControlStackProperties(),
JGroupsUtil.getDataStackProperties(),
5000, 5000, redistPolicy, rf, 1, 1000);
postOffice.start();
return postOffice;
}
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| false | true | protected void notLocal(boolean persistent) throws Throwable
{
ClusteredPostOffice office1 = null;
ClusteredPostOffice office2 = null;
ClusteredPostOffice office3 = null;
ClusteredPostOffice office4 = null;
ClusteredPostOffice office5 = null;
ClusteredPostOffice office6 = null;
try
{
office1 = createClusteredPostOffice("node1", "testgroup");
office2 = createClusteredPostOffice("node2", "testgroup");
office3 = createClusteredPostOffice("node3", "testgroup");
office4 = createClusteredPostOffice("node4", "testgroup");
office5 = createClusteredPostOffice("node5", "testgroup");
office6 = createClusteredPostOffice("node6", "testgroup");
LocalClusteredQueue queue1 = new LocalClusteredQueue(office2, "node2", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding1 = office2.bindClusteredQueue("topic", queue1);
SimpleReceiver receiver1 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue1.add(receiver1);
LocalClusteredQueue queue2 = new LocalClusteredQueue(office3, "node3", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding2 = office3.bindClusteredQueue("topic", queue2);
SimpleReceiver receiver2 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue2.add(receiver2);
LocalClusteredQueue queue3 = new LocalClusteredQueue(office4, "node4", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding3 = office4.bindClusteredQueue("topic", queue3);
SimpleReceiver receiver3 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue3.add(receiver3);
LocalClusteredQueue queue4 = new LocalClusteredQueue(office5, "node5", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding4 = office5.bindClusteredQueue("topic", queue4);
SimpleReceiver receiver4 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue4.add(receiver4);
LocalClusteredQueue queue5 = new LocalClusteredQueue(office6, "node6", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding5 = office6.bindClusteredQueue("topic", queue5);
SimpleReceiver receiver5 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue5.add(receiver5);
List msgs = sendMessages("topic", persistent, office1, 3, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 3, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 3, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkContainsAndAcknowledge(msgs, receiver3, queue1);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 3, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkContainsAndAcknowledge(msgs, receiver4, queue1);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 3, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkContainsAndAcknowledge(msgs, receiver5, queue1);
msgs = sendMessages("topic", persistent, office1, 3, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 3, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
}
finally
{
if (office1 != null)
{
office1.stop();
}
if (office2 != null)
{
office2.stop();
}
if (office3 != null)
{
office3.stop();
}
if (office4 != null)
{
office4.stop();
}
if (office5 != null)
{
office5.stop();
}
if (office6 != null)
{
office6.stop();
}
}
}
| protected void notLocal(boolean persistent) throws Throwable
{
ClusteredPostOffice office1 = null;
ClusteredPostOffice office2 = null;
ClusteredPostOffice office3 = null;
ClusteredPostOffice office4 = null;
ClusteredPostOffice office5 = null;
ClusteredPostOffice office6 = null;
try
{
office1 = createClusteredPostOffice("node1", "testgroup");
office2 = createClusteredPostOffice("node2", "testgroup");
office3 = createClusteredPostOffice("node3", "testgroup");
office4 = createClusteredPostOffice("node4", "testgroup");
office5 = createClusteredPostOffice("node5", "testgroup");
office6 = createClusteredPostOffice("node6", "testgroup");
LocalClusteredQueue queue1 = new LocalClusteredQueue(office2, "node2", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding1 = office2.bindClusteredQueue("topic", queue1);
SimpleReceiver receiver1 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue1.add(receiver1);
LocalClusteredQueue queue2 = new LocalClusteredQueue(office3, "node3", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding2 = office3.bindClusteredQueue("topic", queue2);
SimpleReceiver receiver2 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue2.add(receiver2);
LocalClusteredQueue queue3 = new LocalClusteredQueue(office4, "node4", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding3 = office4.bindClusteredQueue("topic", queue3);
SimpleReceiver receiver3 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue3.add(receiver3);
LocalClusteredQueue queue4 = new LocalClusteredQueue(office5, "node5", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding4 = office5.bindClusteredQueue("topic", queue4);
SimpleReceiver receiver4 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue4.add(receiver4);
LocalClusteredQueue queue5 = new LocalClusteredQueue(office6, "node6", "queue1", im.getId(), ms, pm, true, false, (QueuedExecutor)pool.get(), null, tr);
Binding binding5 = office6.bindClusteredQueue("topic", queue5);
SimpleReceiver receiver5 = new SimpleReceiver("blah", SimpleReceiver.ACCEPTING);
queue5.add(receiver5);
List msgs = sendMessages("topic", persistent, office1, 1, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkContainsAndAcknowledge(msgs, receiver3, queue1);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkContainsAndAcknowledge(msgs, receiver4, queue1);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkContainsAndAcknowledge(msgs, receiver5, queue1);
msgs = sendMessages("topic", persistent, office1, 1, null);
checkContainsAndAcknowledge(msgs, receiver1, queue1);
checkEmpty(receiver2);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
msgs = sendMessages("topic", persistent, office1, 1, null);
checkEmpty(receiver1);
checkContainsAndAcknowledge(msgs, receiver2, queue1);
checkEmpty(receiver3);
checkEmpty(receiver4);
checkEmpty(receiver5);
}
finally
{
if (office1 != null)
{
office1.stop();
}
if (office2 != null)
{
office2.stop();
}
if (office3 != null)
{
office3.stop();
}
if (office4 != null)
{
office4.stop();
}
if (office5 != null)
{
office5.stop();
}
if (office6 != null)
{
office6.stop();
}
}
}
|
diff --git a/src/TestDriver.java b/src/TestDriver.java
index d32b337..fbd92c8 100644
--- a/src/TestDriver.java
+++ b/src/TestDriver.java
@@ -1,149 +1,150 @@
/*---------------------------------------------------------------------------*\
This software is released under a BSD license, adapted from
http://opensource.org/licenses/bsd-license.php.
Copyright (c) 2010 Brian M. Clapper
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names "clapper.org", "Java EditLine", nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\*---------------------------------------------------------------------------*/
import org.clapper.editline.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class TestDriver implements EditLine.CompletionHandler
{
TestDriver()
{
}
private String[] POSSIBLE_COMPLETIONS = new String[]
{
"alice",
"alistair",
"betty",
"bert",
"bob",
"coozin",
"cousin",
"freebsd",
"freelander",
"linux",
"linus",
"solaris",
"slowlaris",
"winders",
"windows"
};
private String[] TO_ARRAY_PROTOTYPE = new String[0];
public String[] complete(String token, String line, int cursor)
{
String[] result = null;
if (token.length() == 0)
result = POSSIBLE_COMPLETIONS;
else
{
ArrayList<String> completions = new ArrayList<String>();
for (String s : POSSIBLE_COMPLETIONS)
{
if (s.startsWith(token))
completions.add(s);
}
if (completions.size() > 0)
{
// Don't trust completions.toArray().
result = new String[completions.size()];
for (int i = 0; i < completions.size(); i++)
result[i] = completions.get(i);
}
}
return result;
}
void run() throws IOException
{
EditLine e = EditLine.init("test", new File("editrc"));
- e.setHistorySize(100);
+ e.setHistorySize(10);
+ System.out.println("Max history=" + e.getHistorySize());
e.setHistoryUnique(true);
e.setCompletionHandler(this);
e.setMaxShownCompletions(POSSIBLE_COMPLETIONS.length / 4);
File historyFile = new File("test.history");
if (historyFile.exists())
e.loadHistory(historyFile);
e.invokeCommand("bind", "^I", "ed-complete");
//e.enableSignalHandling(true);
e.setPrompt("[" + e.historyTotal() + "] Well? ");
String line;
while ((line = e.getLine()) != null)
{
String tline = line.trim();
if (tline.equals("!!"))
{
line = e.currentHistoryLine();
if (line == null)
{
System.out.println("Empty history.");
continue;
}
tline = line.trim();
}
e.addToHistory(line);
if (tline.equals("h"))
{
for (String s: e.getHistory())
System.out.println(s);
}
System.out.println("Got: \"" + line + "\"");
e.setPrompt("[" + e.historyTotal() + "] Well? ");
}
e.saveHistory(historyFile);
e.cleanup();
}
public static void main (String[] args) throws IOException
{
new TestDriver().run();
}
}
| true | true | void run() throws IOException
{
EditLine e = EditLine.init("test", new File("editrc"));
e.setHistorySize(100);
e.setHistoryUnique(true);
e.setCompletionHandler(this);
e.setMaxShownCompletions(POSSIBLE_COMPLETIONS.length / 4);
File historyFile = new File("test.history");
if (historyFile.exists())
e.loadHistory(historyFile);
e.invokeCommand("bind", "^I", "ed-complete");
//e.enableSignalHandling(true);
e.setPrompt("[" + e.historyTotal() + "] Well? ");
String line;
while ((line = e.getLine()) != null)
{
String tline = line.trim();
if (tline.equals("!!"))
{
line = e.currentHistoryLine();
if (line == null)
{
System.out.println("Empty history.");
continue;
}
tline = line.trim();
}
e.addToHistory(line);
if (tline.equals("h"))
{
for (String s: e.getHistory())
System.out.println(s);
}
System.out.println("Got: \"" + line + "\"");
e.setPrompt("[" + e.historyTotal() + "] Well? ");
}
e.saveHistory(historyFile);
e.cleanup();
}
| void run() throws IOException
{
EditLine e = EditLine.init("test", new File("editrc"));
e.setHistorySize(10);
System.out.println("Max history=" + e.getHistorySize());
e.setHistoryUnique(true);
e.setCompletionHandler(this);
e.setMaxShownCompletions(POSSIBLE_COMPLETIONS.length / 4);
File historyFile = new File("test.history");
if (historyFile.exists())
e.loadHistory(historyFile);
e.invokeCommand("bind", "^I", "ed-complete");
//e.enableSignalHandling(true);
e.setPrompt("[" + e.historyTotal() + "] Well? ");
String line;
while ((line = e.getLine()) != null)
{
String tline = line.trim();
if (tline.equals("!!"))
{
line = e.currentHistoryLine();
if (line == null)
{
System.out.println("Empty history.");
continue;
}
tline = line.trim();
}
e.addToHistory(line);
if (tline.equals("h"))
{
for (String s: e.getHistory())
System.out.println(s);
}
System.out.println("Got: \"" + line + "\"");
e.setPrompt("[" + e.historyTotal() + "] Well? ");
}
e.saveHistory(historyFile);
e.cleanup();
}
|
diff --git a/test/Reflection.java b/test/Reflection.java
index 3afe5316..53e2bd1b 100644
--- a/test/Reflection.java
+++ b/test/Reflection.java
@@ -1,252 +1,252 @@
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.InvocationTargetException;
public class Reflection {
public static boolean booleanMethod() {
return true;
}
public static byte byteMethod() {
return 1;
}
public static char charMethod() {
return '2';
}
public static short shortMethod() {
return 3;
}
public static int intMethod() {
return 4;
}
public static float floatMethod() {
return 5.0f;
}
public static long longMethod() {
return 6;
}
public static double doubleMethod() {
return 7.0;
}
public static void expect(boolean v) {
if (! v) throw new RuntimeException();
}
private static class Hello<T> {
private class World<S> { }
}
private static void innerClasses() throws Exception {
Class c = Reflection.class;
Class[] inner = c.getDeclaredClasses();
expect(1 == inner.length);
expect(Hello.class == inner[0]);
}
private int egads;
private static void annotations() throws Exception {
Field egads = Reflection.class.getDeclaredField("egads");
expect(egads.getAnnotation(Deprecated.class) == null);
}
private Integer[] array;
private Integer integer;
public static Hello<Hello<Reflection>>.World<Hello<String>> pinky;
private static void genericType() throws Exception {
Field field = Reflection.class.getDeclaredField("egads");
expect(field.getGenericType() == Integer.TYPE);
field = Reflection.class.getField("pinky");
expect("Reflection$Hello$World".equals(field.getType().getName()));
expect(field.getGenericType() instanceof ParameterizedType);
ParameterizedType type = (ParameterizedType) field.getGenericType();
expect(type.getRawType() instanceof Class);
Class<?> clazz = (Class<?>) type.getRawType();
expect("Reflection$Hello$World".equals(clazz.getName()));
expect(type.getOwnerType() instanceof ParameterizedType);
ParameterizedType owner = (ParameterizedType) type.getOwnerType();
clazz = (Class<?>) owner.getRawType();
expect(clazz == Hello.class);
Type[] args = type.getActualTypeArguments();
expect(1 == args.length);
expect(args[0] instanceof ParameterizedType);
ParameterizedType arg = (ParameterizedType) args[0];
expect(arg.getRawType() instanceof Class);
clazz = (Class<?>) arg.getRawType();
expect("Reflection$Hello".equals(clazz.getName()));
args = arg.getActualTypeArguments();
expect(1 == args.length);
expect(args[0] == String.class);
}
public static void throwOOME() {
throw new OutOfMemoryError();
}
public static void main(String[] args) throws Exception {
innerClasses();
annotations();
genericType();
Class system = Class.forName("java.lang.System");
Field out = system.getDeclaredField("out");
Class output = Class.forName("java.io.PrintStream");
Method println = output.getDeclaredMethod("println", String.class);
println.invoke(out.get(null), "Hello, World!");
expect((Boolean) Reflection.class.getMethod("booleanMethod").invoke(null));
expect(1 == (Byte) Reflection.class.getMethod("byteMethod").invoke(null));
expect('2' == (Character) Reflection.class.getMethod
("charMethod").invoke(null));
expect(3 == (Short) Reflection.class.getMethod
("shortMethod").invoke(null));
expect(4 == (Integer) Reflection.class.getMethod
("intMethod").invoke(null));
expect(5.0 == (Float) Reflection.class.getMethod
("floatMethod").invoke(null));
expect(6 == (Long) Reflection.class.getMethod
("longMethod").invoke(null));
expect(7.0 == (Double) Reflection.class.getMethod
("doubleMethod").invoke(null));
{ Class[][] array = new Class[][] { { Class.class } };
expect("[Ljava.lang.Class;".equals(array[0].getClass().getName()));
expect(Class[].class == array[0].getClass());
expect(array.getClass().getComponentType() == array[0].getClass());
}
{ Reflection r = new Reflection();
expect(r.egads == 0);
- Reflection.class.getDeclaredField("egads").set(r, 42);
- expect(((int) Reflection.class.getDeclaredField("egads").get(r)) == 42);
+ Reflection.class.getDeclaredField("egads").set(r, (Integer)42);
+ expect(((Integer)Reflection.class.getDeclaredField("egads").get(r)) == 42);
Reflection.class.getDeclaredField("egads").setInt(r, 43);
expect(Reflection.class.getDeclaredField("egads").getInt(r) == 43);
Integer[] array = new Integer[0];
Reflection.class.getDeclaredField("array").set(r, array);
expect(Reflection.class.getDeclaredField("array").get(r) == array);
try {
Reflection.class.getDeclaredField("array").set(r, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
Integer integer = 45;
Reflection.class.getDeclaredField("integer").set(r, integer);
expect(Reflection.class.getDeclaredField("integer").get(r) == integer);
try {
Reflection.class.getDeclaredField("integer").set(r, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
try {
Reflection.class.getDeclaredField("integer").set
(new Object(), integer);
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
try {
Reflection.class.getDeclaredField("integer").get(new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
}
try {
Foo.class.getMethod("foo").invoke(null);
expect(false);
} catch (ExceptionInInitializerError e) {
expect(e.getCause() instanceof MyException);
}
try {
Foo.class.getConstructor().newInstance();
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").get(null);
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
- Foo.class.getField("foo").set(null, 42);
+ Foo.class.getField("foo").set(null, (Integer)42);
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").set(null, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
} catch (NoClassDefFoundError e) {
// cool
}
{ Method m = Reflection.class.getMethod("throwOOME");
try {
m.invoke(null);
} catch(Throwable t) {
expect(t.getClass() == InvocationTargetException.class);
}
}
}
}
class Foo {
static {
if (true) throw new MyException();
}
public Foo() { }
public static int foo;
public static void foo() {
// ignore
}
}
class MyException extends RuntimeException { }
| false | true | public static void main(String[] args) throws Exception {
innerClasses();
annotations();
genericType();
Class system = Class.forName("java.lang.System");
Field out = system.getDeclaredField("out");
Class output = Class.forName("java.io.PrintStream");
Method println = output.getDeclaredMethod("println", String.class);
println.invoke(out.get(null), "Hello, World!");
expect((Boolean) Reflection.class.getMethod("booleanMethod").invoke(null));
expect(1 == (Byte) Reflection.class.getMethod("byteMethod").invoke(null));
expect('2' == (Character) Reflection.class.getMethod
("charMethod").invoke(null));
expect(3 == (Short) Reflection.class.getMethod
("shortMethod").invoke(null));
expect(4 == (Integer) Reflection.class.getMethod
("intMethod").invoke(null));
expect(5.0 == (Float) Reflection.class.getMethod
("floatMethod").invoke(null));
expect(6 == (Long) Reflection.class.getMethod
("longMethod").invoke(null));
expect(7.0 == (Double) Reflection.class.getMethod
("doubleMethod").invoke(null));
{ Class[][] array = new Class[][] { { Class.class } };
expect("[Ljava.lang.Class;".equals(array[0].getClass().getName()));
expect(Class[].class == array[0].getClass());
expect(array.getClass().getComponentType() == array[0].getClass());
}
{ Reflection r = new Reflection();
expect(r.egads == 0);
Reflection.class.getDeclaredField("egads").set(r, 42);
expect(((int) Reflection.class.getDeclaredField("egads").get(r)) == 42);
Reflection.class.getDeclaredField("egads").setInt(r, 43);
expect(Reflection.class.getDeclaredField("egads").getInt(r) == 43);
Integer[] array = new Integer[0];
Reflection.class.getDeclaredField("array").set(r, array);
expect(Reflection.class.getDeclaredField("array").get(r) == array);
try {
Reflection.class.getDeclaredField("array").set(r, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
Integer integer = 45;
Reflection.class.getDeclaredField("integer").set(r, integer);
expect(Reflection.class.getDeclaredField("integer").get(r) == integer);
try {
Reflection.class.getDeclaredField("integer").set(r, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
try {
Reflection.class.getDeclaredField("integer").set
(new Object(), integer);
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
try {
Reflection.class.getDeclaredField("integer").get(new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
}
try {
Foo.class.getMethod("foo").invoke(null);
expect(false);
} catch (ExceptionInInitializerError e) {
expect(e.getCause() instanceof MyException);
}
try {
Foo.class.getConstructor().newInstance();
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").get(null);
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").set(null, 42);
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").set(null, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
} catch (NoClassDefFoundError e) {
// cool
}
{ Method m = Reflection.class.getMethod("throwOOME");
try {
m.invoke(null);
} catch(Throwable t) {
expect(t.getClass() == InvocationTargetException.class);
}
}
}
| public static void main(String[] args) throws Exception {
innerClasses();
annotations();
genericType();
Class system = Class.forName("java.lang.System");
Field out = system.getDeclaredField("out");
Class output = Class.forName("java.io.PrintStream");
Method println = output.getDeclaredMethod("println", String.class);
println.invoke(out.get(null), "Hello, World!");
expect((Boolean) Reflection.class.getMethod("booleanMethod").invoke(null));
expect(1 == (Byte) Reflection.class.getMethod("byteMethod").invoke(null));
expect('2' == (Character) Reflection.class.getMethod
("charMethod").invoke(null));
expect(3 == (Short) Reflection.class.getMethod
("shortMethod").invoke(null));
expect(4 == (Integer) Reflection.class.getMethod
("intMethod").invoke(null));
expect(5.0 == (Float) Reflection.class.getMethod
("floatMethod").invoke(null));
expect(6 == (Long) Reflection.class.getMethod
("longMethod").invoke(null));
expect(7.0 == (Double) Reflection.class.getMethod
("doubleMethod").invoke(null));
{ Class[][] array = new Class[][] { { Class.class } };
expect("[Ljava.lang.Class;".equals(array[0].getClass().getName()));
expect(Class[].class == array[0].getClass());
expect(array.getClass().getComponentType() == array[0].getClass());
}
{ Reflection r = new Reflection();
expect(r.egads == 0);
Reflection.class.getDeclaredField("egads").set(r, (Integer)42);
expect(((Integer)Reflection.class.getDeclaredField("egads").get(r)) == 42);
Reflection.class.getDeclaredField("egads").setInt(r, 43);
expect(Reflection.class.getDeclaredField("egads").getInt(r) == 43);
Integer[] array = new Integer[0];
Reflection.class.getDeclaredField("array").set(r, array);
expect(Reflection.class.getDeclaredField("array").get(r) == array);
try {
Reflection.class.getDeclaredField("array").set(r, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
Integer integer = 45;
Reflection.class.getDeclaredField("integer").set(r, integer);
expect(Reflection.class.getDeclaredField("integer").get(r) == integer);
try {
Reflection.class.getDeclaredField("integer").set(r, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
try {
Reflection.class.getDeclaredField("integer").set
(new Object(), integer);
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
try {
Reflection.class.getDeclaredField("integer").get(new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
}
}
try {
Foo.class.getMethod("foo").invoke(null);
expect(false);
} catch (ExceptionInInitializerError e) {
expect(e.getCause() instanceof MyException);
}
try {
Foo.class.getConstructor().newInstance();
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").get(null);
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").set(null, (Integer)42);
expect(false);
} catch (NoClassDefFoundError e) {
// cool
}
try {
Foo.class.getField("foo").set(null, new Object());
expect(false);
} catch (IllegalArgumentException e) {
// cool
} catch (NoClassDefFoundError e) {
// cool
}
{ Method m = Reflection.class.getMethod("throwOOME");
try {
m.invoke(null);
} catch(Throwable t) {
expect(t.getClass() == InvocationTargetException.class);
}
}
}
|
diff --git a/net/sourceforge/pinemup/logic/NoteIO.java b/net/sourceforge/pinemup/logic/NoteIO.java
index 9f42370..927cbce 100755
--- a/net/sourceforge/pinemup/logic/NoteIO.java
+++ b/net/sourceforge/pinemup/logic/NoteIO.java
@@ -1,291 +1,291 @@
/*
* pin 'em up
*
* Copyright (C) 2007 by Mario Koedding
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.sourceforge.pinemup.logic;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.*;
import javax.swing.JOptionPane;
import javax.xml.stream.*;
public class NoteIO {
public static void writeCategoriesToFile(CategoryList c, UserSettings s) {
//write notes to xml file
try {
XMLOutputFactory myFactory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = myFactory.createXMLStreamWriter(new FileOutputStream(s.getNotesFile()));
writer.writeStartDocument();
writer.writeStartElement("notesfile");
writer.writeAttribute("version","0.1");
writer.writeAttribute("encoding","UTF-8");
CategoryList cl = c;
while (cl != null) {
if (cl.getCategory() != null) {
writer.writeStartElement("category");
writer.writeAttribute("name", cl.getCategory().getName());
writer.writeAttribute("default",String.valueOf(cl.getCategory().isDefaultCategory()));
NoteList nl = cl.getCategory().getNotes();
while (nl != null) {
if (nl.getNote() != null) {
writer.writeStartElement("note");
writer.writeAttribute("hidden", String.valueOf(nl.getNote().isHidden()));
writer.writeAttribute("alwaysontop", String.valueOf(nl.getNote().isAlwaysOnTop()));
writer.writeAttribute("xposition", String.valueOf(nl.getNote().getXPos()));
writer.writeAttribute("yposition", String.valueOf(nl.getNote().getYPos()));
writer.writeAttribute("width", String.valueOf(nl.getNote().getXSize()));
writer.writeAttribute("height", String.valueOf(nl.getNote().getYSize()));
writer.writeStartElement("text");
writer.writeAttribute("size", String.valueOf(nl.getNote().getFontSize()));
writer.writeCharacters(nl.getNote().getText());
writer.writeEndElement();
writer.writeEndElement();
}
nl = nl.getNext();
}
writer.writeEndElement();
}
cl = cl.getNext();
}
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
} catch (XMLStreamException e) {
JOptionPane.showMessageDialog(null, "Could save notes to file! Please check file-settings and free disk-space!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Could save notes to file! Please check file-settings and free disk-space!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
}
}
public static CategoryList readCategoriesFromFile(UserSettings s) {
CategoryList c = new CategoryList();
Category currentCategory = null;
Note currentNote = null;
boolean defaultNotAdded = true;
try {
InputStream in = new FileInputStream(s.getNotesFile());
XMLInputFactory myFactory = XMLInputFactory.newInstance();
XMLStreamReader parser = myFactory.createXMLStreamReader(in);
int event;
while(parser.hasNext()) {
event = parser.next();
switch(event) {
case XMLStreamConstants.START_DOCUMENT:
// do nothing
break;
case XMLStreamConstants.END_DOCUMENT:
parser.close();
break;
case XMLStreamConstants.NAMESPACE:
// do nothing
break;
case XMLStreamConstants.START_ELEMENT:
String ename = parser.getLocalName();
if (ename.equals("notesfile")) {
//do nothing yet
} else if (ename.equals("category")) {
String name = "";
boolean def = false;
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("name")) {
name = parser.getAttributeValue(i);
} else if (parser.getAttributeLocalName(i).equals("default")) {
def = (parser.getAttributeValue(i).equals("true")) && defaultNotAdded;
if (def) {
defaultNotAdded = false;
}
}
}
currentCategory = new Category(name,new NoteList(),def);
c.add(currentCategory);
} else if (ename.equals("note")) {
currentNote = new Note("",s,c);
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("hidden")) {
boolean h = parser.getAttributeValue(i).equals("true");
currentNote.setHidden(h);
} else if (parser.getAttributeLocalName(i).equals("xposition")) {
- Short x = Short.parseShort(parser.getAttributeValue(i));
+ short x = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(x, currentNote.getYPos());
} else if (parser.getAttributeLocalName(i).equals("yposition")) {
- Short y = Short.parseShort(parser.getAttributeValue(i));
+ short y = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(currentNote.getXPos(), y);
} else if (parser.getAttributeLocalName(i).equals("width")) {
- Short w = Short.parseShort(parser.getAttributeValue(i));
+ short w = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(w, currentNote.getYSize());
} else if (parser.getAttributeLocalName(i).equals("height")) {
- Short h = Short.parseShort(parser.getAttributeValue(i));
+ short h = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(currentNote.getXSize(), h);
} else if (parser.getAttributeLocalName(i).equals("alwaysontop")) {
boolean a = parser.getAttributeValue(i).equals("true");
currentNote.setAlwaysOnTop(a);
}
}
if (currentCategory != null) {
currentCategory.getNotes().add(currentNote);
}
} else if (ename.equals("text")) {
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("size")) {
short fontSize = Short.parseShort(parser.getAttributeValue(i));
currentNote.setFontSize(fontSize);
}
}
}
break;
case XMLStreamConstants.CHARACTERS:
if(!parser.isWhiteSpace()) {
if (currentNote != null) {
currentNote.setText(parser.getText());
}
}
break;
case XMLStreamConstants.END_ELEMENT:
// do nothing
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
//neu erstellen
c.add(new Category("Home",new NoteList(),true));
c.add(new Category("Office",new NoteList(),false));
} catch (XMLStreamException e) {
//Meldung ausgeben
System.out.println("XML Error");
}
return c;
}
public static void getCategoriesFromFTP(UserSettings us) {
boolean downloaded = true;
try {
File f = new File(us.getNotesFile());
FileOutputStream fos = new FileOutputStream(f);
String filename = f.getName();
String ftpString = "ftp://" + us.getFtpUser() + ":"
+ us.getFtpPasswdString() + "@" + us.getFtpServer()
+ us.getFtpDir() + filename + ";type=i";
URL url = new URL(ftpString);
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream();
int nextByte = is.read();
while(nextByte != -1) {
fos.write(nextByte);
nextByte = is.read();
}
fos.close();
} catch (Exception e) {
downloaded = false;
JOptionPane.showMessageDialog(null, "Could not download file from FTP server!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
}
if (downloaded) {
JOptionPane.showMessageDialog(null, "Notes successfully downloaded from FTP server!", "pin 'em up - information", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void writeCategoriesToFTP(UserSettings us) {
boolean uploaded = true;
try {
String completeFilename = us.getNotesFile();
File f = new File(completeFilename);
String filename = f.getName();
FileInputStream fis = new FileInputStream(f);
String ftpString = "ftp://" + us.getFtpUser() + ":"
+ us.getFtpPasswdString() + "@" + us.getFtpServer()
+ us.getFtpDir() + filename + ";type=i";
URL url = new URL(ftpString);
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream();
int nextByte = fis.read();
while (nextByte != -1) {
os.write(nextByte);
nextByte = fis.read();
}
os.close();
} catch (Exception e) {
uploaded = false;
JOptionPane.showMessageDialog(null, "Error! Notes could not be uploaded to FTP server!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
}
if (uploaded) {
JOptionPane.showMessageDialog(null, "Notes successfully uploaded to FTP server!", "pin 'em up - information", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void exportCategoriesToTextFile(CategoryList c) {
File f = null;
PinEmUp.getFileDialog().setDialogTitle("Export notes to text-file");
PinEmUp.getFileDialog().setFileFilter(new MyFileFilter("TXT"));
if (PinEmUp.getFileDialog().showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String name = NoteIO.checkAndAddExtension(PinEmUp.getFileDialog().getSelectedFile().getAbsolutePath(), ".txt");
f = new File(name);
}
if (f != null) {
try {
PrintWriter ostream = new PrintWriter(new BufferedWriter(new FileWriter(f)));
// write text of notes to file
while (c != null) {
ostream.println("Category: " + c.getCategory().getName());
ostream.println();
NoteList n = c.getCategory().getNotes();
while (n != null) {
if (n.getNote() != null) {
ostream.println(n.getNote().getText());
ostream.println();
ostream.println("---------------------");
ostream.println();
}
n = n.getNext();
}
ostream.println();
ostream.println("################################################################");
ostream.println();
c = c.getNext();
}
ostream.flush();
ostream.close();
}
catch ( IOException e ) {
System.out.println("IOERROR: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
}
public static String checkAndAddExtension(String s, String xt) {
int len = s.length();
String ext = s.substring(len-4, len);
if (!ext.toLowerCase().equals(xt.toLowerCase())) {
s = s + xt.toLowerCase();
}
return s;
}
}
| false | true | public static CategoryList readCategoriesFromFile(UserSettings s) {
CategoryList c = new CategoryList();
Category currentCategory = null;
Note currentNote = null;
boolean defaultNotAdded = true;
try {
InputStream in = new FileInputStream(s.getNotesFile());
XMLInputFactory myFactory = XMLInputFactory.newInstance();
XMLStreamReader parser = myFactory.createXMLStreamReader(in);
int event;
while(parser.hasNext()) {
event = parser.next();
switch(event) {
case XMLStreamConstants.START_DOCUMENT:
// do nothing
break;
case XMLStreamConstants.END_DOCUMENT:
parser.close();
break;
case XMLStreamConstants.NAMESPACE:
// do nothing
break;
case XMLStreamConstants.START_ELEMENT:
String ename = parser.getLocalName();
if (ename.equals("notesfile")) {
//do nothing yet
} else if (ename.equals("category")) {
String name = "";
boolean def = false;
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("name")) {
name = parser.getAttributeValue(i);
} else if (parser.getAttributeLocalName(i).equals("default")) {
def = (parser.getAttributeValue(i).equals("true")) && defaultNotAdded;
if (def) {
defaultNotAdded = false;
}
}
}
currentCategory = new Category(name,new NoteList(),def);
c.add(currentCategory);
} else if (ename.equals("note")) {
currentNote = new Note("",s,c);
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("hidden")) {
boolean h = parser.getAttributeValue(i).equals("true");
currentNote.setHidden(h);
} else if (parser.getAttributeLocalName(i).equals("xposition")) {
Short x = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(x, currentNote.getYPos());
} else if (parser.getAttributeLocalName(i).equals("yposition")) {
Short y = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(currentNote.getXPos(), y);
} else if (parser.getAttributeLocalName(i).equals("width")) {
Short w = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(w, currentNote.getYSize());
} else if (parser.getAttributeLocalName(i).equals("height")) {
Short h = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(currentNote.getXSize(), h);
} else if (parser.getAttributeLocalName(i).equals("alwaysontop")) {
boolean a = parser.getAttributeValue(i).equals("true");
currentNote.setAlwaysOnTop(a);
}
}
if (currentCategory != null) {
currentCategory.getNotes().add(currentNote);
}
} else if (ename.equals("text")) {
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("size")) {
short fontSize = Short.parseShort(parser.getAttributeValue(i));
currentNote.setFontSize(fontSize);
}
}
}
break;
case XMLStreamConstants.CHARACTERS:
if(!parser.isWhiteSpace()) {
if (currentNote != null) {
currentNote.setText(parser.getText());
}
}
break;
case XMLStreamConstants.END_ELEMENT:
// do nothing
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
//neu erstellen
c.add(new Category("Home",new NoteList(),true));
c.add(new Category("Office",new NoteList(),false));
} catch (XMLStreamException e) {
//Meldung ausgeben
System.out.println("XML Error");
}
return c;
}
| public static CategoryList readCategoriesFromFile(UserSettings s) {
CategoryList c = new CategoryList();
Category currentCategory = null;
Note currentNote = null;
boolean defaultNotAdded = true;
try {
InputStream in = new FileInputStream(s.getNotesFile());
XMLInputFactory myFactory = XMLInputFactory.newInstance();
XMLStreamReader parser = myFactory.createXMLStreamReader(in);
int event;
while(parser.hasNext()) {
event = parser.next();
switch(event) {
case XMLStreamConstants.START_DOCUMENT:
// do nothing
break;
case XMLStreamConstants.END_DOCUMENT:
parser.close();
break;
case XMLStreamConstants.NAMESPACE:
// do nothing
break;
case XMLStreamConstants.START_ELEMENT:
String ename = parser.getLocalName();
if (ename.equals("notesfile")) {
//do nothing yet
} else if (ename.equals("category")) {
String name = "";
boolean def = false;
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("name")) {
name = parser.getAttributeValue(i);
} else if (parser.getAttributeLocalName(i).equals("default")) {
def = (parser.getAttributeValue(i).equals("true")) && defaultNotAdded;
if (def) {
defaultNotAdded = false;
}
}
}
currentCategory = new Category(name,new NoteList(),def);
c.add(currentCategory);
} else if (ename.equals("note")) {
currentNote = new Note("",s,c);
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("hidden")) {
boolean h = parser.getAttributeValue(i).equals("true");
currentNote.setHidden(h);
} else if (parser.getAttributeLocalName(i).equals("xposition")) {
short x = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(x, currentNote.getYPos());
} else if (parser.getAttributeLocalName(i).equals("yposition")) {
short y = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(currentNote.getXPos(), y);
} else if (parser.getAttributeLocalName(i).equals("width")) {
short w = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(w, currentNote.getYSize());
} else if (parser.getAttributeLocalName(i).equals("height")) {
short h = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(currentNote.getXSize(), h);
} else if (parser.getAttributeLocalName(i).equals("alwaysontop")) {
boolean a = parser.getAttributeValue(i).equals("true");
currentNote.setAlwaysOnTop(a);
}
}
if (currentCategory != null) {
currentCategory.getNotes().add(currentNote);
}
} else if (ename.equals("text")) {
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("size")) {
short fontSize = Short.parseShort(parser.getAttributeValue(i));
currentNote.setFontSize(fontSize);
}
}
}
break;
case XMLStreamConstants.CHARACTERS:
if(!parser.isWhiteSpace()) {
if (currentNote != null) {
currentNote.setText(parser.getText());
}
}
break;
case XMLStreamConstants.END_ELEMENT:
// do nothing
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
//neu erstellen
c.add(new Category("Home",new NoteList(),true));
c.add(new Category("Office",new NoteList(),false));
} catch (XMLStreamException e) {
//Meldung ausgeben
System.out.println("XML Error");
}
return c;
}
|
diff --git a/src/main/java/ru/altruix/commons/impl/translationtester/DefaultTranslationTesterFactory.java b/src/main/java/ru/altruix/commons/impl/translationtester/DefaultTranslationTesterFactory.java
index 5979b2f..9f95123 100644
--- a/src/main/java/ru/altruix/commons/impl/translationtester/DefaultTranslationTesterFactory.java
+++ b/src/main/java/ru/altruix/commons/impl/translationtester/DefaultTranslationTesterFactory.java
@@ -1,28 +1,28 @@
/**
* This file is part of Project Control Center (PCC).
*
* PCC (Project Control Center) project is intellectual property of
* Dmitri Anatol'evich Pisarenko.
*
* Copyright 2010, 2011 Dmitri Anatol'evich Pisarenko
* All rights reserved
*
**/
package ru.altruix.commons.impl.translationtester;
import ru.altruix.commons.api.translationtester.TranslationTester;
import ru.altruix.commons.api.translationtester.TranslationTesterFactory;
/**
* @author DP118M
*
*/
public class DefaultTranslationTesterFactory implements
TranslationTesterFactory {
@Override
- public TranslationTester create() {
+ public final TranslationTester create() {
return new DefaultTranslationTester();
}
}
| true | true | public TranslationTester create() {
return new DefaultTranslationTester();
}
| public final TranslationTester create() {
return new DefaultTranslationTester();
}
|
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java
index 999f67bf9..42bcc7f43 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java
@@ -1,1016 +1,1015 @@
/*
* Copyright (c) 2009-2011, IETR/INSA of Rennes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.backends;
import static net.sf.orcc.OrccActivator.getDefault;
import static net.sf.orcc.OrccLaunchConstants.CLASSIFY;
import static net.sf.orcc.OrccLaunchConstants.COMPILE_XDF;
import static net.sf.orcc.OrccLaunchConstants.DEBUG_MODE;
import static net.sf.orcc.OrccLaunchConstants.DEFAULT_FIFO_SIZE;
import static net.sf.orcc.OrccLaunchConstants.FIFO_SIZE;
import static net.sf.orcc.OrccLaunchConstants.MAPPING;
import static net.sf.orcc.OrccLaunchConstants.MERGE_ACTIONS;
import static net.sf.orcc.OrccLaunchConstants.MERGE_ACTORS;
import static net.sf.orcc.OrccLaunchConstants.OUTPUT_FOLDER;
import static net.sf.orcc.OrccLaunchConstants.PROJECT;
import static net.sf.orcc.OrccLaunchConstants.XDF_FILE;
import static net.sf.orcc.preferences.PreferenceConstants.P_SOLVER;
import static net.sf.orcc.preferences.PreferenceConstants.P_SOLVER_OPTIONS;
import static net.sf.orcc.util.OrccUtil.getFile;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import net.sf.orcc.OrccException;
import net.sf.orcc.OrccRuntimeException;
import net.sf.orcc.df.Actor;
import net.sf.orcc.df.Instance;
import net.sf.orcc.df.Network;
import net.sf.orcc.df.util.DfSwitch;
import net.sf.orcc.df.util.NetworkValidator;
import net.sf.orcc.graph.Vertex;
import net.sf.orcc.util.OrccLogger;
import net.sf.orcc.util.OrccUtil;
import net.sf.orcc.util.util.EcoreHelper;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
/**
* This class is an abstract implementation of {@link Backend}. The two entry
* points of this class are the public methods {@link #compileVTL()} and
* {@link #compileXDF()} which should NOT be called by back-ends themselves.
*
* <p>
* The following methods are abstract and must be implemented by back-ends:
* <ul>
* <li>{@link #doInitializeOptions()} is called by {@link #setOptions(Map)} to
* initialize the options of the back-end.</li>
* <li>{@link #doTransformActor(Actor)} is called by
* {@link #transformActors(List)} to transform a list of actors.</li>
* <li>{@link #doVtlCodeGeneration(List)} is called to compile a list of actors.
* </li>
* <li>{@link #doXdfCodeGeneration(Network)} is called to compile a network.</li>
* </ul>
* </p>
*
* The following methods may be extended by back-ends, if they print actors or
* instances respectively, or if a library must be exported with source file
* produced.
* <ul>
* <li>{@link #printActor(Actor)} is called by {@link #printActors(List)}.</li>
* <li>{@link #printInstance(Instance)} is called by
* {@link #printInstances(Network)}.</li>
* <li>{@link #exportRuntimeLibrary()} is called by {@link #start}.</li>
* </ul>
*
* The other methods declared <code>final</code> may be called by back-ends.
*
* @author Matthieu Wipliez
*
*/
public abstract class AbstractBackend implements Backend, IApplication {
protected boolean debug;
/**
* Fifo size used in backend.
*/
protected int fifoSize;
private IFile inputFile;
protected Map<String, String> mapping;
/**
* List of transformations to apply on each network
*/
protected List<DfSwitch<?>> networkTransfos;
/**
* List of transformations to apply on each actor
*/
protected List<DfSwitch<?>> actorTransfos;
protected boolean classify;
protected boolean mergeActions;
protected boolean mergeActors;
protected boolean convertMulti2Mono;
/**
* the progress monitor
*/
private IProgressMonitor monitor;
/**
* Options of backend execution. Its content can be manipulated with
* {@link #getAttribute} and {@link #setAttribute}
*/
private Map<String, Object> options;
/**
* Path where output files will be written.
*/
protected String path;
/**
* Represents the project where call application to build is located
*/
protected IProject project;
/**
* Path of the folder that contains VTL under IR form.
*/
private List<IFolder> vtlFolders;
/**
* Initialize some members
*/
public AbstractBackend() {
actorTransfos = new ArrayList<DfSwitch<?>>();
networkTransfos = new ArrayList<DfSwitch<?>>();
}
@Override
public void compile() {
compileVTL();
if ((Boolean) options.get(COMPILE_XDF)) {
compileXDF();
}
}
final private void compileVTL() {
// lists actors
OrccLogger.traceln("Lists actors...");
List<IFile> vtlFiles = OrccUtil.getAllFiles("ir", vtlFolders);
doVtlCodeGeneration(vtlFiles);
}
final private void compileXDF() {
// set FIFO size
ResourceSet set = new ResourceSetImpl();
// parses top network
Network network = EcoreHelper.getEObject(set, inputFile);
if (isCanceled()) {
return;
}
new NetworkValidator().doSwitch(network);
// because the UnitImporter will load additional resources, we filter
// only actors
List<Actor> actors = new ArrayList<Actor>();
for (Resource resource : set.getResources()) {
EObject eObject = resource.getContents().get(0);
if (eObject instanceof Actor) {
actors.add((Actor) eObject);
}
}
if (isCanceled()) {
return;
}
doXdfCodeGeneration(network);
}
/**
* Copy <i>source</i> file at <i>destination</i> path. If <i>destination</i>
* parents folder does not exists, they will be created
*
* @param source
* Resource file path starting with '/'. Must be an existing path
* relative to classpath (JAR file root or project classpath)
* @param destination
* Path of the target file
* @return <code>true</code> if the file has been successfully copied
*/
protected boolean copyFileToFilesystem(final String source,
final String dest) {
int bufferSize = 512;
assert source != null;
assert dest != null;
assert source.startsWith("/");
File fileOut = new File(dest);
if (!fileOut.exists()) {
try {
File parentDir = fileOut.getParentFile();
if (parentDir != null) {
parentDir.mkdirs();
}
fileOut.createNewFile();
} catch (IOException e) {
OrccLogger.warnln("Unable to write " + dest + " file");
return false;
}
}
if (!fileOut.isFile()) {
OrccLogger.warnln(dest + " is not a file path");
fileOut.delete();
return false;
}
InputStream is = this.getClass().getResourceAsStream(source);
if (is == null) {
OrccLogger.warnln("Unable to find " + source);
return false;
}
DataInputStream dis;
dis = new DataInputStream(is);
FileOutputStream out;
try {
out = new FileOutputStream(fileOut);
} catch (FileNotFoundException e1) {
OrccLogger.warnln("File " + dest + " not found !");
return false;
}
try {
byte[] b = new byte[bufferSize];
int i = is.read(b);
while (i != -1) {
out.write(b, 0, i);
i = is.read(b);
}
dis.close();
out.close();
} catch (IOException e) {
OrccLogger.warnln("IOError : " + e.getMessage());
return false;
}
return true;
}
/**
* Copy <i>source</i> folder and all its content under <i>destination</i>.
* Final '/' is not required for both parameters. If <i>destination</i> does
* not exists, it will be created
*
* @param source
* Resource folder path starting with '/'. Must be an existing
* path relative to classpath (JAR file root or project
* classpath)
* @param destination
* Filesystem folder path
* @return <code>true</code> if the folder has been successfully copied
*/
protected boolean copyFolderToFileSystem(final String source,
final String destination) {
assert source != null;
assert destination != null;
assert source.startsWith("/");
File outputDir = new File(destination);
if (!outputDir.exists()) {
if (!outputDir.mkdirs()) {
OrccLogger.warnln("Unable to create " + outputDir + " folder");
return false;
}
}
if (!outputDir.isDirectory()) {
OrccLogger.warnln(outputDir
+ " does not exists or is not a directory.");
return false;
}
String inputDir;
// Remove last '/' character (if needed)
if (source.charAt(source.length() - 1) == '/') {
inputDir = source.substring(0, source.length() - 1);
} else {
inputDir = source;
}
try {
URL toto = this.getClass().getResource(inputDir);
URL inputURL = FileLocator.resolve(toto);
String inputPath = inputURL.toString();
boolean result = true;
if (inputPath.startsWith("jar:file:")) {
// Backend running from jar file
inputPath = inputPath.substring(9, inputPath.indexOf('!'));
JarFile jar = new JarFile(inputPath);
try {
Enumeration<JarEntry> jarEntries = jar.entries();
if (jarEntries == null) {
OrccLogger.warnln("Unable to list content from "
+ jar.getName() + " file.");
return false;
}
// "source" value without starting '/' char
String sourceMinusSlash = source.substring(1);
JarEntry elt;
while (jarEntries.hasMoreElements()) {
elt = jarEntries.nextElement();
// Only deal with sub-files of 'source' path
if (elt.isDirectory()
|| !elt.getName().startsWith(sourceMinusSlash)) {
continue;
}
String newInPath = "/" + elt.getName();
String newOutPath = outputDir
+ File.separator
+ elt.getName().substring(
sourceMinusSlash.length());
result &= copyFileToFilesystem(newInPath, newOutPath);
}
return result;
} finally {
jar.close();
}
} else {
// Backend running from filesystem
File[] listDir = new File(inputPath.substring(5)).listFiles();
for (File elt : listDir) {
String newInPath = inputDir + File.separator
+ elt.getName();
String newOutPath = outputDir + File.separator
+ elt.getName();
if (elt.isDirectory()) {
result &= copyFolderToFileSystem(newInPath, newOutPath);
} else {
result &= copyFileToFilesystem(newInPath, newOutPath);
}
}
return result;
}
} catch (IOException e) {
OrccLogger.warnln("IOError" + e.getMessage());
return false;
}
}
/**
* Called when options are initialized.
*/
abstract protected void doInitializeOptions();
/**
* Transforms the given actor.
*
* @param actor
* the actor
*/
abstract protected void doTransformActor(Actor actor);
/**
* This method must be implemented by subclasses to do the actual code
* generation for VTL.
*
* @param files
* a list of IR files
*/
abstract protected void doVtlCodeGeneration(List<IFile> files);
/**
* This method must be implemented by subclasses to do the actual code
* generation for the network or its instances or both.
*
* @param network
* a network
*/
abstract protected void doXdfCodeGeneration(Network network);
/**
* Executes the given list of tasks using a thread pool with one thread per
* processor available.
*
* @param tasks
* a list of tasks
*/
private int executeTasks(List<Callable<Boolean>> tasks) {
// creates the pool
int nThreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
try {
// invokes all tasks and wait for them to complete
List<Future<Boolean>> completeTasks = pool.invokeAll(tasks);
// counts number of cached actors and checks exceptions
int numCached = 0;
for (Future<Boolean> completeTask : completeTasks) {
try {
if (completeTask.get()) {
numCached++;
}
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof OrccRuntimeException) {
throw (OrccRuntimeException) e.getCause();
} else {
String msg = "";
if (e.getCause().getMessage() != null) {
msg = "(" + e.getCause().getMessage() + ")";
}
throw new OrccRuntimeException(
"One actor could not be printed " + msg,
e.getCause());
}
}
}
// shutdowns the pool
// no need to wait because tasks are completed after invokeAll
pool.shutdown();
return numCached;
} catch (InterruptedException e) {
throw new OrccRuntimeException("actors could not be printed", e);
}
}
/**
* Export runtime library used by source produced. Should be overridden by
* back-ends that produce code source which need third party libraries at
* runtime.
*
* @return <code>true</code> if the libraries were correctly exported
*/
@Override
public boolean exportRuntimeLibrary() {
return false;
}
/**
* Returns the boolean-valued attribute with the given name. Returns the
* given default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
final public boolean getAttribute(String attributeName, boolean defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof Boolean) {
return (Boolean) obj;
} else {
return defaultValue;
}
}
/**
* Returns the integer-valued attribute with the given name. Returns the
* given default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
final public int getAttribute(String attributeName, int defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof Integer) {
return (Integer) obj;
} else {
return defaultValue;
}
}
/**
* Returns the map-valued attribute with the given name. Returns the given
* default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
@SuppressWarnings("unchecked")
final public Map<String, String> getAttribute(String attributeName,
Map<String, String> defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof Map<?, ?>) {
return (Map<String, String>) obj;
} else {
return defaultValue;
}
}
/**
* Returns the string-valued attribute with the given name. Returns the
* given default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
final public String getAttribute(String attributeName, String defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof String) {
return (String) obj;
} else {
return defaultValue;
}
}
/**
* Returns a map containing the backend attributes in this launch
* configuration. Returns an empty map if the backend configuration has no
* attributes.
*
* @return a map of attribute keys and values.
*/
final public Map<String, Object> getAttributes() {
return options;
}
/**
* Returns true if this process has been canceled.
*
* @return true if this process has been canceled
*/
protected boolean isCanceled() {
if (monitor == null) {
return false;
} else {
return monitor.isCanceled();
}
}
/**
* Parses the given file list and returns a list of actors.
*
* @param files
* a list of JSON files
* @return a list of actors
*/
final public List<Actor> parseActors(List<IFile> files) {
// NOTE: the actors are parsed but are NOT put in the actor pool because
// they may be transformed and not have the same properties (in
// particular concerning types), and instantiation then complains.
OrccLogger.traceln("Parsing " + files.size() + " actors...");
ResourceSet set = new ResourceSetImpl();
List<Actor> actors = new ArrayList<Actor>();
for (IFile file : files) {
Resource resource = set.getResource(URI.createPlatformResourceURI(
file.getFullPath().toString(), true), true);
EObject eObject = resource.getContents().get(0);
if (eObject instanceof Actor) {
// do not add units
actors.add((Actor) eObject);
}
if (isCanceled()) {
break;
}
}
return actors;
}
/**
* Prints the given actor. Should be overridden by back-ends that wish to
* print the given actor.
*
* @param actor
* the actor
* @return <code>true</code> if the actor was cached
*/
protected boolean printActor(Actor actor) {
return false;
}
/**
* Print instances of the given network.
*
* @param actors
* a list of actors
*/
final public void printActors(List<Actor> actors) {
OrccLogger.traceln("Printing actors...");
long t0 = System.currentTimeMillis();
// creates a list of tasks: each task will print an actor when called
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (final Actor actor : actors) {
tasks.add(new Callable<Boolean>() {
@Override
public Boolean call() {
if (isCanceled()) {
return false;
}
return printActor(actor);
}
});
}
// executes the tasks
int numCached = executeTasks(tasks);
long t1 = System.currentTimeMillis();
OrccLogger.traceln("Done in " + ((float) (t1 - t0) / (float) 1000)
+ "s");
if (numCached > 0) {
OrccLogger
.traceln("*******************************************************************************");
OrccLogger.traceln("* NOTE: " + numCached
+ " actors were not regenerated "
+ "because they were already up-to-date. *");
OrccLogger
.traceln("*******************************************************************************");
}
}
/**
* Print entities of the given network.
*
* @param entities
* a list of entities
*/
final public void printEntities(Network network) {
OrccLogger.traceln("Printing entities...");
long t0 = System.currentTimeMillis();
// creates a list of tasks: each task will print an actor when called
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (final Vertex vertex : network.getChildren()) {
tasks.add(new Callable<Boolean>() {
@Override
public Boolean call() {
if (isCanceled()) {
return false;
}
return printEntity(vertex);
}
});
}
// executes the tasks
int numCached = executeTasks(tasks);
long t1 = System.currentTimeMillis();
OrccLogger.traceln("Done in " + ((float) (t1 - t0) / (float) 1000)
+ "s");
if (numCached > 0) {
OrccLogger
.traceln("*******************************************************************************");
OrccLogger.traceln("* NOTE: " + numCached
+ " entities were not regenerated "
+ "because they were already up-to-date. *");
OrccLogger
.traceln("*******************************************************************************");
}
}
/**
* Prints the given entity. Should be overridden by back-ends that wish to
* print the given entity.
*
* @param entity
* the entity
* @return <code>true</code> if the actor was cached
*/
protected boolean printEntity(Vertex entity) {
return false;
}
/**
* Prints the given instance. Should be overridden by back-ends that wish to
* print the given instance.
*
* @param instance
* the instance
* @return <code>true</code> if the actor was cached
*/
protected boolean printInstance(Instance instance) {
return false;
}
/**
* Print instances of the given network.
*
* @param network
* a network
* @throws OrccException
*/
final public void printInstances(Network network) {
OrccLogger.traceln("Printing instances...");
long t0 = System.currentTimeMillis();
// creates a list of tasks: each task will print an instance when called
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (Vertex vertex : network.getChildren()) {
final Instance instance = vertex.getAdapter(Instance.class);
if (instance != null) {
tasks.add(new Callable<Boolean>() {
@Override
public Boolean call() {
return printInstance(instance);
}
});
}
}
// executes the tasks
int numCached = executeTasks(tasks);
long t1 = System.currentTimeMillis();
OrccLogger.traceln("Done in " + ((float) (t1 - t0) / (float) 1000)
+ "s");
if (numCached > 0) {
OrccLogger
.traceln("*******************************************************************************");
OrccLogger.traceln("* NOTE: " + numCached
+ " instances were not regenerated "
+ "because they were already up-to-date. *");
OrccLogger
.traceln("*******************************************************************************");
}
}
private void printUsage(IApplicationContext context, Options options,
String parserMsg) {
String footer = "";
if (parserMsg != null && !parserMsg.isEmpty()) {
footer = "\nMessage of the command line parser :\n" + parserMsg;
}
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.setWidth(80);
helpFormatter.printHelp(getClass().getSimpleName()
+ " [options] <network.qualified.name>", "Valid options are :",
options, footer);
}
@Override
public void setOptions(Map<String, Object> options) {
this.options = options;
String name = getAttribute(PROJECT, "");
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
project = root.getProject(name);
vtlFolders = OrccUtil.getOutputFolders(project);
inputFile = getFile(project, getAttribute(XDF_FILE, ""), "xdf");
fifoSize = getAttribute(FIFO_SIZE, DEFAULT_FIFO_SIZE);
debug = getAttribute(DEBUG_MODE, true);
mapping = getAttribute(MAPPING, new HashMap<String, String>());
classify = getAttribute(CLASSIFY, false);
// Merging transformations need the results of classification
mergeActions = classify && getAttribute(MERGE_ACTIONS, false);
mergeActors = classify && getAttribute(MERGE_ACTORS, false);
convertMulti2Mono = getAttribute("net.sf.orcc.backends.multi2mono",
false);
String outputFolder;
Object obj = options.get(OUTPUT_FOLDER);
if (obj instanceof String) {
outputFolder = (String) obj;
if (outputFolder.startsWith("~")) {
outputFolder = outputFolder.replace("~",
System.getProperty("user.home"));
}
} else {
outputFolder = "";
}
if (outputFolder.isEmpty()) {
String tmpdir = System.getProperty("java.io.tmpdir");
File output = new File(tmpdir, "orcc");
output.mkdir();
outputFolder = output.getAbsolutePath();
}
// set output path
path = new File(outputFolder).getAbsolutePath();
doInitializeOptions();
}
@Override
public void setProgressMonitor(IProgressMonitor monitor) {
this.monitor = monitor;
}
@Override
public Object start(IApplicationContext context) throws Exception {
Options options = new Options();
Option opt;
// Required command line arguments
opt = new Option("p", "project", true, "Project name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("o", "output", true, "Output folder");
opt.setRequired(true);
options.addOption(opt);
// Optional command line arguments
options.addOption("d", "debug", false, "Enable debug mode");
options.addOption("c", "classify", false, "Classify the given network");
options.addOption("smt", "smt-solver", true,
"Set path to the binary of the SMT solver (Z3 v4.12+)");
options.addOption("m", "merge", true, "Merge (1) static actions "
+ "(2) static actors (3) both");
options.addOption("s", "advanced-scheduler", false, "(C) Use the "
+ "data-driven/demand-driven strategy for the actor-scheduler");
options.addOption("m2m", "multi2mono", false,
"Transform high-level actors with multi-tokens actions"
+ " in low-level actors with mono-token actions");
// FIXME: choose independently the transformation to apply
options.addOption("t", "transfo_add", false,
"Execute additional transformations before generate code");
try {
CommandLineParser parser = new PosixParser();
// parse the command line arguments
CommandLine line = parser.parse(options, (String[]) context
.getArguments().get(IApplicationContext.APPLICATION_ARGS));
if (line.getArgs().length != 1) {
throw new ParseException(
"Expected network name as last argument");
}
String networkName = line.getArgs()[0];
Map<String, Object> optionMap = new HashMap<String, Object>();
optionMap.put(COMPILE_XDF, true);
optionMap.put(PROJECT, line.getOptionValue('p'));
optionMap.put(XDF_FILE, networkName);
optionMap.put(OUTPUT_FOLDER, line.getOptionValue('o'));
optionMap.put(DEBUG_MODE, line.hasOption('d'));
optionMap.put(CLASSIFY, line.hasOption('c'));
if (line.hasOption("smt")) {
String smt_path = line.getOptionValue("smt");
String smt_option = new String();
if (smt_path.contains("z3")) {
if (Platform.OS_WIN32.equals(Platform.getOS())) {
smt_option = "/smt2";
} else {
smt_option = "-smt2";
}
getDefault().setPreference(P_SOLVER, smt_path);
getDefault().setPreference(P_SOLVER_OPTIONS, smt_option);
} else {
OrccLogger.warnln("Unknown SMT solver.");
}
}
if (line.hasOption('m')) {
String type = line.getOptionValue('m');
optionMap.put(MERGE_ACTIONS,
type.equals("1") || type.equals("3"));
optionMap.put(MERGE_ACTORS,
type.equals("2") || type.equals("3"));
}
optionMap.put("net.sf.orcc.backends.newScheduler",
line.hasOption('s'));
optionMap.put("net.sf.orcc.backends.multi2mono",
line.hasOption("m2m"));
optionMap.put("net.sf.orcc.backends.additionalTransfos",
line.hasOption('t'));
try {
setOptions(optionMap);
exportRuntimeLibrary();
compile();
return IApplication.EXIT_OK;
} catch (OrccRuntimeException e) {
- OrccLogger.severeln(e.getMessage());
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
} catch (Exception e) {
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
e.printStackTrace();
}
return IApplication.EXIT_RELAUNCH;
} catch (UnrecognizedOptionException uoe) {
printUsage(context, options, uoe.getLocalizedMessage());
} catch (ParseException exp) {
printUsage(context, options, exp.getLocalizedMessage());
}
return IApplication.EXIT_RELAUNCH;
}
@Override
public void stop() {
}
/**
* Transforms instances of the given network.
*
* @param actors
* a list of actors
* @throws OrccException
*/
final public void transformActors(List<Actor> actors) {
OrccLogger.traceln("Transforming actors...");
for (Actor actor : actors) {
doTransformActor(actor);
}
}
}
| true | true | public Object start(IApplicationContext context) throws Exception {
Options options = new Options();
Option opt;
// Required command line arguments
opt = new Option("p", "project", true, "Project name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("o", "output", true, "Output folder");
opt.setRequired(true);
options.addOption(opt);
// Optional command line arguments
options.addOption("d", "debug", false, "Enable debug mode");
options.addOption("c", "classify", false, "Classify the given network");
options.addOption("smt", "smt-solver", true,
"Set path to the binary of the SMT solver (Z3 v4.12+)");
options.addOption("m", "merge", true, "Merge (1) static actions "
+ "(2) static actors (3) both");
options.addOption("s", "advanced-scheduler", false, "(C) Use the "
+ "data-driven/demand-driven strategy for the actor-scheduler");
options.addOption("m2m", "multi2mono", false,
"Transform high-level actors with multi-tokens actions"
+ " in low-level actors with mono-token actions");
// FIXME: choose independently the transformation to apply
options.addOption("t", "transfo_add", false,
"Execute additional transformations before generate code");
try {
CommandLineParser parser = new PosixParser();
// parse the command line arguments
CommandLine line = parser.parse(options, (String[]) context
.getArguments().get(IApplicationContext.APPLICATION_ARGS));
if (line.getArgs().length != 1) {
throw new ParseException(
"Expected network name as last argument");
}
String networkName = line.getArgs()[0];
Map<String, Object> optionMap = new HashMap<String, Object>();
optionMap.put(COMPILE_XDF, true);
optionMap.put(PROJECT, line.getOptionValue('p'));
optionMap.put(XDF_FILE, networkName);
optionMap.put(OUTPUT_FOLDER, line.getOptionValue('o'));
optionMap.put(DEBUG_MODE, line.hasOption('d'));
optionMap.put(CLASSIFY, line.hasOption('c'));
if (line.hasOption("smt")) {
String smt_path = line.getOptionValue("smt");
String smt_option = new String();
if (smt_path.contains("z3")) {
if (Platform.OS_WIN32.equals(Platform.getOS())) {
smt_option = "/smt2";
} else {
smt_option = "-smt2";
}
getDefault().setPreference(P_SOLVER, smt_path);
getDefault().setPreference(P_SOLVER_OPTIONS, smt_option);
} else {
OrccLogger.warnln("Unknown SMT solver.");
}
}
if (line.hasOption('m')) {
String type = line.getOptionValue('m');
optionMap.put(MERGE_ACTIONS,
type.equals("1") || type.equals("3"));
optionMap.put(MERGE_ACTORS,
type.equals("2") || type.equals("3"));
}
optionMap.put("net.sf.orcc.backends.newScheduler",
line.hasOption('s'));
optionMap.put("net.sf.orcc.backends.multi2mono",
line.hasOption("m2m"));
optionMap.put("net.sf.orcc.backends.additionalTransfos",
line.hasOption('t'));
try {
setOptions(optionMap);
exportRuntimeLibrary();
compile();
return IApplication.EXIT_OK;
} catch (OrccRuntimeException e) {
OrccLogger.severeln(e.getMessage());
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
} catch (Exception e) {
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
e.printStackTrace();
}
return IApplication.EXIT_RELAUNCH;
} catch (UnrecognizedOptionException uoe) {
printUsage(context, options, uoe.getLocalizedMessage());
} catch (ParseException exp) {
printUsage(context, options, exp.getLocalizedMessage());
}
return IApplication.EXIT_RELAUNCH;
}
| public Object start(IApplicationContext context) throws Exception {
Options options = new Options();
Option opt;
// Required command line arguments
opt = new Option("p", "project", true, "Project name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("o", "output", true, "Output folder");
opt.setRequired(true);
options.addOption(opt);
// Optional command line arguments
options.addOption("d", "debug", false, "Enable debug mode");
options.addOption("c", "classify", false, "Classify the given network");
options.addOption("smt", "smt-solver", true,
"Set path to the binary of the SMT solver (Z3 v4.12+)");
options.addOption("m", "merge", true, "Merge (1) static actions "
+ "(2) static actors (3) both");
options.addOption("s", "advanced-scheduler", false, "(C) Use the "
+ "data-driven/demand-driven strategy for the actor-scheduler");
options.addOption("m2m", "multi2mono", false,
"Transform high-level actors with multi-tokens actions"
+ " in low-level actors with mono-token actions");
// FIXME: choose independently the transformation to apply
options.addOption("t", "transfo_add", false,
"Execute additional transformations before generate code");
try {
CommandLineParser parser = new PosixParser();
// parse the command line arguments
CommandLine line = parser.parse(options, (String[]) context
.getArguments().get(IApplicationContext.APPLICATION_ARGS));
if (line.getArgs().length != 1) {
throw new ParseException(
"Expected network name as last argument");
}
String networkName = line.getArgs()[0];
Map<String, Object> optionMap = new HashMap<String, Object>();
optionMap.put(COMPILE_XDF, true);
optionMap.put(PROJECT, line.getOptionValue('p'));
optionMap.put(XDF_FILE, networkName);
optionMap.put(OUTPUT_FOLDER, line.getOptionValue('o'));
optionMap.put(DEBUG_MODE, line.hasOption('d'));
optionMap.put(CLASSIFY, line.hasOption('c'));
if (line.hasOption("smt")) {
String smt_path = line.getOptionValue("smt");
String smt_option = new String();
if (smt_path.contains("z3")) {
if (Platform.OS_WIN32.equals(Platform.getOS())) {
smt_option = "/smt2";
} else {
smt_option = "-smt2";
}
getDefault().setPreference(P_SOLVER, smt_path);
getDefault().setPreference(P_SOLVER_OPTIONS, smt_option);
} else {
OrccLogger.warnln("Unknown SMT solver.");
}
}
if (line.hasOption('m')) {
String type = line.getOptionValue('m');
optionMap.put(MERGE_ACTIONS,
type.equals("1") || type.equals("3"));
optionMap.put(MERGE_ACTORS,
type.equals("2") || type.equals("3"));
}
optionMap.put("net.sf.orcc.backends.newScheduler",
line.hasOption('s'));
optionMap.put("net.sf.orcc.backends.multi2mono",
line.hasOption("m2m"));
optionMap.put("net.sf.orcc.backends.additionalTransfos",
line.hasOption('t'));
try {
setOptions(optionMap);
exportRuntimeLibrary();
compile();
return IApplication.EXIT_OK;
} catch (OrccRuntimeException e) {
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
} catch (Exception e) {
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
e.printStackTrace();
}
return IApplication.EXIT_RELAUNCH;
} catch (UnrecognizedOptionException uoe) {
printUsage(context, options, uoe.getLocalizedMessage());
} catch (ParseException exp) {
printUsage(context, options, exp.getLocalizedMessage());
}
return IApplication.EXIT_RELAUNCH;
}
|
diff --git a/src/main/java/org/basex/test/w3c/W3CTS.java b/src/main/java/org/basex/test/w3c/W3CTS.java
index 528be4eb8..5c5fd8107 100644
--- a/src/main/java/org/basex/test/w3c/W3CTS.java
+++ b/src/main/java/org/basex/test/w3c/W3CTS.java
@@ -1,878 +1,878 @@
package org.basex.test.w3c;
import static org.basex.core.Text.*;
import static org.basex.util.Token.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.regex.Pattern;
import org.basex.core.Context;
import org.basex.core.Main;
import org.basex.core.Prop;
import org.basex.core.cmd.Check;
import org.basex.core.cmd.Close;
import org.basex.core.cmd.CreateDB;
import org.basex.data.Data;
import org.basex.data.DataText;
import org.basex.data.Nodes;
import org.basex.data.SerializerProp;
import org.basex.data.XMLSerializer;
import org.basex.io.CachedOutput;
import org.basex.io.IO;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.QueryProcessor;
import org.basex.query.expr.Expr;
import org.basex.query.func.FNSimple;
import org.basex.query.func.Fun;
import org.basex.query.func.FunDef;
import org.basex.query.item.DBNode;
import org.basex.query.item.Item;
import org.basex.query.item.QNm;
import org.basex.query.item.Str;
import org.basex.query.item.Type;
import org.basex.query.item.Uri;
import org.basex.query.iter.NodIter;
import org.basex.query.iter.SeqIter;
import org.basex.query.util.Var;
import org.basex.util.Args;
import org.basex.util.Performance;
import org.basex.util.StringList;
import org.basex.util.TokenBuilder;
import org.basex.util.TokenList;
/**
* XQuery Test Suite wrapper.
*
* @author Workgroup DBIS, University of Konstanz 2005-10, ISC License
* @author Christian Gruen
*/
public abstract class W3CTS {
// Try "ulimit -n 65536" if Linux tells you "Too many open files."
/** Inspect flag. */
private static final byte[] INSPECT = token("Inspect");
/** Fragment flag. */
private static final byte[] FRAGMENT = token("Fragment");
/** XML flag. */
private static final byte[] XML = token("XML");
/** Replacement pattern. */
private static final Pattern SLASH = Pattern.compile("/", Pattern.LITERAL);
/** Database context. */
protected final Context context = new Context();
/** Path to the XQuery Test Suite. */
protected String path = "";
/** Data reference. */
protected Data data;
/** History path. */
private final String pathhis;
/** Log file. */
private final String pathlog;
/** Test suite input. */
private final String input;
/** Test suite id. */
private final String testid;
/** Query path. */
private String queries;
/** Expected results. */
private String expected;
/** Reported results. */
private String results;
/** Reports. */
private String report;
/** Test sources. */
private String sources;
/** Maximum length of result output. */
private static int maxout = 500;
/** Query filter string. */
private String single;
/** Flag for printing current time functions into log file. */
private boolean currTime;
/** Flag for creating report files. */
private boolean reporting;
/** Verbose flag. */
private boolean verbose;
/** Debug flag. */
private boolean debug;
/** Minimum conformance. */
private boolean minimum;
/** Print compilation steps. */
private boolean compile;
/** Cached source files. */
private final HashMap<String, String> srcs = new HashMap<String, String>();
/** Cached module files. */
private final HashMap<String, String> mods = new HashMap<String, String>();
/** Cached collections. */
private final HashMap<String, byte[][]> colls =
new HashMap<String, byte[][]>();
/** OK log. */
private final StringBuilder logOK = new StringBuilder();
/** OK log. */
private final StringBuilder logOK2 = new StringBuilder();
/** Error log. */
private final StringBuilder logErr = new StringBuilder();
/** Error log. */
private final StringBuilder logErr2 = new StringBuilder();
/** File log. */
private final StringBuilder logReport = new StringBuilder();
/** Error counter. */
private int err;
/** Error2 counter. */
private int err2;
/** OK counter. */
private int ok;
/** OK2 counter. */
private int ok2;
/**
* Constructor.
* @param nm name of test
*/
public W3CTS(final String nm) {
input = nm + "Catalog" + IO.XMLSUFFIX;
testid = nm.substring(0, 4);
pathhis = testid.toLowerCase() + ".hist";
pathlog = testid.toLowerCase() + ".log";
}
/**
* Runs the test suite.
* @param args command-line arguments
* @throws Exception exception
*/
void run(final String[] args) throws Exception {
final Args arg = new Args(args, this,
" Test Suite [options] [pat]" + NL +
" [pat] perform only tests with the specified pattern" + NL +
" -c print compilation steps" + NL +
" -d show debugging info" + NL +
" -h show this help" + NL +
" -m minimum conformance" + NL +
" -p change path" + NL +
" -r create report" + NL +
" -v verbose output");
while(arg.more()) {
if(arg.dash()) {
final char c = arg.next();
if(c == 'r') {
reporting = true;
currTime = true;
} else if(c == 'c') {
compile = true;
} else if(c == 'd') {
debug = true;
} else if(c == 'm') {
minimum = true;
} else if(c == 'p') {
path = arg.string() + "/";
} else if(c == 'v') {
verbose = true;
} else {
arg.check(false);
}
} else {
single = arg.string();
maxout = Integer.MAX_VALUE;
}
}
if(!arg.finish()) return;
queries = path + "Queries/XQuery/";
expected = path + "ExpectedTestResults/";
results = path + "ReportingResults/Results/";
report = path + "ReportingResults/";
sources = path + "TestSources/";
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final String dat = sdf.format(Calendar.getInstance().getTime());
final Performance perf = new Performance();
context.prop.set(Prop.MAINMEM, false);
context.prop.set(Prop.TABLEMEM, false);
context.prop.set(Prop.CHOP, false);
new CreateDB(input, path + input).execute(context);
data = context.data;
final Nodes root = new Nodes(0, data);
Main.outln(NL + Main.name(this) + " Test Suite " +
text("/*:test-suite/@version", root));
Main.outln(NL + "Caching Sources...");
for(final int s : nodes("//*:source", root).nodes) {
final Nodes srcRoot = new Nodes(s, data);
final String val = (path + text("@FileName", srcRoot)).replace('\\', '/');
srcs.put(text("@ID", srcRoot), val);
}
Main.outln("Caching Modules...");
for(final int s : nodes("//*:module", root).nodes) {
final Nodes srcRoot = new Nodes(s, data);
final String val = (path + text("@FileName", srcRoot)).replace('\\', '/');
mods.put(text("@ID", srcRoot), val);
}
Main.outln("Caching Collections...");
for(final int c : nodes("//*:collection", root).nodes) {
final Nodes nodes = new Nodes(c, data);
final String cname = text("@ID", nodes);
final TokenList dl = new TokenList();
final Nodes doc = nodes("*:input-document", nodes);
for(int d = 0; d < doc.size(); d++) {
dl.add(token(sources + string(data.atom(doc.nodes[d])) + IO.XMLSUFFIX));
}
colls.put(cname, dl.toArray());
}
init(root);
if(reporting) {
Main.outln("Delete old results...");
delete(new File[] { new File(results) });
}
if(verbose) Main.outln();
final Nodes nodes = minimum ?
nodes("//*:test-group[starts-with(@name, 'Minim')]//*:test-case", root) :
nodes("//*:test-case", root);
long total = nodes.size();
Main.out("Parsing " + total + " Queries");
for(int t = 0; t < total; t++) {
if(!parse(new Nodes(nodes.nodes[t], data))) break;
if(!verbose && t % 500 == 0) Main.out(".");
}
Main.outln();
total = ok + ok2 + err + err2;
final String time = perf.getTimer();
Main.outln("Writing log file..." + NL);
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path + pathlog), UTF8));
bw.write("TEST RESULTS ==================================================");
bw.write(NL + NL + "Total #Queries: " + total + NL);
bw.write("Correct / Empty Results: " + ok + " / " + ok2 + NL);
bw.write("Conformance (w/Empty Results): ");
bw.write(pc(ok, total) + " / " + pc(ok + ok2, total) + NL);
bw.write("Wrong Results / Errors: " + err + " / " + err2 + NL);
bw.write("WRONG =========================================================");
bw.write(NL + NL + logErr + NL);
bw.write("WRONG (ERRORS) ================================================");
bw.write(NL + NL + logErr2 + NL);
bw.write("CORRECT? (EMPTY) ==============================================");
bw.write(NL + NL + logOK2 + NL);
bw.write("CORRECT =======================================================");
bw.write(NL + NL + logOK + NL);
bw.write("===============================================================");
bw.close();
bw = new BufferedWriter(new FileWriter(path + pathhis, true));
bw.write(dat + "\t" + ok + "\t" + ok2 + "\t" + err + "\t" + err2 + NL);
bw.close();
if(reporting) {
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(report + NAME + IO.XMLSUFFIX), UTF8));
write(bw, report + NAME + "Pre" + IO.XMLSUFFIX);
bw.write(logReport.toString());
write(bw, report + NAME + "Pos" + IO.XMLSUFFIX);
bw.close();
}
Main.outln("Total #Queries: " + total);
Main.outln("Correct / Empty results: " + ok + " / " + ok2);
Main.out("Conformance (w/empty results): ");
Main.outln(pc(ok, total) + " / " + pc(ok + ok2, total));
Main.outln("Total Time: " + time);
context.close();
}
/**
* Calculates the percentage of correct queries.
* @param v value
* @param t total value
* @return percentage
*/
private String pc(final int v, final long t) {
return (t == 0 ? 100 : v * 10000 / t / 100d) + "%";
}
/**
* Parses the specified test case.
* @param root root node
* @throws Exception exception
* @return true if the query, specified by {@link #single}, was evaluated
*/
private boolean parse(final Nodes root) throws Exception {
final String pth = text("@FilePath", root);
final String outname = text("@name", root);
if(single != null && !outname.startsWith(single)) return true;
Performance perf = new Performance();
if(verbose) Main.out("- " + outname);
boolean inspect = false;
boolean correct = true;
final Nodes nodes = states(root);
for(int n = 0; n < nodes.size(); n++) {
final Nodes state = new Nodes(nodes.nodes[n], nodes.data);
final String inname = text("*:query/@name", state);
context.query = IO.get(queries + pth + inname + IO.XQSUFFIX);
final String in = read(context.query);
String error = null;
SeqIter iter = null;
boolean doc = true;
final TokenBuilder files = new TokenBuilder();
final CachedOutput co = new CachedOutput();
final Nodes cont = nodes("*:contextItem", state);
Nodes curr = null;
if(cont.size() != 0) {
final Data d = Check.check(context,
srcs.get(string(data.atom(cont.nodes[0]))));
curr = new Nodes(d.doc(), d);
curr.doc = true;
}
context.prop.set(Prop.QUERYINFO, compile);
final QueryProcessor xq = new QueryProcessor(in, curr, context);
final QueryContext qctx = xq.ctx;
context.prop.set(Prop.QUERYINFO, false);
try {
files.add(file(nodes("*:input-file", state),
nodes("*:input-file/@variable", state), qctx, n == 0));
files.add(file(nodes("*:defaultCollection", state),
null, qctx, n == 0));
var(nodes("*:input-URI", state),
nodes("*:input-URI/@variable", state), qctx);
eval(nodes("*:input-query/@name", state),
nodes("*:input-query/@variable", state), pth, qctx);
parse(qctx, state);
for(final int p : nodes("*:module", root).nodes) {
final String ns = text("@namespace", new Nodes(p, data));
final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX;
xq.module(ns, f);
}
// evaluate and serialize query
final SerializerProp sp = new SerializerProp();
sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ?
DataText.YES : DataText.NO);
final XMLSerializer xml = new XMLSerializer(co, sp);
iter = SeqIter.get(xq.iter());
Item it;
while((it = iter.next()) != null) {
doc &= it.type == Type.DOC;
it.serialize(xml);
}
xml.close();
} catch(final QueryException ex) {
error = ex.getMessage();
if(error.startsWith(STOPPED)) {
error = error.substring(error.indexOf('\n') + 1);
}
if(error.startsWith("[")) {
error = error.replaceAll("\\[(.*?)\\] (.*)", "$1 $2");
}
} catch(final Exception ex) {
error = ex.getMessage() != null ? ex.getMessage() : ex.toString();
System.err.print("\n" + inname + ": ");
ex.printStackTrace();
}
// print compilation steps
if(compile) {
Main.errln("---------------------------------------------------------");
Main.err(xq.info());
Main.errln(in);
}
final Nodes outFiles = nodes("*:output-file/text()", state);
final Nodes cmpFiles = nodes("*:output-file/@compare", state);
boolean xml = false;
boolean frag = false;
final StringList result = new StringList();
for(int o = 0; o < outFiles.size(); o++) {
final String resFile = string(data.atom(outFiles.nodes[o]));
final IO exp = IO.get(expected + pth + resFile);
result.add(read(exp));
final byte[] type = data.atom(cmpFiles.nodes[o]);
xml |= eq(type, XML);
frag |= eq(type, FRAGMENT);
}
String expError = text("*:expected-error/text()", state);
final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX);
if(files.size() != 0) {
log.append(" [");
log.append(files);
log.append("]");
}
log.append(NL);
/** Remove comments. */
log.append(norm(in));
log.append(NL);
final String logStr = log.toString();
// skip queries with variable results
final boolean print = currTime || !logStr.contains("current-");
boolean correctError = false;
if(error != null && (outFiles.size() == 0 || !expError.isEmpty())) {
expError = error(pth + outname, expError);
final String code = error.substring(0, Math.min(8, error.length()));
for(final String er : SLASH.split(expError)) {
if(code.equals(er)) {
correctError = true;
break;
}
}
}
if(correctError) {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(error));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + ".log", error);
}
ok++;
} else if(error == null) {
int s = -1;
final int rs = result.size();
while(++s < rs) {
inspect |= s < cmpFiles.nodes.length &&
eq(data.atom(cmpFiles.nodes[s]), INSPECT);
if(result.get(s).equals(co.toString())) break;
if(xml || frag) {
iter.reset();
String ri = result.get(s).trim();
if(!doc) {
if(ri.startsWith("<?xml")) ri = ri.replaceAll("^<.*?>\\s*", "");
ri = "<X>" + ri + "</X>";
}
try {
final Data rdata = CreateDB.xml(IO.get(ri), context);
final SeqIter si = new SeqIter();
for(int pre = doc ? 0 : 2; pre < rdata.meta.size;) {
si.add(new DBNode(rdata, pre));
pre += rdata.size(pre, rdata.kind(pre));
}
// [CG] XQuery: check if null reference is safe
final boolean eq = FNSimple.deep(null, iter, si);
if(!eq && debug) {
iter.reset();
si.reset();
final XMLSerializer ser = new XMLSerializer(System.out);
Item it;
Main.outln(NL + "=== " + testid + " ===");
while((it = si.next()) != null) it.serialize(ser);
Main.outln(NL + "=== " + NAME + " ===");
while((it = iter.next()) != null) it.serialize(ser);
Main.outln();
}
rdata.close();
if(eq) break;
- } catch(final IOException ex) {
+ } catch(final Exception ex) {
ex.printStackTrace();
}
}
}
if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) {
if(print) {
if(outFiles.size() == 0) result.add(error(pth + outname, expError));
logErr.append(logStr);
logErr.append("[" + testid + " ] ");
logErr.append(norm(result.get(0)));
logErr.append(NL);
logErr.append("[Wrong] ");
logErr.append(norm(co.toString()));
logErr.append(NL);
logErr.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
co.toString());
}
correct = false;
err++;
} else {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(co.toString()));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
co.toString());
}
ok++;
}
} else {
if(outFiles.size() == 0 || !expError.isEmpty()) {
if(print) {
logOK2.append(logStr);
logOK2.append("[" + testid + " ] ");
logOK2.append(norm(expError));
logOK2.append(NL);
logOK2.append("[Rght?] ");
logOK2.append(norm(error));
logOK2.append(NL);
logOK2.append(NL);
addLog(pth, outname + ".log", error);
}
ok2++;
} else {
if(print) {
logErr2.append(logStr);
logErr2.append("[" + testid + " ] ");
logErr2.append(norm(result.get(0)));
logErr2.append(NL);
logErr2.append("[Wrong] ");
logErr2.append(norm(error));
logErr2.append(NL);
logErr2.append(NL);
addLog(pth, outname + ".log", error);
}
correct = false;
err2++;
}
}
if(curr != null) Close.close(context, curr.data);
xq.close();
}
if(reporting) {
logReport.append(" <test-case name=\"");
logReport.append(outname);
logReport.append("\" result='");
logReport.append(correct ? "pass" : "fail");
if(inspect) logReport.append("' todo='inspect");
logReport.append("'/>");
logReport.append(NL);
}
if(verbose) {
final long t = perf.getTime();
if(t > 100000000) Main.out(": " + Performance.getTimer(t, 1));
Main.outln();
}
return single == null || !outname.equals(single);
}
/**
* Normalizes the specified string.
* @param in input string
* @return result
*/
private String norm(final String in) {
//if(1 == 1) return in;
final StringBuilder sb = new StringBuilder();
int m = 0;
boolean s = false;
final int cl = in.length();
for(int c = 0; c < cl; c++) {
final char ch = in.charAt(c);
if(ch == '(' && c + 1 < cl && in.charAt(c + 1) == ':') {
if(m == 0 && !s) {
sb.append(' ');
s = true;
}
m++;
c++;
} else if(m != 0 && ch == ':' && c + 1 < cl && in.charAt(c + 1) == ')') {
m--;
c++;
} else if(m == 0) {
if(!s || ch > ' ') sb.append(ch);
s = ch <= ' ';
}
}
final String res = sb.toString().replaceAll("(\r|\n)+", " ").trim();
return res.length() < maxout ? res : res.substring(0, maxout) + "...";
}
/**
* Initializes the input files, specified by the context nodes.
* @param nod variables
* @param var documents
* @param ctx query context
* @param first call
* @return string with input files
* @throws QueryException query exception
*/
private byte[] file(final Nodes nod, final Nodes var,
final QueryContext ctx, final boolean first) throws QueryException {
final TokenBuilder tb = new TokenBuilder();
for(int c = 0; c < nod.size(); c++) {
final byte[] nm = data.atom(nod.nodes[c]);
String src = srcs.get(string(nm));
if(tb.size() != 0) tb.add(", ");
tb.add(nm);
Expr expr = null;
if(src == null) {
expr = coll(nm, ctx);
} else {
// assign document
FunDef def = FunDef.DOC;
if(!first) {
def = FunDef.DB;
src = IO.get(src).dbname();
}
// [CG] XQuery/Query Info
expr = Fun.create(null, def, Str.get(src));
}
if(var != null) {
final Var v = new Var(new QNm(data.atom(var.nodes[c])));
ctx.vars.addGlobal(v.bind(expr, ctx));
}
}
return tb.finish();
}
/**
* Assigns the nodes to the specified variables.
* @param nod nodes
* @param var variables
* @param ctx query context
* @throws QueryException query exception
*/
private void var(final Nodes nod, final Nodes var, final QueryContext ctx)
throws QueryException {
for(int c = 0; c < nod.size(); c++) {
final byte[] nm = data.atom(nod.nodes[c]);
final String src = srcs.get(string(nm));
Expr expr = null;
if(src == null) {
expr = coll(nm, ctx);
} else {
expr = Str.get(src);
}
final Var v = new Var(new QNm(data.atom(var.nodes[c])));
ctx.vars.addGlobal(v.bind(expr, ctx));
}
}
/**
* Assigns a collection.
* @param name collection name
* @param ctx query context
* @return expression
* @throws QueryException query exception
*/
private Expr coll(final byte[] name, final QueryContext ctx)
throws QueryException {
// assign collection
final NodIter col = new NodIter();
for(final byte[] cl : colls.get(string(name))) {
if(new File(string(cl)).exists()) col.add(ctx.doc(cl, true, false, null));
else Main.errln("Warning: \"%\" not found.", cl);
}
ctx.addColl(col, name);
return Uri.uri(name);
}
/**
* Evaluates the the input files and assigns the result to the specified
* variables.
* @param nod variables
* @param var documents
* @param pth file path
* @param ctx query context
* @throws Exception exception
*/
private void eval(final Nodes nod, final Nodes var, final String pth,
final QueryContext ctx) throws Exception {
for(int c = 0; c < nod.size(); c++) {
final String file = pth + string(data.atom(nod.nodes[c])) + IO.XQSUFFIX;
final String in = read(IO.get(queries + file));
final QueryProcessor xq = new QueryProcessor(in, context);
final Item item = xq.iter().finish();
final Var v = new Var(new QNm(data.atom(var.nodes[c])));
ctx.vars.addGlobal(v.bind(item, ctx));
xq.close();
}
}
/**
* Adds a log file.
* @param pth file path
* @param nm file name
* @param msg message
* @throws Exception exception
*/
private void addLog(final String pth, final String nm, final String msg)
throws Exception {
if(reporting) {
final File file = new File(results + pth);
if(!file.exists()) file.mkdirs();
final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(results + pth + nm), UTF8));
bw.write(msg);
bw.close();
}
}
/**
* Returns an error message.
* @param nm test name
* @param error XQTS error
* @return error message
*/
private String error(final String nm, final String error) {
final String error2 = expected + nm + ".log";
final IO file = IO.get(error2);
return file.exists() ? error + "/" + read(file) : error;
}
/**
* Returns the resulting query text (text node or attribute value).
* @param qu query
* @param root root node
* @return attribute value
* @throws Exception exception
*/
protected String text(final String qu, final Nodes root) throws Exception {
final Nodes n = nodes(qu, root);
final TokenBuilder sb = new TokenBuilder();
for(int i = 0; i < n.size(); i++) {
if(i != 0) sb.add('/');
sb.add(data.atom(n.nodes[i]));
}
return sb.toString();
}
/**
* Returns the resulting auxiliary uri in multiple strings.
* @param role role
* @param root root node
* @return attribute value
* @throws Exception exception
*/
protected String[] aux(final String role, final Nodes root) throws Exception {
return text("*:aux-URI[@role = '" + role + "']", root).split("/");
}
/**
* Returns the resulting query nodes.
* @param qu query
* @param root root node
* @return attribute value
* @throws Exception exception
*/
protected Nodes nodes(final String qu, final Nodes root) throws Exception {
return new QueryProcessor(qu, root, context).queryNodes();
}
/**
* Recursively deletes a directory.
* @param pth deletion path
*/
void delete(final File[] pth) {
for(final File f : pth) {
if(f.isDirectory()) delete(f.listFiles());
f.delete();
}
}
/**
* Adds the specified file to the writer.
* @param bw writer
* @param f file path
* @throws Exception exception
*/
private void write(final BufferedWriter bw, final String f) throws Exception {
final BufferedReader br = new BufferedReader(new
InputStreamReader(new FileInputStream(f), UTF8));
String line;
while((line = br.readLine()) != null) {
bw.write(line);
bw.write(NL);
}
br.close();
}
/**
* Returns the contents of the specified file.
* @param f file to be read
* @return content
*/
private String read(final IO f) {
try {
return string(f.content()).replaceAll("\r\n?", "\n");
} catch(final IOException ex) {
ex.printStackTrace();
return "";
}
}
/**
* Initializes the test.
* @param root root nodes reference
* @throws Exception exception
*/
@SuppressWarnings("unused")
void init(final Nodes root) throws Exception { }
/**
* Performs test specific parsings.
* @param qctx query context
* @param root root nodes reference
* @throws Exception exception
*/
@SuppressWarnings("unused")
void parse(final QueryContext qctx, final Nodes root) throws Exception { }
/**
* Returns all query states.
* @param root root node
* @return states
* @throws Exception exception
*/
@SuppressWarnings("unused")
Nodes states(final Nodes root) throws Exception {
return root;
}
}
| true | true | private boolean parse(final Nodes root) throws Exception {
final String pth = text("@FilePath", root);
final String outname = text("@name", root);
if(single != null && !outname.startsWith(single)) return true;
Performance perf = new Performance();
if(verbose) Main.out("- " + outname);
boolean inspect = false;
boolean correct = true;
final Nodes nodes = states(root);
for(int n = 0; n < nodes.size(); n++) {
final Nodes state = new Nodes(nodes.nodes[n], nodes.data);
final String inname = text("*:query/@name", state);
context.query = IO.get(queries + pth + inname + IO.XQSUFFIX);
final String in = read(context.query);
String error = null;
SeqIter iter = null;
boolean doc = true;
final TokenBuilder files = new TokenBuilder();
final CachedOutput co = new CachedOutput();
final Nodes cont = nodes("*:contextItem", state);
Nodes curr = null;
if(cont.size() != 0) {
final Data d = Check.check(context,
srcs.get(string(data.atom(cont.nodes[0]))));
curr = new Nodes(d.doc(), d);
curr.doc = true;
}
context.prop.set(Prop.QUERYINFO, compile);
final QueryProcessor xq = new QueryProcessor(in, curr, context);
final QueryContext qctx = xq.ctx;
context.prop.set(Prop.QUERYINFO, false);
try {
files.add(file(nodes("*:input-file", state),
nodes("*:input-file/@variable", state), qctx, n == 0));
files.add(file(nodes("*:defaultCollection", state),
null, qctx, n == 0));
var(nodes("*:input-URI", state),
nodes("*:input-URI/@variable", state), qctx);
eval(nodes("*:input-query/@name", state),
nodes("*:input-query/@variable", state), pth, qctx);
parse(qctx, state);
for(final int p : nodes("*:module", root).nodes) {
final String ns = text("@namespace", new Nodes(p, data));
final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX;
xq.module(ns, f);
}
// evaluate and serialize query
final SerializerProp sp = new SerializerProp();
sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ?
DataText.YES : DataText.NO);
final XMLSerializer xml = new XMLSerializer(co, sp);
iter = SeqIter.get(xq.iter());
Item it;
while((it = iter.next()) != null) {
doc &= it.type == Type.DOC;
it.serialize(xml);
}
xml.close();
} catch(final QueryException ex) {
error = ex.getMessage();
if(error.startsWith(STOPPED)) {
error = error.substring(error.indexOf('\n') + 1);
}
if(error.startsWith("[")) {
error = error.replaceAll("\\[(.*?)\\] (.*)", "$1 $2");
}
} catch(final Exception ex) {
error = ex.getMessage() != null ? ex.getMessage() : ex.toString();
System.err.print("\n" + inname + ": ");
ex.printStackTrace();
}
// print compilation steps
if(compile) {
Main.errln("---------------------------------------------------------");
Main.err(xq.info());
Main.errln(in);
}
final Nodes outFiles = nodes("*:output-file/text()", state);
final Nodes cmpFiles = nodes("*:output-file/@compare", state);
boolean xml = false;
boolean frag = false;
final StringList result = new StringList();
for(int o = 0; o < outFiles.size(); o++) {
final String resFile = string(data.atom(outFiles.nodes[o]));
final IO exp = IO.get(expected + pth + resFile);
result.add(read(exp));
final byte[] type = data.atom(cmpFiles.nodes[o]);
xml |= eq(type, XML);
frag |= eq(type, FRAGMENT);
}
String expError = text("*:expected-error/text()", state);
final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX);
if(files.size() != 0) {
log.append(" [");
log.append(files);
log.append("]");
}
log.append(NL);
/** Remove comments. */
log.append(norm(in));
log.append(NL);
final String logStr = log.toString();
// skip queries with variable results
final boolean print = currTime || !logStr.contains("current-");
boolean correctError = false;
if(error != null && (outFiles.size() == 0 || !expError.isEmpty())) {
expError = error(pth + outname, expError);
final String code = error.substring(0, Math.min(8, error.length()));
for(final String er : SLASH.split(expError)) {
if(code.equals(er)) {
correctError = true;
break;
}
}
}
if(correctError) {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(error));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + ".log", error);
}
ok++;
} else if(error == null) {
int s = -1;
final int rs = result.size();
while(++s < rs) {
inspect |= s < cmpFiles.nodes.length &&
eq(data.atom(cmpFiles.nodes[s]), INSPECT);
if(result.get(s).equals(co.toString())) break;
if(xml || frag) {
iter.reset();
String ri = result.get(s).trim();
if(!doc) {
if(ri.startsWith("<?xml")) ri = ri.replaceAll("^<.*?>\\s*", "");
ri = "<X>" + ri + "</X>";
}
try {
final Data rdata = CreateDB.xml(IO.get(ri), context);
final SeqIter si = new SeqIter();
for(int pre = doc ? 0 : 2; pre < rdata.meta.size;) {
si.add(new DBNode(rdata, pre));
pre += rdata.size(pre, rdata.kind(pre));
}
// [CG] XQuery: check if null reference is safe
final boolean eq = FNSimple.deep(null, iter, si);
if(!eq && debug) {
iter.reset();
si.reset();
final XMLSerializer ser = new XMLSerializer(System.out);
Item it;
Main.outln(NL + "=== " + testid + " ===");
while((it = si.next()) != null) it.serialize(ser);
Main.outln(NL + "=== " + NAME + " ===");
while((it = iter.next()) != null) it.serialize(ser);
Main.outln();
}
rdata.close();
if(eq) break;
} catch(final IOException ex) {
ex.printStackTrace();
}
}
}
if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) {
if(print) {
if(outFiles.size() == 0) result.add(error(pth + outname, expError));
logErr.append(logStr);
logErr.append("[" + testid + " ] ");
logErr.append(norm(result.get(0)));
logErr.append(NL);
logErr.append("[Wrong] ");
logErr.append(norm(co.toString()));
logErr.append(NL);
logErr.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
co.toString());
}
correct = false;
err++;
} else {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(co.toString()));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
co.toString());
}
ok++;
}
} else {
if(outFiles.size() == 0 || !expError.isEmpty()) {
if(print) {
logOK2.append(logStr);
logOK2.append("[" + testid + " ] ");
logOK2.append(norm(expError));
logOK2.append(NL);
logOK2.append("[Rght?] ");
logOK2.append(norm(error));
logOK2.append(NL);
logOK2.append(NL);
addLog(pth, outname + ".log", error);
}
ok2++;
} else {
if(print) {
logErr2.append(logStr);
logErr2.append("[" + testid + " ] ");
logErr2.append(norm(result.get(0)));
logErr2.append(NL);
logErr2.append("[Wrong] ");
logErr2.append(norm(error));
logErr2.append(NL);
logErr2.append(NL);
addLog(pth, outname + ".log", error);
}
correct = false;
err2++;
}
}
if(curr != null) Close.close(context, curr.data);
xq.close();
}
if(reporting) {
logReport.append(" <test-case name=\"");
logReport.append(outname);
logReport.append("\" result='");
logReport.append(correct ? "pass" : "fail");
if(inspect) logReport.append("' todo='inspect");
logReport.append("'/>");
logReport.append(NL);
}
if(verbose) {
final long t = perf.getTime();
if(t > 100000000) Main.out(": " + Performance.getTimer(t, 1));
Main.outln();
}
return single == null || !outname.equals(single);
}
| private boolean parse(final Nodes root) throws Exception {
final String pth = text("@FilePath", root);
final String outname = text("@name", root);
if(single != null && !outname.startsWith(single)) return true;
Performance perf = new Performance();
if(verbose) Main.out("- " + outname);
boolean inspect = false;
boolean correct = true;
final Nodes nodes = states(root);
for(int n = 0; n < nodes.size(); n++) {
final Nodes state = new Nodes(nodes.nodes[n], nodes.data);
final String inname = text("*:query/@name", state);
context.query = IO.get(queries + pth + inname + IO.XQSUFFIX);
final String in = read(context.query);
String error = null;
SeqIter iter = null;
boolean doc = true;
final TokenBuilder files = new TokenBuilder();
final CachedOutput co = new CachedOutput();
final Nodes cont = nodes("*:contextItem", state);
Nodes curr = null;
if(cont.size() != 0) {
final Data d = Check.check(context,
srcs.get(string(data.atom(cont.nodes[0]))));
curr = new Nodes(d.doc(), d);
curr.doc = true;
}
context.prop.set(Prop.QUERYINFO, compile);
final QueryProcessor xq = new QueryProcessor(in, curr, context);
final QueryContext qctx = xq.ctx;
context.prop.set(Prop.QUERYINFO, false);
try {
files.add(file(nodes("*:input-file", state),
nodes("*:input-file/@variable", state), qctx, n == 0));
files.add(file(nodes("*:defaultCollection", state),
null, qctx, n == 0));
var(nodes("*:input-URI", state),
nodes("*:input-URI/@variable", state), qctx);
eval(nodes("*:input-query/@name", state),
nodes("*:input-query/@variable", state), pth, qctx);
parse(qctx, state);
for(final int p : nodes("*:module", root).nodes) {
final String ns = text("@namespace", new Nodes(p, data));
final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX;
xq.module(ns, f);
}
// evaluate and serialize query
final SerializerProp sp = new SerializerProp();
sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ?
DataText.YES : DataText.NO);
final XMLSerializer xml = new XMLSerializer(co, sp);
iter = SeqIter.get(xq.iter());
Item it;
while((it = iter.next()) != null) {
doc &= it.type == Type.DOC;
it.serialize(xml);
}
xml.close();
} catch(final QueryException ex) {
error = ex.getMessage();
if(error.startsWith(STOPPED)) {
error = error.substring(error.indexOf('\n') + 1);
}
if(error.startsWith("[")) {
error = error.replaceAll("\\[(.*?)\\] (.*)", "$1 $2");
}
} catch(final Exception ex) {
error = ex.getMessage() != null ? ex.getMessage() : ex.toString();
System.err.print("\n" + inname + ": ");
ex.printStackTrace();
}
// print compilation steps
if(compile) {
Main.errln("---------------------------------------------------------");
Main.err(xq.info());
Main.errln(in);
}
final Nodes outFiles = nodes("*:output-file/text()", state);
final Nodes cmpFiles = nodes("*:output-file/@compare", state);
boolean xml = false;
boolean frag = false;
final StringList result = new StringList();
for(int o = 0; o < outFiles.size(); o++) {
final String resFile = string(data.atom(outFiles.nodes[o]));
final IO exp = IO.get(expected + pth + resFile);
result.add(read(exp));
final byte[] type = data.atom(cmpFiles.nodes[o]);
xml |= eq(type, XML);
frag |= eq(type, FRAGMENT);
}
String expError = text("*:expected-error/text()", state);
final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX);
if(files.size() != 0) {
log.append(" [");
log.append(files);
log.append("]");
}
log.append(NL);
/** Remove comments. */
log.append(norm(in));
log.append(NL);
final String logStr = log.toString();
// skip queries with variable results
final boolean print = currTime || !logStr.contains("current-");
boolean correctError = false;
if(error != null && (outFiles.size() == 0 || !expError.isEmpty())) {
expError = error(pth + outname, expError);
final String code = error.substring(0, Math.min(8, error.length()));
for(final String er : SLASH.split(expError)) {
if(code.equals(er)) {
correctError = true;
break;
}
}
}
if(correctError) {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(error));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + ".log", error);
}
ok++;
} else if(error == null) {
int s = -1;
final int rs = result.size();
while(++s < rs) {
inspect |= s < cmpFiles.nodes.length &&
eq(data.atom(cmpFiles.nodes[s]), INSPECT);
if(result.get(s).equals(co.toString())) break;
if(xml || frag) {
iter.reset();
String ri = result.get(s).trim();
if(!doc) {
if(ri.startsWith("<?xml")) ri = ri.replaceAll("^<.*?>\\s*", "");
ri = "<X>" + ri + "</X>";
}
try {
final Data rdata = CreateDB.xml(IO.get(ri), context);
final SeqIter si = new SeqIter();
for(int pre = doc ? 0 : 2; pre < rdata.meta.size;) {
si.add(new DBNode(rdata, pre));
pre += rdata.size(pre, rdata.kind(pre));
}
// [CG] XQuery: check if null reference is safe
final boolean eq = FNSimple.deep(null, iter, si);
if(!eq && debug) {
iter.reset();
si.reset();
final XMLSerializer ser = new XMLSerializer(System.out);
Item it;
Main.outln(NL + "=== " + testid + " ===");
while((it = si.next()) != null) it.serialize(ser);
Main.outln(NL + "=== " + NAME + " ===");
while((it = iter.next()) != null) it.serialize(ser);
Main.outln();
}
rdata.close();
if(eq) break;
} catch(final Exception ex) {
ex.printStackTrace();
}
}
}
if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) {
if(print) {
if(outFiles.size() == 0) result.add(error(pth + outname, expError));
logErr.append(logStr);
logErr.append("[" + testid + " ] ");
logErr.append(norm(result.get(0)));
logErr.append(NL);
logErr.append("[Wrong] ");
logErr.append(norm(co.toString()));
logErr.append(NL);
logErr.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
co.toString());
}
correct = false;
err++;
} else {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(co.toString()));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
co.toString());
}
ok++;
}
} else {
if(outFiles.size() == 0 || !expError.isEmpty()) {
if(print) {
logOK2.append(logStr);
logOK2.append("[" + testid + " ] ");
logOK2.append(norm(expError));
logOK2.append(NL);
logOK2.append("[Rght?] ");
logOK2.append(norm(error));
logOK2.append(NL);
logOK2.append(NL);
addLog(pth, outname + ".log", error);
}
ok2++;
} else {
if(print) {
logErr2.append(logStr);
logErr2.append("[" + testid + " ] ");
logErr2.append(norm(result.get(0)));
logErr2.append(NL);
logErr2.append("[Wrong] ");
logErr2.append(norm(error));
logErr2.append(NL);
logErr2.append(NL);
addLog(pth, outname + ".log", error);
}
correct = false;
err2++;
}
}
if(curr != null) Close.close(context, curr.data);
xq.close();
}
if(reporting) {
logReport.append(" <test-case name=\"");
logReport.append(outname);
logReport.append("\" result='");
logReport.append(correct ? "pass" : "fail");
if(inspect) logReport.append("' todo='inspect");
logReport.append("'/>");
logReport.append(NL);
}
if(verbose) {
final long t = perf.getTime();
if(t > 100000000) Main.out(": " + Performance.getTimer(t, 1));
Main.outln();
}
return single == null || !outname.equals(single);
}
|
diff --git a/src/org/gs/campusparty/Ghost.java b/src/org/gs/campusparty/Ghost.java
index e1b9d30..bd552c0 100644
--- a/src/org/gs/campusparty/Ghost.java
+++ b/src/org/gs/campusparty/Ghost.java
@@ -1,35 +1,35 @@
package org.gs.campusparty;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.widget.TextView;
public class Ghost {
int time;
int[] chips;
TextView label;
TextView chiplabel;
public Ghost() {
time = -1;
chips = new int[Field.C_COUNT];
}
public void step() {
- label.setText(Integer.toString(time));
String chiptext = "";
for(int i = 0; i < Field.C_COUNT; i++) {
for(int j = 0; j < chips[i]; j++) {
chiptext += Field.names[i];
}
}
if(chiptext.length() == 0) {
time = -1;
Field.getSingleton().kills += 1;
}
chiplabel.setText(chiptext);
label.setTextColor(Color.RED);
time -= 1;
+ label.setText(Integer.toString(time));
}
}
| false | true | public void step() {
label.setText(Integer.toString(time));
String chiptext = "";
for(int i = 0; i < Field.C_COUNT; i++) {
for(int j = 0; j < chips[i]; j++) {
chiptext += Field.names[i];
}
}
if(chiptext.length() == 0) {
time = -1;
Field.getSingleton().kills += 1;
}
chiplabel.setText(chiptext);
label.setTextColor(Color.RED);
time -= 1;
}
| public void step() {
String chiptext = "";
for(int i = 0; i < Field.C_COUNT; i++) {
for(int j = 0; j < chips[i]; j++) {
chiptext += Field.names[i];
}
}
if(chiptext.length() == 0) {
time = -1;
Field.getSingleton().kills += 1;
}
chiplabel.setText(chiptext);
label.setTextColor(Color.RED);
time -= 1;
label.setText(Integer.toString(time));
}
|
diff --git a/mcu/src/org/smbarbour/mcu/Main.java b/mcu/src/org/smbarbour/mcu/Main.java
index 190be8a..acb3e43 100644
--- a/mcu/src/org/smbarbour/mcu/Main.java
+++ b/mcu/src/org/smbarbour/mcu/Main.java
@@ -1,33 +1,34 @@
package org.smbarbour.mcu;
import java.awt.EventQueue;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class Main {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
+ System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
if (UIManager.getLookAndFeel().getName().equals("Metal")) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
new MainForm();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| true | true | public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
if (UIManager.getLookAndFeel().getName().equals("Metal")) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
new MainForm();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
| public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
if (UIManager.getLookAndFeel().getName().equals("Metal")) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
new MainForm();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
|
diff --git a/sky/org.kevoree.library.sky.lxc/src/main/java/org/kevoree/library/sky/lxc/WatchBackupsContainers.java b/sky/org.kevoree.library.sky.lxc/src/main/java/org/kevoree/library/sky/lxc/WatchBackupsContainers.java
index ae88fea..fcfa2d8 100644
--- a/sky/org.kevoree.library.sky.lxc/src/main/java/org/kevoree/library/sky/lxc/WatchBackupsContainers.java
+++ b/sky/org.kevoree.library.sky.lxc/src/main/java/org/kevoree/library/sky/lxc/WatchBackupsContainers.java
@@ -1,61 +1,62 @@
package org.kevoree.library.sky.lxc;
import org.kevoree.library.sky.lxc.utils.FileManager;
import org.kevoree.log.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: jed
* Date: 26/07/13
* Time: 12:49
* To change this template use File | Settings | File Templates.
*/
public class WatchBackupsContainers implements Runnable {
private LxcHostNode lxcHostNode;
private LxcManager lxcManager;
private final static String backuppath = "/usr/share/kevoree/lxc/backup";
private int daysretentions = 30;
public WatchBackupsContainers(LxcHostNode lxcHostNode, LxcManager lxcManager) {
this.lxcHostNode = lxcHostNode;
this.lxcManager = lxcManager;
}
@Override
public void run() {
List<String> lxNodes = lxcManager.getBackupContainers();
Date today = new Date();
Log.debug("WatchBackupsContainers is starting");
for(String node : lxNodes){
File lxcnode = new File(backuppath+File.separatorChar+node);
+ lxcnode.mkdirs();
// days old
long diff = (today.getTime() - lxcnode.lastModified()) / (1000*60*60*24);
if(diff > daysretentions ){
Log.info("WatchBackupsContainers is destroying "+node);
// backup has more than 30 days
FileManager.deleteOldFile(lxcnode);
} else {
Log.debug("WatchBackupsContainers " + node + " is " + diff + " days old");
}
}
}
public int getDaysretentions() {
return daysretentions;
}
public void setDaysretentions(int daysretentions) {
this.daysretentions = daysretentions;
}
}
| true | true | public void run() {
List<String> lxNodes = lxcManager.getBackupContainers();
Date today = new Date();
Log.debug("WatchBackupsContainers is starting");
for(String node : lxNodes){
File lxcnode = new File(backuppath+File.separatorChar+node);
// days old
long diff = (today.getTime() - lxcnode.lastModified()) / (1000*60*60*24);
if(diff > daysretentions ){
Log.info("WatchBackupsContainers is destroying "+node);
// backup has more than 30 days
FileManager.deleteOldFile(lxcnode);
} else {
Log.debug("WatchBackupsContainers " + node + " is " + diff + " days old");
}
}
}
| public void run() {
List<String> lxNodes = lxcManager.getBackupContainers();
Date today = new Date();
Log.debug("WatchBackupsContainers is starting");
for(String node : lxNodes){
File lxcnode = new File(backuppath+File.separatorChar+node);
lxcnode.mkdirs();
// days old
long diff = (today.getTime() - lxcnode.lastModified()) / (1000*60*60*24);
if(diff > daysretentions ){
Log.info("WatchBackupsContainers is destroying "+node);
// backup has more than 30 days
FileManager.deleteOldFile(lxcnode);
} else {
Log.debug("WatchBackupsContainers " + node + " is " + diff + " days old");
}
}
}
|
diff --git a/examples/src/main/java/org/apache/mahout/clustering/display/DisplaySpectralKMeans.java b/examples/src/main/java/org/apache/mahout/clustering/display/DisplaySpectralKMeans.java
index 144fe69a..ed3f88fb 100644
--- a/examples/src/main/java/org/apache/mahout/clustering/display/DisplaySpectralKMeans.java
+++ b/examples/src/main/java/org/apache/mahout/clustering/display/DisplaySpectralKMeans.java
@@ -1,81 +1,81 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.clustering.display;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.FileWriter;
import java.io.PrintWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.mahout.clustering.spectral.kmeans.SpectralKMeansDriver;
import org.apache.mahout.common.HadoopUtil;
import org.apache.mahout.common.RandomUtils;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.common.distance.ManhattanDistanceMeasure;
class DisplaySpectralKMeans extends DisplayClustering {
DisplaySpectralKMeans() {
initialize();
this.setTitle("Spectral k-Means Clusters (>" + (int) (significance * 100) + "% of population)");
}
public static void main(String[] args) throws Exception {
DistanceMeasure measure = new ManhattanDistanceMeasure();
Path samples = new Path("samples");
Path output = new Path("output");
HadoopUtil.overwriteOutput(samples);
HadoopUtil.overwriteOutput(output);
RandomUtils.useTestSeed();
DisplayClustering.generateSamples();
writeSampleData(samples);
Path affinities = new Path(output, "affinities");
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(output.toUri(), conf);
if (!fs.exists(output)) {
fs.mkdirs(output);
}
FileWriter writer = new FileWriter(affinities.toString());
PrintWriter out = new PrintWriter(writer);
try {
for (int i = 0; i < SAMPLE_DATA.size(); i++) {
for (int j = 0; j < SAMPLE_DATA.size(); j++) {
out.println(i + "," + j + ',' + measure.distance(SAMPLE_DATA.get(i).get(), SAMPLE_DATA.get(j).get()));
}
}
} finally {
out.close();
}
int maxIter = 10;
double convergenceDelta = 0.001;
- SpectralKMeansDriver.run(new Configuration(), affinities, output, 1100, 5, measure, convergenceDelta, maxIter);
+ SpectralKMeansDriver.run(new Configuration(), affinities, output, 1100, 2, measure, convergenceDelta, maxIter);
loadClusters(output);
new DisplaySpectralKMeans();
}
// Override the paint() method
@Override
public void paint(Graphics g) {
plotSampleData((Graphics2D) g);
plotClusters((Graphics2D) g);
}
}
| true | true | public static void main(String[] args) throws Exception {
DistanceMeasure measure = new ManhattanDistanceMeasure();
Path samples = new Path("samples");
Path output = new Path("output");
HadoopUtil.overwriteOutput(samples);
HadoopUtil.overwriteOutput(output);
RandomUtils.useTestSeed();
DisplayClustering.generateSamples();
writeSampleData(samples);
Path affinities = new Path(output, "affinities");
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(output.toUri(), conf);
if (!fs.exists(output)) {
fs.mkdirs(output);
}
FileWriter writer = new FileWriter(affinities.toString());
PrintWriter out = new PrintWriter(writer);
try {
for (int i = 0; i < SAMPLE_DATA.size(); i++) {
for (int j = 0; j < SAMPLE_DATA.size(); j++) {
out.println(i + "," + j + ',' + measure.distance(SAMPLE_DATA.get(i).get(), SAMPLE_DATA.get(j).get()));
}
}
} finally {
out.close();
}
int maxIter = 10;
double convergenceDelta = 0.001;
SpectralKMeansDriver.run(new Configuration(), affinities, output, 1100, 5, measure, convergenceDelta, maxIter);
loadClusters(output);
new DisplaySpectralKMeans();
}
| public static void main(String[] args) throws Exception {
DistanceMeasure measure = new ManhattanDistanceMeasure();
Path samples = new Path("samples");
Path output = new Path("output");
HadoopUtil.overwriteOutput(samples);
HadoopUtil.overwriteOutput(output);
RandomUtils.useTestSeed();
DisplayClustering.generateSamples();
writeSampleData(samples);
Path affinities = new Path(output, "affinities");
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(output.toUri(), conf);
if (!fs.exists(output)) {
fs.mkdirs(output);
}
FileWriter writer = new FileWriter(affinities.toString());
PrintWriter out = new PrintWriter(writer);
try {
for (int i = 0; i < SAMPLE_DATA.size(); i++) {
for (int j = 0; j < SAMPLE_DATA.size(); j++) {
out.println(i + "," + j + ',' + measure.distance(SAMPLE_DATA.get(i).get(), SAMPLE_DATA.get(j).get()));
}
}
} finally {
out.close();
}
int maxIter = 10;
double convergenceDelta = 0.001;
SpectralKMeansDriver.run(new Configuration(), affinities, output, 1100, 2, measure, convergenceDelta, maxIter);
loadClusters(output);
new DisplaySpectralKMeans();
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/SomaticIndelDetectorWalker.java b/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/SomaticIndelDetectorWalker.java
index 7e8985e03..b2d30235a 100644
--- a/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/SomaticIndelDetectorWalker.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/SomaticIndelDetectorWalker.java
@@ -1,2095 +1,2096 @@
/*
* Copyright (c) 2010 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.walkers.indels;
import net.sf.samtools.*;
import org.broadinstitute.sting.commandline.Argument;
import org.broadinstitute.sting.commandline.Hidden;
import org.broadinstitute.sting.commandline.Output;
import org.broadinstitute.sting.commandline.Tags;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.datasources.reads.SAMReaderID;
import org.broadinstitute.sting.gatk.datasources.reference.ReferenceDataSource;
import org.broadinstitute.sting.gatk.filters.MappingQualityZeroReadFilter;
import org.broadinstitute.sting.gatk.filters.Platform454Filter;
import org.broadinstitute.sting.gatk.filters.PlatformUnitFilter;
import org.broadinstitute.sting.gatk.filters.PlatformUnitFilterHelper;
import org.broadinstitute.sting.gatk.refdata.ReadMetaDataTracker;
import org.broadinstitute.sting.gatk.refdata.SeekableRODIterator;
import org.broadinstitute.sting.gatk.refdata.features.refseq.Transcript;
import org.broadinstitute.sting.gatk.refdata.features.refseq.RefSeqCodec;
import org.broadinstitute.sting.gatk.refdata.features.refseq.RefSeqFeature;
import org.broadinstitute.sting.gatk.refdata.tracks.RMDTrack;
import org.broadinstitute.sting.gatk.refdata.tracks.RMDTrackBuilder;
import org.broadinstitute.sting.gatk.refdata.utils.LocationAwareSeekableRODIterator;
import org.broadinstitute.sting.gatk.refdata.utils.RODRecordList;
import org.broadinstitute.sting.gatk.walkers.ReadFilters;
import org.broadinstitute.sting.gatk.walkers.ReadWalker;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocSortedSet;
import org.broadinstitute.sting.utils.SampleUtils;
import org.broadinstitute.sting.utils.codecs.vcf.*;
import org.broadinstitute.sting.utils.collections.CircularArray;
import org.broadinstitute.sting.utils.collections.PrimitivePair;
import org.broadinstitute.sting.utils.exceptions.StingException;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.interval.IntervalFileMergingIterator;
import org.broadinstitute.sting.utils.interval.IntervalMergingRule;
import org.broadinstitute.sting.utils.interval.IntervalUtils;
import org.broadinstitute.sting.utils.interval.OverlappingIntervalIterator;
import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import org.broadinstitute.sting.utils.variantcontext.Allele;
import org.broadinstitute.sting.utils.variantcontext.Genotype;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;
import java.io.*;
import java.util.*;
/**
* This is a simple, counts-and-cutoffs based tool for calling indels from aligned (preferrably MSA cleaned) sequencing
* data. Two output formats supported are: BED format (minimal output, required), and extended output that includes read
* and mismtach statistics around the calls (tuned on with --verbose). The calls can be performed from a single/pooled sample,
* or from a matched pair of samples (with --somatic option). In the latter case, two input bam files must be specified,
* the order is important: indels are called from the second sample ("Tumor") and additionally annotated as germline
* if even a weak evidence for the same indel, not necessarily a confident call, exists in the first sample ("Normal"), or as somatic
* if first bam has coverage at the site but no indication for an indel. In the --somatic mode, BED output contains
* only somatic calls, while --verbose output contains all calls annotated with GERMLINE/SOMATIC keywords.
*/
@ReadFilters({Platform454Filter.class, MappingQualityZeroReadFilter.class, PlatformUnitFilter.class})
public class SomaticIndelDetectorWalker extends ReadWalker<Integer,Integer> {
// @Output
// PrintStream out;
@Output(doc="File to which variants should be written",required=true)
protected VCFWriter vcf_writer = null;
@Argument(fullName="outputFile", shortName="O", doc="output file name (BED format). DEPRECATED> Use --bed", required=true)
@Deprecated
java.io.File output_file;
@Argument(fullName = "metrics_file", shortName = "metrics", doc = "File to print callability metrics output", required = false)
public PrintStream metricsWriter = null;
// @Argument(fullName="vcf_format", shortName="vcf", doc="generate output file in VCF format", required=false)
// boolean FORMAT_VCF = false;
@Hidden
@Argument(fullName = "genotype_intervals", shortName = "genotype",
doc = "Calls will be made at each position within the specified interval(s), whether there is an indel or it's the ref", required = false)
public String genotypeIntervalsFile = null;
@Hidden
@Argument(fullName="genotypeIntervalsAreNotSorted", shortName="giNotSorted", required=false,
doc="This tool assumes that the genotyping interval list (--genotype_intervals) is sorted; "+
"if the list turns out to be unsorted, it will throw an exception. "+
"Use this argument when your interval list is not sorted to instruct the IndelGenotyper "+
"to sort and keep it in memory (increases memory usage!).")
protected boolean GENOTYPE_NOT_SORTED = false;
@Hidden
@Argument(fullName="unpaired", shortName="unpaired",
doc="Perform unpaired calls (no somatic status detection)", required=false)
boolean call_unpaired = false;
boolean call_somatic ;
@Argument(fullName="verboseOutput", shortName="verbose",
doc="Verbose output file in text format", required=false)
java.io.File verboseOutput = null;
@Argument(fullName="bedOutput", shortName="bed",
doc="Lightweight bed output file (only positions and events, no stats/annotations)", required=false)
java.io.File bedOutput = null;
@Argument(fullName="minCoverage", shortName="minCoverage",
doc="indel calls will be made only at sites with coverage of minCoverage or more reads; with --somatic this value is applied to tumor sample", required=false)
int minCoverage = 6;
@Argument(fullName="minNormalCoverage", shortName="minNormalCoverage",
doc="used only with --somatic; normal sample must have at least minNormalCoverage or more reads at the site to call germline/somatic indel, otherwise the indel (in tumor) is ignored", required=false)
int minNormalCoverage = 4;
@Argument(fullName="minFraction", shortName="minFraction",
doc="Minimum fraction of reads with CONSENSUS indel at a site, out of all reads covering the site, required for making a call"+
" (fraction of non-consensus indels at the site is not considered here, see minConsensusFraction)", required=false)
double minFraction = 0.3;
@Argument(fullName="minConsensusFraction", shortName="minConsensusFraction",
doc="Indel call is made only if fraction of CONSENSUS indel observations at a site wrt all indel observations at the site exceeds this threshold", required=false)
double minConsensusFraction = 0.7;
@Argument(fullName="minIndelCount", shortName="minCnt",
doc="Minimum count of reads supporting consensus indel required for making the call. "+
" This filter supercedes minFraction, i.e. indels with acceptable minFraction at low coverage "+
"(minIndelCount not met) will not pass.", required=false)
int minIndelCount = 0;
@Argument(fullName="refseq", shortName="refseq",
doc="Name of RefSeq transcript annotation file. If specified, indels will be annotated with GENOMIC/UTR/INTRON/CODING and with the gene name", required=false)
String RefseqFileName = null;
@Argument(fullName="blacklistedLanes", shortName="BL",
doc="Name of lanes (platform units) that should be ignored. Reads coming from these lanes will never be seen "+
"by this application, so they will not contribute indels to consider and will not be counted.", required=false)
PlatformUnitFilterHelper dummy;
@Argument(fullName="indel_debug", shortName="idebug", doc="Detailed printout for debugging, do not turn this on",required=false) Boolean DEBUG = false;
@Argument(fullName="window_size", shortName="ws", doc="Size (bp) of the sliding window used for accumulating the coverage. "+
"May need to be increased to accomodate longer reads or longer deletions.",required=false) int WINDOW_SIZE = 200;
@Argument(fullName="maxNumberOfReads",shortName="mnr",doc="Maximum number of reads to cache in the window; if number of reads exceeds this number,"+
" the window will be skipped and no calls will be made from it",required=false) int MAX_READ_NUMBER = 10000;
private WindowContext tumor_context;
private WindowContext normal_context;
private int currentContigIndex = -1;
private int contigLength = -1; // we see to much messy data with reads hanging out of contig ends...
private int currentPosition = -1; // position of the last read we've seen on the current contig
private String refName = null;
private java.io.Writer output = null;
private GenomeLoc location = null;
private long normalCallsMade = 0L, tumorCallsMade = 0L;
boolean outOfContigUserWarned = false;
private LocationAwareSeekableRODIterator refseqIterator=null;
// private Set<String> normalReadGroups; // we are going to remember which read groups are normals and which are tumors in order to be able
// private Set<String> tumorReadGroups ; // to properly assign the reads coming from a merged stream
private Set<String> normalSamples; // we are going to remember which samples are normal and which are tumor:
private Set<String> tumorSamples ; // these are used only to generate genotypes for vcf output
private int NQS_WIDTH = 5; // 5 bases on each side of the indel for NQS-style statistics
private Writer bedWriter = null;
private Writer verboseWriter = null;
private static String annGenomic = "GENOMIC";
private static String annIntron = "INTRON";
private static String annUTR = "UTR";
private static String annCoding = "CODING";
private static String annUnknown = "UNKNOWN";
enum CallType {
NOCOVERAGE,
BADCOVERAGE,
NOEVIDENCE,
GERMLINE,
SOMATIC
};
private SAMRecord lastRead;
private byte[] refBases;
private ReferenceDataSource refData;
private Iterator<GenomeLoc> genotypeIntervalIterator = null;
// the current interval in the list of intervals, for which we want to do full genotyping
private GenomeLoc currentGenotypeInterval = null;
private long lastGenotypedPosition = -1; // last position on the currentGenotypeInterval, for which a call was already printed;
// can be 1 base before lastGenotyped start
// "/humgen/gsa-scr1/GATK_Data/refGene.sorted.txt"
private Set<VCFHeaderLine> getVCFHeaderInfo() {
Set<VCFHeaderLine> headerInfo = new HashSet<VCFHeaderLine>();
// first, the basic info
headerInfo.add(new VCFHeaderLine("source", "IndelGenotyperV2"));
headerInfo.add(new VCFHeaderLine("reference", getToolkit().getArguments().referenceFile.getName()));
// FORMAT and INFO fields
// headerInfo.addAll(VCFUtils.getSupportedHeaderStrings());
headerInfo.addAll(VCFIndelAttributes.getAttributeHeaderLines());
if ( call_somatic ) {
headerInfo.add(new VCFInfoHeaderLine(VCFConstants.SOMATIC_KEY, 0, VCFHeaderLineType.Flag, "Somatic event"));
} else {
}
// all of the arguments from the argument collection
Set<Object> args = new HashSet<Object>();
args.add(this);
args.addAll(getToolkit().getFilters());
Map<String,String> commandLineArgs = getToolkit().getApproximateCommandLineArguments(args);
for ( Map.Entry<String, String> commandLineArg : commandLineArgs.entrySet() )
headerInfo.add(new VCFHeaderLine(String.format("IGv2_%s", commandLineArg.getKey()), commandLineArg.getValue()));
// also, the list of input bams
for ( String fileName : getToolkit().getArguments().samFiles )
headerInfo.add(new VCFHeaderLine("IGv2_bam_file_used", fileName));
return headerInfo;
}
@Override
public void initialize() {
call_somatic = (call_unpaired ? false : true);
normal_context = new WindowContext(0,WINDOW_SIZE);
normalSamples = new HashSet<String>();
if ( bedOutput != null && output_file != null ) {
throw new UserException.DeprecatedArgument("-O", "-O option is deprecated and -bed option replaces it; you can not use both at the same time");
}
if ( RefseqFileName != null ) {
logger.info("Using RefSeq annotations from "+RefseqFileName);
RMDTrackBuilder builder = new RMDTrackBuilder(getToolkit().getReferenceDataSource().getReference().getSequenceDictionary(),
getToolkit().getGenomeLocParser(),
getToolkit().getArguments().unsafe);
RMDTrack refseq = builder.createInstanceOfTrack(RefSeqCodec.class,new File(RefseqFileName));
refseqIterator = new SeekableRODIterator(refseq.getHeader(),
refseq.getSequenceDictionary(),
getToolkit().getReferenceDataSource().getReference().getSequenceDictionary(),
getToolkit().getGenomeLocParser(),
refseq.getIterator());
}
if ( refseqIterator == null ) logger.info("No gene annotations available");
int nSams = getToolkit().getArguments().samFiles.size();
if ( call_somatic ) {
if ( nSams < 2 ) throw new UserException.BadInput("In default (paired sample) mode at least two bam files (normal and tumor) must be specified");
tumor_context = new WindowContext(0,WINDOW_SIZE);
tumorSamples = new HashSet<String>();
}
int nNorm = 0;
int nTum = 0;
for ( SAMReaderID rid : getToolkit().getReadsDataSource().getReaderIDs() ) {
Tags tags = rid.getTags() ;
if ( tags.getPositionalTags().isEmpty() && call_somatic )
throw new UserException.BadInput("In default (paired sample) mode all input bam files must be tagged as either 'normal' or 'tumor'. Untagged file: "+
getToolkit().getSourceFileForReaderID(rid));
boolean normal = false;
boolean tumor = false;
for ( String s : tags.getPositionalTags() ) { // we allow additional unrelated tags (and we do not use them), but we REQUIRE one of Tumor/Normal to be present if --somatic is on
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal = true;
nNorm++;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor = true;
nTum++ ;
}
}
if ( call_somatic && normal && tumor ) throw new UserException.BadInput("Input bam file "+
getToolkit().getSourceFileForReaderID(rid)+" is tagged both as normal and as tumor. Which one is it??");
if ( call_somatic && !normal && ! tumor )
throw new UserException.BadInput("In somatic mode all input bams must be tagged as either normal or tumor. Encountered untagged file: "+
getToolkit().getSourceFileForReaderID(rid));
if ( ! call_somatic && (normal || tumor) )
System.out.println("WARNING: input bam file "+getToolkit().getSourceFileForReaderID(rid)
+" is tagged as Normal and/or Tumor, but somatic mode is not on. Tags will ne IGNORED");
if ( call_somatic && tumor ) {
for ( SAMReadGroupRecord rg : getToolkit().getSAMFileHeader(rid).getReadGroups() ) {
tumorSamples.add(rg.getSample());
}
} else {
for ( SAMReadGroupRecord rg : getToolkit().getSAMFileHeader(rid).getReadGroups() ) {
normalSamples.add(rg.getSample());
}
}
if ( genotypeIntervalsFile != null ) {
if ( ! GENOTYPE_NOT_SORTED && IntervalUtils.isIntervalFile(genotypeIntervalsFile)) {
// prepare to read intervals one-by-one, as needed (assuming they are sorted).
genotypeIntervalIterator = new IntervalFileMergingIterator(getToolkit().getGenomeLocParser(),
new java.io.File(genotypeIntervalsFile), IntervalMergingRule.OVERLAPPING_ONLY );
} else {
// read in the whole list of intervals for cleaning
GenomeLocSortedSet locs = IntervalUtils.sortAndMergeIntervals(getToolkit().getGenomeLocParser(),
IntervalUtils.parseIntervalArguments(getToolkit().getGenomeLocParser(),Arrays.asList(genotypeIntervalsFile),true), IntervalMergingRule.OVERLAPPING_ONLY);
genotypeIntervalIterator = locs.iterator();
}
// wrap intervals requested for genotyping inside overlapping iterator, so that we actually
// genotype only on the intersections of the requested intervals with the -L intervals
genotypeIntervalIterator = new OverlappingIntervalIterator(genotypeIntervalIterator, getToolkit().getIntervals().iterator() );
currentGenotypeInterval = genotypeIntervalIterator.hasNext() ? genotypeIntervalIterator.next() : null;
if ( DEBUG) System.out.println("DEBUG>> first genotyping interval="+currentGenotypeInterval);
if ( currentGenotypeInterval != null ) lastGenotypedPosition = currentGenotypeInterval.getStart()-1;
}
}
location = getToolkit().getGenomeLocParser().createGenomeLoc(getToolkit().getSAMFileHeader().getSequence(0).getSequenceName(),1);
normalSamples = getToolkit().getSamplesByReaders().get(0);
try {
// we already checked that bedOutput and output_file are not set simultaneously
if ( bedOutput != null ) bedWriter = new FileWriter(bedOutput);
if ( output_file != null ) bedWriter = new FileWriter(output_file);
} catch (java.io.IOException e) {
throw new UserException.CouldNotReadInputFile(bedOutput, "Failed to open BED file for writing.", e);
}
try {
if ( verboseOutput != null ) verboseWriter = new FileWriter(verboseOutput);
} catch (java.io.IOException e) {
throw new UserException.CouldNotReadInputFile(verboseOutput, "Failed to open BED file for writing.", e);
}
vcf_writer.writeHeader(new VCFHeader(getVCFHeaderInfo(), SampleUtils.getSAMFileSamples(getToolkit().getSAMFileHeader()))) ;
refData = new ReferenceDataSource(getToolkit().getArguments().referenceFile);
}
@Override
public Integer map(ReferenceContext ref, SAMRecord read, ReadMetaDataTracker metaDataTracker) {
// if ( read.getReadName().equals("428EFAAXX090610:2:36:1384:639#0") ) System.out.println("GOT READ");
if ( DEBUG ) {
// System.out.println("DEBUG>> read at "+ read.getAlignmentStart()+"-"+read.getAlignmentEnd()+
// "("+read.getCigarString()+")");
if ( read.getDuplicateReadFlag() ) System.out.println("DEBUG>> Duplicated read (IGNORED)");
}
if ( AlignmentUtils.isReadUnmapped(read) ||
read.getDuplicateReadFlag() ||
read.getNotPrimaryAlignmentFlag() ||
read.getMappingQuality() == 0 ) {
return 0; // we do not need those reads!
}
if ( read.getReferenceIndex() != currentContigIndex ) {
// we just jumped onto a new contig
if ( DEBUG ) System.out.println("DEBUG>>> Moved to contig "+read.getReferenceName());
if ( read.getReferenceIndex() < currentContigIndex ) // paranoidal
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": contig is out of order; input BAM file is unsorted");
// print remaining indels from the previous contig (if any);
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true);
currentContigIndex = read.getReferenceIndex();
currentPosition = read.getAlignmentStart();
refName = new String(read.getReferenceName());
location = getToolkit().getGenomeLocParser().createGenomeLoc(refName,location.getStart(),location.getStop());
contigLength = getToolkit().getGenomeLocParser().getContigInfo(refName).getSequenceLength();
outOfContigUserWarned = false;
lastGenotypedPosition = -1;
normal_context.clear(); // reset coverage window; this will also set reference position to 0
if ( call_somatic) tumor_context.clear();
refBases = new String(refData.getReference().getSequence(read.getReferenceName()).getBases()).toUpperCase().getBytes();
}
// we have reset the window to the new contig if it was required and emitted everything we collected
// on a previous contig. At this point we are guaranteed that we are set up properly for working
// with the contig of the current read.
// NOTE: all the sanity checks and error messages below use normal_context only. We make sure that normal_context and
// tumor_context are synchronized exactly (windows are always shifted together by emit_somatic), so it's safe
if ( read.getAlignmentStart() < currentPosition ) // oops, read out of order?
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName() +" out of order on the contig\n"+
"Read starts at "+refName+":"+read.getAlignmentStart()+"; last read seen started at "+refName+":"+currentPosition
+"\nLast read was: "+lastRead.getReadName()+" RG="+lastRead.getAttribute("RG")+" at "+lastRead.getAlignmentStart()+"-"
+lastRead.getAlignmentEnd()+" cigar="+lastRead.getCigarString());
currentPosition = read.getAlignmentStart();
lastRead = read;
if ( read.getAlignmentEnd() > contigLength ) {
if ( ! outOfContigUserWarned ) {
System.out.println("WARNING: Reads aligned past contig length on "+ location.getContig()+"; all such reads will be skipped");
outOfContigUserWarned = true;
}
return 0;
}
long alignmentEnd = read.getAlignmentEnd();
Cigar c = read.getCigar();
int lastNonClippedElement = 0; // reverse offset to the last unclipped element
CigarOperator op = null;
// moving backwards from the end of the cigar, skip trailing S or H cigar elements:
do {
lastNonClippedElement++;
op = c.getCigarElement( c.numCigarElements()-lastNonClippedElement ).getOperator();
} while ( op == CigarOperator.H || op == CigarOperator.S );
// now op is the last non-S/H operator in the cigar.
// a little trick here: we want to make sure that current read completely fits into the current
// window so that we can accumulate indel observations over the whole length of the read.
// The ::getAlignmentEnd() method returns the last position on the reference where bases from the
// read actually match (M cigar elements). After our cleaning procedure, we can have reads that end
// with I element, which is not gonna be counted into alignment length on the reference. On the other hand,
// in this program we assign insertions, internally, to the first base *after* the insertion position.
// Hence, we have to make sure that that extra base is already in the window or we will get IndexOutOfBounds.
if ( op == CigarOperator.I) alignmentEnd++;
if ( alignmentEnd > normal_context.getStop()) {
// we don't emit anything until we reach a read that does not fit into the current window.
// At that point we try shifting the window to the start of that read (or reasonably close) and emit everything prior to
// that position. This is legitimate, since the reads are sorted and we are not gonna see any more coverage at positions
// below the current read's start.
// Clearly, we assume here that window is large enough to accomodate any single read, so simply shifting
// the window to around the read's start will ensure that the read fits...
if ( DEBUG) System.out.println("DEBUG>> Window at "+normal_context.getStart()+"-"+normal_context.getStop()+", read at "+
read.getAlignmentStart()+": trying to emit and shift" );
if ( call_somatic ) emit_somatic( read.getAlignmentStart(), false );
else emit( read.getAlignmentStart(), false );
// let's double check now that the read fits after the shift
if ( read.getAlignmentEnd() > normal_context.getStop()) {
// ooops, looks like the read does not fit into the window even after the latter was shifted!!
// we used to die over such reads and require user to run with larger window size. Now we
// just print a warning and discard the read (this means that our counts can be slightly off in
// th epresence of such reads)
//throw new UserException.BadArgumentValue("window_size", "Read "+read.getReadName()+": out of coverage window bounds. Probably window is too small, so increase the value of the window_size argument.\n"+
// "Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
// read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
// "; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
System.out.println("WARNING: Read "+read.getReadName()+
" is out of coverage window bounds. Probably window is too small and the window_size value must be increased.\n"+
" The read is ignored in this run (so all the counts/statistics reported will not include it).\n"+
" Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
"; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
+ return 1;
}
}
if ( call_somatic ) {
Tags tags = getToolkit().getReaderIDForRead(read).getTags();
boolean assigned = false;
for ( String s : tags.getPositionalTags() ) {
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal_context.add(read,ref.getBases());
assigned = true;
break;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor_context.add(read,ref.getBases());
assigned = true;
break;
}
}
if ( ! assigned )
throw new StingException("Read "+read.getReadName()+" from "+getToolkit().getSourceFileForReaderID(getToolkit().getReaderIDForRead(read))+
"has no Normal/Tumor tag associated with it");
// String rg = (String)read.getAttribute("RG");
// if ( rg == null )
// throw new UserException.MalformedBam(read, "Read "+read.getReadName()+" has no read group in merged stream. RG is required for somatic calls.");
// if ( normalReadGroups.contains(rg) ) {
// normal_context.add(read,ref.getBases());
// } else if ( tumorReadGroups.contains(rg) ) {
// tumor_context.add(read,ref.getBases());
// } else {
// throw new UserException.MalformedBam(read, "Unrecognized read group in merged stream: "+rg);
// }
if ( tumor_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+tumor_context.getStart()+'-'+tumor_context.getStop()+" in tumor sample. The whole window will be dropped.");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+" in normal sample. The whole window will be dropped");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
} else {
normal_context.add(read, ref.getBases());
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+". The whole window will be dropped");
normal_context.shift(WINDOW_SIZE);
}
}
return 1;
}
/** An auxiliary shortcut: returns true if position(location.getContig(), p) is past l */
private boolean pastInterval(long p, GenomeLoc l) {
return ( location.getContigIndex() > l.getContigIndex() ||
location.getContigIndex() == l.getContigIndex() && p > l.getStop() );
}
/** Emit calls of the specified type across genotyping intervals, from position lastGenotypedPosition+1 to
* pos-1, inclusive.
* @param contigIndex
* @param pos
* @param call
*/
/*
private void emitNoCallsUpTo(int contigIndex, long pos, CallType call) {
if ( contigIndex < currentGenotypeInterval.getContigIndex() ||
contigIndex == currentGenotypeInterval.getContigIndex() && pos <= currentGenotypeInterval.getStart() ) return;
if ( contigIndex == currentGenotypeInterval.getContigIndex() && pos >= currentGenotypeInterval.getStart() ) {
for ( long p = lastGenotypedPosition+1; p < pos; p++ ) {
}
}
while( currentGenotypeInterval != null ) {
while ( )
if ( genotypeIntervalIterator.hasNext() ) {
currentGenotypeInterval = genotypeIntervalIterator.next() ;
if ( pastInterval(p,currentGenotypeInterval) ) {
// if we are about to jump over the whole next interval, we need to emit NO_COVERAGE calls there!
emitNoCoverageCalls(currentGenotypeInterval);
}
} else {
currentGenotypeInterval = null;
}
}
}
*/
/** Output indel calls up to the specified position and shift the window: after this method is executed, the
* first element of the window maps onto 'position', if possible, or at worst a few bases to the left of 'position' if we may need more
* reads to get full NQS-style statistics for an indel in the close proximity of 'position'.
*
* @param position
*/
private void emit(long position, boolean force) {
long adjustedPosition = adjustPosition(position);
if ( adjustedPosition == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(position-normal_context.getStart()));
return;
}
long move_to = adjustedPosition;
for ( int pos = normal_context.getStart() ; pos < Math.min(adjustedPosition,normal_context.getStop()+1) ; pos++ ) {
boolean genotype = false;
// first let's see if we need to genotype current position:
final long p = pos - 1; // our internally used positions (pos) are +1 compared to external format spec (e.g. vcf)
if ( pos <= lastGenotypedPosition ) continue;
while ( currentGenotypeInterval != null ) {
// if we did not even reach next interval yet, no genotyping at current position:
if ( location.getContigIndex() < currentGenotypeInterval.getContigIndex() ||
location.getContigIndex() == currentGenotypeInterval.getContigIndex() &&
p < currentGenotypeInterval.getStart() ) break;
if ( pastInterval(p, currentGenotypeInterval) ) {
// we are past current genotyping interval, so we are done with it; let's load next interval:
currentGenotypeInterval = genotypeIntervalIterator.hasNext() ? genotypeIntervalIterator.next() : null;
continue; // re-enter the loop to check against the interval we just loaded
}
// we reach this point only if p is inside current genotyping interval; set the flag and bail out:
genotype = true;
break;
}
// if ( DEBUG ) System.out.println("DEBUG>> pos="+pos +"; genotyping interval="+currentGenotypeInterval+"; genotype="+genotype);
if ( normal_context.indelsAt(pos).size() == 0 && ! genotype ) continue;
IndelPrecall normalCall = new IndelPrecall(normal_context,pos,NQS_WIDTH);
if ( normalCall.getCoverage() < minCoverage && ! genotype ) {
if ( DEBUG ) {
System.out.println("DEBUG>> Indel at "+pos+"; coverare in normal="+normalCall.getCoverage()+" (SKIPPED)");
}
continue; // low coverage
}
if ( DEBUG ) System.out.println("DEBUG>> "+(normalCall.getAllVariantCount() == 0?"No Indel":"Indel")+" at "+pos);
long left = Math.max( pos-NQS_WIDTH, normal_context.getStart() );
long right = pos+( normalCall.getVariant() == null ? 0 : normalCall.getVariant().lengthOnRef())+NQS_WIDTH-1;
if ( right >= adjustedPosition && ! force) {
// we are not asked to force-shift, and there is more coverage around the current indel that we still need to collect
// we are not asked to force-shift, and there's still additional coverage to the right of current indel, so its too early to emit it;
// instead we shift only up to current indel pos - MISMATCH_WIDTH, so that we could keep collecting that coverage
move_to = adjustPosition(left);
if ( move_to == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(adjustedPosition-normal_context.getStart()));
return;
}
if ( DEBUG ) System.out.println("DEBUG>> waiting for coverage; actual shift performed to "+ move_to);
break;
}
// if indel is too close to the end of the window but we need to emit anyway (force-shift), adjust right:
if ( right > normal_context.getStop() ) right = normal_context.getStop();
// location = getToolkit().getGenomeLocParser().setStart(location,pos);
// location = getToolkit().getGenomeLocParser().setStop(location,pos); // retrieve annotation data
location = getToolkit().getGenomeLocParser().createGenomeLoc(location.getContig(), pos);
boolean haveCall = normalCall.isCall(); // cache the value
if ( haveCall || genotype) {
if ( haveCall ) normalCallsMade++;
printVCFLine(vcf_writer,normalCall);
if ( bedWriter != null ) normalCall.printBedLine(bedWriter);
if ( verboseWriter != null ) printVerboseLine(verboseWriter, normalCall);
lastGenotypedPosition = pos;
}
normal_context.indelsAt(pos).clear();
// we dealt with this indel; don't want to see it again
// (we might otherwise in the case when 1) there is another indel that follows
// within MISMATCH_WIDTH bases and 2) we'd need to wait for more coverage for that next indel)
// for ( IndelVariant var : variants ) {
// System.out.print("\t"+var.getType()+"\t"+var.getBases()+"\t"+var.getCount());
// }
}
if ( DEBUG ) System.out.println("DEBUG>> Actual shift to " + move_to + " ("+adjustedPosition+")");
normal_context.shift((int)(move_to - normal_context.getStart() ) );
}
/** A shortcut. Returns true if we got indels within the specified interval in single and only window context
* (for single-sample calls) or in either of the two window contexts (for two-sample/somatic calls)
*
*/
private boolean indelsPresentInInterval(long start, long stop) {
if ( tumor_context == null ) return normal_context.hasIndelsInInterval(start,stop);
return tumor_context.hasIndelsInInterval(start,stop) ||
normal_context.hasIndelsInInterval(start,stop);
}
/** Takes the position, to which window shift is requested, and tries to adjust it in such a way that no NQS window is broken.
* Namely, this method checks, iteratively, if there is an indel within NQS_WIDTH bases ahead of initially requested or adjusted
* shift position. If there is such an indel,
* then shifting to that position would lose some or all NQS-window bases to the left of the indel (since it's not going to be emitted
* just yet). Instead, this method tries to readjust the shift position leftwards so that full NQS window to the left of the next indel
* is preserved. This method tries thie strategy 4 times (so that it would never walk away too far to the left), and if it fails to find
* an appropriate adjusted shift position (which could happen if there are many indels following each other at short intervals), it will give up,
* go back to the original requested shift position and try finding the first shift poisition that has no indel associated with it.
*/
private long adjustPosition(long request) {
long initial_request = request;
int attempts = 0;
boolean failure = false;
while ( indelsPresentInInterval(request,request+NQS_WIDTH) ) {
request -= NQS_WIDTH;
if ( DEBUG ) System.out.println("DEBUG>> indel observations present within "+NQS_WIDTH+" bases ahead. Resetting shift to "+request);
attempts++;
if ( attempts == 4 ) {
if ( DEBUG ) System.out.println("DEBUG>> attempts to preserve full NQS window failed; now trying to find any suitable position.") ;
failure = true;
break;
}
}
if ( failure ) {
// we tried 4 times but did not find a good shift position that would preserve full nqs window
// around all indels. let's fall back and find any shift position as long and there's no indel at the very
// first position after the shift (this is bad for other reasons); if it breaks a nqs window, so be it
request = initial_request;
attempts = 0;
while ( indelsPresentInInterval(request,request+1) ) {
request--;
if ( DEBUG ) System.out.println("DEBUG>> indel observations present within "+NQS_WIDTH+" bases ahead. Resetting shift to "+request);
attempts++;
if ( attempts == 50 ) {
System.out.println("WARNING: Indel at every position in the interval "+refName+":"+request+"-"+initial_request+
". Can not find a break to shift context window to; no calls will be attempted in the current window.");
return -1;
}
}
}
if ( DEBUG ) System.out.println("DEBUG>> Found acceptable target position "+request);
return request;
}
/** Output somatic indel calls up to the specified position and shift the coverage array(s): after this method is executed
* first elements of the coverage arrays map onto 'position', or a few bases prior to the specified position
* if there is an indel in close proximity to 'position' so that we may get more coverage around it later.
*
* @param position
*/
private void emit_somatic(long position, boolean force) {
long adjustedPosition = adjustPosition(position);
if ( adjustedPosition == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(position-normal_context.getStart()));
tumor_context.shift((int)(position-tumor_context.getStart()));
return;
}
long move_to = adjustedPosition;
if ( DEBUG ) System.out.println("DEBUG>> Emitting in somatic mode up to "+position+" force shift="+force+" current window="+tumor_context.getStart()+"-"+tumor_context.getStop());
for ( int pos = tumor_context.getStart() ; pos < Math.min(adjustedPosition,tumor_context.getStop()+1) ; pos++ ) {
boolean genotype = false;
// first let's see if we need to genotype current position:
final long p = pos - 1; // our internally used positions (pos) are +1 compared to external format spec (e.g. vcf)
if ( pos <= lastGenotypedPosition ) continue;
while ( currentGenotypeInterval != null ) {
// if we did not even reach next interval yet, no genotyping at current position:
if ( location.getContigIndex() < currentGenotypeInterval.getContigIndex() ||
location.getContigIndex() == currentGenotypeInterval.getContigIndex() &&
p < currentGenotypeInterval.getStart() ) break;
if ( pastInterval(p, currentGenotypeInterval) ) {
// we are past current genotyping interval, so we are done with it; let's load next interval:
currentGenotypeInterval = genotypeIntervalIterator.hasNext() ? genotypeIntervalIterator.next() : null;
continue; // re-enter the loop to check against the interval we just loaded
}
// we reach tjis point only if p is inside current genotyping interval; set the flag and bail out:
genotype = true;
break;
}
// if ( DEBUG) System.out.println("DEBUG>> pos="+pos +"; genotyping interval="+currentGenotypeInterval+"; genotype="+genotype);
if ( tumor_context.indelsAt(pos).size() == 0 && ! genotype ) continue; // no indels in tumor
if ( DEBUG && genotype ) System.out.println("DEBUG>> Genotyping requested at "+pos);
IndelPrecall tumorCall = new IndelPrecall(tumor_context,pos,NQS_WIDTH);
IndelPrecall normalCall = new IndelPrecall(normal_context,pos,NQS_WIDTH);
if ( tumorCall.getCoverage() < minCoverage && ! genotype ) {
if ( DEBUG ) {
System.out.println("DEBUG>> Indel in tumor at "+pos+"; coverare in tumor="+tumorCall.getCoverage()+" (SKIPPED)");
}
continue; // low coverage
}
if ( normalCall.getCoverage() < minNormalCoverage && ! genotype ) {
if ( DEBUG ) {
System.out.println("DEBUG>> Indel in tumor at "+pos+"; coverare in normal="+normalCall.getCoverage()+" (SKIPPED)");
}
continue; // low coverage
}
if ( DEBUG ) {
System.out.print("DEBUG>> "+(tumorCall.getAllVariantCount() == 0?"No Indel":"Indel")+" in tumor, ");
System.out.print("DEBUG>> "+(normalCall.getAllVariantCount() == 0?"No Indel":"Indel")+" in normal at "+pos);
}
long left = Math.max( pos-NQS_WIDTH, tumor_context.getStart() );
long right = pos+ ( tumorCall.getVariant() == null ? 0 : tumorCall.getVariant().lengthOnRef() )+NQS_WIDTH-1;
if ( right >= adjustedPosition && ! force) {
// we are not asked to force-shift, and there is more coverage around the current indel that we still need to collect
// we are not asked to force-shift, and there's still additional coverage to the right of current indel, so its too early to emit it;
// instead we shift only up to current indel pos - MISMATCH_WIDTH, so that we could keep collecting that coverage
move_to = adjustPosition(left);
if ( move_to == -1 ) {
// failed to find appropriate shift position, the data are probably to messy anyway so we drop them altogether
normal_context.shift((int)(adjustedPosition-normal_context.getStart()));
tumor_context.shift((int)(adjustedPosition-tumor_context.getStart()));
return;
}
if ( DEBUG ) System.out.println("DEBUG>> waiting for coverage; actual shift performed to "+ move_to);
break;
}
if ( right > tumor_context.getStop() ) right = tumor_context.getStop(); // if indel is too close to the end of the window but we need to emit anyway (force-shift), adjust right
// location = getToolkit().getGenomeLocParser().setStart(location,pos);
// location = getToolkit().getGenomeLocParser().setStop(location,pos); // retrieve annotation data
location = getToolkit().getGenomeLocParser().createGenomeLoc(location.getContig(),pos); // retrieve annotation data
boolean haveCall = tumorCall.isCall(); // cache the value
if ( haveCall || genotype ) {
if ( haveCall ) tumorCallsMade++;
printVCFLine(vcf_writer,normalCall,tumorCall);
if ( bedWriter != null ) tumorCall.printBedLine(bedWriter);
if ( verboseWriter != null ) printVerboseLine(verboseWriter, normalCall, tumorCall );
lastGenotypedPosition = pos;
}
tumor_context.indelsAt(pos).clear();
normal_context.indelsAt(pos).clear();
// we dealt with this indel; don't want to see it again
// (we might otherwise in the case when 1) there is another indel that follows
// within MISMATCH_WIDTH bases and 2) we'd need to wait for more coverage for that next indel)
// for ( IndelVariant var : variants ) {
// System.out.print("\t"+var.getType()+"\t"+var.getBases()+"\t"+var.getCount());
// }
}
if ( DEBUG ) System.out.println("DEBUG>> Actual shift to " + move_to + " ("+adjustedPosition+")");
tumor_context.shift((int)(move_to - tumor_context.getStart() ) );
normal_context.shift((int)(move_to - normal_context.getStart() ) );
}
private String makeFullRecord(IndelPrecall normalCall, IndelPrecall tumorCall) {
StringBuilder fullRecord = new StringBuilder();
if ( tumorCall.getVariant() != null || normalCall.getVariant() == null) {
fullRecord.append(tumorCall.makeEventString());
} else {
fullRecord.append(normalCall.makeEventString());
}
fullRecord.append('\t');
fullRecord.append(normalCall.makeStatsString("N_"));
fullRecord.append('\t');
fullRecord.append(tumorCall.makeStatsString("T_"));
fullRecord.append('\t');
return fullRecord.toString();
}
private String makeFullRecord(IndelPrecall normalCall) {
StringBuilder fullRecord = new StringBuilder();
fullRecord.append(normalCall.makeEventString());
fullRecord.append('\t');
fullRecord.append(normalCall.makeStatsString(""));
fullRecord.append('\t');
return fullRecord.toString();
}
private String getAnnotationString(RODRecordList ann) {
if ( ann == null ) return annGenomic;
else {
StringBuilder b = new StringBuilder();
if ( RefSeqFeature.isExon(ann) ) {
if ( RefSeqFeature.isCodingExon(ann) ) b.append(annCoding); // both exon and coding = coding exon sequence
else b.append(annUTR); // exon but not coding = UTR
} else {
if ( RefSeqFeature.isCoding(ann) ) b.append(annIntron); // not in exon, but within the coding region = intron
else b.append(annUnknown); // we have no idea what this is. this may actually happen when we have a fully non-coding exon...
}
b.append('\t');
b.append(((Transcript)ann.get(0).getUnderlyingObject()).getGeneName()); // there is at least one transcript in the list, guaranteed
// while ( it.hasNext() ) { //
// t.getGeneName()
// }
return b.toString();
}
}
public void printVerboseLine(Writer verboseWriter, IndelPrecall normalCall) {
RODRecordList annotationList = (refseqIterator == null ? null : refseqIterator.seekForward(location));
String annotationString = (refseqIterator == null ? "" : getAnnotationString(annotationList));
StringBuilder fullRecord = new StringBuilder();
fullRecord.append(makeFullRecord(normalCall));
fullRecord.append(annotationString);
if ( ! normalCall.isCall() && normalCall.getVariant() != null ) fullRecord.append("\tFILTERED_NOCALL");
try {
verboseWriter.write(fullRecord.toString());
verboseWriter.write('\n');
} catch (IOException e) {
throw new UserException.CouldNotCreateOutputFile(verboseOutput, "Write failed", e);
}
}
public void printVerboseLine(Writer verboseWriter, IndelPrecall normalCall, IndelPrecall tumorCall) {
RODRecordList annotationList = (refseqIterator == null ? null : refseqIterator.seekForward(location));
String annotationString = (refseqIterator == null ? "" : getAnnotationString(annotationList));
StringBuilder fullRecord = new StringBuilder();
fullRecord.append(makeFullRecord(normalCall,tumorCall));
if ( normalCall.getVariant() == null && tumorCall.getVariant() == null ) {
// did not observe anything
if ( normalCall.getCoverage() >= minNormalCoverage && tumorCall.getCoverage() >= minCoverage ) fullRecord.append("REFERENCE");
else {
if ( tumorCall.getCoverage() >= minCoverage ) fullRecord.append("REFERENCE"); // no coverage in normal but nothing in tumor
else {
// no coverage in tumor; if we have no coverage in normal, it can be anything; if we do have coverage in normal,
// this still could be a somatic event. so either way it is 'unknown'
fullRecord.append("UNKNOWN");
}
}
}
if ( normalCall.getVariant() == null && tumorCall.getVariant() != null ) {
// looks like somatic call
if ( normalCall.getCoverage() >= minNormalCoverage ) fullRecord.append("SOMATIC"); // we confirm there is nothing in normal
else {
// low coverage in normal
fullRecord.append("EVENT_T"); // no coverage in normal, no idea whether it is germline or somatic
}
}
if ( normalCall.getVariant() != null && tumorCall.getVariant() == null ) {
// it's likely germline (with missing observation in tumor - maybe loh?
if ( tumorCall.getCoverage() >= minCoverage ) fullRecord.append("GERMLINE_LOH"); // we confirm there is nothing in tumor
else {
// low coverage in tumor, maybe we missed the event
fullRecord.append("GERMLINE"); // no coverage in tumor but we already saw it in normal...
}
}
if ( normalCall.getVariant() != null && tumorCall.getVariant() != null ) {
// events in both T/N, got to be germline!
fullRecord.append("GERMLINE");
}
fullRecord.append('\t');
fullRecord.append(annotationString);
if ( ! tumorCall.isCall() && tumorCall.getVariant() != null ) fullRecord.append("\tFILTERED_NOCALL");
try {
verboseWriter.write(fullRecord.toString());
verboseWriter.write('\n');
} catch (IOException e) {
throw new UserException.CouldNotCreateOutputFile(verboseOutput, "Write failed", e);
}
}
public void printVCFLine(VCFWriter vcf, IndelPrecall call) {
long start = call.getPosition()-1;
// If the beginning of the chromosome is deleted (possible, however unlikely), it's unclear how to proceed.
// The suggestion is instead of putting the base before the indel, to put the base after the indel.
// For now, just don't print out that site.
if ( start == 0 )
return;
long stop = start;
List<Allele> alleles = new ArrayList<Allele>(2); // actual observed (distinct!) alleles at the site
List<Allele> homref_alleles = null; // when needed, will contain two identical copies of ref allele - needed to generate hom-ref genotype
if ( call.getVariant() == null ) {
// we will need to cteate genotype with two (hom) ref alleles (below).
// we can not use 'alleles' list here, since that list is supposed to contain
// only *distinct* alleles observed at the site or VCFContext will frown upon us...
alleles.add( Allele.create(refBases[(int)start-1],true) );
homref_alleles = new ArrayList<Allele>(2);
homref_alleles.add( alleles.get(0));
homref_alleles.add( alleles.get(0));
} else {
// we always create alt allele when we observe anything but the ref, even if it is not a call!
// (Genotype will tell us whether it is an actual call or not!)
int event_length = call.getVariant().lengthOnRef();
if ( event_length < 0 ) event_length = 0;
fillAlleleList(alleles,call);
stop += event_length;
}
Map<String,Genotype> genotypes = new HashMap<String,Genotype>();
for ( String sample : normalSamples ) {
Map<String,?> attrs = call.makeStatsAttributes(null);
if ( call.isCall() ) // we made a call - put actual het genotype here:
genotypes.put(sample,new Genotype(sample,alleles,Genotype.NO_NEG_LOG_10PERROR,null,attrs,false));
else // no call: genotype is ref/ref (but alleles still contain the alt if we observed anything at all)
genotypes.put(sample,new Genotype(sample, homref_alleles,Genotype.NO_NEG_LOG_10PERROR,null,attrs,false));
}
Set<String> filters = null;
if ( call.getVariant() != null && ! call.isCall() ) {
filters = new HashSet<String>();
filters.add("NoCall");
}
VariantContext vc = new VariantContext("IGv2_Indel_call", refName, start, stop, alleles, genotypes,
-1.0 /* log error */, filters, null, refBases[(int)start-1]);
vcf.add(vc);
}
/** Fills l with appropriate alleles depending on whether call is insertion or deletion
* (l MUST have a variant or this method will crash). It is guaranteed that the *first* allele added
* to the list is ref, and the next one is alt.
* @param l
* @param call
*/
private void fillAlleleList(List<Allele> l, IndelPrecall call) {
int event_length = call.getVariant().lengthOnRef();
if ( event_length == 0 ) { // insertion
l.add( Allele.create(Allele.NULL_ALLELE_STRING,true) );
l.add( Allele.create(call.getVariant().getBases(), false ));
} else { //deletion:
l.add( Allele.create(call.getVariant().getBases(), true ));
l.add( Allele.create(Allele.NULL_ALLELE_STRING,false) );
}
}
public void printVCFLine(VCFWriter vcf, IndelPrecall nCall, IndelPrecall tCall) {
long start = tCall.getPosition()-1;
long stop = start;
// If the beginning of the chromosome is deleted (possible, however unlikely), it's unclear how to proceed.
// The suggestion is instead of putting the base before the indel, to put the base after the indel.
// For now, just don't print out that site.
if ( start == 0 )
return;
Map<String,Object> attrsNormal = nCall.makeStatsAttributes(null);
Map<String,Object> attrsTumor = tCall.makeStatsAttributes(null);
Map<String,Object> attrs = new HashMap();
boolean isSomatic = false;
if ( nCall.getCoverage() >= minNormalCoverage && nCall.getVariant() == null && tCall.getVariant() != null ) {
isSomatic = true;
attrs.put(VCFConstants.SOMATIC_KEY,true);
}
List<Allele> alleles = new ArrayList<Allele>(2); // all alleles at the site
// List<Allele> normal_alleles = null; // all alleles at the site
List<Allele> homRefAlleles = null;
// if ( nCall.getVariant() == null || tCall.getVariant() == null ) {
homRefAlleles = new ArrayList<Allele>(2) ; // we need this for somatic calls (since normal is ref-ref), and also for no-calls
// }
boolean homRefT = ( tCall.getVariant() == null );
boolean homRefN = ( nCall.getVariant() == null );
if ( tCall.getVariant() == null && nCall.getVariant() == null) {
// no indel at all ; create base-representation ref/ref alleles for genotype construction
alleles.add( Allele.create(refBases[(int)start-1],true) );
} else {
// we got indel(s)
int event_length = 0;
if ( tCall.getVariant() != null ) {
// indel in tumor
event_length = tCall.getVariant().lengthOnRef();
fillAlleleList(alleles, tCall);
} else {
event_length = nCall.getVariant().lengthOnRef();
fillAlleleList(alleles, nCall);
}
if ( event_length > 0 ) stop += event_length;
}
homRefAlleles.add( alleles.get(0));
homRefAlleles.add( alleles.get(0));
Map<String,Genotype> genotypes = new HashMap<String,Genotype>();
for ( String sample : normalSamples ) {
genotypes.put(sample,new Genotype(sample, homRefN ? homRefAlleles : alleles,Genotype.NO_NEG_LOG_10PERROR,null,attrsNormal,false));
}
for ( String sample : tumorSamples ) {
genotypes.put(sample,new Genotype(sample, homRefT ? homRefAlleles : alleles,Genotype.NO_NEG_LOG_10PERROR,null,attrsTumor,false) );
}
Set<String> filters = null;
if ( tCall.getVariant() != null && ! tCall.isCall() ) {
filters = new HashSet<String>();
filters.add("NoCall");
}
if ( nCall.getCoverage() < minNormalCoverage ) {
if ( filters == null ) filters = new HashSet<String>();
filters.add("NCov");
}
if ( tCall.getCoverage() < minCoverage ) {
if ( filters == null ) filters = new HashSet<String>();
filters.add("TCov");
}
VariantContext vc = new VariantContext("IGv2_Indel_call", refName, start, stop, alleles, genotypes,
-1.0 /* log error */, filters, attrs, refBases[(int)start-1]);
vcf.add(vc);
}
@Override
public void onTraversalDone(Integer result) {
if ( DEBUG ) {
System.out.println("DEBUG>> Emitting last window at "+normal_context.getStart()+"-"+normal_context.getStop());
}
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true); // emit everything we might have left
if ( metricsWriter != null ) {
metricsWriter.println(String.format("Normal calls made %d", normalCallsMade));
metricsWriter.println(String.format("Tumor calls made %d", tumorCallsMade));
metricsWriter.close();
}
try {
if ( bedWriter != null ) bedWriter.close();
if ( verboseWriter != null ) verboseWriter.close();
} catch (IOException e) {
System.out.println("Failed to close output BED file gracefully, data may be lost");
e.printStackTrace();
}
super.onTraversalDone(result);
}
@Override
public Integer reduce(Integer value, Integer sum) {
if ( value == -1 ) {
onTraversalDone(sum);
System.exit(1);
}
sum += value;
return sum;
}
@Override
public Integer reduceInit() {
return new Integer(0);
}
static class IndelVariant {
public static enum Type { I, D};
private String bases;
private Type type;
private ArrayList<Integer> fromStartOffsets = null;
private ArrayList<Integer> fromEndOffsets = null;
private Set<ExpandedSAMRecord> reads = new HashSet<ExpandedSAMRecord>(); // keep track of reads that have this indel
private Set<String> samples = new HashSet<String>(); // which samples had the indel described by this object
public IndelVariant(ExpandedSAMRecord read , Type type, String bases) {
this.type = type;
this.bases = bases.toUpperCase();
addObservation(read);
fromStartOffsets = new ArrayList<Integer>();
fromEndOffsets = new ArrayList<Integer>();
}
/** Adds another observation for the current indel. It is assumed that the read being registered
* does contain the observation, no checks are performed. Read's sample is added to the list of samples
* this indel was observed in as well.
* @param read
*/
public void addObservation(ExpandedSAMRecord read) {
if ( reads.contains(read) ) {
//TODO fix CleanedReadInjector and reinstate exception here: duplicate records may signal a problem with the bam
// seeing the same read again can mean only one thing: the input bam file is corrupted and contains
// duplicate records. We KNOW that this may happen for the time being due to bug in CleanedReadInjector
// so this is a short-term patch: don't cry, but just ignore the duplicate record
//throw new StingException("Attempting to add indel observation that was already registered");
return;
}
reads.add(read);
String sample = null;
if ( read.getSAMRecord().getReadGroup() != null ) sample = read.getSAMRecord().getReadGroup().getSample();
if ( sample != null ) samples.add(sample);
}
/** Returns length of the event on the reference (number of deleted bases
* for deletions, -1 for insertions.
* @return
*/
public int lengthOnRef() {
if ( type == Type.D ) return bases.length();
else return 0;
}
public void addSample(String sample) {
if ( sample != null )
samples.add(sample);
}
public void addReadPositions(int fromStart, int fromEnd) {
fromStartOffsets.add(fromStart);
fromEndOffsets.add(fromEnd);
}
public List<Integer> getOffsetsFromStart() { return fromStartOffsets ; }
public List<Integer> getOffsetsFromEnd() { return fromEndOffsets; }
public String getSamples() {
StringBuffer sb = new StringBuffer();
Iterator<String> i = samples.iterator();
while ( i.hasNext() ) {
sb.append(i.next());
if ( i.hasNext() )
sb.append(",");
}
return sb.toString();
}
public Set<ExpandedSAMRecord> getReadSet() { return reads; }
public int getCount() { return reads.size(); }
public String getBases() { return bases; }
public Type getType() { return type; }
@Override
public boolean equals(Object o) {
if ( ! ( o instanceof IndelVariant ) ) return false;
IndelVariant that = (IndelVariant)o;
return ( this.type == that.type && this.bases.equals(that.bases) );
}
public boolean equals(Type type, String bases) {
return ( this.type == type && this.bases.equals(bases.toUpperCase()) );
}
}
/**
* Utility class that encapsulates the logic related to collecting all the stats and counts required to
* make (or discard) a call, as well as the calling heuristics that uses those data.
*/
class IndelPrecall {
// private boolean DEBUG = false;
private int NQS_MISMATCH_CUTOFF = 1000000;
private double AV_MISMATCHES_PER_READ = 1.5;
private int nqs = 0;
private IndelVariant consensus_indel = null; // indel we are going to call
private long pos = -1 ; // position on the ref
private int total_coverage = 0; // total number of reads overlapping with the event
private int consensus_indel_count = 0; // number of reads, in which consensus indel was observed
private int all_indel_count = 0 ; // number of reads, in which any indel was observed at current position
private int total_mismatches_in_nqs_window = 0; // total number of mismatches in the nqs window around the indel
private int total_bases_in_nqs_window = 0; // total number of bases in the nqs window (some reads may not fully span the window so it's not coverage*nqs_size)
private int total_base_qual_in_nqs_window = 0; // sum of qualitites of all the bases in the nqs window
private int total_mismatching_base_qual_in_nqs_window = 0; // sum of qualitites of all mismatching bases in the nqs window
private int indel_read_mismatches_in_nqs_window = 0; // mismatches inside the nqs window in indel-containing reads only
private int indel_read_bases_in_nqs_window = 0; // number of bases in the nqs window from indel-containing reads only
private int indel_read_base_qual_in_nqs_window = 0; // sum of qualitites of bases in nqs window from indel-containing reads only
private int indel_read_mismatching_base_qual_in_nqs_window = 0; // sum of qualitites of mismatching bases in the nqs window from indel-containing reads only
private int consensus_indel_read_mismatches_in_nqs_window = 0; // mismatches within the nqs window from consensus indel reads only
private int consensus_indel_read_bases_in_nqs_window = 0; // number of bases in the nqs window from consensus indel-containing reads only
private int consensus_indel_read_base_qual_in_nqs_window = 0; // sum of qualitites of bases in nqs window from consensus indel-containing reads only
private int consensus_indel_read_mismatching_base_qual_in_nqs_window = 0; // sum of qualitites of mismatching bases in the nqs window from consensus indel-containing reads only
private double consensus_indel_read_total_mm = 0.0; // sum of all mismatches in reads that contain consensus indel
private double all_indel_read_total_mm = 0.0; // sum of all mismatches in reads that contain any indel at given position
private double all_read_total_mm = 0.0; // sum of all mismatches in all reads
private double consensus_indel_read_total_mapq = 0.0; // sum of mapping qualitites of all reads with consensus indel
private double all_indel_read_total_mapq = 0.0 ; // sum of mapping qualitites of all reads with (any) indel at current position
private double all_read_total_mapq = 0.0; // sum of all mapping qualities of all reads
private PrimitivePair.Int consensus_indel_read_orientation_cnt = new PrimitivePair.Int();
private PrimitivePair.Int all_indel_read_orientation_cnt = new PrimitivePair.Int();
private PrimitivePair.Int all_read_orientation_cnt = new PrimitivePair.Int();
private int from_start_median = 0;
private int from_start_mad = 0;
private int from_end_median = 0;
private int from_end_mad = 0;
/** Makes an empty call (no-call) with all stats set to 0
*
* @param position
*/
public IndelPrecall(long position) {
this.pos = position;
}
public IndelPrecall(WindowContext context, long position, int nqs_width) {
this.pos = position;
this.nqs = nqs_width;
total_coverage = context.coverageAt(pos,true);
List<IndelVariant> variants = context.indelsAt(pos);
findConsensus(variants);
// pos is the first base after the event: first deleted base or first base after insertion.
// hence, [pos-nqs, pos+nqs-1] (inclusive) is the window with nqs bases on each side of a no-event or an insertion
// and [pos-nqs, pos+Ndeleted+nqs-1] is the window with nqs bases on each side of a deletion.
// we initialize the nqs window for no-event/insertion case
long left = Math.max( pos-nqs, context.getStart() );
long right = Math.min(pos+nqs-1, context.getStop());
//if ( pos == 3534096 ) System.out.println("pos="+pos +" total reads: "+context.getReads().size());
Iterator<ExpandedSAMRecord> read_iter = context.getReads().iterator();
while ( read_iter.hasNext() ) {
ExpandedSAMRecord rec = read_iter.next();
SAMRecord read = rec.getSAMRecord();
byte[] flags = rec.getExpandedMMFlags();
byte[] quals = rec.getExpandedQuals();
int mm = rec.getMMCount();
if( read.getAlignmentStart() > pos || read.getAlignmentEnd() < pos ) continue;
long local_right = right; // end of nqs window for this particular read. May need to be advanced further right
// if read has a deletion. The gap in the middle of nqs window will be skipped
// automatically since flags/quals are set to -1 there
boolean read_has_a_variant = false;
boolean read_has_consensus = ( consensus_indel!= null && consensus_indel.getReadSet().contains(rec) );
for ( IndelVariant v : variants ) {
if ( v.getReadSet().contains(rec) ) {
read_has_a_variant = true;
local_right += v.lengthOnRef();
break;
}
}
if ( read_has_consensus ) {
consensus_indel_read_total_mm += mm;
consensus_indel_read_total_mapq += read.getMappingQuality();
if ( read.getReadNegativeStrandFlag() ) consensus_indel_read_orientation_cnt.second++;
else consensus_indel_read_orientation_cnt.first++;
}
if ( read_has_a_variant ) {
all_indel_read_total_mm += mm;
all_indel_read_total_mapq += read.getMappingQuality();
if ( read.getReadNegativeStrandFlag() ) all_indel_read_orientation_cnt.second++;
else all_indel_read_orientation_cnt.first++;
}
all_read_total_mm+= mm;
all_read_total_mapq += read.getMappingQuality();
if ( read.getReadNegativeStrandFlag() ) all_read_orientation_cnt.second++;
else all_read_orientation_cnt.first++;
for ( int pos_in_flags = Math.max((int)(left - read.getAlignmentStart()),0);
pos_in_flags <= Math.min((int)local_right-read.getAlignmentStart(),flags.length - 1);
pos_in_flags++) {
if ( flags[pos_in_flags] == -1 ) continue; // gap (deletion), skip it; we count only bases aligned to the ref
total_bases_in_nqs_window++;
if ( read_has_consensus ) consensus_indel_read_bases_in_nqs_window++;
if ( read_has_a_variant ) indel_read_bases_in_nqs_window++;
if ( quals[pos_in_flags] != -1 ) {
total_base_qual_in_nqs_window += quals[pos_in_flags];
if ( read_has_a_variant ) indel_read_base_qual_in_nqs_window += quals[pos_in_flags];
if ( read_has_consensus ) consensus_indel_read_base_qual_in_nqs_window += quals[pos_in_flags];
}
if ( flags[pos_in_flags] == 1 ) { // it's a mismatch
total_mismatches_in_nqs_window++;
total_mismatching_base_qual_in_nqs_window += quals[pos_in_flags];
if ( read_has_consensus ) {
consensus_indel_read_mismatches_in_nqs_window++;
consensus_indel_read_mismatching_base_qual_in_nqs_window += quals[pos_in_flags];
}
if ( read_has_a_variant ) {
indel_read_mismatches_in_nqs_window++;
indel_read_mismatching_base_qual_in_nqs_window += quals[pos_in_flags];
}
}
}
// if ( pos == 3534096 ) {
// System.out.println(read.getReadName());
// System.out.println(" cons nqs bases="+consensus_indel_read_bases_in_nqs_window);
// System.out.println(" qual sum="+consensus_indel_read_base_qual_in_nqs_window);
// }
}
// compute median/mad for offsets from the read starts/ends
if ( consensus_indel != null ) {
from_start_median = median(consensus_indel.getOffsetsFromStart()) ;
from_start_mad = mad(consensus_indel.getOffsetsFromStart(),from_start_median);
from_end_median = median(consensus_indel.getOffsetsFromEnd()) ;
from_end_mad = mad(consensus_indel.getOffsetsFromEnd(),from_end_median);
}
}
/** As a side effect will sort l!
*
* @param l
* @return
*/
private int median(List<Integer> l) {
Collections.sort(l);
int k = l.size()/2;
return ( l.size() % 2 == 0 ?
(l.get(k-1).intValue()+l.get(k).intValue())/2 :
l.get(k).intValue());
}
private int median(int[] l) {
Arrays.sort(l);
int k = l.length/2;
return ( l.length % 2 == 0 ?
(l[k-1]+l[k])/2 :
l[k]);
}
private int mad(List<Integer> l, int med) {
int [] diff = new int[l.size()];
for ( int i = 0; i < l.size(); i++ ) {
diff[i] = Math.abs(l.get(i).intValue() - med);
}
return median(diff);
}
public long getPosition() { return pos; }
public boolean hasObservation() { return consensus_indel != null; }
public int getCoverage() { return total_coverage; }
public double getTotalMismatches() { return all_read_total_mm; }
public double getConsensusMismatches() { return consensus_indel_read_total_mm; }
public double getAllVariantMismatches() { return all_indel_read_total_mm; }
/** Returns average number of mismatches per consensus indel-containing read */
public double getAvConsensusMismatches() {
return ( consensus_indel_count != 0 ? consensus_indel_read_total_mm/consensus_indel_count : 0.0 );
}
/** Returns average number of mismatches per read across all reads matching the ref (not containing any indel variants) */
public double getAvRefMismatches() {
int coverage_ref = total_coverage-all_indel_count;
return ( coverage_ref != 0 ? (all_read_total_mm - all_indel_read_total_mm )/coverage_ref : 0.0 );
}
public PrimitivePair.Int getConsensusStrandCounts() {
return consensus_indel_read_orientation_cnt;
}
public PrimitivePair.Int getRefStrandCounts() {
return new PrimitivePair.Int(all_read_orientation_cnt.first-all_indel_read_orientation_cnt.first,
all_read_orientation_cnt.second - all_indel_read_orientation_cnt.second);
}
/** Returns a sum of mapping qualities of all reads spanning the event. */
public double getTotalMapq() { return all_read_total_mapq; }
/** Returns a sum of mapping qualities of all reads, in which the consensus variant is observed. */
public double getConsensusMapq() { return consensus_indel_read_total_mapq; }
/** Returns a sum of mapping qualities of all reads, in which any variant is observed at the current event site. */
public double getAllVariantMapq() { return all_indel_read_total_mapq; }
/** Returns average mapping quality per consensus indel-containing read. */
public double getAvConsensusMapq() {
return ( consensus_indel_count != 0 ? consensus_indel_read_total_mapq/consensus_indel_count : 0.0 );
}
/** Returns average number of mismatches per read across all reads matching the ref (not containing any indel variants). */
public double getAvRefMapq() {
int coverage_ref = total_coverage-all_indel_count;
return ( coverage_ref != 0 ? (all_read_total_mapq - all_indel_read_total_mapq )/coverage_ref : 0.0 );
}
/** Returns fraction of bases in NQS window around the indel that are mismatches, across all reads,
* in which consensus indel is observed. NOTE: NQS window for indel containing reads is defined around
* the indel itself (e.g. for a 10-base deletion spanning [X,X+9], the 5-NQS window is {[X-5,X-1],[X+10,X+15]}
* */
public double getNQSConsensusMMRate() {
if ( consensus_indel_read_bases_in_nqs_window == 0 ) return 0;
return ((double)consensus_indel_read_mismatches_in_nqs_window)/consensus_indel_read_bases_in_nqs_window;
}
/** Returns fraction of bases in NQS window around the indel start position that are mismatches, across all reads
* that align to the ref (i.e. contain no indel observation at the current position). NOTE: NQS window for ref
* reads is defined around the event start position, NOT around the actual consensus indel.
* */
public double getNQSRefMMRate() {
int num_ref_bases = total_bases_in_nqs_window - indel_read_bases_in_nqs_window;
if ( num_ref_bases == 0 ) return 0;
return ((double)(total_mismatches_in_nqs_window - indel_read_mismatches_in_nqs_window))/num_ref_bases;
}
/** Returns average base quality in NQS window around the indel, across all reads,
* in which consensus indel is observed. NOTE: NQS window for indel containing reads is defined around
* the indel itself (e.g. for a 10-base deletion spanning [X,X+9], the 5-NQS window is {[X-5,X-1],[X+10,X+15]}
* */
public double getNQSConsensusAvQual() {
if ( consensus_indel_read_bases_in_nqs_window == 0 ) return 0;
return ((double)consensus_indel_read_base_qual_in_nqs_window)/consensus_indel_read_bases_in_nqs_window;
}
/** Returns fraction of bases in NQS window around the indel start position that are mismatches, across all reads
* that align to the ref (i.e. contain no indel observation at the current position). NOTE: NQS window for ref
* reads is defined around the event start position, NOT around the actual consensus indel.
* */
public double getNQSRefAvQual() {
int num_ref_bases = total_bases_in_nqs_window - indel_read_bases_in_nqs_window;
if ( num_ref_bases == 0 ) return 0;
return ((double)(total_base_qual_in_nqs_window - indel_read_base_qual_in_nqs_window))/num_ref_bases;
}
public int getTotalNQSMismatches() { return total_mismatches_in_nqs_window; }
public int getAllVariantCount() { return all_indel_count; }
public int getConsensusVariantCount() { return consensus_indel_count; }
// public boolean failsNQSMismatch() {
// //TODO wrong fraction: mismatches are counted only in indel-containing reads, but total_coverage is used!
// return ( indel_read_mismatches_in_nqs_window > NQS_MISMATCH_CUTOFF ) ||
// ( indel_read_mismatches_in_nqs_window > total_coverage * AV_MISMATCHES_PER_READ );
// }
public IndelVariant getVariant() { return consensus_indel; }
public boolean isCall() {
boolean ret = ( consensus_indel_count >= minIndelCount &&
(double)consensus_indel_count > minFraction * total_coverage &&
(double) consensus_indel_count > minConsensusFraction*all_indel_count && total_coverage >= minCoverage);
if ( DEBUG && ! ret ) System.out.println("DEBUG>> NOT a call: count="+consensus_indel_count+
" total_count="+all_indel_count+" cov="+total_coverage+
" minConsensusF="+((double)consensus_indel_count)/all_indel_count+
" minF="+((double)consensus_indel_count)/total_coverage);
return ret;
}
/** Utility method: finds the indel variant with the largest count (ie consensus) among all the observed
* variants, and sets the counts of consensus observations and all observations of any indels (including non-consensus)
* @param variants
* @return
*/
private void findConsensus(List<IndelVariant> variants) {
for ( IndelVariant var : variants ) {
if ( DEBUG ) System.out.println("DEBUG>> Variant "+var.getBases()+" (cnt="+var.getCount()+")");
int cnt = var.getCount();
all_indel_count +=cnt;
if ( cnt > consensus_indel_count ) {
consensus_indel = var;
consensus_indel_count = cnt;
}
}
if ( DEBUG && consensus_indel != null ) System.out.println("DEBUG>> Returning: "+consensus_indel.getBases()+
" (cnt="+consensus_indel.getCount()+") with total count of "+all_indel_count);
}
public void printBedLine(Writer bed) {
int event_length;
if ( consensus_indel == null ) event_length = 0;
else {
event_length = consensus_indel.lengthOnRef();
if ( event_length < 0 ) event_length = 0;
}
StringBuffer message = new StringBuffer();
message.append(refName+"\t"+(pos-1)+"\t");
message.append((pos-1+event_length)+"\t");
if ( consensus_indel != null ) {
message.append((event_length>0? "-":"+")+consensus_indel.getBases());
} else {
message.append('.');
}
message.append(":"+all_indel_count+"/"+total_coverage);
try {
bed.write(message.toString()+"\n");
} catch (IOException e) {
throw new UserException.CouldNotCreateOutputFile(bedOutput, "Error encountered while writing into output BED file", e);
}
}
public String makeEventString() {
int event_length;
if ( consensus_indel == null ) event_length = 0;
else {
event_length = consensus_indel.lengthOnRef();
if ( event_length < 0 ) event_length = 0;
}
StringBuffer message = new StringBuffer();
message.append(refName);
message.append('\t');
message.append(pos-1);
message.append('\t');
message.append(pos-1+event_length);
message.append('\t');
if ( consensus_indel != null ) {
message.append((event_length>0?'-':'+'));
message.append(consensus_indel.getBases());
} else {
message.append('.');
}
return message.toString();
}
public String makeStatsString(String prefix) {
StringBuilder message = new StringBuilder();
message.append(prefix+"OBS_COUNTS[C/A/T]:"+getConsensusVariantCount()+"/"+getAllVariantCount()+"/"+getCoverage());
message.append('\t');
message.append(prefix+"AV_MM[C/R]:"+String.format("%.2f/%.2f",getAvConsensusMismatches(),
getAvRefMismatches()));
message.append('\t');
message.append(prefix+"AV_MAPQ[C/R]:"+String.format("%.2f/%.2f",getAvConsensusMapq(),
getAvRefMapq()));
message.append('\t');
message.append(prefix+"NQS_MM_RATE[C/R]:"+String.format("%.2f/%.2f",getNQSConsensusMMRate(),getNQSRefMMRate()));
message.append('\t');
message.append(prefix+"NQS_AV_QUAL[C/R]:"+String.format("%.2f/%.2f",getNQSConsensusAvQual(),getNQSRefAvQual()));
PrimitivePair.Int strand_cons = getConsensusStrandCounts();
PrimitivePair.Int strand_ref = getRefStrandCounts();
message.append('\t');
message.append(prefix+"STRAND_COUNTS[C/C/R/R]:"+strand_cons.first+"/"+strand_cons.second+"/"+strand_ref.first+"/"+strand_ref.second);
message.append('\t');
message.append(prefix+"OFFSET_RSTART:"+from_start_median+"/"+from_start_mad);
message.append('\t');
message.append(prefix+"OFFSET_REND:"+from_end_median+"/"+from_end_mad);
return message.toString();
}
/**
* Places alignment statistics into attribute map and returns the map. If attr parameter is null,
* a new map is allocated, filled and returned. If attr is not null, new attributes are added to that
* preexisting map, and the same instance of the (updated) map is returned.
*
* @param attr
* @return
*/
public Map<String,Object> makeStatsAttributes(Map<String,Object> attr) {
if ( attr == null ) attr = new HashMap<String, Object>();
VCFIndelAttributes.recordDepth(getConsensusVariantCount(),getAllVariantCount(),getCoverage(),attr);
VCFIndelAttributes.recordAvMM(getAvConsensusMismatches(),getAvRefMismatches(),attr);
VCFIndelAttributes.recordAvMapQ(getAvConsensusMapq(),getAvRefMapq(),attr);
VCFIndelAttributes.recordNQSMMRate(getNQSConsensusMMRate(),getNQSRefMMRate(),attr);
VCFIndelAttributes.recordNQSAvQ(getNQSConsensusAvQual(),getNQSRefAvQual(),attr);
VCFIndelAttributes.recordOffsetFromStart(from_start_median,from_start_mad,attr);
VCFIndelAttributes.recordOffsetFromEnd(from_end_median,from_end_mad,attr);
PrimitivePair.Int strand_cons = getConsensusStrandCounts();
PrimitivePair.Int strand_ref = getRefStrandCounts();
VCFIndelAttributes.recordStrandCounts(strand_cons.first,strand_cons.second,strand_ref.first,strand_ref.second,attr);
return attr;
}
}
interface IndelListener {
public void addObservation(int pos, IndelVariant.Type t, String bases, int fromStart, int fromEnd, ExpandedSAMRecord r);
}
class WindowContext implements IndelListener {
private Set<ExpandedSAMRecord> reads;
private int start=0; // where the window starts on the ref, 1-based
private CircularArray< List< IndelVariant > > indels;
private List<IndelVariant> emptyIndelList = new ArrayList<IndelVariant>();
public WindowContext(int start, int length) {
this.start = start;
indels = new CircularArray< List<IndelVariant> >(length);
// reads = new LinkedList<SAMRecord>();
reads = new HashSet<ExpandedSAMRecord>();
}
/** Returns 1-based reference start position of the interval this object keeps context for.
*
* @return
*/
public int getStart() { return start; }
/** Returns 1-based reference stop position (inclusive) of the interval this object keeps context for.
*
* @return
*/
public int getStop() { return start + indels.length() - 1; }
/** Resets reference start position to 0 and clears the context.
*
*/
public void clear() {
start = 0;
reads.clear();
indels.clear();
}
/**
* Returns true if any indel observations are present in the specified interval
* [begin,end] (1-based, inclusive). Interval can be partially of fully outside of the
* current context window: positions outside of the window will be ignored.
* @param begin
* @param end
*/
public boolean hasIndelsInInterval(long begin, long end) {
for ( long k = Math.max(start,begin); k < Math.min(getStop(),end); k++ ) {
if ( indelsAt(k) != emptyIndelList ) return true;
}
return false;
}
public Set<ExpandedSAMRecord> getReads() { return reads; }
/** Returns the number of reads spanning over the specified reference position
* (regardless of whether they have a base or indel at that specific location).
* The second argument controls whether to count with indels in mind (this is relevant for insertions only,
* deletions do not require any special treatment since they occupy non-zero length on the ref and since
* alignment can not start or end with a deletion). For insertions, note that, internally, we assign insertions
* to the reference position right after the actual event, and we count all events assigned to a given position.
* This count (reads with indels) should be contrasted to reads without indels, or more rigorously, reads
* that support the ref rather than the indel. Few special cases may occur here:
* 1) an alignment that ends (as per getAlignmentEnd()) right before the current position but has I as its
* last element: we have to count that read into the "coverage" at the current position for the purposes of indel
* assessment, as the indel in that read <i>will</i> be counted at the current position, so the total coverage
* should be consistent with that.
*/
/* NOT IMPLEMENTED: 2) alsignments that start exactly at the current position do <i>not</i> count for the purpose of insertion
* assessment since they do not contribute any evidence to either Ref or Alt=insertion hypothesis, <i>unless</i>
* the alignment starts with I (so that we do have evidence for an indel assigned to the current position and
* read should be counted). For deletions, reads starting at the current position should always be counted (as they
* show no deletion=ref).
* @param refPos position on the reference; must be within the bounds of the window
*/
public int coverageAt(final long refPos, boolean countForIndels) {
int cov = 0;
for ( ExpandedSAMRecord read : reads ) {
if ( read.getSAMRecord().getAlignmentStart() > refPos || read.getSAMRecord().getAlignmentEnd() < refPos ) {
if ( countForIndels && read.getSAMRecord().getAlignmentEnd() == refPos - 1) {
Cigar c = read.getSAMRecord().getCigar();
if ( c.getCigarElement(c.numCigarElements()-1).getOperator() == CigarOperator.I ) cov++;
}
continue;
}
cov++;
}
return cov;
}
/** Shifts current window to the right along the reference contig by the specified number of bases.
* The context will be updated accordingly (indels and reads that go out of scope will be dropped).
* @param offset
*/
public void shift(int offset) {
start += offset;
indels.shiftData(offset);
if ( indels.get(0) != null && indels.get(0).size() != 0 ) {
IndelVariant indel = indels.get(0).get(0);
System.out.println("WARNING: Indel(s) at first position in the window ("+refName+":"+start+"): currently not supported: "+
(indel.getType()==IndelVariant.Type.I?"+":"-")+indel.getBases()+"; read: "+indel.getReadSet().iterator().next().getSAMRecord().getReadName()+"; site ignored");
indels.get(0).clear();
// throw new StingException("Indel found at the first position ("+start+") after a shift was performed: currently not supported: "+
// (indel.getType()==IndelVariant.Type.I?"+":"-")+indel.getBases()+"; reads: "+indel.getReadSet().iterator().next().getSAMRecord().getReadName());
}
Iterator<ExpandedSAMRecord> read_iter = reads.iterator();
while ( read_iter.hasNext() ) {
ExpandedSAMRecord r = read_iter.next();
if ( r.getSAMRecord().getAlignmentEnd() < start ) { // discard reads and associated data that went out of scope
read_iter.remove();
}
}
}
public void add(SAMRecord read, byte [] ref) {
if ( read.getAlignmentStart() < start ) return; // silently ignore reads starting before the window start
ExpandedSAMRecord er = new ExpandedSAMRecord(read,ref,read.getAlignmentStart()-start,this);
//TODO duplicate records may actually indicate a problem with input bam file; throw an exception when the bug in CleanedReadInjector is fixed
if ( reads.contains(er)) return; // ignore duplicate records
reads.add(er);
}
public void addObservation(int pos, IndelVariant.Type type, String bases, int fromStart, int fromEnd, ExpandedSAMRecord rec) {
List<IndelVariant> indelsAtSite;
try {
indelsAtSite = indels.get(pos);
} catch (IndexOutOfBoundsException e) {
SAMRecord r = rec.getSAMRecord();
System.out.println("Failed to add indel observation, probably out of coverage window bounds (trailing indel?):\nRead "+
r.getReadName()+": "+
"read length="+r.getReadLength()+"; cigar="+r.getCigarString()+"; start="+
r.getAlignmentStart()+"; end="+r.getAlignmentEnd()+"; window start="+getStart()+
"; window end="+getStop());
throw e;
}
if ( indelsAtSite == null ) {
indelsAtSite = new ArrayList<IndelVariant>();
indels.set(pos, indelsAtSite);
}
IndelVariant indel = null;
for ( IndelVariant v : indelsAtSite ) {
if ( ! v.equals(type, bases) ) continue;
indel = v;
indel.addObservation(rec);
break;
}
if ( indel == null ) { // not found:
indel = new IndelVariant(rec, type, bases);
indelsAtSite.add(indel);
}
indel.addReadPositions(fromStart,fromEnd);
}
public List<IndelVariant> indelsAt( final long refPos ) {
List<IndelVariant> l = indels.get((int)( refPos - start ));
if ( l == null ) return emptyIndelList;
else return l;
}
}
class ExpandedSAMRecord {
private SAMRecord read;
private byte[] mismatch_flags;
private byte[] expanded_quals;
private int mms;
public ExpandedSAMRecord(SAMRecord r, byte [] ref, long offset, IndelListener l) {
read = r;
final long rStart = read.getAlignmentStart();
final long rStop = read.getAlignmentEnd();
final byte[] readBases = read.getReadString().toUpperCase().getBytes();
ref = new String(ref).toUpperCase().getBytes();
mismatch_flags = new byte[(int)(rStop-rStart+1)];
expanded_quals = new byte[(int)(rStop-rStart+1)];
// now let's extract indels:
Cigar c = read.getCigar();
final int nCigarElems = c.numCigarElements();
int readLength = 0; // length of the aligned part of the read NOT counting clipped bases
for ( CigarElement cel : c.getCigarElements() ) {
switch(cel.getOperator()) {
case H:
case S:
case D:
case N:
case P:
break; // do not count gaps or clipped bases
case I:
case M:
readLength += cel.getLength();
break; // advance along the gapless block in the alignment
default :
throw new IllegalArgumentException("Unexpected operator in cigar string: "+cel.getOperator());
}
}
int fromStart = 0;
int posOnRead = 0;
int posOnRef = 0; // the chunk of reference ref[] that we have access to is aligned with the read:
// its start on the actual full reference contig is r.getAlignmentStart()
for ( int i = 0 ; i < nCigarElems ; i++ ) {
final CigarElement ce = c.getCigarElement(i);
IndelVariant.Type type = null;
String indel_bases = null;
int eventPosition = posOnRef;
switch(ce.getOperator()) {
case H: break; // hard clipped reads do not have clipped indel_bases in their sequence, so we just ignore the H element...
case I:
type = IndelVariant.Type.I;
indel_bases = read.getReadString().substring(posOnRead,posOnRead+ce.getLength());
// will increment position on the read below, there's no 'break' statement yet...
case S:
// here we also skip soft-clipped indel_bases on the read; according to SAM format specification,
// alignment start position on the reference points to where the actually aligned
// (not clipped) indel_bases go, so we do not need to increment reference position here
posOnRead += ce.getLength();
break;
case D:
type = IndelVariant.Type.D;
indel_bases = new String( ref, posOnRef, ce.getLength() );
for( int k = 0 ; k < ce.getLength(); k++, posOnRef++ ) mismatch_flags[posOnRef] = expanded_quals[posOnRef] = -1;
break;
case M:
for ( int k = 0; k < ce.getLength(); k++, posOnRef++, posOnRead++ ) {
if ( readBases[posOnRead] != ref[posOnRef] ) { // mismatch!
mms++;
mismatch_flags[posOnRef] = 1;
}
expanded_quals[posOnRef] = read.getBaseQualities()[posOnRead];
}
fromStart += ce.getLength();
break; // advance along the gapless block in the alignment
default :
throw new IllegalArgumentException("Unexpected operator in cigar string: "+ce.getOperator());
}
if ( type == null ) continue; // element was not an indel, go grab next element...
// we got an indel if we are here...
if ( i == 0 ) logger.debug("Indel at the start of the read "+read.getReadName());
if ( i == nCigarElems - 1) logger.debug("Indel at the end of the read "+read.getReadName());
// note that here we will be assigning indels to the first deleted base or to the first
// base after insertion, not to the last base before the event!
int fromEnd = readLength - fromStart;
if ( type == IndelVariant.Type.I ) fromEnd -= ce.getLength();
l.addObservation((int)(offset+eventPosition), type, indel_bases, fromStart, fromEnd, this);
if ( type == IndelVariant.Type.I ) fromStart += ce.getLength();
}
}
public SAMRecord getSAMRecord() { return read; }
public byte [] getExpandedMMFlags() { return mismatch_flags; }
public byte [] getExpandedQuals() { return expanded_quals; }
public int getMMCount() { return mms; }
public boolean equals(Object o) {
if ( this == o ) return true;
if ( read == null ) return false;
if ( o instanceof SAMRecord ) return read.equals(o);
if ( o instanceof ExpandedSAMRecord ) return read.equals(((ExpandedSAMRecord)o).read);
return false;
}
}
}
class VCFIndelAttributes {
public static String ALLELIC_DEPTH_KEY = "AD";
public static String DEPTH_TOTAL_KEY = VCFConstants.DEPTH_KEY;
public static String MAPQ_KEY = "MQS";
public static String MM_KEY = "MM";
public static String NQS_MMRATE_KEY = "NQSMM";
public static String NQS_AVQ_KEY = "NQSBQ";
public static String STRAND_COUNT_KEY = "SC";
public static String RSTART_OFFSET_KEY = "RStart";
public static String REND_OFFSET_KEY = "REnd";
public static Set<? extends VCFHeaderLine> getAttributeHeaderLines() {
Set<VCFHeaderLine> lines = new HashSet<VCFHeaderLine>();
lines.add(new VCFFormatHeaderLine(ALLELIC_DEPTH_KEY, 2, VCFHeaderLineType.Integer, "# of reads supporting consensus indel/reference at the site"));
lines.add(new VCFFormatHeaderLine(DEPTH_TOTAL_KEY, 1, VCFHeaderLineType.Integer, "Total coverage at the site"));
lines.add(new VCFFormatHeaderLine(MAPQ_KEY, 2, VCFHeaderLineType.Float, "Average mapping qualities of consensus indel-supporting reads/reference-supporting reads"));
lines.add(new VCFFormatHeaderLine(MM_KEY, 2, VCFHeaderLineType.Float, "Average # of mismatches per consensus indel-supporting read/per reference-supporting read"));
lines.add(new VCFFormatHeaderLine(NQS_MMRATE_KEY, 2, VCFHeaderLineType.Float, "Within NQS window: fraction of mismatching bases in consensus indel-supporting reads/in reference-supporting reads"));
lines.add(new VCFFormatHeaderLine(NQS_AVQ_KEY, 2, VCFHeaderLineType.Float, "Within NQS window: average quality of bases from consensus indel-supporting reads/from reference-supporting reads"));
lines.add(new VCFFormatHeaderLine(STRAND_COUNT_KEY, 4, VCFHeaderLineType.Integer, "Strandness: counts of forward-/reverse-aligned indel-supporting reads / forward-/reverse-aligned reference supporting reads"));
lines.add(new VCFFormatHeaderLine(RSTART_OFFSET_KEY, 2, VCFHeaderLineType.Integer, "Median/mad of indel offsets from the starts of the reads"));
lines.add(new VCFFormatHeaderLine(REND_OFFSET_KEY, 2, VCFHeaderLineType.Integer, "Median/mad of indel offsets from the ends of the reads"));
return lines;
}
public static Map<String,Object> recordStrandCounts(int cnt_cons_fwd, int cnt_cons_rev, int cnt_ref_fwd, int cnt_ref_rev, Map<String,Object> attrs) {
attrs.put(STRAND_COUNT_KEY, new Integer[] {cnt_cons_fwd, cnt_cons_rev, cnt_ref_fwd, cnt_ref_rev} );
return attrs;
}
public static Map<String,Object> recordDepth(int cnt_cons, int cnt_indel, int cnt_total, Map<String,Object> attrs) {
attrs.put(ALLELIC_DEPTH_KEY, new Integer[] {cnt_cons, cnt_indel} );
attrs.put(DEPTH_TOTAL_KEY, cnt_total);
return attrs;
}
public static Map<String,Object> recordAvMapQ(double cons, double ref, Map<String,Object> attrs) {
attrs.put(MAPQ_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
public static Map<String,Object> recordAvMM(double cons, double ref, Map<String,Object> attrs) {
attrs.put(MM_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
public static Map<String,Object> recordNQSMMRate(double cons, double ref, Map<String,Object> attrs) {
attrs.put(NQS_MMRATE_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
public static Map<String,Object> recordNQSAvQ(double cons, double ref, Map<String,Object> attrs) {
attrs.put(NQS_AVQ_KEY, new Float[] {(float)cons, (float)ref} );
return attrs;
}
public static Map<String,Object> recordOffsetFromStart(int median, int mad, Map<String,Object> attrs) {
attrs.put(RSTART_OFFSET_KEY, new Integer[] {median, mad} );
return attrs;
}
public static Map<String,Object> recordOffsetFromEnd(int median, int mad, Map<String,Object> attrs) {
attrs.put(REND_OFFSET_KEY, new Integer[] {median, mad} );
return attrs;
}
}
| true | true | public Integer map(ReferenceContext ref, SAMRecord read, ReadMetaDataTracker metaDataTracker) {
// if ( read.getReadName().equals("428EFAAXX090610:2:36:1384:639#0") ) System.out.println("GOT READ");
if ( DEBUG ) {
// System.out.println("DEBUG>> read at "+ read.getAlignmentStart()+"-"+read.getAlignmentEnd()+
// "("+read.getCigarString()+")");
if ( read.getDuplicateReadFlag() ) System.out.println("DEBUG>> Duplicated read (IGNORED)");
}
if ( AlignmentUtils.isReadUnmapped(read) ||
read.getDuplicateReadFlag() ||
read.getNotPrimaryAlignmentFlag() ||
read.getMappingQuality() == 0 ) {
return 0; // we do not need those reads!
}
if ( read.getReferenceIndex() != currentContigIndex ) {
// we just jumped onto a new contig
if ( DEBUG ) System.out.println("DEBUG>>> Moved to contig "+read.getReferenceName());
if ( read.getReferenceIndex() < currentContigIndex ) // paranoidal
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": contig is out of order; input BAM file is unsorted");
// print remaining indels from the previous contig (if any);
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true);
currentContigIndex = read.getReferenceIndex();
currentPosition = read.getAlignmentStart();
refName = new String(read.getReferenceName());
location = getToolkit().getGenomeLocParser().createGenomeLoc(refName,location.getStart(),location.getStop());
contigLength = getToolkit().getGenomeLocParser().getContigInfo(refName).getSequenceLength();
outOfContigUserWarned = false;
lastGenotypedPosition = -1;
normal_context.clear(); // reset coverage window; this will also set reference position to 0
if ( call_somatic) tumor_context.clear();
refBases = new String(refData.getReference().getSequence(read.getReferenceName()).getBases()).toUpperCase().getBytes();
}
// we have reset the window to the new contig if it was required and emitted everything we collected
// on a previous contig. At this point we are guaranteed that we are set up properly for working
// with the contig of the current read.
// NOTE: all the sanity checks and error messages below use normal_context only. We make sure that normal_context and
// tumor_context are synchronized exactly (windows are always shifted together by emit_somatic), so it's safe
if ( read.getAlignmentStart() < currentPosition ) // oops, read out of order?
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName() +" out of order on the contig\n"+
"Read starts at "+refName+":"+read.getAlignmentStart()+"; last read seen started at "+refName+":"+currentPosition
+"\nLast read was: "+lastRead.getReadName()+" RG="+lastRead.getAttribute("RG")+" at "+lastRead.getAlignmentStart()+"-"
+lastRead.getAlignmentEnd()+" cigar="+lastRead.getCigarString());
currentPosition = read.getAlignmentStart();
lastRead = read;
if ( read.getAlignmentEnd() > contigLength ) {
if ( ! outOfContigUserWarned ) {
System.out.println("WARNING: Reads aligned past contig length on "+ location.getContig()+"; all such reads will be skipped");
outOfContigUserWarned = true;
}
return 0;
}
long alignmentEnd = read.getAlignmentEnd();
Cigar c = read.getCigar();
int lastNonClippedElement = 0; // reverse offset to the last unclipped element
CigarOperator op = null;
// moving backwards from the end of the cigar, skip trailing S or H cigar elements:
do {
lastNonClippedElement++;
op = c.getCigarElement( c.numCigarElements()-lastNonClippedElement ).getOperator();
} while ( op == CigarOperator.H || op == CigarOperator.S );
// now op is the last non-S/H operator in the cigar.
// a little trick here: we want to make sure that current read completely fits into the current
// window so that we can accumulate indel observations over the whole length of the read.
// The ::getAlignmentEnd() method returns the last position on the reference where bases from the
// read actually match (M cigar elements). After our cleaning procedure, we can have reads that end
// with I element, which is not gonna be counted into alignment length on the reference. On the other hand,
// in this program we assign insertions, internally, to the first base *after* the insertion position.
// Hence, we have to make sure that that extra base is already in the window or we will get IndexOutOfBounds.
if ( op == CigarOperator.I) alignmentEnd++;
if ( alignmentEnd > normal_context.getStop()) {
// we don't emit anything until we reach a read that does not fit into the current window.
// At that point we try shifting the window to the start of that read (or reasonably close) and emit everything prior to
// that position. This is legitimate, since the reads are sorted and we are not gonna see any more coverage at positions
// below the current read's start.
// Clearly, we assume here that window is large enough to accomodate any single read, so simply shifting
// the window to around the read's start will ensure that the read fits...
if ( DEBUG) System.out.println("DEBUG>> Window at "+normal_context.getStart()+"-"+normal_context.getStop()+", read at "+
read.getAlignmentStart()+": trying to emit and shift" );
if ( call_somatic ) emit_somatic( read.getAlignmentStart(), false );
else emit( read.getAlignmentStart(), false );
// let's double check now that the read fits after the shift
if ( read.getAlignmentEnd() > normal_context.getStop()) {
// ooops, looks like the read does not fit into the window even after the latter was shifted!!
// we used to die over such reads and require user to run with larger window size. Now we
// just print a warning and discard the read (this means that our counts can be slightly off in
// th epresence of such reads)
//throw new UserException.BadArgumentValue("window_size", "Read "+read.getReadName()+": out of coverage window bounds. Probably window is too small, so increase the value of the window_size argument.\n"+
// "Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
// read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
// "; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
System.out.println("WARNING: Read "+read.getReadName()+
" is out of coverage window bounds. Probably window is too small and the window_size value must be increased.\n"+
" The read is ignored in this run (so all the counts/statistics reported will not include it).\n"+
" Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
"; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
}
}
if ( call_somatic ) {
Tags tags = getToolkit().getReaderIDForRead(read).getTags();
boolean assigned = false;
for ( String s : tags.getPositionalTags() ) {
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal_context.add(read,ref.getBases());
assigned = true;
break;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor_context.add(read,ref.getBases());
assigned = true;
break;
}
}
if ( ! assigned )
throw new StingException("Read "+read.getReadName()+" from "+getToolkit().getSourceFileForReaderID(getToolkit().getReaderIDForRead(read))+
"has no Normal/Tumor tag associated with it");
// String rg = (String)read.getAttribute("RG");
// if ( rg == null )
// throw new UserException.MalformedBam(read, "Read "+read.getReadName()+" has no read group in merged stream. RG is required for somatic calls.");
// if ( normalReadGroups.contains(rg) ) {
// normal_context.add(read,ref.getBases());
// } else if ( tumorReadGroups.contains(rg) ) {
// tumor_context.add(read,ref.getBases());
// } else {
// throw new UserException.MalformedBam(read, "Unrecognized read group in merged stream: "+rg);
// }
if ( tumor_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+tumor_context.getStart()+'-'+tumor_context.getStop()+" in tumor sample. The whole window will be dropped.");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+" in normal sample. The whole window will be dropped");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
} else {
normal_context.add(read, ref.getBases());
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+". The whole window will be dropped");
normal_context.shift(WINDOW_SIZE);
}
}
return 1;
}
| public Integer map(ReferenceContext ref, SAMRecord read, ReadMetaDataTracker metaDataTracker) {
// if ( read.getReadName().equals("428EFAAXX090610:2:36:1384:639#0") ) System.out.println("GOT READ");
if ( DEBUG ) {
// System.out.println("DEBUG>> read at "+ read.getAlignmentStart()+"-"+read.getAlignmentEnd()+
// "("+read.getCigarString()+")");
if ( read.getDuplicateReadFlag() ) System.out.println("DEBUG>> Duplicated read (IGNORED)");
}
if ( AlignmentUtils.isReadUnmapped(read) ||
read.getDuplicateReadFlag() ||
read.getNotPrimaryAlignmentFlag() ||
read.getMappingQuality() == 0 ) {
return 0; // we do not need those reads!
}
if ( read.getReferenceIndex() != currentContigIndex ) {
// we just jumped onto a new contig
if ( DEBUG ) System.out.println("DEBUG>>> Moved to contig "+read.getReferenceName());
if ( read.getReferenceIndex() < currentContigIndex ) // paranoidal
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName()+": contig is out of order; input BAM file is unsorted");
// print remaining indels from the previous contig (if any);
if ( call_somatic ) emit_somatic(1000000000, true);
else emit(1000000000,true);
currentContigIndex = read.getReferenceIndex();
currentPosition = read.getAlignmentStart();
refName = new String(read.getReferenceName());
location = getToolkit().getGenomeLocParser().createGenomeLoc(refName,location.getStart(),location.getStop());
contigLength = getToolkit().getGenomeLocParser().getContigInfo(refName).getSequenceLength();
outOfContigUserWarned = false;
lastGenotypedPosition = -1;
normal_context.clear(); // reset coverage window; this will also set reference position to 0
if ( call_somatic) tumor_context.clear();
refBases = new String(refData.getReference().getSequence(read.getReferenceName()).getBases()).toUpperCase().getBytes();
}
// we have reset the window to the new contig if it was required and emitted everything we collected
// on a previous contig. At this point we are guaranteed that we are set up properly for working
// with the contig of the current read.
// NOTE: all the sanity checks and error messages below use normal_context only. We make sure that normal_context and
// tumor_context are synchronized exactly (windows are always shifted together by emit_somatic), so it's safe
if ( read.getAlignmentStart() < currentPosition ) // oops, read out of order?
throw new UserException.MissortedBAM(SAMFileHeader.SortOrder.coordinate, read, "Read "+read.getReadName() +" out of order on the contig\n"+
"Read starts at "+refName+":"+read.getAlignmentStart()+"; last read seen started at "+refName+":"+currentPosition
+"\nLast read was: "+lastRead.getReadName()+" RG="+lastRead.getAttribute("RG")+" at "+lastRead.getAlignmentStart()+"-"
+lastRead.getAlignmentEnd()+" cigar="+lastRead.getCigarString());
currentPosition = read.getAlignmentStart();
lastRead = read;
if ( read.getAlignmentEnd() > contigLength ) {
if ( ! outOfContigUserWarned ) {
System.out.println("WARNING: Reads aligned past contig length on "+ location.getContig()+"; all such reads will be skipped");
outOfContigUserWarned = true;
}
return 0;
}
long alignmentEnd = read.getAlignmentEnd();
Cigar c = read.getCigar();
int lastNonClippedElement = 0; // reverse offset to the last unclipped element
CigarOperator op = null;
// moving backwards from the end of the cigar, skip trailing S or H cigar elements:
do {
lastNonClippedElement++;
op = c.getCigarElement( c.numCigarElements()-lastNonClippedElement ).getOperator();
} while ( op == CigarOperator.H || op == CigarOperator.S );
// now op is the last non-S/H operator in the cigar.
// a little trick here: we want to make sure that current read completely fits into the current
// window so that we can accumulate indel observations over the whole length of the read.
// The ::getAlignmentEnd() method returns the last position on the reference where bases from the
// read actually match (M cigar elements). After our cleaning procedure, we can have reads that end
// with I element, which is not gonna be counted into alignment length on the reference. On the other hand,
// in this program we assign insertions, internally, to the first base *after* the insertion position.
// Hence, we have to make sure that that extra base is already in the window or we will get IndexOutOfBounds.
if ( op == CigarOperator.I) alignmentEnd++;
if ( alignmentEnd > normal_context.getStop()) {
// we don't emit anything until we reach a read that does not fit into the current window.
// At that point we try shifting the window to the start of that read (or reasonably close) and emit everything prior to
// that position. This is legitimate, since the reads are sorted and we are not gonna see any more coverage at positions
// below the current read's start.
// Clearly, we assume here that window is large enough to accomodate any single read, so simply shifting
// the window to around the read's start will ensure that the read fits...
if ( DEBUG) System.out.println("DEBUG>> Window at "+normal_context.getStart()+"-"+normal_context.getStop()+", read at "+
read.getAlignmentStart()+": trying to emit and shift" );
if ( call_somatic ) emit_somatic( read.getAlignmentStart(), false );
else emit( read.getAlignmentStart(), false );
// let's double check now that the read fits after the shift
if ( read.getAlignmentEnd() > normal_context.getStop()) {
// ooops, looks like the read does not fit into the window even after the latter was shifted!!
// we used to die over such reads and require user to run with larger window size. Now we
// just print a warning and discard the read (this means that our counts can be slightly off in
// th epresence of such reads)
//throw new UserException.BadArgumentValue("window_size", "Read "+read.getReadName()+": out of coverage window bounds. Probably window is too small, so increase the value of the window_size argument.\n"+
// "Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
// read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
// "; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
System.out.println("WARNING: Read "+read.getReadName()+
" is out of coverage window bounds. Probably window is too small and the window_size value must be increased.\n"+
" The read is ignored in this run (so all the counts/statistics reported will not include it).\n"+
" Read length="+read.getReadLength()+"; cigar="+read.getCigarString()+"; start="+
read.getAlignmentStart()+"; end="+read.getAlignmentEnd()+
"; window start (after trying to accomodate the read)="+normal_context.getStart()+"; window end="+normal_context.getStop());
return 1;
}
}
if ( call_somatic ) {
Tags tags = getToolkit().getReaderIDForRead(read).getTags();
boolean assigned = false;
for ( String s : tags.getPositionalTags() ) {
if ( "NORMAL".equals(s.toUpperCase()) ) {
normal_context.add(read,ref.getBases());
assigned = true;
break;
}
if ( "TUMOR".equals(s.toUpperCase()) ) {
tumor_context.add(read,ref.getBases());
assigned = true;
break;
}
}
if ( ! assigned )
throw new StingException("Read "+read.getReadName()+" from "+getToolkit().getSourceFileForReaderID(getToolkit().getReaderIDForRead(read))+
"has no Normal/Tumor tag associated with it");
// String rg = (String)read.getAttribute("RG");
// if ( rg == null )
// throw new UserException.MalformedBam(read, "Read "+read.getReadName()+" has no read group in merged stream. RG is required for somatic calls.");
// if ( normalReadGroups.contains(rg) ) {
// normal_context.add(read,ref.getBases());
// } else if ( tumorReadGroups.contains(rg) ) {
// tumor_context.add(read,ref.getBases());
// } else {
// throw new UserException.MalformedBam(read, "Unrecognized read group in merged stream: "+rg);
// }
if ( tumor_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+tumor_context.getStart()+'-'+tumor_context.getStop()+" in tumor sample. The whole window will be dropped.");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+" in normal sample. The whole window will be dropped");
tumor_context.shift(WINDOW_SIZE);
normal_context.shift(WINDOW_SIZE);
}
} else {
normal_context.add(read, ref.getBases());
if ( normal_context.getReads().size() > MAX_READ_NUMBER ) {
System.out.println("WARNING: a count of "+MAX_READ_NUMBER+" reads reached in a window "+
refName+':'+normal_context.getStart()+'-'+normal_context.getStop()+". The whole window will be dropped");
normal_context.shift(WINDOW_SIZE);
}
}
return 1;
}
|
diff --git a/src/com/android/phone/CallForwardEditPreference.java b/src/com/android/phone/CallForwardEditPreference.java
index bd8dcb54..1301708d 100644
--- a/src/com/android/phone/CallForwardEditPreference.java
+++ b/src/com/android/phone/CallForwardEditPreference.java
@@ -1,199 +1,200 @@
package com.android.phone;
import com.android.internal.telephony.CallForwardInfo;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import static com.android.phone.TimeConsumingPreferenceActivity.EXCEPTION_ERROR;
import static com.android.phone.TimeConsumingPreferenceActivity.RESPONSE_ERROR;
public class CallForwardEditPreference extends EditPhoneNumberPreference {
private static final String LOG_TAG = "CallForwardEditPreference";
private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2);
private static final String SRC_TAGS[] = {"{0}"};
private CharSequence mSummaryOnTemplate;
private int mButtonClicked;
private int mServiceClass;
private MyHandler mHandler = new MyHandler();
int reason;
Phone phone;
CallForwardInfo callForwardInfo;
TimeConsumingPreferenceListener tcpListener;
public CallForwardEditPreference(Context context, AttributeSet attrs) {
super(context, attrs);
phone = PhoneFactory.getDefaultPhone();
mSummaryOnTemplate = this.getSummaryOn();
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.CallForwardEditPreference, 0, R.style.EditPhoneNumberPreference);
mServiceClass = a.getInt(R.styleable.CallForwardEditPreference_serviceClass,
CommandsInterface.SERVICE_CLASS_VOICE);
reason = a.getInt(R.styleable.CallForwardEditPreference_reason,
CommandsInterface.CF_REASON_UNCONDITIONAL);
a.recycle();
if (DBG) Log.d(LOG_TAG, "mServiceClass=" + mServiceClass + ", reason=" + reason);
}
public CallForwardEditPreference(Context context) {
this(context, null);
}
void init(TimeConsumingPreferenceListener listener, boolean skipReading) {
tcpListener = listener;
if (!skipReading) {
phone.getCallForwardingOption(reason,
mHandler.obtainMessage(MyHandler.MESSAGE_GET_CF, reason,
MyHandler.MESSAGE_GET_CF, null));
if (tcpListener != null) {
tcpListener.onStarted(this, true);
}
}
}
@Override
public void onClick(DialogInterface dialog, int which) {
super.onClick(dialog, which);
mButtonClicked = which;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (DBG) Log.d(LOG_TAG, "mButtonClicked=" + mButtonClicked
+ ", positiveResult=" + positiveResult);
if (this.mButtonClicked != DialogInterface.BUTTON_NEGATIVE) {
int action = (isToggled() || (mButtonClicked == DialogInterface.BUTTON_POSITIVE)) ?
CommandsInterface.CF_ACTION_REGISTRATION :
CommandsInterface.CF_ACTION_DISABLE;
int time = (reason != CommandsInterface.CF_REASON_NO_REPLY) ? 0 : 20;
String number = PhoneNumberUtils.stripSeparators(getPhoneNumber());
if (DBG) Log.d(LOG_TAG, "callForwardInfo=" + callForwardInfo);
if (action == CommandsInterface.CF_ACTION_REGISTRATION
&& callForwardInfo != null
+ && callForwardInfo.status == 1
&& number.equals(callForwardInfo.number)) {
// no change, do nothing
if (DBG) Log.d(LOG_TAG, "no change, do nothing");
} else {
// set to network
if (DBG) Log.d(LOG_TAG, "reason=" + reason + ", action=" + action
+ ", number=" + number);
setSummaryOn("");
// the interface of Phone.setCallForwardingOption has error:
// should be action, reason...
phone.setCallForwardingOption(action,
reason,
number,
time,
mHandler.obtainMessage(MyHandler.MESSAGE_SET_CF));
if (tcpListener != null) {
tcpListener.onStarted(this, false);
}
}
}
}
void handleCallForwardResult(CallForwardInfo cf) {
callForwardInfo = cf;
if (DBG) Log.d(LOG_TAG, "handleGetCFResponse done, callForwardInfo=" + callForwardInfo);
CharSequence summaryOn = "";
boolean active = (callForwardInfo.status == 1);
if (active) {
if (callForwardInfo.number != null) {
String values[] = {callForwardInfo.number};
summaryOn = TextUtils.replace(mSummaryOnTemplate, SRC_TAGS, values);
}
setSummaryOn(summaryOn);
}
setToggled(active);
setPhoneNumber(callForwardInfo.number);
}
private class MyHandler extends Handler {
private static final int MESSAGE_GET_CF = 0;
private static final int MESSAGE_SET_CF = 1;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_GET_CF:
handleGetCFResponse(msg);
break;
case MESSAGE_SET_CF:
handleSetCFResponse(msg);
break;
}
}
private void handleGetCFResponse(Message msg) {
if (DBG) Log.d(LOG_TAG, "handleGetCFResponse: done");
if (msg.arg2 == MESSAGE_SET_CF) {
tcpListener.onFinished(CallForwardEditPreference.this, false);
} else {
tcpListener.onFinished(CallForwardEditPreference.this, true);
}
AsyncResult ar = (AsyncResult) msg.obj;
callForwardInfo = null;
if (ar.exception != null) {
if (DBG) Log.d(LOG_TAG, "handleGetCFResponse: ar.exception=" + ar.exception);
setEnabled(false);
tcpListener.onError(CallForwardEditPreference.this, EXCEPTION_ERROR);
} else {
if (ar.userObj instanceof Throwable) {
tcpListener.onError(CallForwardEditPreference.this, RESPONSE_ERROR);
}
CallForwardInfo cfInfoArray[] = (CallForwardInfo[]) ar.result;
if (cfInfoArray.length == 0) {
if (DBG) Log.d(LOG_TAG, "handleGetCFResponse: cfInfoArray.length==0");
setEnabled(false);
tcpListener.onError(CallForwardEditPreference.this, RESPONSE_ERROR);
} else {
for (int i = 0, length = cfInfoArray.length; i < length; i++) {
if (DBG) Log.d(LOG_TAG, "handleGetCFResponse, cfInfoArray[" + i + "]="
+ cfInfoArray[i]);
if ((mServiceClass & cfInfoArray[i].serviceClass) != 0) {
// corresponding class
handleCallForwardResult(cfInfoArray[i]);
}
}
}
}
}
private void handleSetCFResponse(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
if (ar.exception != null) {
if (DBG) Log.d(LOG_TAG, "handleSetCFResponse: ar.exception=" + ar.exception);
// setEnabled(false);
}
if (DBG) Log.d(LOG_TAG, "handleSetCFResponse: re get");
phone.getCallForwardingOption(reason,
obtainMessage(MESSAGE_GET_CF, reason, MESSAGE_SET_CF, ar.exception));
}
}
}
| true | true | protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (DBG) Log.d(LOG_TAG, "mButtonClicked=" + mButtonClicked
+ ", positiveResult=" + positiveResult);
if (this.mButtonClicked != DialogInterface.BUTTON_NEGATIVE) {
int action = (isToggled() || (mButtonClicked == DialogInterface.BUTTON_POSITIVE)) ?
CommandsInterface.CF_ACTION_REGISTRATION :
CommandsInterface.CF_ACTION_DISABLE;
int time = (reason != CommandsInterface.CF_REASON_NO_REPLY) ? 0 : 20;
String number = PhoneNumberUtils.stripSeparators(getPhoneNumber());
if (DBG) Log.d(LOG_TAG, "callForwardInfo=" + callForwardInfo);
if (action == CommandsInterface.CF_ACTION_REGISTRATION
&& callForwardInfo != null
&& number.equals(callForwardInfo.number)) {
// no change, do nothing
if (DBG) Log.d(LOG_TAG, "no change, do nothing");
} else {
// set to network
if (DBG) Log.d(LOG_TAG, "reason=" + reason + ", action=" + action
+ ", number=" + number);
setSummaryOn("");
// the interface of Phone.setCallForwardingOption has error:
// should be action, reason...
phone.setCallForwardingOption(action,
reason,
number,
time,
mHandler.obtainMessage(MyHandler.MESSAGE_SET_CF));
if (tcpListener != null) {
tcpListener.onStarted(this, false);
}
}
}
}
| protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (DBG) Log.d(LOG_TAG, "mButtonClicked=" + mButtonClicked
+ ", positiveResult=" + positiveResult);
if (this.mButtonClicked != DialogInterface.BUTTON_NEGATIVE) {
int action = (isToggled() || (mButtonClicked == DialogInterface.BUTTON_POSITIVE)) ?
CommandsInterface.CF_ACTION_REGISTRATION :
CommandsInterface.CF_ACTION_DISABLE;
int time = (reason != CommandsInterface.CF_REASON_NO_REPLY) ? 0 : 20;
String number = PhoneNumberUtils.stripSeparators(getPhoneNumber());
if (DBG) Log.d(LOG_TAG, "callForwardInfo=" + callForwardInfo);
if (action == CommandsInterface.CF_ACTION_REGISTRATION
&& callForwardInfo != null
&& callForwardInfo.status == 1
&& number.equals(callForwardInfo.number)) {
// no change, do nothing
if (DBG) Log.d(LOG_TAG, "no change, do nothing");
} else {
// set to network
if (DBG) Log.d(LOG_TAG, "reason=" + reason + ", action=" + action
+ ", number=" + number);
setSummaryOn("");
// the interface of Phone.setCallForwardingOption has error:
// should be action, reason...
phone.setCallForwardingOption(action,
reason,
number,
time,
mHandler.obtainMessage(MyHandler.MESSAGE_SET_CF));
if (tcpListener != null) {
tcpListener.onStarted(this, false);
}
}
}
}
|
diff --git a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/impl/components/StandardPropertiesEditionComponent.java b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/impl/components/StandardPropertiesEditionComponent.java
index 380a77521..973e72812 100644
--- a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/impl/components/StandardPropertiesEditionComponent.java
+++ b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/impl/components/StandardPropertiesEditionComponent.java
@@ -1,374 +1,369 @@
/*******************************************************************************
* Copyright (c) 2008, 2012 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.emf.eef.runtime.impl.components;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.change.util.ChangeRecorder;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener;
import org.eclipse.emf.eef.runtime.api.notify.PropertiesEditingSemanticLister;
import org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.context.PropertiesEditingContext;
import org.eclipse.emf.eef.runtime.context.impl.EObjectPropertiesEditionContext;
import org.eclipse.emf.eef.runtime.impl.command.StandardEditingCommand;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesValidationEditionEvent;
import org.eclipse.emf.eef.runtime.impl.utils.StringTools;
/**
* @author <a href="mailto:[email protected]">Goulwen Le Fur</a>
* @author <a href="mailto:[email protected]">Mikaël Barbero</a>
*/
public abstract class StandardPropertiesEditionComponent implements IPropertiesEditionComponent {
private static final long DELAY = 500L;
public static final Object FIRE_PROPERTIES_CHANGED_JOB_FAMILY = new Object();
/**
* List of IPropertiesEditionComponentListeners
*/
private List<IPropertiesEditionListener> listeners;
/**
* the semantic listener dedicated to update view
*/
protected PropertiesEditingSemanticLister semanticAdapter;
/**
* the editing domain where to perform live update
*/
protected EditingDomain liveEditingDomain;
/**
* the job that will fire the property changed event
*/
protected FirePropertiesChangedJob firePropertiesChangedJob;
/**
* Editing context
*/
protected PropertiesEditingContext editingContext;
/**
* the editing mode
*/
protected String editing_mode;
/**
* Is the component is current initializing
*/
protected boolean initializing = false;
/**
* List of {@link IPropertiesEditionPart}'s key managed by the component.
*/
protected String[] parts;
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#initPart(java.lang.Object,
* int, org.eclipse.emf.ecore.EObject)
*/
public void initPart(Object key, int kind, EObject element) {
this.initPart(key, kind, element, editingContext.getResourceSet());
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#partsList()
*/
public String[] partsList() {
return parts;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#addListener(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener)
*/
public void addListener(IPropertiesEditionListener listener) {
if (listeners == null)
listeners = new ArrayList<IPropertiesEditionListener>();
listeners.add(listener);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#removeListener(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener)
*/
public void removeListener(IPropertiesEditionListener listener) {
if (listeners != null)
listeners.remove(listener);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#setLiveEditingDomain(org.eclipse.emf.edit.domain.EditingDomain)
*/
public void setLiveEditingDomain(EditingDomain editingDomain) {
this.liveEditingDomain = editingDomain;
}
/**
* Initialize the semantic model listener for live editing mode
*
* @return the semantic model listener
*/
protected PropertiesEditingSemanticLister initializeSemanticAdapter() {
return new PropertiesEditingSemanticLister(this) {
public void runUpdateRunnable(Notification msg) {
updatePart(msg);
}
};
}
/**
* Update the part in response to a semantic event
*
* @param msg
* the semantic event
*/
public abstract void updatePart(Notification msg);
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*/
private void propagateEvent(IPropertiesEditionEvent event) {
event.addHolder(this);
for (IPropertiesEditionListener listener : listeners) {
if (!event.hold(listener))
listener.firePropertiesChanged(event);
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*/
public void firePropertiesChanged(final IPropertiesEditionEvent event) {
if (!isInitializing() && shouldProcess(event)) {
Diagnostic valueDiagnostic = validateValue(event);
if (valueDiagnostic.getSeverity() != Diagnostic.OK && valueDiagnostic instanceof BasicDiagnostic)
propagateEvent(new PropertiesValidationEditionEvent(event, valueDiagnostic));
else {
editingContext.initializeRecorder();
if (IPropertiesEditionComponent.BATCH_MODE.equals(editing_mode)) {
updateSemanticModel(event);
} else if (IPropertiesEditionComponent.LIVE_MODE.equals(editing_mode)) {
liveEditingDomain.getCommandStack().execute(
new StandardEditingCommand(new EObjectPropertiesEditionContext(editingContext,
this, editingContext.getEObject(), editingContext.getAdapterFactory())) {
public void execute() {
updateSemanticModel(event);
- ChangeRecorder changeRecorder = context.getChangeRecorder();
- if (changeRecorder != null) {
- description = changeRecorder.endRecording();
- changeRecorder.dispose();
- }
}
});
}
Diagnostic validate = validate();
propagateEvent(new PropertiesValidationEditionEvent(event, validate));
}
propagateEvent(event);
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#lazyFirePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*/
public void delayedFirePropertiesChanged(IPropertiesEditionEvent event) {
if (IPropertiesEditionComponent.BATCH_MODE.equals(editing_mode)) {
firePropertiesChanged(event);
} else if (IPropertiesEditionComponent.LIVE_MODE.equals(editing_mode)) {
if (getFirePropertiesChangedJob().cancel()) {
getFirePropertiesChangedJob().setEvent(event);
getFirePropertiesChangedJob().schedule(DELAY);
} else {
try {
getFirePropertiesChangedJob().join();
getFirePropertiesChangedJob().setEvent(event);
getFirePropertiesChangedJob().schedule();
} catch (InterruptedException e) {
getFirePropertiesChangedJob().setEvent(null);
}
}
}
}
protected FirePropertiesChangedJob getFirePropertiesChangedJob() {
if (firePropertiesChangedJob == null) {
firePropertiesChangedJob = new FirePropertiesChangedJob("Fire properties changed...");
}
return firePropertiesChangedJob;
}
protected class FirePropertiesChangedJob extends Job {
private IPropertiesEditionEvent fEvent;
public FirePropertiesChangedJob(String name) {
super(name);
}
@Override
public boolean belongsTo(Object family) {
return family == FIRE_PROPERTIES_CHANGED_JOB_FAMILY;
}
@Override
public boolean shouldSchedule() {
return fEvent != null;
}
@Override
public boolean shouldRun() {
return fEvent != null;
}
@Override
protected void canceling() {
super.canceling();
fEvent = null;
}
public void setEvent(IPropertiesEditionEvent event) {
fEvent = event;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
deactivate();
firePropertiesChanged(fEvent);
activate();
fEvent = null;
return Status.OK_STATUS;
}
}
/**
* @param event
* event to process
* @return <code>true</code> if the event should really launch a command.
* @since 0.9
*/
protected boolean shouldProcess(IPropertiesEditionEvent event) {
return true;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#associatedFeature(Object)
*/
public EStructuralFeature associatedFeature(Object editorKey) {
return null;
}
/**
* Update the model in response to a view event
*
* @param event
* the view event
*/
public abstract void updateSemanticModel(IPropertiesEditionEvent event);
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#mustBeComposed(java.lang.Object,
* int)
*/
public boolean mustBeComposed(Object key, int kind) {
return true;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#isRequired(java.lang.String,
* int)
*/
public boolean isRequired(Object key, int kind) {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#getHelpContent(java.lang.String,
* int)
*/
public String getHelpContent(Object key, int kind) {
return StringTools.EMPTY_STRING;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#translatePart(java.lang.String)
*/
public Object translatePart(String key) {
return null;
}
/**
* @return the initializing
*/
public boolean isInitializing() {
return initializing;
}
/**
* @param initializing
* the initializing to set
*/
public void setInitializing(boolean initializing) {
this.initializing = initializing;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#setPropertiesEditionPart(java.lang.Object,
* int, org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart)
*/
public void setPropertiesEditionPart(Object key, int kind, IPropertiesEditionPart propertiesEditionPart) {
// Default case : nothing to do
}
}
| true | true | public void firePropertiesChanged(final IPropertiesEditionEvent event) {
if (!isInitializing() && shouldProcess(event)) {
Diagnostic valueDiagnostic = validateValue(event);
if (valueDiagnostic.getSeverity() != Diagnostic.OK && valueDiagnostic instanceof BasicDiagnostic)
propagateEvent(new PropertiesValidationEditionEvent(event, valueDiagnostic));
else {
editingContext.initializeRecorder();
if (IPropertiesEditionComponent.BATCH_MODE.equals(editing_mode)) {
updateSemanticModel(event);
} else if (IPropertiesEditionComponent.LIVE_MODE.equals(editing_mode)) {
liveEditingDomain.getCommandStack().execute(
new StandardEditingCommand(new EObjectPropertiesEditionContext(editingContext,
this, editingContext.getEObject(), editingContext.getAdapterFactory())) {
public void execute() {
updateSemanticModel(event);
ChangeRecorder changeRecorder = context.getChangeRecorder();
if (changeRecorder != null) {
description = changeRecorder.endRecording();
changeRecorder.dispose();
}
}
});
}
Diagnostic validate = validate();
propagateEvent(new PropertiesValidationEditionEvent(event, validate));
}
propagateEvent(event);
}
}
| public void firePropertiesChanged(final IPropertiesEditionEvent event) {
if (!isInitializing() && shouldProcess(event)) {
Diagnostic valueDiagnostic = validateValue(event);
if (valueDiagnostic.getSeverity() != Diagnostic.OK && valueDiagnostic instanceof BasicDiagnostic)
propagateEvent(new PropertiesValidationEditionEvent(event, valueDiagnostic));
else {
editingContext.initializeRecorder();
if (IPropertiesEditionComponent.BATCH_MODE.equals(editing_mode)) {
updateSemanticModel(event);
} else if (IPropertiesEditionComponent.LIVE_MODE.equals(editing_mode)) {
liveEditingDomain.getCommandStack().execute(
new StandardEditingCommand(new EObjectPropertiesEditionContext(editingContext,
this, editingContext.getEObject(), editingContext.getAdapterFactory())) {
public void execute() {
updateSemanticModel(event);
}
});
}
Diagnostic validate = validate();
propagateEvent(new PropertiesValidationEditionEvent(event, validate));
}
propagateEvent(event);
}
}
|
diff --git a/src/net/rptools/maptool/model/Token.java b/src/net/rptools/maptool/model/Token.java
index 498eb6c1..4cf4eb12 100644
--- a/src/net/rptools/maptool/model/Token.java
+++ b/src/net/rptools/maptool/model/Token.java
@@ -1,864 +1,865 @@
/* The MIT License
*
* Copyright (c) 2005 David Rice, Trevor Croft
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.rptools.maptool.model;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.ImageIcon;
import antlr.StringUtils;
import net.rptools.lib.MD5Key;
import net.rptools.lib.image.ImageUtil;
import net.rptools.lib.swing.SwingUtil;
import net.rptools.lib.transferable.TokenTransferData;
import net.rptools.maptool.util.ImageManager;
import net.rptools.maptool.util.StringUtil;
/**
* This object represents the placeable objects on a map. For example an icon
* that represents a character would exist as an {@link Asset} (the image
* itself) and a location and scale.
*/
public class Token extends BaseModel {
private GUID id = new GUID();
public static final String NAME_USE_FILENAME = "Use Filename";
public static final String NAME_USE_CREATURE = "Use \"Creature\"";
public static final String NUM_INCREMENT = "Increment";
public static final String NUM_RANDOM = "Random 2-digit";
public static final String NUM_ON_NAME = "Name";
public static final String NUM_ON_GM = "GM Name";
public static final String NUM_ON_BOTH = "Both";
public enum TokenShape {
TOP_DOWN("Top down"),
CIRCLE("Circle"),
SQUARE("Square");
private String displayName;
private TokenShape(String displayName) {
this.displayName = displayName;
}
public String toString() {
return displayName;
}
}
public enum Type {
PC,
NPC
}
public static final Comparator<Token> NAME_COMPARATOR = new Comparator<Token>() {
public int compare(Token o1, Token o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
private MD5Key assetID;
private int x;
private int y;
private int z;
private int lastX;
private int lastY;
private Path lastPath;
private boolean snapToScale = true; // Whether the scaleX and scaleY
// represent snap-to-grid measurements
private int width = 1; // Default to using exactly 1x1 grid cell
private int height = 1;
private int size = TokenSize.Size.Medium.value(); // Abstract size
private boolean snapToGrid = true; // Whether the token snaps to the
// current grid or is free floating
private boolean isVisible = true;
private String name;
private Set<String> ownerList;
private int ownerType;
private static final int OWNER_TYPE_ALL = 1;
private static final int OWNER_TYPE_LIST = 0;
private String tokenType; // TODO: 2.0 => change this to tokenShape
private String tokenMobType; // TODO: 2.0 => change this to tokenType
private String layer;
private String propertyType = Campaign.DEFAULT_TOKEN_PROPERTY_TYPE;
private Integer facing = null;
private Integer haloColorValue;
private transient Color haloColor;
private List<Vision> visionList;
private boolean isFlippedX;
private boolean isFlippedY;
/**
* The notes that are displayed for this token.
*/
private String notes;
private String gmNotes;
private String gmName;
/**
* A state properties for this token. This allows state to be added that can
* change appearance of the token.
*/
private Map<String, Object> state;
/**
* Properties
*/
private Map<String, Object> propertyMap;
private Map<String, String> macroMap;
private Map<String, String> speechMap;
public enum ChangeEvent {
name
}
public Token(Token token) {
id = new GUID();
assetID = token.assetID;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
size = token.size;
facing = token.facing;
tokenType = token.tokenType;
tokenMobType = token.tokenMobType;
+ haloColorValue = token.haloColorValue;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.visionList != null) {
visionList = new ArrayList<Vision>();
visionList.addAll(token.visionList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
}
public Token() {
}
public Token(MD5Key assetID) {
this("", assetID);
}
public Token(String name, MD5Key assetID) {
this.name = name;
this.assetID = assetID;
state = new HashMap<String, Object>();
}
public boolean isMarker() {
return (isStamp() || isBackground()) && (!StringUtil.isEmpty(notes) || !StringUtil.isEmpty(gmNotes));
}
public String getPropertyType() {
return propertyType;
}
public void setPropertyType(String propertyType) {
this.propertyType = propertyType;
}
public String getGMNotes() {
return gmNotes;
}
public void setGMNote(String notes) {
gmNotes = notes;
}
public String getGMName() {
return gmName;
}
public void setGMName(String name) {
gmName = name;
}
public boolean hasHalo() {
return haloColorValue != null;
}
public void setHaloColor(Color color) {
if (color != null) {
haloColorValue = color.getRGB();
} else {
haloColorValue = null;
}
haloColor = color;
}
public Color getHaloColor() {
if (haloColor == null && haloColorValue != null) {
haloColor = new Color(haloColorValue);
}
return haloColor;
}
public boolean isStamp() {
return getLayer() == Zone.Layer.OBJECT;
}
public boolean isBackground() {
return getLayer() == Zone.Layer.BACKGROUND;
}
public boolean isToken() {
return getLayer() == Zone.Layer.TOKEN;
}
public TokenShape getShape() {
try {
return tokenType != null ? TokenShape.valueOf(tokenType) : TokenShape.SQUARE; // TODO: make this a psf
} catch (IllegalArgumentException iae) {
return TokenShape.SQUARE;
}
}
public void setShape(TokenShape type) {
this.tokenType = type.name();
}
public Type getType() {
try {
return tokenMobType != null ? Type.valueOf(tokenMobType) : Type.NPC; // TODO: make this a psf
} catch (IllegalArgumentException iae) {
return Type.NPC;
}
}
public void setType(Type type) {
this.tokenMobType = type.name();
}
public Zone.Layer getLayer() {
try {
return layer != null ? Zone.Layer.valueOf(layer) : Zone.Layer.TOKEN;
} catch (IllegalArgumentException iae) {
return Zone.Layer.TOKEN;
}
}
public void setLayer(Zone.Layer layer) {
this.layer = layer.name();
}
public boolean hasFacing() {
return facing != null;
}
public void setFacing(Integer facing) {
this.facing = facing;
}
public Integer getFacing() {
return facing;
}
public boolean hasVision() {
return visionList != null && visionList.size() > 0;
}
public void addVision(Vision vision) {
if (visionList == null) {
visionList = new ArrayList<Vision>();
}
if (!visionList.contains(vision)) {
visionList.add(vision);
}
}
public void removeVision(Vision vision) {
if (visionList != null) {
visionList.remove(vision);
}
}
public List<Vision> getVisionList() {
return (List<Vision>)(visionList != null ? Collections.unmodifiableList(visionList) : Collections.emptyList());
}
public synchronized void addOwner(String playerId) {
ownerType = OWNER_TYPE_LIST;
if (ownerList == null) {
ownerList = new HashSet<String>();
}
ownerList.add(playerId);
}
public synchronized boolean hasOwners() {
return ownerType == OWNER_TYPE_ALL || (ownerList != null && !ownerList.isEmpty());
}
public synchronized void removeOwner(String playerId) {
ownerType = OWNER_TYPE_LIST;
if (ownerList == null) {
return;
}
ownerList.remove(playerId);
if (ownerList.size() == 0) {
ownerList = null;
}
}
public synchronized void setAllOwners() {
ownerType = OWNER_TYPE_ALL;
ownerList = null;
}
public Set<String> getOwners() {
return ownerList != null ? Collections.unmodifiableSet(ownerList) : new HashSet<String>();
}
public boolean isOwnedByAll() {
return ownerType == OWNER_TYPE_ALL;
}
public synchronized void clearAllOwners() {
ownerList = null;
ownerType = OWNER_TYPE_LIST;
}
public synchronized boolean isOwner(String playerId) {
return /*getType() == Type.PC && */(ownerType == OWNER_TYPE_ALL
|| (ownerList != null && ownerList.contains(playerId)));
}
@Override
public int hashCode() {
return id.hashCode();
}
public boolean equals(Object o) {
if (!(o instanceof Token)) {
return false;
}
return id.equals(((Token) o).id);
}
public void setZOrder(int z) {
this.z = z;
}
public int getZOrder() {
return z;
}
public void setName(String name) {
this.name = name;
fireModelChangeEvent(new ModelChangeEvent(this, ChangeEvent.name, name));
}
public MD5Key getAssetID() {
return assetID;
}
public void setAsset(MD5Key assetID) {
this.assetID = assetID;
}
public GUID getId() {
return id;
}
public void setId(GUID id) {
this.id = id;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
lastX = this.x;
this.x = x;
}
public void setY(int y) {
lastY = this.y;
this.y = y;
}
public void applyMove(int xOffset, int yOffset, Path path) {
setX(x + xOffset);
setY(y + yOffset);
lastPath = path;
}
public void setLastPath(Path path) {
lastPath = path;
}
public int getLastY() {
return lastY;
}
public int getLastX() {
return lastX;
}
public Path getLastPath() {
return lastPath;
}
/**
* @return Returns the scaleX.
*/
public int getWidth() {
return width;
}
/**
* @param scaleX
* The scaleX to set.
*/
public void setWidth(int width) {
this.width = width;
}
/**
* @return Returns the sizeY.
*/
public int getHeight() {
return height;
}
/**
* @param height
* The sizeY to set.
*/
public void setHeight(int height) {
this.height = height;
}
/**
* @return Returns the snapScale.
*/
public boolean isSnapToScale() {
return snapToScale;
}
/**
* @param snapScale
* The snapScale to set.
*/
public void setSnapToScale(boolean snapScale) {
this.snapToScale = snapScale;
}
public void setVisible(boolean visible) {
this.isVisible = visible;
}
public boolean isVisible() {
return isVisible;
}
public String getName() {
return name != null ? name : "";
}
/**
* @return Returns the size.
*/
public int getSize() {
return size;
}
/**
* @param size
* The size to set.
*/
public void setSize(int size) {
this.size = size;
}
public boolean isSnapToGrid() {
return snapToGrid;
}
public void setSnapToGrid(boolean snapToGrid) {
this.snapToGrid = snapToGrid;
}
/**
* Get a particular state property for this Token.
*
* @param property
* The name of the property being read.
* @return Returns the current value of property.
*/
public Object getState(String property) {
return state.get(property);
}
/**
* Set the value of state for this Token.
*
* @param aState
* The property to set.
* @param aValue
* The new value for the property.
* @return The original vaoue of the property, if any.
*/
public Object setState(String aState, Object aValue) {
if (aValue == null)
return state.remove(aState);
return state.put(aState, aValue);
}
public void setProperty(String key, Object value) {
getPropertyMap().put(key, value);
}
public Object getProperty(String key) {
return getPropertyMap().get(key);
}
public Set<String> getPropertyNames() {
return getPropertyMap().keySet();
}
private Map<String, Object> getPropertyMap() {
if (propertyMap == null) {
propertyMap = new HashMap<String, Object>();
}
return propertyMap;
}
public void setMacroMap(Map<String, String> map) {
getMacroMap().clear();
getMacroMap().putAll(map);
}
public Set<String> getMacroNames() {
return getMacroMap().keySet();
}
public String getMacro(String key) {
return getMacroMap().get(key);
}
private Map<String, String> getMacroMap() {
if (macroMap == null) {
macroMap = new HashMap<String, String>();
}
return macroMap;
}
public void setSpeechMap(Map<String, String> map) {
getSpeechMap().clear();
getSpeechMap().putAll(map);
}
public Set<String> getSpeechNames() {
return getSpeechMap().keySet();
}
public String getSpeech(String key) {
return getSpeechMap().get(key);
}
private Map<String, String> getSpeechMap() {
if (speechMap == null) {
speechMap = new HashMap<String, String>();
}
return speechMap;
}
/**
* Get a set containing the names of all set properties on this token.
*
* @return The set of state property names that have a value associated with
* them.
*/
public Set<String> getStatePropertyNames() {
return state.keySet();
}
/** @return Getter for notes */
public String getNotes() {
return notes;
}
/**
* @param aNotes
* Setter for notes
*/
public void setNotes(String aNotes) {
notes = aNotes;
}
public boolean isFlippedY() {
return isFlippedY;
}
public void setFlippedY(boolean isFlippedY) {
this.isFlippedY = isFlippedY;
}
public boolean isFlippedX() {
return isFlippedX;
}
public void setFlippedX(boolean isFlippedX) {
this.isFlippedX = isFlippedX;
}
/**
* Convert the token into a hash map. This is used to ship all of the
* properties for the token to other apps that do need access to the
* <code>Token</code> class.
*
* @return A map containing the properties of the token.
*/
public TokenTransferData toTransferData() {
TokenTransferData td = new TokenTransferData();
td.setName(name);
td.setPlayers(ownerList);
td.setVisible(isVisible);
td.setLocation(new Point(x, y));
td.setFacing(facing);
// Set the properties
td.put(TokenTransferData.ID, id.toString());
td.put(TokenTransferData.ASSET_ID, assetID);
td.put(TokenTransferData.Z, z);
td.put(TokenTransferData.SNAP_TO_SCALE, snapToScale);
td.put(TokenTransferData.WIDTH, width);
td.put(TokenTransferData.HEIGHT, height);
td.put(TokenTransferData.SIZE, size);
td.put(TokenTransferData.SNAP_TO_GRID, snapToGrid);
td.put(TokenTransferData.OWNER_TYPE, ownerType);
td.put(TokenTransferData.TOKEN_TYPE, tokenType);
td.put(TokenTransferData.NOTES, notes);
td.put(TokenTransferData.GM_NOTES, gmNotes);
td.put(TokenTransferData.GM_NAME, gmName);
// Put all of the serializable state into the map
for (String key : getStatePropertyNames()) {
Object value = getState(key);
if (value instanceof Serializable)
td.put(key, value);
} // endfor
td.putAll(state);
// Create the image from the asset and add it to the map
Asset asset = AssetManager.getAsset(assetID);
Image image = ImageManager.getImageAndWait(asset);
if (image != null)
td.setToken(new ImageIcon(image)); // Image icon makes it serializable.
return td;
}
/**
* Constructor to create a new token from a transfer object containing its property
* values. This is used to read in a new token from other apps that don't
* have access to the <code>Token</code> class.
*
* @param td
* Read the values from this transfer object.
*/
public Token(TokenTransferData td) {
if (td.getLocation() != null) {
x = td.getLocation().x;
y = td.getLocation().y;
} // endif
snapToScale = getBoolean(td, TokenTransferData.SNAP_TO_SCALE, true);
width = getInt(td, TokenTransferData.WIDTH, 1);
height = getInt(td, TokenTransferData.HEIGHT, 1);
size = getInt(td, TokenTransferData.SIZE, TokenSize.Size.Medium.value());
snapToGrid = getBoolean(td, TokenTransferData.SNAP_TO_GRID, true);
isVisible = td.isVisible();
name = td.getName();
ownerList = td.getPlayers();
ownerType = getInt(td, TokenTransferData.OWNER_TYPE,
ownerList == null ? OWNER_TYPE_ALL : OWNER_TYPE_LIST);
tokenType = (String) td.get(TokenTransferData.TOKEN_TYPE);
facing = td.getFacing();
notes = (String) td.get(TokenTransferData.NOTES);
gmNotes = (String) td.get(TokenTransferData.GM_NOTES);
gmName = (String) td.get(TokenTransferData.GM_NAME);
// Get the image for the token
ImageIcon icon = td.getToken();
if (icon != null) {
// Make sure there is a buffered image for it
Image image = icon.getImage();
if (!(image instanceof BufferedImage)) {
image = new BufferedImage(icon.getIconWidth(), icon
.getIconHeight(), Transparency.TRANSLUCENT);
Graphics2D g = ((BufferedImage) image).createGraphics();
icon.paintIcon(null, g, 0, 0);
} // endif
// Create the asset
try {
Asset asset = new Asset(name, ImageUtil
.imageToBytes((BufferedImage) image));
if (!AssetManager.hasAsset(asset))
AssetManager.putAsset(asset);
assetID = asset.getId();
} catch (IOException e) {
e.printStackTrace();
} // endtry
} // endtry
// Get all of the non maptool state
state = new HashMap<String, Object>();
for (String key : td.keySet()) {
if (key.startsWith(TokenTransferData.MAPTOOL))
continue;
setState(key, td.get(key));
} // endfor
}
/**
* Get an integer value from the map or return the default value
*
* @param map
* Get the value from this map
* @param propName
* The name of the property being read.
* @param defaultValue
* The value for the property if it is not set in the map.
* @return The value for the passed property
*/
private static int getInt(Map<String, Object> map, String propName,
int defaultValue) {
Integer integer = (Integer) map.get(propName);
if (integer == null)
return defaultValue;
return integer.intValue();
}
/**
* Get a boolean value from the map or return the default value
*
* @param map
* Get the value from this map
* @param propName
* The name of the property being read.
* @param defaultValue
* The value for the property if it is not set in the map.
* @return The value for the passed property
*/
private static boolean getBoolean(Map<String, Object> map, String propName,
boolean defaultValue) {
Boolean bool = (Boolean) map.get(propName);
if (bool == null)
return defaultValue;
return bool.booleanValue();
}
}
| true | true | public Token(Token token) {
id = new GUID();
assetID = token.assetID;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
size = token.size;
facing = token.facing;
tokenType = token.tokenType;
tokenMobType = token.tokenMobType;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.visionList != null) {
visionList = new ArrayList<Vision>();
visionList.addAll(token.visionList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
}
| public Token(Token token) {
id = new GUID();
assetID = token.assetID;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
size = token.size;
facing = token.facing;
tokenType = token.tokenType;
tokenMobType = token.tokenMobType;
haloColorValue = token.haloColorValue;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.visionList != null) {
visionList = new ArrayList<Vision>();
visionList.addAll(token.visionList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
}
|
diff --git a/test/web/org/openmrs/web/controller/user/UserFormControllerTest.java b/test/web/org/openmrs/web/controller/user/UserFormControllerTest.java
index 52f4f54c..bef5287b 100644
--- a/test/web/org/openmrs/web/controller/user/UserFormControllerTest.java
+++ b/test/web/org/openmrs/web/controller/user/UserFormControllerTest.java
@@ -1,48 +1,48 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.user;
import org.junit.Test;
import org.openmrs.PersonName;
import org.openmrs.User;
import org.openmrs.test.Verifies;
import org.openmrs.web.test.BaseWebContextSensitiveTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
/**
* Tests the {@link oldUserFormController} class.
*/
public class UserFormControllerTest extends BaseWebContextSensitiveTest {
/**
* @see {@link UserFormController#handleSubmission(WebRequest,HttpSession,String,String,String,null,User,BindingResult)}
*
*/
@Test
@Verifies(value = "should work for an example", method = "handleSubmission(WebRequest,HttpSession,String,String,String,null,User,BindingResult)")
public void handleSubmission_shouldWorkForAnExample() throws Exception {
UserFormController controller = new UserFormController();
WebRequest request = new ServletWebRequest(new MockHttpServletRequest());
User user = controller.formBackingObject(request, null);
user.addName(new PersonName("This", "is", "Test"));
user.getPerson().setGender("F");
- controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "Save User", "pass123", "pass123", new String[0], user, new BindException(user, "user"));
+ controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "Save User", "pass123", "pass123", new String[0], "true", user, new BindException(user, "user"));
}
}
| true | true | public void handleSubmission_shouldWorkForAnExample() throws Exception {
UserFormController controller = new UserFormController();
WebRequest request = new ServletWebRequest(new MockHttpServletRequest());
User user = controller.formBackingObject(request, null);
user.addName(new PersonName("This", "is", "Test"));
user.getPerson().setGender("F");
controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "Save User", "pass123", "pass123", new String[0], user, new BindException(user, "user"));
}
| public void handleSubmission_shouldWorkForAnExample() throws Exception {
UserFormController controller = new UserFormController();
WebRequest request = new ServletWebRequest(new MockHttpServletRequest());
User user = controller.formBackingObject(request, null);
user.addName(new PersonName("This", "is", "Test"));
user.getPerson().setGender("F");
controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "Save User", "pass123", "pass123", new String[0], "true", user, new BindException(user, "user"));
}
|
diff --git a/jkit/java/stages/TypeChecking.java b/jkit/java/stages/TypeChecking.java
index b9f329c..59f1c44 100644
--- a/jkit/java/stages/TypeChecking.java
+++ b/jkit/java/stages/TypeChecking.java
@@ -1,797 +1,799 @@
package jkit.java.stages;
import java.util.*;
import static jkit.compiler.SyntaxError.*;
import static jkit.jil.util.Types.*;
import jkit.compiler.ClassLoader;
import jkit.compiler.Clazz;
import jkit.java.io.JavaFile;
import jkit.java.tree.Decl;
import jkit.java.tree.Expr;
import jkit.java.tree.Stmt;
import jkit.java.tree.Value;
import jkit.java.tree.Decl.*;
import jkit.java.tree.Expr.*;
import jkit.java.tree.Stmt.*;
import jkit.jil.tree.SourceLocation;
import jkit.jil.tree.Type;
import jkit.jil.util.Types;
import jkit.util.Triple;
/**
* The purpose of this class is to type check the statements and expressions
* within a Java File. The process of propogating type information (i.e. the
* Typing stage) is separated from the process of checking those types. This is
* for two reasons: firstly, it divides the problem into two (simpler)
* subproblems; secondly, it provides for different ways of propagating type
* information (e.e.g type inference).
*
* @author djp
*
*/
public class TypeChecking {
private ClassLoader loader;
private Stack<Decl> enclosingScopes = new Stack<Decl>();
private TypeSystem types;
public TypeChecking(ClassLoader loader, TypeSystem types) {
this.loader = loader;
this.types = types;
}
public void apply(JavaFile file) {
for(Decl d : file.declarations()) {
checkDeclaration(d);
}
}
protected void checkDeclaration(Decl d) {
if(d instanceof JavaInterface) {
checkInterface((JavaInterface)d);
} else if(d instanceof JavaClass) {
checkClass((JavaClass)d);
} else if(d instanceof JavaMethod) {
checkMethod((JavaMethod)d);
} else if(d instanceof JavaField) {
checkField((JavaField)d);
}
}
protected void checkInterface(JavaInterface c) {
enclosingScopes.push(c);
for(Decl d : c.declarations()) {
checkDeclaration(d);
}
enclosingScopes.pop();
}
protected void checkClass(JavaClass c) {
enclosingScopes.push(c);
for(Decl d : c.declarations()) {
checkDeclaration(d);
}
enclosingScopes.pop();
}
protected void checkMethod(JavaMethod d) {
enclosingScopes.push(d);
checkStatement(d.body());
enclosingScopes.pop();
}
protected void checkField(JavaField d) {
checkExpression(d.initialiser());
Type lhs_t = (Type) d.type().attribute(Type.class);
if(d.initialiser() != null) {
Type rhs_t = (Type) d.initialiser().attribute(Type.class);
try {
if (!types.subtype(lhs_t, rhs_t, loader)) {
syntax_error(
"required type " + lhs_t + ", found type " + rhs_t, d);
}
} catch (ClassNotFoundException ex) {
syntax_error(ex.getMessage(), d);
}
}
}
protected void checkStatement(Stmt e) {
if(e instanceof Stmt.SynchronisedBlock) {
checkSynchronisedBlock((Stmt.SynchronisedBlock)e);
} else if(e instanceof Stmt.TryCatchBlock) {
checkTryCatchBlock((Stmt.TryCatchBlock)e);
} else if(e instanceof Stmt.Block) {
checkBlock((Stmt.Block)e);
} else if(e instanceof Stmt.VarDef) {
checkVarDef((Stmt.VarDef) e);
} else if(e instanceof Stmt.AssignmentOp) {
checkAssignmentOp((Stmt.AssignmentOp) e);
} else if(e instanceof Stmt.Assignment) {
checkAssignment((Stmt.Assignment) e);
} else if(e instanceof Stmt.Return) {
checkReturn((Stmt.Return) e);
} else if(e instanceof Stmt.Throw) {
checkThrow((Stmt.Throw) e);
} else if(e instanceof Stmt.Assert) {
checkAssert((Stmt.Assert) e);
} else if(e instanceof Stmt.Break) {
checkBreak((Stmt.Break) e);
} else if(e instanceof Stmt.Continue) {
checkContinue((Stmt.Continue) e);
} else if(e instanceof Stmt.Label) {
checkLabel((Stmt.Label) e);
} else if(e instanceof Stmt.If) {
checkIf((Stmt.If) e);
} else if(e instanceof Stmt.For) {
checkFor((Stmt.For) e);
} else if(e instanceof Stmt.ForEach) {
checkForEach((Stmt.ForEach) e);
} else if(e instanceof Stmt.While) {
checkWhile((Stmt.While) e);
} else if(e instanceof Stmt.DoWhile) {
checkDoWhile((Stmt.DoWhile) e);
} else if(e instanceof Stmt.Switch) {
checkSwitch((Stmt.Switch) e);
} else if(e instanceof Expr.Invoke) {
checkInvoke((Expr.Invoke) e);
} else if(e instanceof Expr.New) {
checkNew((Expr.New) e);
} else if(e instanceof Decl.JavaClass) {
checkClass((Decl.JavaClass)e);
} else if(e instanceof Stmt.PrePostIncDec) {
checkExpression((Stmt.PrePostIncDec)e);
} else if(e != null) {
throw new RuntimeException("Invalid statement encountered: "
+ e.getClass());
}
}
protected void checkBlock(Stmt.Block block) {
if(block != null) {
for(Stmt s : block.statements()) {
checkStatement(s);
}
}
}
protected void checkSynchronisedBlock(Stmt.SynchronisedBlock block) {
checkExpression(block.expr());
checkBlock(block);
Type e_t = (Type) block.expr().attribute(Type.class);
if (!(e_t instanceof Type.Reference)) {
syntax_error("required reference type, found type "
+ e_t, block);
}
}
protected void checkTryCatchBlock(Stmt.TryCatchBlock block) {
checkBlock(block);
checkBlock(block.finaly());
for(Stmt.CatchBlock cb : block.handlers()) {
checkBlock(cb);
try {
if (!types.subtype(Types.JAVA_LANG_THROWABLE,
(Type.Clazz) cb.type().attribute(Type.class), loader)) {
syntax_error(
"required subtype of java.lang.Throwable, found type "
+ cb.type(), cb);
}
} catch (ClassNotFoundException ex) {
syntax_error(ex.getMessage(), block);
}
}
}
protected void checkVarDef(Stmt.VarDef def) {
// Observe that we cannot use the declared type here, rather we have to
// use the resolved type!
Type t = (Type) def.type().attribute(Type.class);
for(Triple<String, Integer, Expr> d : def.definitions()) {
if(d.third() != null) {
checkExpression(d.third());
Type nt = t;
for(int i=0;i!=d.second();++i) {
nt = new Type.Array(nt);
}
Type i_t = (Type) d.third().attribute(Type.class);
try {
if (!types.subtype(nt, i_t, loader)) {
syntax_error("required type " + nt + ", found type " + i_t, def);
}
} catch (ClassNotFoundException ex) {
syntax_error(ex.getMessage(), def);
}
}
}
}
protected void checkAssignment(Stmt.Assignment def) {
checkExpression(def.lhs());
checkExpression(def.rhs());
Type lhs_t = (Type) def.lhs().attribute(Type.class);
Type rhs_t = (Type) def.rhs().attribute(Type.class);
try {
if (!types.subtype(lhs_t, rhs_t, loader)) {
syntax_error(
"required type " + lhs_t + ", found type " + rhs_t, def);
}
} catch (ClassNotFoundException ex) {
syntax_error(ex.getMessage(), def);
}
}
protected void checkAssignmentOp(Stmt.AssignmentOp def) {
checkExpression(def.lhs());
checkExpression(def.rhs());
Type lhs_t = (Type) def.lhs().attribute(Type.class);
Type rhs_t = (Type) def.rhs().attribute(Type.class);
try {
if(def.op() == Expr.BinOp.CONCAT) {
// special case.
if (!types.subtype(Types.JAVA_LANG_STRING,lhs_t, loader)) {
syntax_error(
"required type string, found type " + lhs_t, def);
}
} else if (!types.subtype(lhs_t, rhs_t, loader)) {
syntax_error(
"required type " + lhs_t + ", found type " + rhs_t, def);
}
} catch (ClassNotFoundException ex) {
syntax_error(ex.getMessage(), def);
}
}
protected void checkReturn(Stmt.Return ret) {
JavaMethod method = (JavaMethod) getEnclosingScope(JavaMethod.class);
Type retType = (Type) method.returnType().attribute(Type.class);
if(ret.expr() != null) {
checkExpression(ret.expr());
Type ret_t = (Type) ret.expr().attribute(Type.class);
try {
if(ret_t.equals(new Type.Void())) {
syntax_error(
"cannot return a value from method whose result type is void",
ret);
} else if (!types.subtype(retType, ret_t, loader)) {
syntax_error("required return type " + method.returnType()
+ ", found type " + ret_t, ret);
}
} catch (ClassNotFoundException ex) {
syntax_error(ex.getMessage(), ret);
}
} else if(!(retType instanceof Type.Void)) {
syntax_error("missing return value", ret);
}
}
protected void checkThrow(Stmt.Throw ret) {
checkExpression(ret.expr());
}
protected void checkAssert(Stmt.Assert ret) {
checkExpression(ret.expr());
}
protected void checkBreak(Stmt.Break brk) {
// could check break label exists (if there is one)
}
protected void checkContinue(Stmt.Continue brk) {
// could check continue label exists (if there is one)
}
protected void checkLabel(Stmt.Label lab) {
// do nothing
}
protected void checkIf(Stmt.If stmt) {
checkExpression(stmt.condition());
checkStatement(stmt.trueStatement());
checkStatement(stmt.falseStatement());
if(stmt.condition() != null) {
Type c_t = (Type) stmt.condition().attribute(Type.class);
if(!(c_t instanceof Type.Bool)) {
syntax_error("required type boolean, found " + c_t, stmt);
}
}
}
protected void checkWhile(Stmt.While stmt) {
checkExpression(stmt.condition());
checkStatement(stmt.body());
if(stmt.condition() != null) {
Type c_t = (Type) stmt.condition().attribute(Type.class);
if (!(c_t instanceof Type.Bool)) {
syntax_error("required type boolean, found " + c_t, stmt);
}
}
}
protected void checkDoWhile(Stmt.DoWhile stmt) {
checkExpression(stmt.condition());
checkStatement(stmt.body());
if(stmt.condition() != null) {
Type c_t = (Type) stmt.condition().attribute(Type.class);
if (!(c_t instanceof Type.Bool)) {
syntax_error("required type boolean, found " + c_t, stmt);
}
}
}
protected void checkFor(Stmt.For stmt) {
checkStatement(stmt.initialiser());
checkExpression(stmt.condition());
checkStatement(stmt.increment());
checkStatement(stmt.body());
if(stmt.condition() != null) {
Type c_t = (Type) stmt.condition().attribute(Type.class);
if (!(c_t instanceof Type.Bool)) {
syntax_error("required type boolean, found " + c_t, stmt);
}
}
}
protected void checkForEach(Stmt.ForEach stmt) {
checkExpression(stmt.source());
checkStatement(stmt.body());
// need to check that the static type of the source expression
// implements java.lang.iterable
Type s_t = (Type) stmt.source().attribute(Type.class);
try {
if (!(s_t instanceof Type.Array)
&& !types.subtype(new Type.Clazz("java.lang", "Iterable"),
s_t, loader)) {
syntax_error("foreach not applicable to expression type", stmt);
}
} catch (ClassNotFoundException ex) {
syntax_error(ex.getMessage(), stmt);
}
}
protected void checkSwitch(Stmt.Switch sw) {
checkExpression(sw.condition());
Type condT = (Type) sw.condition().attribute(Type.class);
if(!(condT instanceof Type.Int)) {
syntax_error("found type " + condT + ", required int",sw);
}
for(Case c : sw.cases()) {
checkExpression(c.condition());
for(Stmt s : c.statements()) {
checkStatement(s);
}
}
}
protected void checkExpression(Expr e) {
if(e instanceof Value.Bool) {
checkBoolVal((Value.Bool)e);
} else if(e instanceof Value.Byte) {
checkByteVal((Value.Byte)e);
} else if(e instanceof Value.Char) {
checkCharVal((Value.Char)e);
} else if(e instanceof Value.Int) {
checkIntVal((Value.Int)e);
} else if(e instanceof Value.Short) {
checkShortVal((Value.Short)e);
} else if(e instanceof Value.Long) {
checkLongVal((Value.Long)e);
} else if(e instanceof Value.Float) {
checkFloatVal((Value.Float)e);
} else if(e instanceof Value.Double) {
checkDoubleVal((Value.Double)e);
} else if(e instanceof Value.String) {
checkStringVal((Value.String)e);
} else if(e instanceof Value.Null) {
checkNullVal((Value.Null)e);
} else if(e instanceof Value.TypedArray) {
checkTypedArrayVal((Value.TypedArray)e);
} else if(e instanceof Value.Array) {
checkArrayVal((Value.Array)e);
} else if(e instanceof Value.Class) {
checkClassVal((Value.Class) e);
} else if(e instanceof Expr.LocalVariable) {
checkLocalVariable((Expr.LocalVariable)e);
} else if(e instanceof Expr.NonLocalVariable) {
checkNonLocalVariable((Expr.NonLocalVariable)e);
} else if(e instanceof Expr.ClassVariable) {
checkClassVariable((Expr.ClassVariable)e);
} else if(e instanceof Expr.UnOp) {
checkUnOp((Expr.UnOp)e);
} else if(e instanceof Expr.BinOp) {
checkBinOp((Expr.BinOp)e);
} else if(e instanceof Expr.TernOp) {
checkTernOp((Expr.TernOp)e);
} else if(e instanceof Expr.Cast) {
checkCast((Expr.Cast)e);
} else if(e instanceof Expr.Convert) {
checkConvert((Expr.Convert)e);
} else if(e instanceof Expr.InstanceOf) {
checkInstanceOf((Expr.InstanceOf)e);
} else if(e instanceof Expr.Invoke) {
checkInvoke((Expr.Invoke) e);
} else if(e instanceof Expr.New) {
checkNew((Expr.New) e);
} else if(e instanceof Expr.ArrayIndex) {
checkArrayIndex((Expr.ArrayIndex) e);
} else if(e instanceof Expr.Deref) {
checkDeref((Expr.Deref) e);
} else if(e instanceof Stmt.Assignment) {
checkAssignment((Stmt.Assignment) e);
} else if(e != null) {
throw new RuntimeException("Invalid expression encountered: "
+ e.getClass());
}
}
protected void checkDeref(Expr.Deref e) {
checkExpression(e.target());
// here, we need to check that the field in question actually exists!
}
protected void checkArrayIndex(Expr.ArrayIndex e) {
checkExpression(e.index());
checkExpression(e.target());
Type i_t = (Type) e.index().attribute(Type.class);
if(!(i_t instanceof Type.Int)) {
syntax_error("required type int, found type " + i_t, e);
}
Type t_t = (Type) e.target().attribute(Type.class);
if(!(t_t instanceof Type.Array)) {
syntax_error("array required, but " + t_t + " found", e);
}
}
protected void checkNew(Expr.New e) {
checkExpression(e.context());
for(Decl d : e.declarations()) {
checkDeclaration(d);
}
}
protected void checkInvoke(Expr.Invoke e) {
for(Expr p : e.parameters()) {
checkExpression(p);
}
}
protected void checkInstanceOf(Expr.InstanceOf e) {
checkExpression(e.lhs());
Type lhs_t = (Type) e.lhs().attribute(Type.class);
Type rhs_t = (Type) e.rhs().attribute(Type.class);
try {
if(lhs_t instanceof Type.Primitive) {
syntax_error("required reference type, found " + lhs_t , e);
} else if(!(rhs_t instanceof Type.Reference)) {
syntax_error("required class or array type, found " + rhs_t , e);
} else if((lhs_t instanceof Type.Array || rhs_t instanceof Type.Array)
&& !(types.subtype(lhs_t,rhs_t,loader))) {
syntax_error("inconvertible types: " + lhs_t + ", " + rhs_t, e);
}
} catch(ClassNotFoundException cne) {
syntax_error("type error",e,cne);
}
}
protected void checkCast(Expr.Cast e) {
Type e_t = (Type) e.expr().attribute(Type.class);
Type c_t = (Type) e.type().attribute(Type.class);
try {
if(e_t instanceof Type.Clazz && c_t instanceof Type.Clazz) {
Clazz c_c = loader.loadClass((Type.Clazz) c_t);
Clazz e_c = loader.loadClass((Type.Clazz) e_t);
// the trick here, is that javac will never reject a cast
// between an interface and a class or interface. However, if we
// have a cast from one class to another class, then it will
// reject this if neither is a subclass of the other.
if(c_c.isInterface() || e_c.isInterface()) {
// cast cannot fail here.
return;
}
}
if (types.boxSubtype(c_t, e_t, loader)
|| types.boxSubtype(e_t, c_t, loader)) {
// this is OK
return;
} else if (c_t instanceof Type.Primitive
&& e_t instanceof Type.Primitive) {
if (e_t instanceof Type.Char
&& (c_t instanceof Type.Byte || c_t instanceof Type.Short)) {
return;
} else if (c_t instanceof Type.Char
&& (e_t instanceof Type.Byte || e_t instanceof Type.Short)) {
return;
}
}
syntax_error("inconvertible types: " + e_t + ", " + c_t, e);
} catch(ClassNotFoundException ex) {
syntax_error (ex.getMessage(),e);
}
}
protected void checkConvert(Expr.Convert e) {
Type rhs_t = (Type) e.expr().attribute(Type.class);
Type c_t = (Type) e.type().attribute(Type.class);
SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class);
try {
if(!types.subtype(c_t,rhs_t, loader)) {
if(rhs_t instanceof Type.Primitive) {
syntax_error("possible loss of precision (" + rhs_t + "=>" + c_t+")",e);
} else {
syntax_error("incompatible types",e);
}
}
} catch(ClassNotFoundException ex) {
syntax_error (ex.getMessage(),e);
}
}
protected void checkBoolVal(Value.Bool e) {
// do nothing!
}
protected void checkByteVal(Value.Byte e) {
// do nothing!
}
protected void checkCharVal(Value.Char e) {
// do nothing!
}
protected void checkShortVal(Value.Short e) {
// do nothing!
}
protected void checkIntVal(Value.Int e) {
// do nothing!
}
protected void checkLongVal(Value.Long e) {
// do nothing!
}
protected void checkFloatVal(Value.Float e) {
// do nothing!
}
protected void checkDoubleVal(Value.Double e) {
// do nothing!
}
protected void checkStringVal(Value.String e) {
// do nothing!
}
protected void checkNullVal(Value.Null e) {
// do nothing!
}
protected void checkTypedArrayVal(Value.TypedArray e) {
for(Expr v : e.values()) {
checkExpression(v);
}
}
protected void checkArrayVal(Value.Array e) {
for(Expr v : e.values()) {
checkExpression(v);
}
}
protected void checkClassVal(Value.Class e) {
// do nothing!
}
protected void checkLocalVariable(Expr.LocalVariable e) {
// do nothing!
}
protected void checkNonLocalVariable(Expr.NonLocalVariable e) {
// do nothing!
}
protected void checkClassVariable(Expr.ClassVariable e) {
// do nothing!
}
protected void checkUnOp(Expr.UnOp uop) {
checkExpression(uop.expr());
Type e_t = (Type) uop.expr().attribute(Type.class);
switch(uop.op()) {
case UnOp.NEG:
if (!(e_t instanceof Type.Byte
|| e_t instanceof Type.Char
|| e_t instanceof Type.Short
|| e_t instanceof Type.Int
|| e_t instanceof Type.Long
|| e_t instanceof Type.Float
|| e_t instanceof Type.Double)) {
syntax_error("cannot negate type " + e_t, uop);
}
break;
case UnOp.NOT:
if (!(e_t instanceof Type.Bool)) {
syntax_error("required type boolean, found " + e_t, uop);
}
break;
case UnOp.INV:
if (!(e_t instanceof Type.Byte
|| e_t instanceof Type.Char
|| e_t instanceof Type.Short
|| e_t instanceof Type.Int
|| e_t instanceof Type.Long)) {
syntax_error("cannot invert type " + e_t, uop);
}
break;
}
}
protected void checkBinOp(Expr.BinOp e) {
checkExpression(e.lhs());
checkExpression(e.rhs());
Type lhs_t = (Type) e.lhs().attribute(Type.class);
Type rhs_t = (Type) e.rhs().attribute(Type.class);
Type e_t = (Type) e.attribute(Type.class);
SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class);
if ((lhs_t instanceof Type.Primitive || rhs_t instanceof Type.Primitive)
&& !lhs_t.equals(rhs_t)) {
if ((lhs_t instanceof Type.Long
|| lhs_t instanceof Type.Int
|| lhs_t instanceof Type.Short
|| lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte)
&& rhs_t instanceof Type.Int
&& (e.op() == BinOp.SHL || e.op() == BinOp.SHR || e.op() == BinOp.USHR)) {
return; // Ok!
} else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == BinOp.CONCAT) {
return; // OK
}
} else if((lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte
|| lhs_t instanceof Type.Int || lhs_t instanceof Type.Long
|| lhs_t instanceof Type.Short || lhs_t instanceof Type.Float
|| lhs_t instanceof Type.Double) &&
(rhs_t instanceof Type.Char || rhs_t instanceof Type.Byte
|| rhs_t instanceof Type.Int || rhs_t instanceof Type.Long
|| rhs_t instanceof Type.Short || rhs_t instanceof Type.Float
|| rhs_t instanceof Type.Double)) {
switch(e.op()) {
// easy cases first
case BinOp.EQ:
case BinOp.NEQ:
case BinOp.LT:
case BinOp.LTEQ:
case BinOp.GT:
case BinOp.GTEQ:
// need more checks here
if(!(e_t instanceof Type.Bool)) {
syntax_error("required type boolean, found "
+ rhs_t,e);
}
return;
case BinOp.ADD:
case BinOp.SUB:
case BinOp.MUL:
case BinOp.DIV:
case BinOp.MOD:
{
// hmmmm ?
return;
}
case BinOp.SHL:
case BinOp.SHR:
case BinOp.USHR:
{
// bit-shift operations always take an int as their rhs, so
// make sure we have an int type
if (lhs_t instanceof Type.Float
|| lhs_t instanceof Type.Double) {
syntax_error("Invalid operation on type "
+ lhs_t, e);
} else if (!(rhs_t instanceof Type.Int)) {
syntax_error("Invalid operation on type "
+ rhs_t, e);
}
return;
}
case BinOp.AND:
case BinOp.OR:
case BinOp.XOR:
{
if (rhs_t instanceof Type.Float || rhs_t instanceof Type.Double) {
syntax_error("Invalid operation on type " + rhs_t, e);
}
return;
}
}
} else if(lhs_t instanceof Type.Bool && rhs_t instanceof Type.Bool) {
switch(e.op()) {
case BinOp.LOR:
case BinOp.LAND:
case BinOp.AND:
case BinOp.OR:
case BinOp.XOR:
+ case BinOp.EQ:
+ case BinOp.NEQ:
return; // OK
}
} else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == Expr.BinOp.CONCAT) {
return; // OK
} else if (lhs_t instanceof Type.Reference
&& rhs_t instanceof Type.Reference
&& (e.op() == Expr.BinOp.EQ || e.op() == Expr.BinOp.NEQ)) {
return;
}
syntax_error("operand types do not go together: " + lhs_t + ", " + rhs_t,e);
}
protected void checkTernOp(Expr.TernOp e) {
checkExpression(e.condition());
checkExpression(e.trueBranch());
checkExpression(e.falseBranch());
Type c_t = (Type) e.condition().attribute(Type.class);
if (!(c_t instanceof Type.Bool)) {
syntax_error("required type boolean, found " + c_t, e);
}
}
protected Decl getEnclosingScope(Class c) {
for(int i=enclosingScopes.size()-1;i>=0;--i) {
Decl d = enclosingScopes.get(i);
if(c.isInstance(d)) {
return d;
}
}
return null;
}
}
| true | true | protected void checkBinOp(Expr.BinOp e) {
checkExpression(e.lhs());
checkExpression(e.rhs());
Type lhs_t = (Type) e.lhs().attribute(Type.class);
Type rhs_t = (Type) e.rhs().attribute(Type.class);
Type e_t = (Type) e.attribute(Type.class);
SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class);
if ((lhs_t instanceof Type.Primitive || rhs_t instanceof Type.Primitive)
&& !lhs_t.equals(rhs_t)) {
if ((lhs_t instanceof Type.Long
|| lhs_t instanceof Type.Int
|| lhs_t instanceof Type.Short
|| lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte)
&& rhs_t instanceof Type.Int
&& (e.op() == BinOp.SHL || e.op() == BinOp.SHR || e.op() == BinOp.USHR)) {
return; // Ok!
} else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == BinOp.CONCAT) {
return; // OK
}
} else if((lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte
|| lhs_t instanceof Type.Int || lhs_t instanceof Type.Long
|| lhs_t instanceof Type.Short || lhs_t instanceof Type.Float
|| lhs_t instanceof Type.Double) &&
(rhs_t instanceof Type.Char || rhs_t instanceof Type.Byte
|| rhs_t instanceof Type.Int || rhs_t instanceof Type.Long
|| rhs_t instanceof Type.Short || rhs_t instanceof Type.Float
|| rhs_t instanceof Type.Double)) {
switch(e.op()) {
// easy cases first
case BinOp.EQ:
case BinOp.NEQ:
case BinOp.LT:
case BinOp.LTEQ:
case BinOp.GT:
case BinOp.GTEQ:
// need more checks here
if(!(e_t instanceof Type.Bool)) {
syntax_error("required type boolean, found "
+ rhs_t,e);
}
return;
case BinOp.ADD:
case BinOp.SUB:
case BinOp.MUL:
case BinOp.DIV:
case BinOp.MOD:
{
// hmmmm ?
return;
}
case BinOp.SHL:
case BinOp.SHR:
case BinOp.USHR:
{
// bit-shift operations always take an int as their rhs, so
// make sure we have an int type
if (lhs_t instanceof Type.Float
|| lhs_t instanceof Type.Double) {
syntax_error("Invalid operation on type "
+ lhs_t, e);
} else if (!(rhs_t instanceof Type.Int)) {
syntax_error("Invalid operation on type "
+ rhs_t, e);
}
return;
}
case BinOp.AND:
case BinOp.OR:
case BinOp.XOR:
{
if (rhs_t instanceof Type.Float || rhs_t instanceof Type.Double) {
syntax_error("Invalid operation on type " + rhs_t, e);
}
return;
}
}
} else if(lhs_t instanceof Type.Bool && rhs_t instanceof Type.Bool) {
switch(e.op()) {
case BinOp.LOR:
case BinOp.LAND:
case BinOp.AND:
case BinOp.OR:
case BinOp.XOR:
return; // OK
}
} else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == Expr.BinOp.CONCAT) {
return; // OK
} else if (lhs_t instanceof Type.Reference
&& rhs_t instanceof Type.Reference
&& (e.op() == Expr.BinOp.EQ || e.op() == Expr.BinOp.NEQ)) {
return;
}
syntax_error("operand types do not go together: " + lhs_t + ", " + rhs_t,e);
}
| protected void checkBinOp(Expr.BinOp e) {
checkExpression(e.lhs());
checkExpression(e.rhs());
Type lhs_t = (Type) e.lhs().attribute(Type.class);
Type rhs_t = (Type) e.rhs().attribute(Type.class);
Type e_t = (Type) e.attribute(Type.class);
SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class);
if ((lhs_t instanceof Type.Primitive || rhs_t instanceof Type.Primitive)
&& !lhs_t.equals(rhs_t)) {
if ((lhs_t instanceof Type.Long
|| lhs_t instanceof Type.Int
|| lhs_t instanceof Type.Short
|| lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte)
&& rhs_t instanceof Type.Int
&& (e.op() == BinOp.SHL || e.op() == BinOp.SHR || e.op() == BinOp.USHR)) {
return; // Ok!
} else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == BinOp.CONCAT) {
return; // OK
}
} else if((lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte
|| lhs_t instanceof Type.Int || lhs_t instanceof Type.Long
|| lhs_t instanceof Type.Short || lhs_t instanceof Type.Float
|| lhs_t instanceof Type.Double) &&
(rhs_t instanceof Type.Char || rhs_t instanceof Type.Byte
|| rhs_t instanceof Type.Int || rhs_t instanceof Type.Long
|| rhs_t instanceof Type.Short || rhs_t instanceof Type.Float
|| rhs_t instanceof Type.Double)) {
switch(e.op()) {
// easy cases first
case BinOp.EQ:
case BinOp.NEQ:
case BinOp.LT:
case BinOp.LTEQ:
case BinOp.GT:
case BinOp.GTEQ:
// need more checks here
if(!(e_t instanceof Type.Bool)) {
syntax_error("required type boolean, found "
+ rhs_t,e);
}
return;
case BinOp.ADD:
case BinOp.SUB:
case BinOp.MUL:
case BinOp.DIV:
case BinOp.MOD:
{
// hmmmm ?
return;
}
case BinOp.SHL:
case BinOp.SHR:
case BinOp.USHR:
{
// bit-shift operations always take an int as their rhs, so
// make sure we have an int type
if (lhs_t instanceof Type.Float
|| lhs_t instanceof Type.Double) {
syntax_error("Invalid operation on type "
+ lhs_t, e);
} else if (!(rhs_t instanceof Type.Int)) {
syntax_error("Invalid operation on type "
+ rhs_t, e);
}
return;
}
case BinOp.AND:
case BinOp.OR:
case BinOp.XOR:
{
if (rhs_t instanceof Type.Float || rhs_t instanceof Type.Double) {
syntax_error("Invalid operation on type " + rhs_t, e);
}
return;
}
}
} else if(lhs_t instanceof Type.Bool && rhs_t instanceof Type.Bool) {
switch(e.op()) {
case BinOp.LOR:
case BinOp.LAND:
case BinOp.AND:
case BinOp.OR:
case BinOp.XOR:
case BinOp.EQ:
case BinOp.NEQ:
return; // OK
}
} else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == Expr.BinOp.CONCAT) {
return; // OK
} else if (lhs_t instanceof Type.Reference
&& rhs_t instanceof Type.Reference
&& (e.op() == Expr.BinOp.EQ || e.op() == Expr.BinOp.NEQ)) {
return;
}
syntax_error("operand types do not go together: " + lhs_t + ", " + rhs_t,e);
}
|
diff --git a/src/main/java/com/stationmillenium/coverart/web/gwt/player/client/activities/PlayerActivity.java b/src/main/java/com/stationmillenium/coverart/web/gwt/player/client/activities/PlayerActivity.java
index 0193bd3..8d91feb 100644
--- a/src/main/java/com/stationmillenium/coverart/web/gwt/player/client/activities/PlayerActivity.java
+++ b/src/main/java/com/stationmillenium/coverart/web/gwt/player/client/activities/PlayerActivity.java
@@ -1,175 +1,180 @@
/**
*
*/
package com.stationmillenium.coverart.web.gwt.player.client.activities;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.safehtml.shared.SafeUri;
import com.google.gwt.safehtml.shared.UriUtils;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.stationmillenium.coverart.web.gwt.player.client.clientfactory.ClientFactory;
import com.stationmillenium.coverart.web.gwt.player.client.events.UpdateHistoryListEvent;
import com.stationmillenium.coverart.web.gwt.player.client.view.PlayerViewInterface;
import com.stationmillenium.coverart.web.gwt.player.client.view.PlayerViewInterface.PlayerViewPresenter;
import com.stationmillenium.coverart.web.gwt.player.shared.SongGWTDTO;
/**
* Player GWT module main activity
* @author vincent
*
*/
public class PlayerActivity extends AbstractActivity implements PlayerViewPresenter {
private ClientFactory clientFactory;
//local instances
private SongGWTDTO currentSong;
private boolean inError = false;
/**
* Instanciate new activity
* @param clientFactory client factory
*/
public PlayerActivity(ClientFactory clientFactory) {
this.clientFactory = clientFactory;
Window.setTitle(clientFactory.getConstants().getWindowTitle());
}
/* (non-Javadoc)
* @see com.google.gwt.activity.shared.Activity#start(com.google.gwt.user.client.ui.AcceptsOneWidget, com.google.gwt.event.shared.EventBus)
*/
@Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
PlayerViewInterface view = clientFactory.getPlayerView();
view.setPresenter(this);
panel.setWidget(view);
}
@Override
public void updatePlayer() {
//load current song
clientFactory.getService().getLastSong(new AsyncCallback<SongGWTDTO>() {
@Override
public void onSuccess(SongGWTDTO newSong) {
if ((newSong != null) && (newSong.getArtist() != null) && (newSong.getTitle() != null)) { //if some song provided
if (!newSong.equals(currentSong)) {
//set up image and text
String text = clientFactory.getMessages().currentSongText(newSong.getArtist(), newSong.getTitle());
clientFactory.getPlayerView().setCurrentSong(SafeHtmlUtils.fromString(text));
if (newSong.getImagePath() != null) {
SafeUri imageUri = UriUtils.fromString(GWT.getHostPageBaseURL() + newSong.getImagePath());
clientFactory.getPlayerView().setImage(imageUri, newSong.getImageWidth(), newSong.getImageHeight());
+ } else {
+ clientFactory.getPlayerView().setImage(
+ clientFactory.getResources().logoMillenium().getSafeUri(),
+ String.valueOf(clientFactory.getResources().logoMillenium().getWidth()),
+ String.valueOf(clientFactory.getResources().logoMillenium().getHeight()));
}
//finish update
currentSong = newSong;
inError = false;
clientFactory.getEventBus().fireEvent(new UpdateHistoryListEvent()); //fire update history list event
GWT.log("Player updated : " + newSong);
} else
GWT.log("Player already up-to-date");
} else {
GWT.log("Player updated : null");
displayErrorSong();
}
}
@Override
public void onFailure(Throwable caught) { //in case of error
GWT.log("Error during player update", caught);
displayErrorSong();
}
});
}
@Override
public void updateHistoryList(boolean displayLastSong) {
//load songs history list
clientFactory.getService().getLast5PreviousSongs(displayLastSong, new AsyncCallback<List<SongGWTDTO>>() {
@Override
public void onSuccess(List<SongGWTDTO> result) {
//fill in song history list
List<String> historyList = new ArrayList<String>();
for (SongGWTDTO song : result) { // for each song to add
if ((song != null) && (song.getArtist() != null) && (song.getTitle() != null)) { //if some data
String text = clientFactory.getMessages().currentSongText(song.getArtist(), song.getTitle()); //format text
historyList.add(text); //add text
GWT.log("Added to history list : " + text);
}
}
//update list
clientFactory.getPlayerView().setSongHistoryList(historyList);
}
@Override
public void onFailure(Throwable caught) {
GWT.log("Error during songs history loading", caught);
}
});
}
/**
* Display "unavailable" song
*/
private void displayErrorSong() {
//update player
String text = clientFactory.getConstants().songUnaivalaible();
clientFactory.getPlayerView().setCurrentSong(SafeHtmlUtils.fromString(text));
clientFactory.getPlayerView().setImage(
clientFactory.getResources().logoMillenium().getSafeUri(),
String.valueOf(clientFactory.getResources().logoMillenium().getWidth()),
String.valueOf(clientFactory.getResources().logoMillenium().getHeight()));
if (!inError) {
//update history list
UpdateHistoryListEvent event = new UpdateHistoryListEvent();
event.setDisplayLastSong(true);
clientFactory.getEventBus().fireEvent(event); //fire update history list event for init
inError = true;
}
}
/**
* Manage song history
* @param text text to add
*/
// private void manageSongHistory(String text) {
// //manage history
// if ((historyList.size() > 0) && (historyList.get(0) != null)) { //if some entry
// if (!historyList.contains(text)) { //if not already
// historyList.add(0, text);
// GWT.log("Added to history list : " + text);
// } else
// GWT.log("Already existing in history list : " + text);
//
// } else { //if no entry, add it
// historyList.add(text);
// GWT.log("Added to history list : " + text);
// }
//
// //manage hisotry length
// if (historyList.size() > 5) { //no more than 5 history items
// historyList.remove(5);
// }
//
// //update list
// clientFactory.getPlayerView().setSongHistoryList(historyList);
// }
}
| true | true | public void updatePlayer() {
//load current song
clientFactory.getService().getLastSong(new AsyncCallback<SongGWTDTO>() {
@Override
public void onSuccess(SongGWTDTO newSong) {
if ((newSong != null) && (newSong.getArtist() != null) && (newSong.getTitle() != null)) { //if some song provided
if (!newSong.equals(currentSong)) {
//set up image and text
String text = clientFactory.getMessages().currentSongText(newSong.getArtist(), newSong.getTitle());
clientFactory.getPlayerView().setCurrentSong(SafeHtmlUtils.fromString(text));
if (newSong.getImagePath() != null) {
SafeUri imageUri = UriUtils.fromString(GWT.getHostPageBaseURL() + newSong.getImagePath());
clientFactory.getPlayerView().setImage(imageUri, newSong.getImageWidth(), newSong.getImageHeight());
}
//finish update
currentSong = newSong;
inError = false;
clientFactory.getEventBus().fireEvent(new UpdateHistoryListEvent()); //fire update history list event
GWT.log("Player updated : " + newSong);
} else
GWT.log("Player already up-to-date");
} else {
GWT.log("Player updated : null");
displayErrorSong();
}
}
@Override
public void onFailure(Throwable caught) { //in case of error
GWT.log("Error during player update", caught);
displayErrorSong();
}
});
}
| public void updatePlayer() {
//load current song
clientFactory.getService().getLastSong(new AsyncCallback<SongGWTDTO>() {
@Override
public void onSuccess(SongGWTDTO newSong) {
if ((newSong != null) && (newSong.getArtist() != null) && (newSong.getTitle() != null)) { //if some song provided
if (!newSong.equals(currentSong)) {
//set up image and text
String text = clientFactory.getMessages().currentSongText(newSong.getArtist(), newSong.getTitle());
clientFactory.getPlayerView().setCurrentSong(SafeHtmlUtils.fromString(text));
if (newSong.getImagePath() != null) {
SafeUri imageUri = UriUtils.fromString(GWT.getHostPageBaseURL() + newSong.getImagePath());
clientFactory.getPlayerView().setImage(imageUri, newSong.getImageWidth(), newSong.getImageHeight());
} else {
clientFactory.getPlayerView().setImage(
clientFactory.getResources().logoMillenium().getSafeUri(),
String.valueOf(clientFactory.getResources().logoMillenium().getWidth()),
String.valueOf(clientFactory.getResources().logoMillenium().getHeight()));
}
//finish update
currentSong = newSong;
inError = false;
clientFactory.getEventBus().fireEvent(new UpdateHistoryListEvent()); //fire update history list event
GWT.log("Player updated : " + newSong);
} else
GWT.log("Player already up-to-date");
} else {
GWT.log("Player updated : null");
displayErrorSong();
}
}
@Override
public void onFailure(Throwable caught) { //in case of error
GWT.log("Error during player update", caught);
displayErrorSong();
}
});
}
|
diff --git a/engine/src/test/jme3test/bullet/BombControl.java b/engine/src/test/jme3test/bullet/BombControl.java
index 4438382b4..29d49c481 100644
--- a/engine/src/test/jme3test/bullet/BombControl.java
+++ b/engine/src/test/jme3test/bullet/BombControl.java
@@ -1,190 +1,189 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jme3test.bullet;
import com.jme3.asset.AssetManager;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.PhysicsTickListener;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.collision.shapes.SphereCollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.objects.PhysicsGhostObject;
import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.effect.ParticleEmitter;
import com.jme3.effect.ParticleMesh.Type;
import com.jme3.effect.shapes.EmitterSphereShape;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import java.io.IOException;
import java.util.Iterator;
/**
*
* @author normenhansen
*/
public class BombControl extends RigidBodyControl implements PhysicsCollisionListener, PhysicsTickListener {
private float explosionRadius = 10;
private PhysicsGhostObject ghostObject;
private Vector3f vector = new Vector3f();
private Vector3f vector2 = new Vector3f();
private float forceFactor = 1;
private ParticleEmitter effect;
private float fxTime = 0.5f;
private float maxTime = 4f;
private float curTime = -1.0f;
private float timer;
public BombControl(CollisionShape shape, float mass) {
super(shape, mass);
createGhostObject();
}
public BombControl(AssetManager manager, CollisionShape shape, float mass) {
super(shape, mass);
createGhostObject();
prepareEffect(manager);
}
public void setPhysicsSpace(PhysicsSpace space) {
super.setPhysicsSpace(space);
if (space != null) {
space.addCollisionListener(this);
}
}
private void prepareEffect(AssetManager assetManager) {
int COUNT_FACTOR = 1;
float COUNT_FACTOR_F = 1f;
effect = new ParticleEmitter("Flame", Type.Triangle, 32 * COUNT_FACTOR);
effect.setSelectRandomImage(true);
effect.setStartColor(new ColorRGBA(1f, 0.4f, 0.05f, (float) (1f / COUNT_FACTOR_F)));
effect.setEndColor(new ColorRGBA(.4f, .22f, .12f, 0f));
effect.setStartSize(1.3f);
effect.setEndSize(2f);
effect.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
effect.setParticlesPerSec(0);
effect.setGravity(0, -5f, 0);
effect.setLowLife(.4f);
effect.setHighLife(.5f);
effect.setInitialVelocity(new Vector3f(0, 7, 0));
effect.setVelocityVariation(1f);
effect.setImagesX(2);
effect.setImagesY(2);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png"));
effect.setMaterial(mat);
- effect.setLocalScale(100);
}
protected void createGhostObject() {
ghostObject = new PhysicsGhostObject(new SphereCollisionShape(explosionRadius));
}
public void collision(PhysicsCollisionEvent event) {
if (space == null) {
return;
}
if (event.getObjectA() == this || event.getObjectB() == this) {
space.add(ghostObject);
ghostObject.setPhysicsLocation(getPhysicsLocation(vector));
space.addTickListener(this);
if (effect != null && spatial.getParent() != null) {
curTime = 0;
effect.setLocalTranslation(spatial.getLocalTranslation());
spatial.getParent().attachChild(effect);
effect.emitAllParticles();
}
space.remove(this);
spatial.removeFromParent();
}
}
public void prePhysicsTick(PhysicsSpace space, float f) {
space.removeCollisionListener(this);
}
public void physicsTick(PhysicsSpace space, float f) {
//get all overlapping objects and apply impulse to them
for (Iterator<PhysicsCollisionObject> it = ghostObject.getOverlappingObjects().iterator(); it.hasNext();) {
PhysicsCollisionObject physicsCollisionObject = it.next();
if (physicsCollisionObject instanceof PhysicsRigidBody) {
PhysicsRigidBody rBody = (PhysicsRigidBody) physicsCollisionObject;
rBody.getPhysicsLocation(vector2);
vector2.subtractLocal(vector);
float force = explosionRadius - vector2.length();
force *= forceFactor;
force = force > 0 ? force : 0;
vector2.normalizeLocal();
vector2.multLocal(force);
((PhysicsRigidBody) physicsCollisionObject).applyImpulse(vector2, Vector3f.ZERO);
}
}
space.removeTickListener(this);
space.remove(ghostObject);
}
@Override
public void update(float tpf) {
super.update(tpf);
if(enabled){
timer+=tpf;
if(timer>maxTime){
if(spatial.getParent()!=null){
space.removeCollisionListener(this);
space.remove(this);
spatial.removeFromParent();
}
}
}
if (enabled && curTime >= 0) {
curTime += tpf;
if (curTime > fxTime) {
curTime = -1;
effect.removeFromParent();
}
}
}
/**
* @return the explosionRadius
*/
public float getExplosionRadius() {
return explosionRadius;
}
/**
* @param explosionRadius the explosionRadius to set
*/
public void setExplosionRadius(float explosionRadius) {
this.explosionRadius = explosionRadius;
createGhostObject();
}
public float getForceFactor() {
return forceFactor;
}
public void setForceFactor(float forceFactor) {
this.forceFactor = forceFactor;
}
@Override
public void read(JmeImporter im) throws IOException {
throw new UnsupportedOperationException("Reading not supported.");
}
@Override
public void write(JmeExporter ex) throws IOException {
throw new UnsupportedOperationException("Saving not supported.");
}
}
| true | true | private void prepareEffect(AssetManager assetManager) {
int COUNT_FACTOR = 1;
float COUNT_FACTOR_F = 1f;
effect = new ParticleEmitter("Flame", Type.Triangle, 32 * COUNT_FACTOR);
effect.setSelectRandomImage(true);
effect.setStartColor(new ColorRGBA(1f, 0.4f, 0.05f, (float) (1f / COUNT_FACTOR_F)));
effect.setEndColor(new ColorRGBA(.4f, .22f, .12f, 0f));
effect.setStartSize(1.3f);
effect.setEndSize(2f);
effect.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
effect.setParticlesPerSec(0);
effect.setGravity(0, -5f, 0);
effect.setLowLife(.4f);
effect.setHighLife(.5f);
effect.setInitialVelocity(new Vector3f(0, 7, 0));
effect.setVelocityVariation(1f);
effect.setImagesX(2);
effect.setImagesY(2);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png"));
effect.setMaterial(mat);
effect.setLocalScale(100);
}
| private void prepareEffect(AssetManager assetManager) {
int COUNT_FACTOR = 1;
float COUNT_FACTOR_F = 1f;
effect = new ParticleEmitter("Flame", Type.Triangle, 32 * COUNT_FACTOR);
effect.setSelectRandomImage(true);
effect.setStartColor(new ColorRGBA(1f, 0.4f, 0.05f, (float) (1f / COUNT_FACTOR_F)));
effect.setEndColor(new ColorRGBA(.4f, .22f, .12f, 0f));
effect.setStartSize(1.3f);
effect.setEndSize(2f);
effect.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
effect.setParticlesPerSec(0);
effect.setGravity(0, -5f, 0);
effect.setLowLife(.4f);
effect.setHighLife(.5f);
effect.setInitialVelocity(new Vector3f(0, 7, 0));
effect.setVelocityVariation(1f);
effect.setImagesX(2);
effect.setImagesY(2);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png"));
effect.setMaterial(mat);
}
|
diff --git a/StevenDimDoors/mod_pocketDim/ticking/RiftRegenerator.java b/StevenDimDoors/mod_pocketDim/ticking/RiftRegenerator.java
index 386c73b..aeaaf32 100644
--- a/StevenDimDoors/mod_pocketDim/ticking/RiftRegenerator.java
+++ b/StevenDimDoors/mod_pocketDim/ticking/RiftRegenerator.java
@@ -1,72 +1,75 @@
package StevenDimDoors.mod_pocketDim.ticking;
import net.minecraft.world.World;
import StevenDimDoors.mod_pocketDim.DDProperties;
import StevenDimDoors.mod_pocketDim.LinkData;
import StevenDimDoors.mod_pocketDim.TileEntityRift;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import StevenDimDoors.mod_pocketDim.helpers.dimHelper;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
public class RiftRegenerator implements IRegularTickReceiver {
private static final int RIFT_REGENERATION_INTERVAL = 100; //Regenerate random rifts every 100 ticks
private DDProperties properties;
public RiftRegenerator(IRegularTickSender sender, DDProperties properties)
{
sender.registerForTicking(this, RIFT_REGENERATION_INTERVAL, false);
this.properties = properties;
}
@Override
public void notifyTick()
{
regenerate();
}
private void regenerate()
{
try
{
//Regenerate rifts that have been replaced (not permanently removed) by players
int i = 0;
while (i < 15 && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER)
{
i++;
LinkData link;
//actually gets the random rift based on the size of the list
link = (LinkData) dimHelper.instance.getRandomLinkData(true);
if (link != null)
{
World world = dimHelper.getWorld(link.locDimID);
if (world != null && !mod_pocketDim.blockRift.isBlockImmune(world, link.locXCoord, link.locYCoord, link.locZCoord))
{
if (dimHelper.instance.getLinkDataFromCoords(link.locXCoord, link.locYCoord, link.locZCoord, link.locDimID) != null)
{
world.setBlock(link.locXCoord, link.locYCoord, link.locZCoord, properties.RiftBlockID);
TileEntityRift rift = (TileEntityRift) world.getBlockTileEntity(link.locXCoord, link.locYCoord, link.locZCoord);
if (rift == null)
{
dimHelper.getWorld(link.locDimID).setBlockTileEntity(link.locXCoord, link.locYCoord, link.locZCoord, new TileEntityRift());
}
- rift.hasGrownRifts = true;
+ if (rift != null)
+ {
+ rift.hasGrownRifts = true;
+ }
}
}
}
}
}
catch (Exception e)
{
System.err.println("An exception occurred in RiftRegenerator.regenerate():");
e.printStackTrace();
}
}
}
| true | true | private void regenerate()
{
try
{
//Regenerate rifts that have been replaced (not permanently removed) by players
int i = 0;
while (i < 15 && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER)
{
i++;
LinkData link;
//actually gets the random rift based on the size of the list
link = (LinkData) dimHelper.instance.getRandomLinkData(true);
if (link != null)
{
World world = dimHelper.getWorld(link.locDimID);
if (world != null && !mod_pocketDim.blockRift.isBlockImmune(world, link.locXCoord, link.locYCoord, link.locZCoord))
{
if (dimHelper.instance.getLinkDataFromCoords(link.locXCoord, link.locYCoord, link.locZCoord, link.locDimID) != null)
{
world.setBlock(link.locXCoord, link.locYCoord, link.locZCoord, properties.RiftBlockID);
TileEntityRift rift = (TileEntityRift) world.getBlockTileEntity(link.locXCoord, link.locYCoord, link.locZCoord);
if (rift == null)
{
dimHelper.getWorld(link.locDimID).setBlockTileEntity(link.locXCoord, link.locYCoord, link.locZCoord, new TileEntityRift());
}
rift.hasGrownRifts = true;
}
}
}
}
}
catch (Exception e)
{
System.err.println("An exception occurred in RiftRegenerator.regenerate():");
e.printStackTrace();
}
}
| private void regenerate()
{
try
{
//Regenerate rifts that have been replaced (not permanently removed) by players
int i = 0;
while (i < 15 && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER)
{
i++;
LinkData link;
//actually gets the random rift based on the size of the list
link = (LinkData) dimHelper.instance.getRandomLinkData(true);
if (link != null)
{
World world = dimHelper.getWorld(link.locDimID);
if (world != null && !mod_pocketDim.blockRift.isBlockImmune(world, link.locXCoord, link.locYCoord, link.locZCoord))
{
if (dimHelper.instance.getLinkDataFromCoords(link.locXCoord, link.locYCoord, link.locZCoord, link.locDimID) != null)
{
world.setBlock(link.locXCoord, link.locYCoord, link.locZCoord, properties.RiftBlockID);
TileEntityRift rift = (TileEntityRift) world.getBlockTileEntity(link.locXCoord, link.locYCoord, link.locZCoord);
if (rift == null)
{
dimHelper.getWorld(link.locDimID).setBlockTileEntity(link.locXCoord, link.locYCoord, link.locZCoord, new TileEntityRift());
}
if (rift != null)
{
rift.hasGrownRifts = true;
}
}
}
}
}
}
catch (Exception e)
{
System.err.println("An exception occurred in RiftRegenerator.regenerate():");
e.printStackTrace();
}
}
|
diff --git a/src/kpsmart/KPSmart.java b/src/kpsmart/KPSmart.java
index 91990fe..d0310d9 100644
--- a/src/kpsmart/KPSmart.java
+++ b/src/kpsmart/KPSmart.java
@@ -1,254 +1,256 @@
package kpsmart;
import java.awt.BorderLayout;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import priority.Priority;
import routes.DistributionCentre;
import routes.Firm;
import gui.*;
import backend.*;
public class KPSmart implements ActionListener{
KPSBackend kBackend;
KPSFrame kFrame;
JPasswordField kPasswordField;
public KPSmart() {
kBackend = new KPSBackend();
kBackend.parseXMLRecord();
kFrame = new KPSFrame(this, kBackend.getDistributionCentres(), kBackend.findFirms());
kPasswordField = new JPasswordField(10);
//KPSpasswordField.setActionCommand("OK");
//KPSpasswordField.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
//FILE OPTIONS
if ("Save".equals(e.getActionCommand())) {
kBackend.createXMLRecord();
return;
}
if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
//ACTION OPTIONS
if ("Send Mail".equals(e.getActionCommand())) {
kFrame.displayPanel("mailPanel");
return;
}
if ("Update Costs".equals(e.getActionCommand())) {
kFrame.displayPanel("updatePanel");
return;
}
if ("View Business Figures".equals(e.getActionCommand())) {
int i = kBackend.getNumberOfEvents();
kFrame.populateEvents(i, kBackend.calculateDeliveryTimes(i), kBackend.calculateAmountOfMail(i),
kBackend.calculateTotalWeightOfMail(i), kBackend.calculateTotalVolumeOfMail(i),
kBackend.getCriticalRoute(i), kBackend.getEvents(i), kBackend.calculateRevenue(i), kBackend.calculateExpenditure(i));
kFrame.displayPanel("eventsPanel");
+ kFrame.enableBackward();
+ kFrame.disableForward();
return;
}
if ("Sign in as manager".equals(e.getActionCommand())) {
kPasswordField = new JPasswordField(10);
JOptionPane.showMessageDialog(kFrame, kPasswordField, "Password Required", JOptionPane.WARNING_MESSAGE);
String pass = String.valueOf(kPasswordField.getPassword());
if(kBackend.authenticateManager(pass)) {
kFrame.manager();
System.out.println("MANAGER MODE");
return;
}
}
if ("Sign out as manager".equals(e.getActionCommand())) {
kFrame.notManager();
if (kFrame.getPanel("eventsPanel")) {
kFrame.displayPanel("defaultPanel");
}
return;
}
//SEND MAIL HANDLING
if ("Send".equals(e.getActionCommand())) {
//Check for mail panel
if (kFrame.getPanel("mailPanel")) {
ArrayList<Object> info = kFrame.returnMailPanelInfo();
for (Object o : info) {
System.out.println(String.valueOf(o));
}
int i = 0;
int id = Integer.valueOf(String.valueOf(info.get(i++)));
i++; //Address
double weight = Double.valueOf(String.valueOf(info.get(i++)));
double volume = Double.valueOf(String.valueOf(info.get(i++)));
String o = String.valueOf(info.get(i++));
DistributionCentre origin = null;
String d = String.valueOf(info.get(i++));
DistributionCentre destination = null;
Priority priority = (Priority)info.get(i);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
boolean success = kBackend.sendMail(id, weight, volume, origin, destination, priority);
if (success) {
JOptionPane.showMessageDialog(kFrame, "Mail Sent Successfully", "Send Mail", JOptionPane.INFORMATION_MESSAGE);
kFrame.resetMailPanel();
}
- else JOptionPane.showMessageDialog(kFrame, "Mail Could Not Be Sent", "Send Mail", JOptionPane.ERROR_MESSAGE);
+ else JOptionPane.showMessageDialog(kFrame, "Mail Could Not Be Sent: No Route At That Priority Exists", "Send Mail", JOptionPane.ERROR_MESSAGE);
}
return;
}
//EVENT DISPLAY UPDATE HANDLING
if ("<".equals(e.getActionCommand())) {
int eventTime = kFrame.returnEventTime();
eventTime--;
if (eventTime >= 0) {
kFrame.populateEvents(eventTime, kBackend.calculateDeliveryTimes(eventTime), kBackend.calculateAmountOfMail(eventTime),
kBackend.calculateTotalWeightOfMail(eventTime), kBackend.calculateTotalVolumeOfMail(eventTime),
kBackend.getCriticalRoute(eventTime), kBackend.getEvents(eventTime), kBackend.calculateRevenue(eventTime), kBackend.calculateExpenditure(eventTime));
kFrame.enableForward();
if (eventTime == 0) { kFrame.disableBackward(); }
}
else {
eventTime = 0;
}
return;
}
if (">".equals(e.getActionCommand())) {
int eventTime = kFrame.returnEventTime();
eventTime++;
if (eventTime <= kBackend.getNumberOfEvents()) {
kFrame.populateEvents(eventTime, kBackend.calculateDeliveryTimes(eventTime), kBackend.calculateAmountOfMail(eventTime),
kBackend.calculateTotalWeightOfMail(eventTime), kBackend.calculateTotalVolumeOfMail(eventTime),
kBackend.getCriticalRoute(eventTime), kBackend.getEvents(eventTime), kBackend.calculateRevenue(eventTime), kBackend.calculateExpenditure(eventTime));
kFrame.enableBackward();
if (eventTime == kBackend.getNumberOfEvents()) { kFrame.disableForward(); }
}
else {
eventTime = kBackend.getNumberOfEvents();
}
return;
}
//CUSTOMER PRICE UPDATE HANDLING
if ("Update Customer Cost".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnCustomerPriceUpdateInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
double customerPriceCC = Double.valueOf(String.valueOf(info.get(i++)));
double customerPriceG = Double.valueOf(String.valueOf(info.get(i)));
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.updatePrice(origin, destination, customerPriceG, customerPriceCC, priority, firm);
- System.out.println("UPDATE CUSTOMER SUCCESSFUL");
+ JOptionPane.showMessageDialog(kFrame, "Customer Price Update Successful", "Successful Update is Successful", JOptionPane.INFORMATION_MESSAGE);
kFrame.resetUpdatePanel();
}
return;
}
//TRANSPORT COST UPDATE HANDLING
if ("Update Transport Cost".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnTransportCostUpdateInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
double transportPriceCC = Double.valueOf(String.valueOf(info.get(i++)));
double transportPriceG = Double.valueOf(String.valueOf(info.get(i++)));
int frequency = Integer.valueOf(String.valueOf(info.get(i++)));;
int duration = Integer.valueOf(String.valueOf(info.get(i++)));;;
Day day = (Day)info.get(i);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.updateTransport(origin, destination, transportPriceG, transportPriceCC, frequency, duration, day, priority, firm);
- System.out.println("UPDATE TRANSPORT SUCCESSFUL");
- kFrame.resetUpdatePanel();
+ JOptionPane.showMessageDialog(kFrame, "Transport Cost Update Successful", "Successful Update is Successful", JOptionPane.INFORMATION_MESSAGE); kFrame.resetUpdatePanel();
}
return;
}
//DISCONTINUE TRANSPORT HANDLING
if ("Discontinue Transport".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnDiscontinueTransportInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.discontinueTransport(origin, destination, priority, firm);
- System.out.println("DISCONTINUE TRANSPORT SUCCESSFUL");
+ JOptionPane.showMessageDialog(kFrame, "Discontinue Update Successful", "Successful Update is Successful", JOptionPane.INFORMATION_MESSAGE);
+ kFrame.resetUpdatePanel();
}
return;
}
//CANCEL BUTTON HANDLING
if ("Cancel".equals(e.getActionCommand())) {
kFrame.resetAll();
return;
}
//HELP OPTIONS
if ("About KPSSmart".equals(e.getActionCommand())) {
JOptionPane.showMessageDialog(kFrame, "KPSSmart by\n Nick Malcolm\n Liam O'Connor\n " +
" Janella Espinas\n Sean Arnold\n Robert Crowe");
return;
}
}
}
| false | true | public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
//FILE OPTIONS
if ("Save".equals(e.getActionCommand())) {
kBackend.createXMLRecord();
return;
}
if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
//ACTION OPTIONS
if ("Send Mail".equals(e.getActionCommand())) {
kFrame.displayPanel("mailPanel");
return;
}
if ("Update Costs".equals(e.getActionCommand())) {
kFrame.displayPanel("updatePanel");
return;
}
if ("View Business Figures".equals(e.getActionCommand())) {
int i = kBackend.getNumberOfEvents();
kFrame.populateEvents(i, kBackend.calculateDeliveryTimes(i), kBackend.calculateAmountOfMail(i),
kBackend.calculateTotalWeightOfMail(i), kBackend.calculateTotalVolumeOfMail(i),
kBackend.getCriticalRoute(i), kBackend.getEvents(i), kBackend.calculateRevenue(i), kBackend.calculateExpenditure(i));
kFrame.displayPanel("eventsPanel");
return;
}
if ("Sign in as manager".equals(e.getActionCommand())) {
kPasswordField = new JPasswordField(10);
JOptionPane.showMessageDialog(kFrame, kPasswordField, "Password Required", JOptionPane.WARNING_MESSAGE);
String pass = String.valueOf(kPasswordField.getPassword());
if(kBackend.authenticateManager(pass)) {
kFrame.manager();
System.out.println("MANAGER MODE");
return;
}
}
if ("Sign out as manager".equals(e.getActionCommand())) {
kFrame.notManager();
if (kFrame.getPanel("eventsPanel")) {
kFrame.displayPanel("defaultPanel");
}
return;
}
//SEND MAIL HANDLING
if ("Send".equals(e.getActionCommand())) {
//Check for mail panel
if (kFrame.getPanel("mailPanel")) {
ArrayList<Object> info = kFrame.returnMailPanelInfo();
for (Object o : info) {
System.out.println(String.valueOf(o));
}
int i = 0;
int id = Integer.valueOf(String.valueOf(info.get(i++)));
i++; //Address
double weight = Double.valueOf(String.valueOf(info.get(i++)));
double volume = Double.valueOf(String.valueOf(info.get(i++)));
String o = String.valueOf(info.get(i++));
DistributionCentre origin = null;
String d = String.valueOf(info.get(i++));
DistributionCentre destination = null;
Priority priority = (Priority)info.get(i);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
boolean success = kBackend.sendMail(id, weight, volume, origin, destination, priority);
if (success) {
JOptionPane.showMessageDialog(kFrame, "Mail Sent Successfully", "Send Mail", JOptionPane.INFORMATION_MESSAGE);
kFrame.resetMailPanel();
}
else JOptionPane.showMessageDialog(kFrame, "Mail Could Not Be Sent", "Send Mail", JOptionPane.ERROR_MESSAGE);
}
return;
}
//EVENT DISPLAY UPDATE HANDLING
if ("<".equals(e.getActionCommand())) {
int eventTime = kFrame.returnEventTime();
eventTime--;
if (eventTime >= 0) {
kFrame.populateEvents(eventTime, kBackend.calculateDeliveryTimes(eventTime), kBackend.calculateAmountOfMail(eventTime),
kBackend.calculateTotalWeightOfMail(eventTime), kBackend.calculateTotalVolumeOfMail(eventTime),
kBackend.getCriticalRoute(eventTime), kBackend.getEvents(eventTime), kBackend.calculateRevenue(eventTime), kBackend.calculateExpenditure(eventTime));
kFrame.enableForward();
if (eventTime == 0) { kFrame.disableBackward(); }
}
else {
eventTime = 0;
}
return;
}
if (">".equals(e.getActionCommand())) {
int eventTime = kFrame.returnEventTime();
eventTime++;
if (eventTime <= kBackend.getNumberOfEvents()) {
kFrame.populateEvents(eventTime, kBackend.calculateDeliveryTimes(eventTime), kBackend.calculateAmountOfMail(eventTime),
kBackend.calculateTotalWeightOfMail(eventTime), kBackend.calculateTotalVolumeOfMail(eventTime),
kBackend.getCriticalRoute(eventTime), kBackend.getEvents(eventTime), kBackend.calculateRevenue(eventTime), kBackend.calculateExpenditure(eventTime));
kFrame.enableBackward();
if (eventTime == kBackend.getNumberOfEvents()) { kFrame.disableForward(); }
}
else {
eventTime = kBackend.getNumberOfEvents();
}
return;
}
//CUSTOMER PRICE UPDATE HANDLING
if ("Update Customer Cost".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnCustomerPriceUpdateInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
double customerPriceCC = Double.valueOf(String.valueOf(info.get(i++)));
double customerPriceG = Double.valueOf(String.valueOf(info.get(i)));
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.updatePrice(origin, destination, customerPriceG, customerPriceCC, priority, firm);
System.out.println("UPDATE CUSTOMER SUCCESSFUL");
kFrame.resetUpdatePanel();
}
return;
}
//TRANSPORT COST UPDATE HANDLING
if ("Update Transport Cost".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnTransportCostUpdateInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
double transportPriceCC = Double.valueOf(String.valueOf(info.get(i++)));
double transportPriceG = Double.valueOf(String.valueOf(info.get(i++)));
int frequency = Integer.valueOf(String.valueOf(info.get(i++)));;
int duration = Integer.valueOf(String.valueOf(info.get(i++)));;;
Day day = (Day)info.get(i);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.updateTransport(origin, destination, transportPriceG, transportPriceCC, frequency, duration, day, priority, firm);
System.out.println("UPDATE TRANSPORT SUCCESSFUL");
kFrame.resetUpdatePanel();
}
return;
}
//DISCONTINUE TRANSPORT HANDLING
if ("Discontinue Transport".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnDiscontinueTransportInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.discontinueTransport(origin, destination, priority, firm);
System.out.println("DISCONTINUE TRANSPORT SUCCESSFUL");
}
return;
}
//CANCEL BUTTON HANDLING
if ("Cancel".equals(e.getActionCommand())) {
kFrame.resetAll();
return;
}
//HELP OPTIONS
if ("About KPSSmart".equals(e.getActionCommand())) {
JOptionPane.showMessageDialog(kFrame, "KPSSmart by\n Nick Malcolm\n Liam O'Connor\n " +
" Janella Espinas\n Sean Arnold\n Robert Crowe");
return;
}
}
| public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
//FILE OPTIONS
if ("Save".equals(e.getActionCommand())) {
kBackend.createXMLRecord();
return;
}
if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
//ACTION OPTIONS
if ("Send Mail".equals(e.getActionCommand())) {
kFrame.displayPanel("mailPanel");
return;
}
if ("Update Costs".equals(e.getActionCommand())) {
kFrame.displayPanel("updatePanel");
return;
}
if ("View Business Figures".equals(e.getActionCommand())) {
int i = kBackend.getNumberOfEvents();
kFrame.populateEvents(i, kBackend.calculateDeliveryTimes(i), kBackend.calculateAmountOfMail(i),
kBackend.calculateTotalWeightOfMail(i), kBackend.calculateTotalVolumeOfMail(i),
kBackend.getCriticalRoute(i), kBackend.getEvents(i), kBackend.calculateRevenue(i), kBackend.calculateExpenditure(i));
kFrame.displayPanel("eventsPanel");
kFrame.enableBackward();
kFrame.disableForward();
return;
}
if ("Sign in as manager".equals(e.getActionCommand())) {
kPasswordField = new JPasswordField(10);
JOptionPane.showMessageDialog(kFrame, kPasswordField, "Password Required", JOptionPane.WARNING_MESSAGE);
String pass = String.valueOf(kPasswordField.getPassword());
if(kBackend.authenticateManager(pass)) {
kFrame.manager();
System.out.println("MANAGER MODE");
return;
}
}
if ("Sign out as manager".equals(e.getActionCommand())) {
kFrame.notManager();
if (kFrame.getPanel("eventsPanel")) {
kFrame.displayPanel("defaultPanel");
}
return;
}
//SEND MAIL HANDLING
if ("Send".equals(e.getActionCommand())) {
//Check for mail panel
if (kFrame.getPanel("mailPanel")) {
ArrayList<Object> info = kFrame.returnMailPanelInfo();
for (Object o : info) {
System.out.println(String.valueOf(o));
}
int i = 0;
int id = Integer.valueOf(String.valueOf(info.get(i++)));
i++; //Address
double weight = Double.valueOf(String.valueOf(info.get(i++)));
double volume = Double.valueOf(String.valueOf(info.get(i++)));
String o = String.valueOf(info.get(i++));
DistributionCentre origin = null;
String d = String.valueOf(info.get(i++));
DistributionCentre destination = null;
Priority priority = (Priority)info.get(i);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
boolean success = kBackend.sendMail(id, weight, volume, origin, destination, priority);
if (success) {
JOptionPane.showMessageDialog(kFrame, "Mail Sent Successfully", "Send Mail", JOptionPane.INFORMATION_MESSAGE);
kFrame.resetMailPanel();
}
else JOptionPane.showMessageDialog(kFrame, "Mail Could Not Be Sent: No Route At That Priority Exists", "Send Mail", JOptionPane.ERROR_MESSAGE);
}
return;
}
//EVENT DISPLAY UPDATE HANDLING
if ("<".equals(e.getActionCommand())) {
int eventTime = kFrame.returnEventTime();
eventTime--;
if (eventTime >= 0) {
kFrame.populateEvents(eventTime, kBackend.calculateDeliveryTimes(eventTime), kBackend.calculateAmountOfMail(eventTime),
kBackend.calculateTotalWeightOfMail(eventTime), kBackend.calculateTotalVolumeOfMail(eventTime),
kBackend.getCriticalRoute(eventTime), kBackend.getEvents(eventTime), kBackend.calculateRevenue(eventTime), kBackend.calculateExpenditure(eventTime));
kFrame.enableForward();
if (eventTime == 0) { kFrame.disableBackward(); }
}
else {
eventTime = 0;
}
return;
}
if (">".equals(e.getActionCommand())) {
int eventTime = kFrame.returnEventTime();
eventTime++;
if (eventTime <= kBackend.getNumberOfEvents()) {
kFrame.populateEvents(eventTime, kBackend.calculateDeliveryTimes(eventTime), kBackend.calculateAmountOfMail(eventTime),
kBackend.calculateTotalWeightOfMail(eventTime), kBackend.calculateTotalVolumeOfMail(eventTime),
kBackend.getCriticalRoute(eventTime), kBackend.getEvents(eventTime), kBackend.calculateRevenue(eventTime), kBackend.calculateExpenditure(eventTime));
kFrame.enableBackward();
if (eventTime == kBackend.getNumberOfEvents()) { kFrame.disableForward(); }
}
else {
eventTime = kBackend.getNumberOfEvents();
}
return;
}
//CUSTOMER PRICE UPDATE HANDLING
if ("Update Customer Cost".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnCustomerPriceUpdateInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
double customerPriceCC = Double.valueOf(String.valueOf(info.get(i++)));
double customerPriceG = Double.valueOf(String.valueOf(info.get(i)));
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.updatePrice(origin, destination, customerPriceG, customerPriceCC, priority, firm);
JOptionPane.showMessageDialog(kFrame, "Customer Price Update Successful", "Successful Update is Successful", JOptionPane.INFORMATION_MESSAGE);
kFrame.resetUpdatePanel();
}
return;
}
//TRANSPORT COST UPDATE HANDLING
if ("Update Transport Cost".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnTransportCostUpdateInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
double transportPriceCC = Double.valueOf(String.valueOf(info.get(i++)));
double transportPriceG = Double.valueOf(String.valueOf(info.get(i++)));
int frequency = Integer.valueOf(String.valueOf(info.get(i++)));;
int duration = Integer.valueOf(String.valueOf(info.get(i++)));;;
Day day = (Day)info.get(i);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.updateTransport(origin, destination, transportPriceG, transportPriceCC, frequency, duration, day, priority, firm);
JOptionPane.showMessageDialog(kFrame, "Transport Cost Update Successful", "Successful Update is Successful", JOptionPane.INFORMATION_MESSAGE); kFrame.resetUpdatePanel();
}
return;
}
//DISCONTINUE TRANSPORT HANDLING
if ("Discontinue Transport".equals(e.getActionCommand())) {
ArrayList info = kFrame.returnDiscontinueTransportInfo();
if (info != null) {
int i = 0;
DistributionCentre origin = null;
DistributionCentre destination = null;
String o = String.valueOf(info.get(i++));
String d = String.valueOf(info.get(i++));
Firm firm = new Firm((String)info.get(i++));
Priority priority = (Priority)info.get(i++);
for (DistributionCentre dist : kBackend.getDistributionCentres()) {
if (dist.getName().equals(o)) { origin = dist; }
if (dist.getName().equals(d)) { destination = dist; }
}
kBackend.discontinueTransport(origin, destination, priority, firm);
JOptionPane.showMessageDialog(kFrame, "Discontinue Update Successful", "Successful Update is Successful", JOptionPane.INFORMATION_MESSAGE);
kFrame.resetUpdatePanel();
}
return;
}
//CANCEL BUTTON HANDLING
if ("Cancel".equals(e.getActionCommand())) {
kFrame.resetAll();
return;
}
//HELP OPTIONS
if ("About KPSSmart".equals(e.getActionCommand())) {
JOptionPane.showMessageDialog(kFrame, "KPSSmart by\n Nick Malcolm\n Liam O'Connor\n " +
" Janella Espinas\n Sean Arnold\n Robert Crowe");
return;
}
}
|
diff --git a/it.unibg.robotics.resolutionmodel.ros.commands.resolution/src/it/unibg/robotics/resolutionmodel/ros/commands/resolution/expressions/ROSResolutionModelTypeTester.java b/it.unibg.robotics.resolutionmodel.ros.commands.resolution/src/it/unibg/robotics/resolutionmodel/ros/commands/resolution/expressions/ROSResolutionModelTypeTester.java
index 0893193..f508f3e 100644
--- a/it.unibg.robotics.resolutionmodel.ros.commands.resolution/src/it/unibg/robotics/resolutionmodel/ros/commands/resolution/expressions/ROSResolutionModelTypeTester.java
+++ b/it.unibg.robotics.resolutionmodel.ros.commands.resolution/src/it/unibg/robotics/resolutionmodel/ros/commands/resolution/expressions/ROSResolutionModelTypeTester.java
@@ -1,49 +1,50 @@
package it.unibg.robotics.resolutionmodel.ros.commands.resolution.expressions;
import it.unibg.robotics.resolutionmodel.RMAbstractTransformation;
import it.unibg.robotics.resolutionmodel.RMResolutionElement;
import it.unibg.robotics.resolutionmodel.ResolutionModel;
import it.unibg.robotics.resolutionmodel.rosresolutionmodel.ROSRequiredComponents;
import it.unibg.robotics.resolutionmodel.rosresolutionmodel.ROSRequiredConnections;
import it.unibg.robotics.resolutionmodel.rosresolutionmodel.ROSTransfConnection;
import it.unibg.robotics.resolutionmodel.rosresolutionmodel.ROSTransfImplementation;
import it.unibg.robotics.resolutionmodel.rosresolutionmodel.ROSTransfProperty;
import org.eclipse.core.expressions.PropertyTester;
public class ROSResolutionModelTypeTester extends PropertyTester{
@Override
public boolean test(Object receiver, String property, Object[] args,
Object expectedValue) {
if (property.equals("is_a_ROS_resolution_model")) {
ResolutionModel model = (ResolutionModel)receiver;
+ System.out.println(model);
for(RMResolutionElement resElem : model.getResolutionElements()){
if(resElem.getRequiredComponents() instanceof ROSRequiredComponents){
return true;
}
if(resElem.getRequiredConnections() instanceof ROSRequiredConnections){
return true;
}
for(RMAbstractTransformation transf : resElem.getTransformations()){
if(transf instanceof ROSTransfImplementation ||
transf instanceof ROSTransfProperty ||
transf instanceof ROSTransfConnection){
return true;
}
}
}
}
return false;
}
}
| true | true | public boolean test(Object receiver, String property, Object[] args,
Object expectedValue) {
if (property.equals("is_a_ROS_resolution_model")) {
ResolutionModel model = (ResolutionModel)receiver;
for(RMResolutionElement resElem : model.getResolutionElements()){
if(resElem.getRequiredComponents() instanceof ROSRequiredComponents){
return true;
}
if(resElem.getRequiredConnections() instanceof ROSRequiredConnections){
return true;
}
for(RMAbstractTransformation transf : resElem.getTransformations()){
if(transf instanceof ROSTransfImplementation ||
transf instanceof ROSTransfProperty ||
transf instanceof ROSTransfConnection){
return true;
}
}
}
}
return false;
}
| public boolean test(Object receiver, String property, Object[] args,
Object expectedValue) {
if (property.equals("is_a_ROS_resolution_model")) {
ResolutionModel model = (ResolutionModel)receiver;
System.out.println(model);
for(RMResolutionElement resElem : model.getResolutionElements()){
if(resElem.getRequiredComponents() instanceof ROSRequiredComponents){
return true;
}
if(resElem.getRequiredConnections() instanceof ROSRequiredConnections){
return true;
}
for(RMAbstractTransformation transf : resElem.getTransformations()){
if(transf instanceof ROSTransfImplementation ||
transf instanceof ROSTransfProperty ||
transf instanceof ROSTransfConnection){
return true;
}
}
}
}
return false;
}
|
diff --git a/ui/web/IdentityPage.java b/ui/web/IdentityPage.java
index 3cd4e14f..163bd918 100644
--- a/ui/web/IdentityPage.java
+++ b/ui/web/IdentityPage.java
@@ -1,132 +1,132 @@
/*
* freenet - IdentityPage.java
* Copyright © 2008 David Roden
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package plugins.WoT.ui.web;
import java.util.Iterator;
import java.util.List;
import plugins.WoT.Identity;
import plugins.WoT.Trust;
import plugins.WoT.WoT;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
/**
* @author David ‘Bombe’ Roden <[email protected]>
* @version $Id$
*/
public class IdentityPage extends WebPageImpl {
/** The identity to show trust relationships of. */
private final Identity identity;
/** All trusts that trust the identity. */
private final List<Trust> trustersTrusts;
/** All trusts that the identity trusts. */
private final List<Trust> trusteesTrusts;
/**
* Creates a new trust-relationship web page.
*
* @param webOfTrust
* The web of trust
* @param httpRequest
* The HTTP request
* @param identity
* The identity
* @param trustersTrusts
* The trusts having the given identity as truster
* @param trusteesTrusts
* The trusts having the given identity as trustee
*/
public IdentityPage(WoT webOfTrust, HTTPRequest httpRequest, Identity identity, List<Trust> trustersTrusts, List<Trust> trusteesTrusts) {
super(webOfTrust, httpRequest);
this.identity = identity;
this.trustersTrusts = trustersTrusts;
this.trusteesTrusts = trusteesTrusts;
}
private void makeURIBox() {
HTMLNode boxContent = getContentBox("Reference of identity '" + identity.getNickName() + "'");
boxContent.addChild("p", "The following Freenet URI is a reference to this identity. If you want to tell other people about this identity, give the URI to them: ");
boxContent.addChild("p", identity.getRequestURI().toString());
}
private void makeServicesBox() {
HTMLNode boxContent = getContentBox("Services of identity '" + identity.getNickName() + "'");
Iterator<String> iter = identity.getContexts();
StringBuilder contexts = new StringBuilder(128);
while(iter.hasNext()) {
contexts.append(iter.next());
if(iter.hasNext())
contexts.append(", ");
}
boxContent.addChild("p", contexts.toString());
}
/**
* {@inheritDoc}
*
* @see WebPage#make()
*/
public void make() {
makeURIBox();
makeServicesBox();
- HTMLNode trusteeTrustsNode = getContentBox("Identities that “" + identity.getNickName() + "” trusts");
+ HTMLNode trusteeTrustsNode = getContentBox("Identities that '" + identity.getNickName() + "' trusts");
HTMLNode trustersTable = trusteeTrustsNode.addChild("table");
HTMLNode trustersTableHeader = trustersTable.addChild("tr");
trustersTableHeader.addChild("th", "NickName");
trustersTableHeader.addChild("th", "Identity");
trustersTableHeader.addChild("th", "Trust Value");
trustersTableHeader.addChild("th", "Comment");
for (Trust trust : trusteesTrusts) {
HTMLNode trustRow = trustersTable.addChild("tr");
Identity trustee = trust.getTrustee();
trustRow.addChild("td").addChild("a", "href", "?showIdentity&id=" + trustee.getId(), trustee.getNickName());
trustRow.addChild("td", trustee.getId());
trustRow.addChild("td", "align", "right", String.valueOf(trust.getValue()));
trustRow.addChild("td", trust.getComment());
}
- HTMLNode trusterTrustsNode = getContentBox("Identities that trust “" + identity.getNickName() + "”");
+ HTMLNode trusterTrustsNode = getContentBox("Identities that trust '" + identity.getNickName() + "'");
HTMLNode trusteesTable = trusterTrustsNode.addChild("table");
HTMLNode trusteesTableHeader = trusteesTable.addChild("tr");
trusteesTableHeader.addChild("th", "NickName");
trusteesTableHeader.addChild("th", "Identity");
trusteesTableHeader.addChild("th", "Trust Value");
trusteesTableHeader.addChild("th", "Comment");
for (Trust trust : trustersTrusts) {
HTMLNode trustRow = trusteesTable.addChild("tr");
Identity truster = trust.getTruster();
trustRow.addChild("td").addChild("a", "href", "?showIdentity&id=" + truster.getId(), truster.getNickName());
trustRow.addChild("td", truster.getId());
trustRow.addChild("td", "align", "right", String.valueOf(trust.getValue()));
trustRow.addChild("td", trust.getComment());
}
}
}
| false | true | public void make() {
makeURIBox();
makeServicesBox();
HTMLNode trusteeTrustsNode = getContentBox("Identities that “" + identity.getNickName() + "” trusts");
HTMLNode trustersTable = trusteeTrustsNode.addChild("table");
HTMLNode trustersTableHeader = trustersTable.addChild("tr");
trustersTableHeader.addChild("th", "NickName");
trustersTableHeader.addChild("th", "Identity");
trustersTableHeader.addChild("th", "Trust Value");
trustersTableHeader.addChild("th", "Comment");
for (Trust trust : trusteesTrusts) {
HTMLNode trustRow = trustersTable.addChild("tr");
Identity trustee = trust.getTrustee();
trustRow.addChild("td").addChild("a", "href", "?showIdentity&id=" + trustee.getId(), trustee.getNickName());
trustRow.addChild("td", trustee.getId());
trustRow.addChild("td", "align", "right", String.valueOf(trust.getValue()));
trustRow.addChild("td", trust.getComment());
}
HTMLNode trusterTrustsNode = getContentBox("Identities that trust “" + identity.getNickName() + "”");
HTMLNode trusteesTable = trusterTrustsNode.addChild("table");
HTMLNode trusteesTableHeader = trusteesTable.addChild("tr");
trusteesTableHeader.addChild("th", "NickName");
trusteesTableHeader.addChild("th", "Identity");
trusteesTableHeader.addChild("th", "Trust Value");
trusteesTableHeader.addChild("th", "Comment");
for (Trust trust : trustersTrusts) {
HTMLNode trustRow = trusteesTable.addChild("tr");
Identity truster = trust.getTruster();
trustRow.addChild("td").addChild("a", "href", "?showIdentity&id=" + truster.getId(), truster.getNickName());
trustRow.addChild("td", truster.getId());
trustRow.addChild("td", "align", "right", String.valueOf(trust.getValue()));
trustRow.addChild("td", trust.getComment());
}
}
| public void make() {
makeURIBox();
makeServicesBox();
HTMLNode trusteeTrustsNode = getContentBox("Identities that '" + identity.getNickName() + "' trusts");
HTMLNode trustersTable = trusteeTrustsNode.addChild("table");
HTMLNode trustersTableHeader = trustersTable.addChild("tr");
trustersTableHeader.addChild("th", "NickName");
trustersTableHeader.addChild("th", "Identity");
trustersTableHeader.addChild("th", "Trust Value");
trustersTableHeader.addChild("th", "Comment");
for (Trust trust : trusteesTrusts) {
HTMLNode trustRow = trustersTable.addChild("tr");
Identity trustee = trust.getTrustee();
trustRow.addChild("td").addChild("a", "href", "?showIdentity&id=" + trustee.getId(), trustee.getNickName());
trustRow.addChild("td", trustee.getId());
trustRow.addChild("td", "align", "right", String.valueOf(trust.getValue()));
trustRow.addChild("td", trust.getComment());
}
HTMLNode trusterTrustsNode = getContentBox("Identities that trust '" + identity.getNickName() + "'");
HTMLNode trusteesTable = trusterTrustsNode.addChild("table");
HTMLNode trusteesTableHeader = trusteesTable.addChild("tr");
trusteesTableHeader.addChild("th", "NickName");
trusteesTableHeader.addChild("th", "Identity");
trusteesTableHeader.addChild("th", "Trust Value");
trusteesTableHeader.addChild("th", "Comment");
for (Trust trust : trustersTrusts) {
HTMLNode trustRow = trusteesTable.addChild("tr");
Identity truster = trust.getTruster();
trustRow.addChild("td").addChild("a", "href", "?showIdentity&id=" + truster.getId(), truster.getNickName());
trustRow.addChild("td", truster.getId());
trustRow.addChild("td", "align", "right", String.valueOf(trust.getValue()));
trustRow.addChild("td", trust.getComment());
}
}
|
diff --git a/services/src/main/java/org/keycloak/services/resources/TokenService.java b/services/src/main/java/org/keycloak/services/resources/TokenService.java
index d3a262e5db..580473b7b6 100755
--- a/services/src/main/java/org/keycloak/services/resources/TokenService.java
+++ b/services/src/main/java/org/keycloak/services/resources/TokenService.java
@@ -1,608 +1,608 @@
package org.keycloak.services.resources;
import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.jose.jws.JWSBuilder;
import org.jboss.resteasy.jose.jws.JWSInput;
import org.jboss.resteasy.jose.jws.crypto.RSAProvider;
import org.jboss.resteasy.jwt.JsonSerialization;
import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.Constants;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModel.RequiredAction;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.SkeletonKeyToken;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.managers.AccessCodeEntry;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationManager.AuthenticationStatus;
import org.keycloak.services.managers.ResourceAdminManager;
import org.keycloak.services.managers.TokenManager;
import org.keycloak.services.messages.Messages;
import org.keycloak.services.resources.flows.Flows;
import org.keycloak.services.resources.flows.OAuthFlows;
import org.keycloak.services.validation.Validation;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class TokenService {
protected static final Logger logger = Logger.getLogger(TokenService.class);
protected RealmModel realm;
protected TokenManager tokenManager;
protected AuthenticationManager authManager = new AuthenticationManager();
@Context
protected Providers providers;
@Context
protected SecurityContext securityContext;
@Context
protected UriInfo uriInfo;
@Context
protected HttpHeaders headers;
@Context
protected HttpRequest request;
@Context
protected HttpResponse response;
@Context
protected KeycloakSession session;
@Context
protected KeycloakTransaction transaction;
@Context
protected ResourceContext resourceContext;
private ResourceAdminManager resourceAdminManager = new ResourceAdminManager();
public TokenService(RealmModel realm, TokenManager tokenManager) {
this.realm = realm;
this.tokenManager = tokenManager;
}
public static UriBuilder tokenServiceBaseUrl(UriInfo uriInfo) {
UriBuilder base = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(RealmsResource.class, "getTokenService");
return base;
}
public static UriBuilder accessCodeToTokenUrl(UriInfo uriInfo) {
return tokenServiceBaseUrl(uriInfo).path(TokenService.class, "accessCodeToToken");
}
public static UriBuilder grantAccessTokenUrl(UriInfo uriInfo) {
return tokenServiceBaseUrl(uriInfo).path(TokenService.class, "grantAccessToken");
}
public static UriBuilder grantIdentityTokenUrl(UriInfo uriInfo) {
return tokenServiceBaseUrl(uriInfo).path(TokenService.class, "grantIdentityToken");
}
public static UriBuilder loginPageUrl(UriInfo uriInfo) {
return tokenServiceBaseUrl(uriInfo).path(TokenService.class, "loginPage");
}
public static UriBuilder processLoginUrl(UriInfo uriInfo) {
return tokenServiceBaseUrl(uriInfo).path(TokenService.class, "processLogin");
}
public static UriBuilder processOAuthUrl(UriInfo uriInfo) {
return tokenServiceBaseUrl(uriInfo).path(TokenService.class, "processOAuth");
}
@Path("grants/identity-token")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response grantIdentityToken(final MultivaluedMap<String, String> form) {
String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
if (username == null) {
throw new NotAuthorizedException("No user");
}
if (!realm.isEnabled()) {
throw new NotAuthorizedException("Disabled realm");
}
UserModel user = realm.getUser(username);
AuthenticationStatus status = authManager.authenticateForm(realm, user, form);
if (status != AuthenticationStatus.SUCCESS) {
throw new NotAuthorizedException(status);
}
tokenManager = new TokenManager();
SkeletonKeyToken token = authManager.createIdentityToken(realm, username);
String encoded = tokenManager.encodeToken(realm, token);
AccessTokenResponse res = accessTokenResponse(token, encoded);
return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();
}
@Path("grants/access")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response grantAccessToken(final MultivaluedMap<String, String> form) {
String username = form.getFirst(AuthenticationManager.FORM_USERNAME);
if (username == null) {
throw new NotAuthorizedException("No user");
}
if (!realm.isEnabled()) {
throw new NotAuthorizedException("Disabled realm");
}
UserModel user = realm.getUser(username);
if (user == null) {
throw new NotAuthorizedException("No user");
}
if (!user.isEnabled()) {
throw new NotAuthorizedException("Disabled user.");
}
if (authManager.authenticateForm(realm, user, form) != AuthenticationStatus.SUCCESS) {
throw new NotAuthorizedException("Auth failed");
}
SkeletonKeyToken token = tokenManager.createAccessToken(realm, user);
String encoded = tokenManager.encodeToken(realm, token);
AccessTokenResponse res = accessTokenResponse(token, encoded);
return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();
}
@Path("auth/request/login")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processLogin(@QueryParam("client_id") final String clientId, @QueryParam("scope") final String scopeParam,
@QueryParam("state") final String state, @QueryParam("redirect_uri") final String redirect,
final MultivaluedMap<String, String> formData) {
logger.debug("TokenService.processLogin");
OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
if (!realm.isEnabled()) {
return oauth.forwardToSecurityFailure("Realm not enabled.");
}
UserModel client = realm.getUser(clientId);
if (client == null) {
return oauth.forwardToSecurityFailure("Unknown login requester.");
}
if (!client.isEnabled()) {
return oauth.forwardToSecurityFailure("Login requester not enabled.");
}
String username = formData.getFirst("username");
UserModel user = realm.getUser(username);
if (user == null){
return Flows.forms(realm, request, uriInfo).setError(Messages.INVALID_USER).setFormData(formData)
.forwardToLogin();
}
isTotpConfigurationRequired(user);
isEmailVerificationRequired(user);
AuthenticationStatus status = authManager.authenticateForm(realm, user, formData);
switch (status) {
case SUCCESS:
case ACTIONS_REQUIRED:
return oauth.processAccessCode(scopeParam, state, redirect, client, user);
case ACCOUNT_DISABLED:
return Flows.forms(realm, request, uriInfo).setError(Messages.ACCOUNT_DISABLED).setFormData(formData)
.forwardToLogin();
case MISSING_TOTP:
return Flows.forms(realm, request, uriInfo).setFormData(formData).forwardToLoginTotp();
default:
return Flows.forms(realm, request, uriInfo).setError(Messages.INVALID_USER).setFormData(formData)
.forwardToLogin();
}
}
@Path("auth/request/login-actions")
public RequiredActionsService getRequiredActionsService() {
RequiredActionsService service = new RequiredActionsService(realm, tokenManager);
resourceContext.initResource(service);
return service;
}
private void isTotpConfigurationRequired(UserModel user) {
for (RequiredCredentialModel c : realm.getRequiredCredentials()) {
if (c.getType().equals(CredentialRepresentation.TOTP) && !user.isTotp()) {
user.addRequiredAction(RequiredAction.CONFIGURE_TOTP);
logger.debug("User is required to configure totp");
}
}
}
private void isEmailVerificationRequired(UserModel user) {
if (realm.isVerifyEmail() && !user.isEmailVerified()) {
user.addRequiredAction(RequiredAction.VERIFY_EMAIL);
logger.debug("User is required to verify email");
}
}
@Path("registrations")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processRegister(@QueryParam("client_id") final String clientId,
@QueryParam("scope") final String scopeParam, @QueryParam("state") final String state,
@QueryParam("redirect_uri") final String redirect, final MultivaluedMap<String, String> formData) {
Response registrationResponse = processRegisterImpl(clientId, scopeParam, state, redirect, formData, false);
// If request has been already forwarded (either due to security or validation error) then we won't continue with login
if (registrationResponse != null || request.wasForwarded()) {
logger.warn("Registration attempt wasn't successful. Request already forwarded or redirected.");
return registrationResponse;
} else {
return processLogin(clientId, scopeParam, state, redirect, formData);
}
}
public Response processRegisterImpl(String clientId, String scopeParam, String state, String redirect,
MultivaluedMap<String, String> formData, boolean isSocialRegistration) {
OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
if (!realm.isEnabled()) {
logger.warn("Realm not enabled");
return oauth.forwardToSecurityFailure("Realm not enabled");
}
UserModel client = realm.getUser(clientId);
if (client == null) {
logger.warn("Unknown login requester.");
return oauth.forwardToSecurityFailure("Unknown login requester.");
}
if (!client.isEnabled()) {
logger.warn("Login requester not enabled.");
return oauth.forwardToSecurityFailure("Login requester not enabled.");
}
if (!realm.isRegistrationAllowed()) {
logger.warn("Registration not allowed");
return oauth.forwardToSecurityFailure("Registration not allowed");
}
List<String> requiredCredentialTypes = new LinkedList<String>();
for (RequiredCredentialModel m : realm.getRequiredCredentials()) {
requiredCredentialTypes.add(m.getType());
}
String error = Validation.validateRegistrationForm(formData, requiredCredentialTypes);
if (error != null) {
return Flows.forms(realm, request, uriInfo).setError(error).setFormData(formData)
.setSocialRegistration(isSocialRegistration).forwardToRegistration();
}
String username = formData.getFirst("username");
UserModel user = realm.getUser(username);
if (user != null) {
return Flows.forms(realm, request, uriInfo).setError(Messages.USERNAME_EXISTS).setFormData(formData)
.setSocialRegistration(isSocialRegistration).forwardToRegistration();
}
user = realm.addUser(username);
user.setEnabled(true);
user.setFirstName(formData.getFirst("firstName"));
user.setLastName(formData.getFirst("lastName"));
user.setEmail(formData.getFirst("email"));
if (requiredCredentialTypes.contains(CredentialRepresentation.PASSWORD)) {
UserCredentialModel credentials = new UserCredentialModel();
credentials.setType(CredentialRepresentation.PASSWORD);
credentials.setValue(formData.getFirst("password"));
realm.updateCredential(user, credentials);
}
for (String r : realm.getDefaultRoles()) {
realm.grantRole(user, realm.getRole(r));
}
for (ApplicationModel application : realm.getApplications()) {
for (String r : application.getDefaultRoles()) {
application.grantRole(user, application.getRole(r));
}
}
return null;
}
@Path("access/codes")
@POST
@Produces("application/json")
public Response accessCodeToToken(final MultivaluedMap<String, String> formData) {
logger.debug("accessRequest <---");
if (!realm.isEnabled()) {
throw new NotAuthorizedException("Realm not enabled");
}
String code = formData.getFirst("code");
if (code == null) {
logger.debug("code not specified");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_request");
error.put("error_description", "code not specified");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
String client_id = formData.getFirst("client_id");
if (client_id == null) {
logger.debug("client_id not specified");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_request");
error.put("error_description", "client_id not specified");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
UserModel client = realm.getUser(client_id);
if (client == null) {
logger.debug("Could not find user");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_client");
error.put("error_description", "Could not find user");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
if (!client.isEnabled()) {
logger.debug("user is not enabled");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_client");
error.put("error_description", "User is not enabled");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
AuthenticationStatus status = authManager.authenticateForm(realm, client, formData);
if (status != AuthenticationStatus.SUCCESS) {
Map<String, String> error = new HashMap<String, String>();
error.put("error", "unauthorized_client");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
JWSInput input = new JWSInput(code, providers);
boolean verifiedCode = false;
try {
verifiedCode = RSAProvider.verify(input, realm.getPublicKey());
} catch (Exception ignored) {
logger.debug("Failed to verify signature", ignored);
}
if (!verifiedCode) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Unable to verify code signature");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
String key = input.readContent(String.class);
AccessCodeEntry accessCode = tokenManager.pullAccessCode(key);
if (accessCode == null) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Code not found");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (accessCode.isExpired()) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Code is expired");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (!accessCode.getToken().isActive()) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Token expired");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (!client.getLoginName().equals(accessCode.getClient().getLoginName())) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Auth error");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
logger.debug("accessRequest SUCCESS");
AccessTokenResponse res = accessTokenResponse(realm.getPrivateKey(), accessCode.getToken());
- return Cors.add(request, Response.ok(res)).allowedOrigins(client).build();
+ return Cors.add(request, Response.ok(res)).allowedOrigins(client).allowedMethods("POST").build();
}
protected AccessTokenResponse accessTokenResponse(PrivateKey privateKey, SkeletonKeyToken token) {
byte[] tokenBytes = null;
try {
tokenBytes = JsonSerialization.toByteArray(token, false);
} catch (Exception e) {
throw new RuntimeException(e);
}
String encodedToken = new JWSBuilder().content(tokenBytes).rsa256(privateKey);
return accessTokenResponse(token, encodedToken);
}
protected AccessTokenResponse accessTokenResponse(SkeletonKeyToken token, String encodedToken) {
AccessTokenResponse res = new AccessTokenResponse();
res.setToken(encodedToken);
res.setTokenType("bearer");
if (token.getExpiration() != 0) {
long time = token.getExpiration() - (System.currentTimeMillis() / 1000);
res.setExpiresIn(time);
}
return res;
}
@Path("login")
@GET
public Response loginPage(final @QueryParam("response_type") String responseType,
final @QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId,
final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state, final @QueryParam("prompt") String prompt) {
logger.info("TokenService.loginPage");
OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
if (!realm.isEnabled()) {
logger.warn("Realm not enabled");
oauth.forwardToSecurityFailure("Realm not enabled");
return null;
}
UserModel client = realm.getUser(clientId);
if (client == null) {
logger.warn("Unknown login requester: " + clientId);
oauth.forwardToSecurityFailure("Unknown login requester.");
transaction.rollback();
return null;
}
if (!client.isEnabled()) {
logger.warn("Login requester not enabled.");
oauth.forwardToSecurityFailure("Login requester not enabled.");
transaction.rollback();
session.close();
return null;
}
logger.info("Checking roles...");
RoleModel resourceRole = realm.getRole(Constants.APPLICATION_ROLE);
RoleModel identityRequestRole = realm.getRole(Constants.IDENTITY_REQUESTER_ROLE);
boolean isResource = realm.hasRole(client, resourceRole);
if (!isResource && !realm.hasRole(client, identityRequestRole)) {
logger.warn("Login requester not allowed to request login.");
oauth.forwardToSecurityFailure("Login requester not allowed to request login.");
transaction.rollback();
session.close();
return null;
}
logger.info("Checking cookie...");
UserModel user = authManager.authenticateIdentityCookie(realm, uriInfo, headers);
if (user != null) {
logger.debug(user.getLoginName() + " already logged in.");
return oauth.processAccessCode(scopeParam, state, redirect, client, user);
}
if (prompt != null && prompt.equals("none")) {
return oauth.redirectError(client, "access_denied", state, redirect);
}
logger.info("forwardToLogin() now...");
return Flows.forms(realm, request, uriInfo).forwardToLogin();
}
@Path("registrations")
@GET
public Response registerPage(final @QueryParam("response_type") String responseType,
final @QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId,
final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state) {
logger.info("**********registerPage()");
OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
if (!realm.isEnabled()) {
logger.warn("Realm not enabled");
return oauth.forwardToSecurityFailure("Realm not enabled");
}
UserModel client = realm.getUser(clientId);
if (client == null) {
logger.warn("Unknown login requester.");
return oauth.forwardToSecurityFailure("Unknown login requester.");
}
if (!client.isEnabled()) {
logger.warn("Login requester not enabled.");
return oauth.forwardToSecurityFailure("Login requester not enabled.");
}
if (!realm.isRegistrationAllowed()) {
logger.warn("Registration not allowed");
return oauth.forwardToSecurityFailure("Registration not allowed");
}
authManager.expireIdentityCookie(realm, uriInfo);
return Flows.forms(realm, request, uriInfo).forwardToRegistration();
}
@Path("logout")
@GET
@NoCache
public Response logout(final @QueryParam("redirect_uri") String redirectUri) {
// todo do we care if anybody can trigger this?
UserModel user = authManager.authenticateIdentityCookie(realm, uriInfo, headers);
if (user != null) {
logger.debug("Logging out: {0}", user.getLoginName());
authManager.expireIdentityCookie(realm, uriInfo);
resourceAdminManager.singleLogOut(realm, user.getLoginName());
}
// todo manage legal redirects
return Response.status(302).location(UriBuilder.fromUri(redirectUri).build()).build();
}
@Path("oauth/grant")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processOAuth(final MultivaluedMap<String, String> formData) {
OAuthFlows oauth = Flows.oauth(realm, request, uriInfo, authManager, tokenManager);
String code = formData.getFirst("code");
JWSInput input = new JWSInput(code, providers);
boolean verifiedCode = false;
try {
verifiedCode = RSAProvider.verify(input, realm.getPublicKey());
} catch (Exception ignored) {
logger.debug("Failed to verify signature", ignored);
}
if (!verifiedCode) {
return oauth.forwardToSecurityFailure("Illegal access code.");
}
String key = input.readContent(String.class);
AccessCodeEntry accessCodeEntry = tokenManager.getAccessCode(key);
if (accessCodeEntry == null) {
return oauth.forwardToSecurityFailure("Unknown access code.");
}
String redirect = accessCodeEntry.getRedirectUri();
String state = accessCodeEntry.getState();
if (formData.containsKey("cancel")) {
return redirectAccessDenied(redirect, state);
}
accessCodeEntry.setExpiration((System.currentTimeMillis() / 1000) + realm.getAccessCodeLifespan());
return oauth.redirectAccessCode(accessCodeEntry, state, redirect);
}
protected Response redirectAccessDenied(String redirect, String state) {
UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam("error", "access_denied");
if (state != null)
redirectUri.queryParam("state", state);
Response.ResponseBuilder location = Response.status(302).location(redirectUri.build());
return location.build();
}
}
| true | true | public Response accessCodeToToken(final MultivaluedMap<String, String> formData) {
logger.debug("accessRequest <---");
if (!realm.isEnabled()) {
throw new NotAuthorizedException("Realm not enabled");
}
String code = formData.getFirst("code");
if (code == null) {
logger.debug("code not specified");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_request");
error.put("error_description", "code not specified");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
String client_id = formData.getFirst("client_id");
if (client_id == null) {
logger.debug("client_id not specified");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_request");
error.put("error_description", "client_id not specified");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
UserModel client = realm.getUser(client_id);
if (client == null) {
logger.debug("Could not find user");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_client");
error.put("error_description", "Could not find user");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
if (!client.isEnabled()) {
logger.debug("user is not enabled");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_client");
error.put("error_description", "User is not enabled");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
AuthenticationStatus status = authManager.authenticateForm(realm, client, formData);
if (status != AuthenticationStatus.SUCCESS) {
Map<String, String> error = new HashMap<String, String>();
error.put("error", "unauthorized_client");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
JWSInput input = new JWSInput(code, providers);
boolean verifiedCode = false;
try {
verifiedCode = RSAProvider.verify(input, realm.getPublicKey());
} catch (Exception ignored) {
logger.debug("Failed to verify signature", ignored);
}
if (!verifiedCode) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Unable to verify code signature");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
String key = input.readContent(String.class);
AccessCodeEntry accessCode = tokenManager.pullAccessCode(key);
if (accessCode == null) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Code not found");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (accessCode.isExpired()) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Code is expired");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (!accessCode.getToken().isActive()) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Token expired");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (!client.getLoginName().equals(accessCode.getClient().getLoginName())) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Auth error");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
logger.debug("accessRequest SUCCESS");
AccessTokenResponse res = accessTokenResponse(realm.getPrivateKey(), accessCode.getToken());
return Cors.add(request, Response.ok(res)).allowedOrigins(client).build();
}
| public Response accessCodeToToken(final MultivaluedMap<String, String> formData) {
logger.debug("accessRequest <---");
if (!realm.isEnabled()) {
throw new NotAuthorizedException("Realm not enabled");
}
String code = formData.getFirst("code");
if (code == null) {
logger.debug("code not specified");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_request");
error.put("error_description", "code not specified");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
String client_id = formData.getFirst("client_id");
if (client_id == null) {
logger.debug("client_id not specified");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_request");
error.put("error_description", "client_id not specified");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
UserModel client = realm.getUser(client_id);
if (client == null) {
logger.debug("Could not find user");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_client");
error.put("error_description", "Could not find user");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
if (!client.isEnabled()) {
logger.debug("user is not enabled");
Map<String, String> error = new HashMap<String, String>();
error.put("error", "invalid_client");
error.put("error_description", "User is not enabled");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
AuthenticationStatus status = authManager.authenticateForm(realm, client, formData);
if (status != AuthenticationStatus.SUCCESS) {
Map<String, String> error = new HashMap<String, String>();
error.put("error", "unauthorized_client");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
}
JWSInput input = new JWSInput(code, providers);
boolean verifiedCode = false;
try {
verifiedCode = RSAProvider.verify(input, realm.getPublicKey());
} catch (Exception ignored) {
logger.debug("Failed to verify signature", ignored);
}
if (!verifiedCode) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Unable to verify code signature");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
String key = input.readContent(String.class);
AccessCodeEntry accessCode = tokenManager.pullAccessCode(key);
if (accessCode == null) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Code not found");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (accessCode.isExpired()) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Code is expired");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (!accessCode.getToken().isActive()) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Token expired");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
if (!client.getLoginName().equals(accessCode.getClient().getLoginName())) {
Map<String, String> res = new HashMap<String, String>();
res.put("error", "invalid_grant");
res.put("error_description", "Auth error");
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
.build();
}
logger.debug("accessRequest SUCCESS");
AccessTokenResponse res = accessTokenResponse(realm.getPrivateKey(), accessCode.getToken());
return Cors.add(request, Response.ok(res)).allowedOrigins(client).allowedMethods("POST").build();
}
|
diff --git a/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java b/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
index e6e5fdcb2..8c8f6b945 100644
--- a/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
+++ b/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
@@ -1,656 +1,656 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.commons.spring;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.GrailsDataSource;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.GrailsPageFlowClass;
import org.codehaus.groovy.grails.commons.GrailsServiceClass;
import org.codehaus.groovy.grails.commons.GrailsTagLibClass;
import org.codehaus.groovy.grails.commons.GrailsTaskClass;
import org.codehaus.groovy.grails.commons.GrailsTaskClassProperty;
import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean;
import org.codehaus.groovy.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean;
import org.codehaus.groovy.grails.orm.hibernate.validation.GrailsDomainClassValidator;
import org.codehaus.groovy.grails.scaffolding.DefaultGrailsResponseHandlerFactory;
import org.codehaus.groovy.grails.scaffolding.DefaultGrailsScaffoldViewResolver;
import org.codehaus.groovy.grails.scaffolding.DefaultGrailsScaffolder;
import org.codehaus.groovy.grails.scaffolding.DefaultScaffoldRequestHandler;
import org.codehaus.groovy.grails.scaffolding.GrailsScaffoldDomain;
import org.codehaus.groovy.grails.scaffolding.ViewDelegatingScaffoldResponseHandler;
import org.codehaus.groovy.grails.support.ClassEditor;
import org.codehaus.groovy.grails.web.errors.GrailsExceptionResolver;
import org.codehaus.groovy.grails.web.pageflow.GrailsFlowBuilder;
import org.codehaus.groovy.grails.web.pageflow.execution.servlet.GrailsServletFlowExecutionManager;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsUrlHandlerMapping;
import org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController;
import org.codehaus.groovy.grails.web.servlet.view.GrailsViewResolver;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.target.HotSwappableTargetSource;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateAccessor;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerBean;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;
import org.springframework.util.Assert;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.webflow.config.FlowFactoryBean;
import org.springframework.webflow.mvc.FlowController;
import org.springmodules.beans.factory.config.MapToPropertiesFactoryBean;
import org.springmodules.beans.factory.drivers.Bean;
import org.springmodules.db.hsqldb.ServerBean;
/**
* <p>Creates beans and bean references for a Grails application.
*
* @author Steven Devijver
* @since Jul 2, 2005
*/
public class SpringConfig {
private GrailsApplication application = null;
private static final Log LOG = LogFactory.getLog(SpringConfig.class);
public SpringConfig(GrailsApplication application) {
super();
this.application = application;
}
public Collection getBeanReferences() {
Collection beanReferences = new ArrayList();
Map urlMappings = new HashMap();
/**
* Regarding conversion to plugins:
*
* N/A: not applicable, does not need to be converted
* OK: already converted to plugin (please mention plugin name
*/
Assert.notNull(application);
// configure general references
// N/A
Bean classLoader = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
classLoader.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
classLoader.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClassLoader"));
// Register custom class editor
// OK: org.codehaus.groovy.grails.plugins.support.classeditor.ClassEditorPlugin
Bean classEditor = SpringConfigUtils.createSingletonBean(ClassEditor.class);
classEditor.setProperty("classLoader", classLoader);
Bean propertyEditors = SpringConfigUtils.createSingletonBean(CustomEditorConfigurer.class);
Map customEditors = new HashMap();
customEditors.put(SpringConfigUtils.createLiteralValue("java.lang.Class"), classEditor);
propertyEditors.setProperty("customEditors", SpringConfigUtils.createMap(customEditors));
beanReferences.add(SpringConfigUtils.createBeanReference("customEditors", propertyEditors));
// configure exception handler
// OK: org.codehaus.groovy.grails.web.plugins.support.exceptionResolver.GrailsExceptionResolverPlugin
Bean exceptionHandler = SpringConfigUtils.createSingletonBean(GrailsExceptionResolver.class);
exceptionHandler.setProperty("exceptionMappings", SpringConfigUtils.createLiteralValue("java.lang.Exception=error"));
beanReferences.add(SpringConfigUtils.createBeanReference("exceptionHandler", exceptionHandler));
// configure multipart support
// OK: org.codehaus.groovy.grails.web.plugins.support.multipartresolver.CommonsMultipartResolverPlugin
Bean multipartResolver = SpringConfigUtils.createSingletonBean(CommonsMultipartResolver.class);
beanReferences.add(SpringConfigUtils.createBeanReference("multipartResolver", multipartResolver));
// configure data source & hibernate
LOG.info("[SpringConfig] Configuring i18n support");
populateI18nSupport(beanReferences);
// configure data source & hibernate
LOG.info("[SpringConfig] Configuring Grails data source");
populateDataSourceReferences(beanReferences);
// configure domain classes
LOG.info("[SpringConfig] Configuring Grails domain");
populateDomainClassReferences(beanReferences, classLoader);
// configure services
LOG.info("[SpringConfig] Configuring Grails services");
populateServiceClassReferences(beanReferences);
// configure grails page flows
LOG.info("[SpringConfig] Configuring GrabuildSessionFactoryils page flows");
populatePageFlowReferences(beanReferences, urlMappings);
// configure grails controllers
LOG.info("[SpringConfig] Configuring Grails controllers");
populateControllerReferences(beanReferences, urlMappings);
// configure scaffolding
LOG.info("[SpringConfig] Configuring Grails scaffolding");
populateScaffoldingReferences(beanReferences);
// configure tasks
LOG.info("[SpringConfig] Configuring Grails tasks");
populateTasksReferences(beanReferences);
return beanReferences;
}
// configures tasks
private void populateTasksReferences(Collection beanReferences) {
GrailsTaskClass[] grailsTaskClasses = application.getGrailsTasksClasses();
Collection schedulerReferences = new ArrayList();
// todo jdbc job loading
for (int i = 0; i < grailsTaskClasses.length; i++) {
GrailsTaskClass grailsTaskClass = grailsTaskClasses[i];
Bean taskClassBean = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taskClassBean.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taskClassBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTaskClass"));
taskClassBean.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTaskClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName() + "Class", taskClassBean));
/* additional indirrection so that autowireing would be possible */
Bean taskInstance = SpringConfigUtils.createSingletonBean();
taskInstance.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName() + "Class"));
taskInstance.setFactoryMethod("newInstance");
taskInstance.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference( grailsTaskClass.getFullName(), taskInstance));
Bean jobDetailFactoryBean = SpringConfigUtils.createSingletonBean( MethodInvokingJobDetailFactoryBean.class );
jobDetailFactoryBean.setProperty("targetObject", SpringConfigUtils.createBeanReference( grailsTaskClass.getFullName() ));
jobDetailFactoryBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue(GrailsTaskClassProperty.EXECUTE));
jobDetailFactoryBean.setProperty("group", SpringConfigUtils.createLiteralValue(grailsTaskClass.getGroup()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"JobDetail", jobDetailFactoryBean));
if( !grailsTaskClass.isCronExpressionConfigured() ){ /* configuring Task using startDelay and timeOut */
Bean triggerBean = SpringConfigUtils.createSingletonBean(SimpleTriggerBean.class);
triggerBean.setProperty("jobDetail", SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"JobDetail"));
triggerBean.setProperty("startDelay", SpringConfigUtils.createLiteralValue( grailsTaskClass.getStartDelay() ));
triggerBean.setProperty("repeatInterval", SpringConfigUtils.createLiteralValue( grailsTaskClass.getTimeout() ));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"SimpleTrigger", triggerBean));
schedulerReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"SimpleTrigger"));
}else{ /* configuring Task using cronExpression */
Bean triggerBean = SpringConfigUtils.createSingletonBean(CronTriggerBean.class);
triggerBean.setProperty("jobDetail", SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"JobDetail"));
triggerBean.setProperty("cronExpression", SpringConfigUtils.createLiteralValue(grailsTaskClass.getCronExpression()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"CronTrigger", triggerBean));
schedulerReferences.add(SpringConfigUtils.createBeanReference(grailsTaskClass.getFullName()+"CronTrigger"));
}
}
Bean schedulerFactoryBean = SpringConfigUtils.createSingletonBean(SchedulerFactoryBean.class);
schedulerFactoryBean.setProperty("triggers", SpringConfigUtils.createList(schedulerReferences));
beanReferences.add(SpringConfigUtils.createBeanReference("GrailsSchedulerBean",schedulerFactoryBean));
}
private void populateI18nSupport(Collection beanReferences) {
// setup message source
// OK: org.codehaus.groovy.grails.web.plugins.support.i18n.ReloadableResourceBundleMessageSourcePlugin
Bean messageSource = SpringConfigUtils.createSingletonBean( ReloadableResourceBundleMessageSource.class );
messageSource.setProperty( "basename", SpringConfigUtils.createLiteralValue("WEB-INF/classes/grails-app/i18n/messages"));
beanReferences.add(SpringConfigUtils.createBeanReference("messageSource", messageSource));
// setup locale change interceptor
// OK: org.codehaus.groovy.grails.web.plugins.support.i18n.LocaleChangeInterceptorPlugin
Bean localeChangeInterceptor = SpringConfigUtils.createSingletonBean(LocaleChangeInterceptor.class);
localeChangeInterceptor.setProperty("paramName", SpringConfigUtils.createLiteralValue("lang"));
beanReferences.add(SpringConfigUtils.createBeanReference("localeChangeInterceptor", localeChangeInterceptor));
// setup locale resolver
// OK: org.codehaus.groovy.grails.web.plugins.support.i18n.CookieLocaleResolverPlugin
Bean localeResolver = SpringConfigUtils.createSingletonBean(CookieLocaleResolver.class);
beanReferences.add(SpringConfigUtils.createBeanReference("localeResolver", localeResolver));
}
// configures scaffolding
private void populateScaffoldingReferences(Collection beanReferences) {
// go through all the controllers
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
// retrieve appropriate domain class
Class scaffoldedClass = simpleControllers[i].getScaffoldedClass();
GrailsDomainClass domainClass;
if(scaffoldedClass == null) {
domainClass = application.getGrailsDomainClass(simpleControllers[i].getName());
if(domainClass != null) {
scaffoldedClass = domainClass.getClazz();
}
}
if(scaffoldedClass == null) {
LOG.info("[Spring] Scaffolding disabled for controller ["+simpleControllers[i].getFullName()+"], no equivalent domain class named ["+simpleControllers[i].getName()+"]");
}
else {
Bean scaffolder = SpringConfigUtils.createSingletonBean(DefaultGrailsScaffolder.class);
// create scaffold domain
Collection constructorArguments = new ArrayList();
constructorArguments.add(SpringConfigUtils.createLiteralValue(scaffoldedClass.getName()));
constructorArguments.add(SpringConfigUtils.createBeanReference("sessionFactory"));
Bean domain = SpringConfigUtils.createSingletonBean(GrailsScaffoldDomain.class, constructorArguments);
// domain.setProperty("validator", SpringConfigUtils.createBeanReference( domainClass.getFullName() + "Validator"));
beanReferences.add( SpringConfigUtils.createBeanReference( scaffoldedClass.getName() + "ScaffoldDomain",domain ) );
// create and configure request handler
Bean requestHandler = SpringConfigUtils.createSingletonBean(DefaultScaffoldRequestHandler.class);
requestHandler.setProperty("scaffoldDomain", SpringConfigUtils.createBeanReference(scaffoldedClass.getName() + "ScaffoldDomain"));
// create response factory
constructorArguments = new ArrayList();
constructorArguments.add(SpringConfigUtils.createBeanReference("grailsApplication"));
// configure default response handler
Bean defaultResponseHandler = SpringConfigUtils.createSingletonBean(ViewDelegatingScaffoldResponseHandler.class);
// configure a simple view delegating resolver
Bean defaultViewResolver = SpringConfigUtils.createSingletonBean(DefaultGrailsScaffoldViewResolver.class,constructorArguments);
defaultResponseHandler.setProperty("scaffoldViewResolver", defaultViewResolver);
// create constructor arguments response handler factory
constructorArguments = new ArrayList();
constructorArguments.add(SpringConfigUtils.createBeanReference("grailsApplication"));
constructorArguments.add(defaultResponseHandler);
Bean responseHandlerFactory = SpringConfigUtils.createSingletonBean( DefaultGrailsResponseHandlerFactory.class,constructorArguments );
scaffolder.setProperty( "scaffoldResponseHandlerFactory", responseHandlerFactory );
scaffolder.setProperty("scaffoldRequestHandler", requestHandler);
beanReferences.add( SpringConfigUtils.createBeanReference( simpleControllers[i].getFullName() + "Scaffolder",scaffolder ) );
}
}
}
private void populateControllerReferences(Collection beanReferences, Map urlMappings) {
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference(SimpleGrailsController.APPLICATION_CONTEXT_ID, simpleGrailsController));
Bean grailsViewResolver = SpringConfigUtils.createSingletonBean(GrailsViewResolver.class);
grailsViewResolver.setProperty("viewClass",SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.view.JstlView"));
- grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS));
+ grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS + '/'));
grailsViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", grailsViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(GrailsUrlHandlerMapping.class);
//beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID + "Target", simpleUrlHandlerMapping));
Collection args = new ArrayList();
args.add(simpleUrlHandlerMapping);
Bean simpleUrlHandlerMappingTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE,simpleUrlHandlerMappingTargetSource));
// configure handler interceptors
Bean openSessionInViewInterceptor = SpringConfigUtils.createSingletonBean(OpenSessionInViewInterceptor.class);
openSessionInViewInterceptor.setProperty("flushMode",SpringConfigUtils.createLiteralValue(String.valueOf(HibernateAccessor.FLUSH_AUTO)));
openSessionInViewInterceptor.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor",openSessionInViewInterceptor));
Collection interceptors = new ArrayList();
interceptors.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor"));
simpleUrlHandlerMapping.setProperty("interceptors", SpringConfigUtils.createList(interceptors));
Bean simpleUrlHandlerMappingProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
simpleUrlHandlerMappingProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE));
simpleUrlHandlerMappingProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.HandlerMapping"));
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID, simpleUrlHandlerMappingProxy));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
// setup controller class by retrieving it from the grails application
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
// configure controller class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
Bean controllerTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource", controllerTargetSource));
// setup AOP proxy that uses hot swappable target source
Bean controllerClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
controllerClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource"));
controllerClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsControllerClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy", controllerClassProxy));
// create prototype bean that uses the controller AOP proxy controller class bean as a factory
Bean controller = SpringConfigUtils.createPrototypeBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy"));
controller.setFactoryMethod("newInstance");
controller.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
if(!urlMappings.containsKey(simpleController.getURIs()[x]))
urlMappings.put(simpleController.getURIs()[x], SimpleGrailsController.APPLICATION_CONTEXT_ID);
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
GrailsTagLibClass[] tagLibs = application.getGrailsTabLibClasses();
for (int i = 0; i < tagLibs.length; i++) {
GrailsTagLibClass grailsTagLib = tagLibs[i];
// setup taglib class by retrieving it from the grails application bean
Bean taglibClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taglibClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taglibClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTagLibClass"));
taglibClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTagLib.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class", taglibClass));
// configure taglib class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class"));
Bean taglibTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
// setup AOP proxy that uses hot swappable target source
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource", taglibTargetSource));
Bean taglibClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
taglibClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource"));
taglibClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsTagLibClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy", taglibClassProxy));
// create prototype bean that refers to the AOP proxied taglib class uses it as a factory
Bean taglib = SpringConfigUtils.createPrototypeBean();
taglib.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy"));
taglib.setFactoryMethod("newInstance");
taglib.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName(), taglib));
}
}
private void populateDataSourceReferences(Collection beanReferences) {
boolean dependsOnHsqldbServer = false;
GrailsDataSource grailsDataSource = application.getGrailsDataSource();
Bean localSessionFactoryBean = SpringConfigUtils.createSingletonBean(ConfigurableLocalSessionFactoryBean.class);
if (grailsDataSource != null) {
// OK: org.codehaus.groovy.grails.plugins.datasource.PooledDatasourcePlugin
// OK: org.codehaus.groovy.grails.plugins.datasource.NonPooledDataSourcePlugin
Bean dataSource;
if (grailsDataSource.isPooled()) {
dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
} else {
dataSource = SpringConfigUtils.createSingletonBean(DriverManagerDataSource.class);
}
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue(grailsDataSource.getDriverClassName()));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue(grailsDataSource.getUrl()));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue(grailsDataSource.getUsername()));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(grailsDataSource.getPassword()));
if(grailsDataSource.getConfigurationClass() != null) {
LOG.info("[SpringConfig] Using custom Hibernate configuration class ["+grailsDataSource.getConfigurationClass()+"]");
localSessionFactoryBean.setProperty("configClass", SpringConfigUtils.createLiteralValue(grailsDataSource.getConfigurationClass().getName()));
}
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
} else {
// N/A
Bean dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue("org.hsqldb.jdbcDriver"));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue("jdbc:hsqldb:hsql://localhost:9101/"));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue("sa"));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(""));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
Bean hsqldbServer = SpringConfigUtils.createSingletonBean(ServerBean.class);
hsqldbServer.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
Map hsqldbProperties = new HashMap();
hsqldbProperties.put("server.port", "9101");
hsqldbProperties.put("server.database.0", "mem:temp");
hsqldbServer.setProperty("serverProperties", SpringConfigUtils.createProperties(hsqldbProperties));
beanReferences.add(SpringConfigUtils.createBeanReference("hsqldbServer", hsqldbServer));
dependsOnHsqldbServer = true;
}
// OK: org.codehaus.groovy.grails.plugins.hibernate.HibernateDialectDetectorPlugin
Map vendorNameDialectMappings = new HashMap();
URL hibernateDialects = this.application.getClassLoader().getResource("hibernate-dialects.properties");
if(hibernateDialects != null) {
Properties p = new Properties();
try {
p.load(hibernateDialects.openStream());
Iterator iter = p.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry e = (Map.Entry)iter.next();
// Note: the entry is reversed in the properties file since the database product
// name can contain spaces.
vendorNameDialectMappings.put(e.getValue(), "org.hibernate.dialect." + e.getKey());
}
} catch (IOException e) {
LOG.info("[SpringConfig] Error loading hibernate-dialects.properties file: " + e.getMessage());
}
}
Bean dialectDetector = SpringConfigUtils.createSingletonBean(HibernateDialectDetectorFactoryBean.class);
dialectDetector.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
dialectDetector.setProperty("vendorNameDialectMappings", SpringConfigUtils.createProperties(vendorNameDialectMappings));
if (dependsOnHsqldbServer) {
Collection dependsOn = new ArrayList();
dependsOn.add(SpringConfigUtils.createBeanReference("hsqldbServer"));
dialectDetector.setDependsOn(dependsOn);
}
Map hibernatePropertiesMap = new HashMap();
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.dialect"), dialectDetector);
if(grailsDataSource == null ) {
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.hbm2ddl.auto"), SpringConfigUtils.createLiteralValue("create-drop"));
}
else {
if(grailsDataSource.getDbCreate() != null) {
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.hbm2ddl.auto"), SpringConfigUtils.createLiteralValue(grailsDataSource.getDbCreate()));
}
}
Bean hibernateProperties = SpringConfigUtils.createSingletonBean(MapToPropertiesFactoryBean.class);
hibernateProperties.setProperty("map", SpringConfigUtils.createMap(hibernatePropertiesMap));
// N/A
Bean grailsClassLoader = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
grailsClassLoader.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
grailsClassLoader.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClassLoader"));
localSessionFactoryBean.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
ClassLoader cl = this.application.getClassLoader();
URL hibernateConfig = cl.getResource("hibernate.cfg.xml");
if(hibernateConfig != null) {
localSessionFactoryBean.setProperty("configLocation", SpringConfigUtils.createLiteralValue("classpath:hibernate.cfg.xml"));
}
localSessionFactoryBean.setProperty("hibernateProperties", hibernateProperties);
localSessionFactoryBean.setProperty("grailsApplication", SpringConfigUtils.createBeanReference("grailsApplication"));
localSessionFactoryBean.setProperty("classLoader", grailsClassLoader);
beanReferences.add(SpringConfigUtils.createBeanReference("sessionFactory", localSessionFactoryBean));
// OK: org.codehaus.groovy.grails.plugins.hibernate.HibernateTransactionManagerPlugin
Bean transactionManager = SpringConfigUtils.createSingletonBean(HibernateTransactionManager.class);
transactionManager.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("transactionManager", transactionManager));
}
private void populateDomainClassReferences(Collection beanReferences, Bean classLoader) {
GrailsDomainClass[] grailsDomainClasses = application.getGrailsDomainClasses();
for (int i = 0; i < grailsDomainClasses.length; i++) {
GrailsDomainClass grailsDomainClass = grailsDomainClasses[i];
Bean domainClassBean = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
domainClassBean.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
domainClassBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsDomainClass"));
domainClassBean.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsDomainClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "DomainClass", domainClassBean));
// create persistent class bean references
Bean persistentClassBean = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
persistentClassBean.setProperty("targetObject", SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "DomainClass"));
persistentClassBean.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClazz"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "PersistentClass", persistentClassBean));
/*Collection constructorArguments = new ArrayList();
// configure persistent methods
constructorArguments.add(SpringConfigUtils.createBeanReference("grailsApplication"));
constructorArguments.add(SpringConfigUtils.createLiteralValue(grailsDomainClass.getClazz().getName()));
constructorArguments.add(SpringConfigUtils.createBeanReference("sessionFactory"));
constructorArguments.add(classLoader);
Bean hibernatePersistentMethods = SpringConfigUtils.createSingletonBean(DomainClassMethods.class, constructorArguments);
beanReferences.add(SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "PersistentMethods", hibernatePersistentMethods));*/
// configure validator
Bean validatorBean = SpringConfigUtils.createSingletonBean( GrailsDomainClassValidator.class);
validatorBean.setProperty( "domainClass" ,SpringConfigUtils.createBeanReference(grailsDomainClass.getFullName() + "DomainClass") );
validatorBean.setProperty( "sessionFactory" ,SpringConfigUtils.createBeanReference("sessionFactory") );
validatorBean.setProperty( "messageSource" ,SpringConfigUtils.createBeanReference("messageSource") );
beanReferences.add( SpringConfigUtils.createBeanReference( grailsDomainClass.getFullName() + "Validator", validatorBean ) );
}
}
private void populateServiceClassReferences(Collection beanReferences) {
GrailsServiceClass[] serviceClasses = application.getGrailsServiceClasses();
for (int i = 0; i <serviceClasses.length; i++) {
GrailsServiceClass grailsServiceClass = serviceClasses[i];
Bean serviceClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
serviceClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
serviceClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsServiceClass"));
serviceClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsServiceClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class", serviceClass));
Bean serviceInstance = SpringConfigUtils.createSingletonBean();
serviceInstance.setFactoryBean(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class"));
serviceInstance.setFactoryMethod("newInstance");
if (grailsServiceClass.byName()) {
serviceInstance.setAutowire("byName");
} else if (grailsServiceClass.byType()) {
serviceInstance.setAutowire("byType");
}
// configure the service instance as a hotswappable target source
// if its transactional configure transactional proxy
if (grailsServiceClass.isTransactional()) {
Map transactionAttributes = new HashMap();
transactionAttributes.put("*", "PROPAGATION_REQUIRED");
Bean transactionalProxy = SpringConfigUtils.createSingletonBean(TransactionProxyFactoryBean.class);
transactionalProxy.setProperty("target", serviceInstance);
transactionalProxy.setProperty("proxyTargetClass", SpringConfigUtils.createLiteralValue("true"));
transactionalProxy.setProperty("transactionAttributes", SpringConfigUtils.createProperties(transactionAttributes));
transactionalProxy.setProperty("transactionManager", SpringConfigUtils.createBeanReference("transactionManager"));
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", transactionalProxy));
} else {
// otherwise configure a standard proxy
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", serviceInstance));
}
}
}
/**
* Configures Grails page flows
*/
private void populatePageFlowReferences(Collection beanReferences, Map urlMappings) {
GrailsPageFlowClass[] pageFlows = application.getPageFlows();
for (int i = 0; i < pageFlows.length; i++) {
GrailsPageFlowClass pageFlow = pageFlows[i];
if (!pageFlow.getAvailable()) {
continue;
}
Bean pageFlowClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
pageFlowClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
pageFlowClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getPageFlow"));
pageFlowClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(pageFlow.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class", pageFlowClass));
Bean pageFlowInstance = SpringConfigUtils.createSingletonBean();
pageFlowInstance.setFactoryBean(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
pageFlowInstance.setFactoryMethod("newInstance");
if (pageFlow.byType()) {
pageFlowInstance.setAutowire("byType");
} else if (pageFlow.byName()) {
pageFlowInstance.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName(), pageFlowInstance));
Bean flowBuilder = SpringConfigUtils.createSingletonBean(GrailsFlowBuilder.class);
flowBuilder.setProperty("pageFlowClass", SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
Bean flowFactoryBean = SpringConfigUtils.createSingletonBean(FlowFactoryBean.class);
flowFactoryBean.setProperty("flowBuilder", flowBuilder);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFlowId(), flowFactoryBean));
if (pageFlow.getAccessible()) {
Bean flowExecutionManager = SpringConfigUtils.createSingletonBean(GrailsServletFlowExecutionManager.class);
flowExecutionManager.setProperty("flow", SpringConfigUtils.createBeanReference(pageFlow.getFlowId()));
Bean flowController = SpringConfigUtils.createSingletonBean(FlowController.class);
flowController.setProperty("flowExecutionManager", flowExecutionManager);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Controller", flowController));
urlMappings.put(pageFlow.getUri(), pageFlow.getFullName() + "Controller");
}
}
}
}
| true | true | private void populateControllerReferences(Collection beanReferences, Map urlMappings) {
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference(SimpleGrailsController.APPLICATION_CONTEXT_ID, simpleGrailsController));
Bean grailsViewResolver = SpringConfigUtils.createSingletonBean(GrailsViewResolver.class);
grailsViewResolver.setProperty("viewClass",SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.view.JstlView"));
grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS));
grailsViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", grailsViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(GrailsUrlHandlerMapping.class);
//beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID + "Target", simpleUrlHandlerMapping));
Collection args = new ArrayList();
args.add(simpleUrlHandlerMapping);
Bean simpleUrlHandlerMappingTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE,simpleUrlHandlerMappingTargetSource));
// configure handler interceptors
Bean openSessionInViewInterceptor = SpringConfigUtils.createSingletonBean(OpenSessionInViewInterceptor.class);
openSessionInViewInterceptor.setProperty("flushMode",SpringConfigUtils.createLiteralValue(String.valueOf(HibernateAccessor.FLUSH_AUTO)));
openSessionInViewInterceptor.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor",openSessionInViewInterceptor));
Collection interceptors = new ArrayList();
interceptors.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor"));
simpleUrlHandlerMapping.setProperty("interceptors", SpringConfigUtils.createList(interceptors));
Bean simpleUrlHandlerMappingProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
simpleUrlHandlerMappingProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE));
simpleUrlHandlerMappingProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.HandlerMapping"));
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID, simpleUrlHandlerMappingProxy));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
// setup controller class by retrieving it from the grails application
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
// configure controller class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
Bean controllerTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource", controllerTargetSource));
// setup AOP proxy that uses hot swappable target source
Bean controllerClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
controllerClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource"));
controllerClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsControllerClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy", controllerClassProxy));
// create prototype bean that uses the controller AOP proxy controller class bean as a factory
Bean controller = SpringConfigUtils.createPrototypeBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy"));
controller.setFactoryMethod("newInstance");
controller.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
if(!urlMappings.containsKey(simpleController.getURIs()[x]))
urlMappings.put(simpleController.getURIs()[x], SimpleGrailsController.APPLICATION_CONTEXT_ID);
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
GrailsTagLibClass[] tagLibs = application.getGrailsTabLibClasses();
for (int i = 0; i < tagLibs.length; i++) {
GrailsTagLibClass grailsTagLib = tagLibs[i];
// setup taglib class by retrieving it from the grails application bean
Bean taglibClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taglibClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taglibClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTagLibClass"));
taglibClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTagLib.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class", taglibClass));
// configure taglib class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class"));
Bean taglibTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
// setup AOP proxy that uses hot swappable target source
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource", taglibTargetSource));
Bean taglibClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
taglibClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource"));
taglibClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsTagLibClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy", taglibClassProxy));
// create prototype bean that refers to the AOP proxied taglib class uses it as a factory
Bean taglib = SpringConfigUtils.createPrototypeBean();
taglib.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy"));
taglib.setFactoryMethod("newInstance");
taglib.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName(), taglib));
}
}
| private void populateControllerReferences(Collection beanReferences, Map urlMappings) {
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference(SimpleGrailsController.APPLICATION_CONTEXT_ID, simpleGrailsController));
Bean grailsViewResolver = SpringConfigUtils.createSingletonBean(GrailsViewResolver.class);
grailsViewResolver.setProperty("viewClass",SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.view.JstlView"));
grailsViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue(GrailsApplicationAttributes.PATH_TO_VIEWS + '/'));
grailsViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", grailsViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(GrailsUrlHandlerMapping.class);
//beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID + "Target", simpleUrlHandlerMapping));
Collection args = new ArrayList();
args.add(simpleUrlHandlerMapping);
Bean simpleUrlHandlerMappingTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE,simpleUrlHandlerMappingTargetSource));
// configure handler interceptors
Bean openSessionInViewInterceptor = SpringConfigUtils.createSingletonBean(OpenSessionInViewInterceptor.class);
openSessionInViewInterceptor.setProperty("flushMode",SpringConfigUtils.createLiteralValue(String.valueOf(HibernateAccessor.FLUSH_AUTO)));
openSessionInViewInterceptor.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor",openSessionInViewInterceptor));
Collection interceptors = new ArrayList();
interceptors.add(SpringConfigUtils.createBeanReference("openSessionInViewInterceptor"));
simpleUrlHandlerMapping.setProperty("interceptors", SpringConfigUtils.createList(interceptors));
Bean simpleUrlHandlerMappingProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
simpleUrlHandlerMappingProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_TARGET_SOURCE));
simpleUrlHandlerMappingProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.springframework.web.servlet.HandlerMapping"));
beanReferences.add(SpringConfigUtils.createBeanReference(GrailsUrlHandlerMapping.APPLICATION_CONTEXT_ID, simpleUrlHandlerMappingProxy));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
// setup controller class by retrieving it from the grails application
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
// configure controller class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
Bean controllerTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource", controllerTargetSource));
// setup AOP proxy that uses hot swappable target source
Bean controllerClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
controllerClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(simpleController.getFullName() + "TargetSource"));
controllerClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsControllerClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy", controllerClassProxy));
// create prototype bean that uses the controller AOP proxy controller class bean as a factory
Bean controller = SpringConfigUtils.createPrototypeBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Proxy"));
controller.setFactoryMethod("newInstance");
controller.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
if(!urlMappings.containsKey(simpleController.getURIs()[x]))
urlMappings.put(simpleController.getURIs()[x], SimpleGrailsController.APPLICATION_CONTEXT_ID);
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
GrailsTagLibClass[] tagLibs = application.getGrailsTabLibClasses();
for (int i = 0; i < tagLibs.length; i++) {
GrailsTagLibClass grailsTagLib = tagLibs[i];
// setup taglib class by retrieving it from the grails application bean
Bean taglibClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
taglibClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
taglibClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsTagLibClass"));
taglibClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsTagLib.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class", taglibClass));
// configure taglib class as hot swappable target source
Collection args = new ArrayList();
args.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Class"));
Bean taglibTargetSource = SpringConfigUtils.createSingletonBean(HotSwappableTargetSource.class, args);
// setup AOP proxy that uses hot swappable target source
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource", taglibTargetSource));
Bean taglibClassProxy = SpringConfigUtils.createSingletonBean(ProxyFactoryBean.class);
taglibClassProxy.setProperty("targetSource", SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "TargetSource"));
taglibClassProxy.setProperty("proxyInterfaces", SpringConfigUtils.createLiteralValue("org.codehaus.groovy.grails.commons.GrailsTagLibClass"));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy", taglibClassProxy));
// create prototype bean that refers to the AOP proxied taglib class uses it as a factory
Bean taglib = SpringConfigUtils.createPrototypeBean();
taglib.setFactoryBean(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName() + "Proxy"));
taglib.setFactoryMethod("newInstance");
taglib.setAutowire("byName");
beanReferences.add(SpringConfigUtils.createBeanReference(grailsTagLib.getFullName(), taglib));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.